renderer.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { MutableRefObject } from 'react';
  2. import { HastNode } from 'hast-util-select';
  3. import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown';
  4. import katex from 'rehype-katex';
  5. import raw from 'rehype-raw';
  6. import sanitize, { defaultSchema as sanitizeDefaultSchema } from 'rehype-sanitize';
  7. import slug from 'rehype-slug';
  8. import toc from 'rehype-toc';
  9. import breaks from 'remark-breaks';
  10. import emoji from 'remark-emoji';
  11. import gfm from 'remark-gfm';
  12. import math from 'remark-math';
  13. import { CodeBlock } from '~/components/ReactMarkdownComponents/CodeBlock';
  14. import { Header } from '~/components/ReactMarkdownComponents/Header';
  15. import { NextLink } from '~/components/ReactMarkdownComponents/NextLink';
  16. import { RendererConfig } from '~/interfaces/services/renderer';
  17. import loggerFactory from '~/utils/logger';
  18. import { addClass } from './rehype-plugins/add-class';
  19. import { relativeLinks } from './rehype-plugins/relative-links';
  20. // import CsvToTable from './PreProcessor/CsvToTable';
  21. // import EasyGrid from './PreProcessor/EasyGrid';
  22. // import Linker from './PreProcessor/Linker';
  23. // import XssFilter from './PreProcessor/XssFilter';
  24. // import BlockdiagConfigurer from './markdown-it/blockdiag';
  25. // import DrawioViewerConfigurer from './markdown-it/drawio-viewer';
  26. // import EmojiConfigurer from './markdown-it/emoji';
  27. // import FooternoteConfigurer from './markdown-it/footernote';
  28. // import HeaderConfigurer from './markdown-it/header';
  29. // import HeaderLineNumberConfigurer from './markdown-it/header-line-number';
  30. // import HeaderWithEditLinkConfigurer from './markdown-it/header-with-edit-link';
  31. // import LinkerByRelativePathConfigurer from './markdown-it/link-by-relative-path';
  32. // import MathJaxConfigurer from './markdown-it/mathjax';
  33. // import PlantUMLConfigurer from './markdown-it/plantuml';
  34. // import TableConfigurer from './markdown-it/table';
  35. // import TableWithHandsontableButtonConfigurer from './markdown-it/table-with-handsontable-button';
  36. // import TaskListsConfigurer from './markdown-it/task-lists';
  37. // import TocAndAnchorConfigurer from './markdown-it/toc-and-anchor';
  38. const logger = loggerFactory('growi:util:GrowiRenderer');
  39. // declare const hljs;
  40. // type MarkdownSettings = {
  41. // breaks?: boolean,
  42. // };
  43. // export default class GrowiRenderer {
  44. // RendererConfig: RendererConfig;
  45. // constructor(RendererConfig: RendererConfig, pagePath?: Nullable<string>) {
  46. // this.RendererConfig = RendererConfig;
  47. // this.pagePath = pagePath;
  48. // if (isClient() && (window as CustomWindow).growiRenderer != null) {
  49. // this.preProcessors = (window as CustomWindow).growiRenderer.preProcessors;
  50. // this.postProcessors = (window as CustomWindow).growiRenderer.postProcessors;
  51. // }
  52. // else {
  53. // this.preProcessors = [
  54. // new EasyGrid(),
  55. // new Linker(),
  56. // new CsvToTable(),
  57. // new XssFilter({
  58. // isEnabledXssPrevention: this.RendererConfig.isEnabledXssPrevention,
  59. // tagWhiteList: this.RendererConfig.tagWhiteList,
  60. // attrWhiteList: this.RendererConfig.attrWhiteList,
  61. // }),
  62. // ];
  63. // this.postProcessors = [
  64. // ];
  65. // }
  66. // this.init = this.init.bind(this);
  67. // this.addConfigurers = this.addConfigurers.bind(this);
  68. // this.setMarkdownSettings = this.setMarkdownSettings.bind(this);
  69. // this.configure = this.configure.bind(this);
  70. // this.process = this.process.bind(this);
  71. // this.codeRenderer = this.codeRenderer.bind(this);
  72. // }
  73. // init() {
  74. // let parser: Processor = unified().use(parse);
  75. // this.remarkPlugins.forEach((item) => {
  76. // parser = applyPlugin(parser, item);
  77. // });
  78. // let rehype: Processor = parser.use(remark2rehype);
  79. // this.rehypePlugins.forEach((item) => {
  80. // rehype = applyPlugin(rehype, item);
  81. // });
  82. // this.processor = rehype.use(rehype2react, {
  83. // createElement: React.createElement,
  84. // components: {
  85. // // a: NextLink,
  86. // },
  87. // });
  88. // }
  89. // init() {
  90. // // init markdown-it
  91. // this.md = new MarkdownIt({
  92. // html: true,
  93. // linkify: true,
  94. // highlight: this.codeRenderer,
  95. // });
  96. // this.isMarkdownItConfigured = false;
  97. // this.markdownItConfigurers = [
  98. // new TaskListsConfigurer(),
  99. // new HeaderConfigurer(),
  100. // new EmojiConfigurer(),
  101. // new MathJaxConfigurer(),
  102. // new DrawioViewerConfigurer(),
  103. // new PlantUMLConfigurer(this.RendererConfig),
  104. // new BlockdiagConfigurer(this.RendererConfig),
  105. // ];
  106. // if (this.pagePath != null) {
  107. // this.markdownItConfigurers.push(
  108. // new LinkerByRelativePathConfigurer(this.pagePath),
  109. // );
  110. // }
  111. // }
  112. // addConfigurers(configurers: any[]): void {
  113. // this.markdownItConfigurers.push(...configurers);
  114. // }
  115. // setMarkdownSettings(settings: MarkdownSettings): void {
  116. // this.md.set(settings);
  117. // }
  118. // configure(): void {
  119. // if (!this.isMarkdownItConfigured) {
  120. // this.markdownItConfigurers.forEach((configurer) => {
  121. // configurer.configure(this.md);
  122. // });
  123. // }
  124. // }
  125. // preProcess(markdown, context) {
  126. // let processed = markdown;
  127. // for (let i = 0; i < this.preProcessors.length; i++) {
  128. // if (!this.preProcessors[i].process) {
  129. // continue;
  130. // }
  131. // processed = this.preProcessors[i].process(processed, context);
  132. // }
  133. // return processed;
  134. // }
  135. // process(markdown, context) {
  136. // return this.md.render(markdown, context);
  137. // }
  138. // postProcess(html, context) {
  139. // let processed = html;
  140. // for (let i = 0; i < this.postProcessors.length; i++) {
  141. // if (!this.postProcessors[i].process) {
  142. // continue;
  143. // }
  144. // processed = this.postProcessors[i].process(processed, context);
  145. // }
  146. // return processed;
  147. // }
  148. // codeRenderer(code, langExt) {
  149. // const noborder = (!this.RendererConfig.highlightJsStyleBorder) ? 'hljs-no-border' : '';
  150. // let citeTag = '';
  151. // let hljsLang = 'plaintext';
  152. // let showLinenumbers = false;
  153. // if (langExt) {
  154. // // https://regex101.com/r/qGs7eZ/3
  155. // const match = langExt.match(/^([^:=\n]+)?(=([^:=\n]*))?(:([^:=\n]*))?(=([^:=\n]*))?$/);
  156. // const lang = match[1];
  157. // const fileName = match[5] || null;
  158. // showLinenumbers = (match[2] != null) || (match[6] != null);
  159. // if (fileName != null) {
  160. // citeTag = `<cite>${fileName}</cite>`;
  161. // }
  162. // if (hljs.getLanguage(lang)) {
  163. // hljsLang = lang;
  164. // }
  165. // }
  166. // let highlightCode = code;
  167. // try {
  168. // highlightCode = hljs.highlight(hljsLang, code, true).value;
  169. // // add line numbers
  170. // if (showLinenumbers) {
  171. // highlightCode = hljs.lineNumbersValue((highlightCode));
  172. // }
  173. // }
  174. // catch (err) {
  175. // logger.error(err);
  176. // }
  177. // return `<pre class="hljs ${noborder}">${citeTag}<code>${highlightCode}</code></pre>`;
  178. // }
  179. // }
  180. export type RendererOptions = Partial<ReactMarkdownOptions>;
  181. const generateCommonOptions = (pagePath: string|undefined, config: RendererConfig): RendererOptions => {
  182. return {
  183. remarkPlugins: [gfm],
  184. rehypePlugins: [
  185. slug,
  186. [relativeLinks, { pagePath }],
  187. raw,
  188. [sanitize, {
  189. ...sanitizeDefaultSchema,
  190. attributes: {
  191. ...sanitizeDefaultSchema.attributes,
  192. '*': sanitizeDefaultSchema.attributes != null
  193. ? sanitizeDefaultSchema.attributes['*'].concat('class', 'className')
  194. : ['class', 'className'],
  195. },
  196. }],
  197. [addClass, {
  198. table: 'table table-bordered',
  199. }],
  200. ],
  201. components: {
  202. a: NextLink,
  203. code: CodeBlock,
  204. },
  205. };
  206. };
  207. export const generateViewOptions = (
  208. pagePath: string,
  209. config: RendererConfig,
  210. tocRef: MutableRefObject<HastNode | undefined>,
  211. ): RendererOptions => {
  212. const options = generateCommonOptions(pagePath, config);
  213. const { remarkPlugins, rehypePlugins, components } = options;
  214. // add remark plugins
  215. if (remarkPlugins != null) {
  216. remarkPlugins.push(emoji);
  217. remarkPlugins.push(math);
  218. if (config.isEnabledLinebreaks) {
  219. remarkPlugins.push(breaks);
  220. }
  221. }
  222. // store toc node
  223. if (rehypePlugins != null) {
  224. rehypePlugins.push(katex);
  225. rehypePlugins.push([toc, {
  226. nav: false,
  227. headings: ['h1', 'h2', 'h3'],
  228. customizeTOC: (toc: HastNode) => {
  229. // method for replace <ol> to <ul>
  230. const replacer = (children) => {
  231. children.forEach((child) => {
  232. if (child.type === 'element' && child.tagName === 'ol') {
  233. child.tagName = 'ul';
  234. }
  235. if (child.children) {
  236. replacer(child.children);
  237. }
  238. });
  239. };
  240. replacer([toc]); // replace <ol> to <ul>
  241. // For storing tocNode to global state with swr
  242. tocRef.current = toc;
  243. return false; // not show toc in body
  244. },
  245. }]);
  246. }
  247. // renderer.rehypePlugins.push([autoLinkHeadings, {
  248. // behavior: 'append',
  249. // }]);
  250. // add components
  251. if (components != null) {
  252. components.h1 = Header;
  253. components.h2 = Header;
  254. components.h3 = Header;
  255. }
  256. // // Add configurers for viewer
  257. // renderer.addConfigurers([
  258. // new FooternoteConfigurer(),
  259. // new TocAndAnchorConfigurer(),
  260. // new HeaderLineNumberConfigurer(),
  261. // new HeaderWithEditLinkConfigurer(),
  262. // new TableWithHandsontableButtonConfigurer(),
  263. // ]);
  264. // renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  265. // renderer.configure();
  266. return options;
  267. };
  268. export const generateTocOptions = (config: RendererConfig, tocNode: HastNode | undefined): RendererOptions => {
  269. const options = generateCommonOptions(undefined, config);
  270. const { remarkPlugins, rehypePlugins } = options;
  271. // add remark plugins
  272. if (remarkPlugins != null) {
  273. remarkPlugins.push(emoji);
  274. }
  275. // set toc node
  276. if (rehypePlugins != null) {
  277. rehypePlugins.push([toc, {
  278. headings: ['h1', 'h2', 'h3'],
  279. customizeTOC: () => tocNode,
  280. }]);
  281. }
  282. // renderer.rehypePlugins.push([autoLinkHeadings, {
  283. // behavior: 'append',
  284. // }]);
  285. return options;
  286. };
  287. export const generatePreviewOptions = (config: RendererConfig): RendererOptions => {
  288. const options = generateCommonOptions(undefined, config);
  289. // // Add configurers for preview
  290. // renderer.addConfigurers([
  291. // new FooternoteConfigurer(),
  292. // new HeaderLineNumberConfigurer(),
  293. // new TableConfigurer(),
  294. // ]);
  295. // renderer.setMarkdownSettings({ breaks: rendererSettings?.isEnabledLinebreaks });
  296. // renderer.configure();
  297. return options;
  298. };
  299. export const generateCommentPreviewOptions = (config: RendererConfig): RendererOptions => {
  300. const options = generateCommonOptions(undefined, config);
  301. const { remarkPlugins } = options;
  302. // add remark plugins
  303. if (remarkPlugins != null) {
  304. remarkPlugins.push(emoji);
  305. if (config.isEnabledLinebreaksInComments) {
  306. remarkPlugins.push(breaks);
  307. }
  308. }
  309. // renderer.addConfigurers([
  310. // new TableConfigurer(),
  311. // ]);
  312. // renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaksInComments });
  313. // renderer.configure();
  314. return options;
  315. };
  316. export const generateOthersOptions = (config: RendererConfig): RendererOptions => {
  317. const options = generateCommonOptions(undefined, config);
  318. // renderer.addConfigurers([
  319. // new TableConfigurer(),
  320. // ]);
  321. // renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  322. // renderer.configure();
  323. return options;
  324. };