renderer.ts 11 KB

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