renderer.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // allow only types to import from react
  2. import { ComponentType } from 'react';
  3. import { Lsx } from '@growi/plugin-lsx/components';
  4. import * as lsxGrowiPlugin from '@growi/plugin-lsx/services/renderer';
  5. import * as drawioPlugin from '@growi/remark-drawio-plugin';
  6. import growiPlugin from '@growi/remark-growi-plugin';
  7. import { Schema as SanitizeOption } from 'hast-util-sanitize';
  8. import { SpecialComponents } from 'react-markdown/lib/ast-to-react';
  9. import { NormalComponents } from 'react-markdown/lib/complex-types';
  10. import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown';
  11. import katex from 'rehype-katex';
  12. import raw from 'rehype-raw';
  13. import sanitize, { defaultSchema as sanitizeDefaultSchema } from 'rehype-sanitize';
  14. import slug from 'rehype-slug';
  15. import { HtmlElementNode } from 'rehype-toc';
  16. import breaks from 'remark-breaks';
  17. import emoji from 'remark-emoji';
  18. import gfm from 'remark-gfm';
  19. import math from 'remark-math';
  20. import deepmerge from 'ts-deepmerge';
  21. import { PluggableList, Pluggable, PluginTuple } from 'unified';
  22. import { CodeBlock } from '~/components/ReactMarkdownComponents/CodeBlock';
  23. import { DrawioViewerWithEditButton } from '~/components/ReactMarkdownComponents/DrawioViewerWithEditButton';
  24. import { Header } from '~/components/ReactMarkdownComponents/Header';
  25. import { NextLink } from '~/components/ReactMarkdownComponents/NextLink';
  26. import { RendererConfig } from '~/interfaces/services/renderer';
  27. import loggerFactory from '~/utils/logger';
  28. import * as addClass from './rehype-plugins/add-class';
  29. import * as addLineNumberAttribute from './rehype-plugins/add-line-number-attribute';
  30. import * as keywordHighlighter from './rehype-plugins/keyword-highlighter';
  31. import { relativeLinks } from './rehype-plugins/relative-links';
  32. import { relativeLinksByPukiwikiLikeLinker } from './rehype-plugins/relative-links-by-pukiwiki-like-linker';
  33. import * as toc from './rehype-plugins/relocate-toc';
  34. import * as plantuml from './remark-plugins/plantuml';
  35. import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
  36. import * as xsvToTable from './remark-plugins/xsv-to-table';
  37. // import CsvToTable from './PreProcessor/CsvToTable';
  38. // import EasyGrid from './PreProcessor/EasyGrid';
  39. // import Linker from './PreProcessor/Linker';
  40. // import XssFilter from './PreProcessor/XssFilter';
  41. // import BlockdiagConfigurer from './markdown-it/blockdiag';
  42. // import DrawioViewerConfigurer from './markdown-it/drawio-viewer';
  43. // import EmojiConfigurer from './markdown-it/emoji';
  44. // import FooternoteConfigurer from './markdown-it/footernote';
  45. // import HeaderConfigurer from './markdown-it/header';
  46. // import HeaderLineNumberConfigurer from './markdown-it/header-line-number';
  47. // import HeaderWithEditLinkConfigurer from './markdown-it/header-with-edit-link';
  48. // import LinkerByRelativePathConfigurer from './markdown-it/link-by-relative-path';
  49. // import MathJaxConfigurer from './markdown-it/mathjax';
  50. // import PlantUMLConfigurer from './markdown-it/plantuml';
  51. // import TableConfigurer from './markdown-it/table';
  52. // import TableWithHandsontableButtonConfigurer from './markdown-it/table-with-handsontable-button';
  53. // import TaskListsConfigurer from './markdown-it/task-lists';
  54. // import TocAndAnchorConfigurer from './markdown-it/toc-and-anchor';
  55. const logger = loggerFactory('growi:util:GrowiRenderer');
  56. // declare const hljs;
  57. // type MarkdownSettings = {
  58. // breaks?: boolean,
  59. // };
  60. // export default class GrowiRenderer {
  61. // RendererConfig: RendererConfig;
  62. // constructor(RendererConfig: RendererConfig, pagePath?: Nullable<string>) {
  63. // this.RendererConfig = RendererConfig;
  64. // this.pagePath = pagePath;
  65. // if (isClient() && (window as CustomWindow).growiRenderer != null) {
  66. // this.preProcessors = (window as CustomWindow).growiRenderer.preProcessors;
  67. // this.postProcessors = (window as CustomWindow).growiRenderer.postProcessors;
  68. // }
  69. // else {
  70. // this.preProcessors = [
  71. // new EasyGrid(),
  72. // new Linker(),
  73. // new CsvToTable(),
  74. // new XssFilter({
  75. // isEnabledXssPrevention: this.RendererConfig.isEnabledXssPrevention,
  76. // tagWhiteList: this.RendererConfig.tagWhiteList,
  77. // attrWhiteList: this.RendererConfig.attrWhiteList,
  78. // }),
  79. // ];
  80. // this.postProcessors = [
  81. // ];
  82. // }
  83. // this.init = this.init.bind(this);
  84. // this.addConfigurers = this.addConfigurers.bind(this);
  85. // this.setMarkdownSettings = this.setMarkdownSettings.bind(this);
  86. // this.configure = this.configure.bind(this);
  87. // this.process = this.process.bind(this);
  88. // this.codeRenderer = this.codeRenderer.bind(this);
  89. // }
  90. // init() {
  91. // let parser: Processor = unified().use(parse);
  92. // this.remarkPlugins.forEach((item) => {
  93. // parser = applyPlugin(parser, item);
  94. // });
  95. // let rehype: Processor = parser.use(remark2rehype);
  96. // this.rehypePlugins.forEach((item) => {
  97. // rehype = applyPlugin(rehype, item);
  98. // });
  99. // this.processor = rehype.use(rehype2react, {
  100. // createElement: React.createElement,
  101. // components: {
  102. // // a: NextLink,
  103. // },
  104. // });
  105. // }
  106. // init() {
  107. // // init markdown-it
  108. // this.md = new MarkdownIt({
  109. // html: true,
  110. // linkify: true,
  111. // highlight: this.codeRenderer,
  112. // });
  113. // this.isMarkdownItConfigured = false;
  114. // this.markdownItConfigurers = [
  115. // new TaskListsConfigurer(),
  116. // new HeaderConfigurer(),
  117. // new EmojiConfigurer(),
  118. // new MathJaxConfigurer(),
  119. // new DrawioViewerConfigurer(),
  120. // new PlantUMLConfigurer(this.RendererConfig),
  121. // new BlockdiagConfigurer(this.RendererConfig),
  122. // ];
  123. // if (this.pagePath != null) {
  124. // this.markdownItConfigurers.push(
  125. // new LinkerByRelativePathConfigurer(this.pagePath),
  126. // );
  127. // }
  128. // }
  129. // addConfigurers(configurers: any[]): void {
  130. // this.markdownItConfigurers.push(...configurers);
  131. // }
  132. // setMarkdownSettings(settings: MarkdownSettings): void {
  133. // this.md.set(settings);
  134. // }
  135. // configure(): void {
  136. // if (!this.isMarkdownItConfigured) {
  137. // this.markdownItConfigurers.forEach((configurer) => {
  138. // configurer.configure(this.md);
  139. // });
  140. // }
  141. // }
  142. // preProcess(markdown, context) {
  143. // let processed = markdown;
  144. // for (let i = 0; i < this.preProcessors.length; i++) {
  145. // if (!this.preProcessors[i].process) {
  146. // continue;
  147. // }
  148. // processed = this.preProcessors[i].process(processed, context);
  149. // }
  150. // return processed;
  151. // }
  152. // process(markdown, context) {
  153. // return this.md.render(markdown, context);
  154. // }
  155. // postProcess(html, context) {
  156. // let processed = html;
  157. // for (let i = 0; i < this.postProcessors.length; i++) {
  158. // if (!this.postProcessors[i].process) {
  159. // continue;
  160. // }
  161. // processed = this.postProcessors[i].process(processed, context);
  162. // }
  163. // return processed;
  164. // }
  165. // codeRenderer(code, langExt) {
  166. // const noborder = (!this.RendererConfig.highlightJsStyleBorder) ? 'hljs-no-border' : '';
  167. // let citeTag = '';
  168. // let hljsLang = 'plaintext';
  169. // let showLinenumbers = false;
  170. // if (langExt) {
  171. // // https://regex101.com/r/qGs7eZ/3
  172. // const match = langExt.match(/^([^:=\n]+)?(=([^:=\n]*))?(:([^:=\n]*))?(=([^:=\n]*))?$/);
  173. // const lang = match[1];
  174. // const fileName = match[5] || null;
  175. // showLinenumbers = (match[2] != null) || (match[6] != null);
  176. // if (fileName != null) {
  177. // citeTag = `<cite>${fileName}</cite>`;
  178. // }
  179. // if (hljs.getLanguage(lang)) {
  180. // hljsLang = lang;
  181. // }
  182. // }
  183. // let highlightCode = code;
  184. // try {
  185. // highlightCode = hljs.highlight(hljsLang, code, true).value;
  186. // // add line numbers
  187. // if (showLinenumbers) {
  188. // highlightCode = hljs.lineNumbersValue((highlightCode));
  189. // }
  190. // }
  191. // catch (err) {
  192. // logger.error(err);
  193. // }
  194. // return `<pre class="hljs ${noborder}">${citeTag}<code>${highlightCode}</code></pre>`;
  195. // }
  196. // }
  197. type SanitizePlugin = PluginTuple<[SanitizeOption]>;
  198. export type RendererOptions = Omit<ReactMarkdownOptions, 'remarkPlugins' | 'rehypePlugins' | 'components' | 'children'> & {
  199. remarkPlugins: PluggableList,
  200. rehypePlugins: PluggableList,
  201. components?:
  202. | Partial<
  203. Omit<NormalComponents, keyof SpecialComponents>
  204. & SpecialComponents
  205. & {
  206. [elem: string]: ComponentType<any>,
  207. }
  208. >
  209. | undefined
  210. };
  211. const commonSanitizeOption: SanitizeOption = deepmerge(
  212. sanitizeDefaultSchema,
  213. {
  214. clobberPrefix: 'mdcont-',
  215. attributes: {
  216. '*': ['class', 'className', 'style'],
  217. },
  218. },
  219. );
  220. const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
  221. if (!Array.isArray(pluggable) || pluggable.length < 2) {
  222. return false;
  223. }
  224. const sanitizeOption = pluggable[1];
  225. return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
  226. };
  227. const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
  228. const { rehypePlugins } = options;
  229. if (rehypePlugins == null || rehypePlugins.length === 0) {
  230. return false;
  231. }
  232. return shouldBeTheLastItem
  233. ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
  234. : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
  235. };
  236. const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
  237. if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
  238. return;
  239. }
  240. throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
  241. };
  242. const generateCommonOptions = (pagePath: string|undefined, config: RendererConfig): RendererOptions => {
  243. return {
  244. remarkPlugins: [
  245. gfm,
  246. emoji,
  247. pukiwikiLikeLinker,
  248. growiPlugin,
  249. ],
  250. rehypePlugins: [
  251. [relativeLinksByPukiwikiLikeLinker, { pagePath }],
  252. [relativeLinks, { pagePath }],
  253. raw,
  254. [addClass.rehypePlugin, {
  255. table: 'table table-bordered',
  256. }],
  257. ],
  258. components: {
  259. a: NextLink,
  260. code: CodeBlock,
  261. },
  262. };
  263. };
  264. export const generateViewOptions = (
  265. pagePath: string,
  266. config: RendererConfig,
  267. storeTocNode: (toc: HtmlElementNode) => void,
  268. ): RendererOptions => {
  269. const options = generateCommonOptions(pagePath, config);
  270. const { remarkPlugins, rehypePlugins, components } = options;
  271. // add remark plugins
  272. remarkPlugins.push(
  273. math,
  274. [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
  275. drawioPlugin.remarkPlugin,
  276. xsvToTable.remarkPlugin,
  277. lsxGrowiPlugin.remarkPlugin,
  278. );
  279. if (config.isEnabledLinebreaks) {
  280. remarkPlugins.push(breaks);
  281. }
  282. // add rehype plugins
  283. rehypePlugins.push(
  284. slug,
  285. [lsxGrowiPlugin.rehypePlugin, { pagePath }],
  286. [sanitize, deepmerge(
  287. commonSanitizeOption,
  288. drawioPlugin.sanitizeOption,
  289. lsxGrowiPlugin.sanitizeOption,
  290. )],
  291. katex,
  292. [toc.rehypePluginStore, { storeTocNode }],
  293. // [autoLinkHeadings, {
  294. // behavior: 'append',
  295. // }]
  296. );
  297. // add components
  298. if (components != null) {
  299. components.h1 = Header;
  300. components.h2 = Header;
  301. components.h3 = Header;
  302. components.lsx = props => <Lsx {...props} forceToFetchData />;
  303. components.drawio = DrawioViewerWithEditButton;
  304. }
  305. // // Add configurers for viewer
  306. // renderer.addConfigurers([
  307. // new FooternoteConfigurer(),
  308. // new TocAndAnchorConfigurer(),
  309. // new HeaderLineNumberConfigurer(),
  310. // new HeaderWithEditLinkConfigurer(),
  311. // new TableWithHandsontableButtonConfigurer(),
  312. // ]);
  313. // renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  314. // renderer.configure();
  315. verifySanitizePlugin(options, false);
  316. return options;
  317. };
  318. export const generateTocOptions = (config: RendererConfig, tocNode: HtmlElementNode | undefined): RendererOptions => {
  319. const options = generateCommonOptions(undefined, config);
  320. const { rehypePlugins } = options;
  321. // add remark plugins
  322. // remarkPlugins.push();
  323. // add rehype plugins
  324. rehypePlugins.push(
  325. [toc.rehypePluginRestore, { tocNode }],
  326. [sanitize, commonSanitizeOption],
  327. );
  328. // renderer.rehypePlugins.push([autoLinkHeadings, {
  329. // behavior: 'append',
  330. // }]);
  331. verifySanitizePlugin(options);
  332. return options;
  333. };
  334. export const generateSimpleViewOptions = (config: RendererConfig, pagePath: string, highlightKeywords?: string | string[]): RendererOptions => {
  335. const options = generateCommonOptions(pagePath, config);
  336. const { remarkPlugins, rehypePlugins, components } = options;
  337. // add remark plugins
  338. remarkPlugins.push(
  339. math,
  340. [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
  341. drawioPlugin.remarkPlugin,
  342. xsvToTable.remarkPlugin,
  343. lsxGrowiPlugin.remarkPlugin,
  344. );
  345. if (config.isEnabledLinebreaks) {
  346. remarkPlugins.push(breaks);
  347. }
  348. // add rehype plugins
  349. rehypePlugins.push(
  350. [lsxGrowiPlugin.rehypePlugin, { pagePath }],
  351. [keywordHighlighter.rehypePlugin, { keywords: highlightKeywords }],
  352. [sanitize, deepmerge(
  353. commonSanitizeOption,
  354. drawioPlugin.sanitizeOption,
  355. lsxGrowiPlugin.sanitizeOption,
  356. )],
  357. katex,
  358. );
  359. // add components
  360. if (components != null) {
  361. components.lsx = props => <Lsx {...props} />;
  362. components.drawio = drawioPlugin.DrawioViewer;
  363. }
  364. verifySanitizePlugin(options, false);
  365. return options;
  366. };
  367. export const generatePreviewOptions = (config: RendererConfig, pagePath: string): RendererOptions => {
  368. const options = generateCommonOptions(pagePath, config);
  369. const { remarkPlugins, rehypePlugins, components } = options;
  370. // add remark plugins
  371. remarkPlugins.push(
  372. math,
  373. [plantuml.remarkPlugin, { baseUrl: config.plantumlUri }],
  374. drawioPlugin.remarkPlugin,
  375. xsvToTable.remarkPlugin,
  376. lsxGrowiPlugin.remarkPlugin,
  377. );
  378. if (config.isEnabledLinebreaks) {
  379. remarkPlugins.push(breaks);
  380. }
  381. // add rehype plugins
  382. rehypePlugins.push(
  383. [lsxGrowiPlugin.rehypePlugin, { pagePath }],
  384. addLineNumberAttribute.rehypePlugin,
  385. [sanitize, deepmerge(
  386. commonSanitizeOption,
  387. lsxGrowiPlugin.sanitizeOption,
  388. drawioPlugin.sanitizeOption,
  389. addLineNumberAttribute.sanitizeOption,
  390. )],
  391. katex,
  392. );
  393. // add components
  394. if (components != null) {
  395. components.lsx = props => <Lsx {...props} />;
  396. components.drawio = drawioPlugin.DrawioViewer;
  397. }
  398. // verifySanitizePlugin(options, false);
  399. return options;
  400. };
  401. export const generateOthersOptions = (config: RendererConfig): RendererOptions => {
  402. const options = generateCommonOptions(undefined, config);
  403. const { rehypePlugins } = options;
  404. // renderer.addConfigurers([
  405. // new TableConfigurer(),
  406. // ]);
  407. // renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  408. // renderer.configure();
  409. // add rehype plugins
  410. rehypePlugins.push(
  411. [sanitize, commonSanitizeOption],
  412. );
  413. verifySanitizePlugin(options);
  414. return options;
  415. };