renderer.tsx 15 KB

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