renderer.tsx 11 KB

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