renderer.tsx 14 KB

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