renderer.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // allow only types to import from react
  2. import type { ComponentType } from 'react';
  3. import { isClient } from '@growi/core';
  4. import * as drawioPlugin from '@growi/remark-drawio';
  5. import growiDirective from '@growi/remark-growi-directive';
  6. import { Lsx, LsxImmutable } from '@growi/remark-lsx/components';
  7. import * as lsxGrowiPlugin from '@growi/remark-lsx/services/renderer';
  8. import type { Schema as SanitizeOption } from 'hast-util-sanitize';
  9. import type { SpecialComponents } from 'react-markdown-customkeyprop/lib/ast-to-react';
  10. import type { NormalComponents } from 'react-markdown-customkeyprop/lib/complex-types';
  11. import type { ReactMarkdownOptions } from 'react-markdown-customkeyprop/lib/react-markdown';
  12. import katex from 'rehype-katex';
  13. import raw from 'rehype-raw';
  14. import sanitize, { defaultSchema as rehypeSanitizeDefaultSchema } from 'rehype-sanitize';
  15. import slug from 'rehype-slug';
  16. import type { HtmlElementNode } from 'rehype-toc';
  17. import breaks from 'remark-breaks';
  18. import emoji from 'remark-emoji';
  19. import gfm from 'remark-gfm';
  20. import math from 'remark-math';
  21. import toc from 'remark-toc';
  22. import deepmerge from 'ts-deepmerge';
  23. import type { PluggableList, Pluggable, PluginTuple } from 'unified';
  24. import { CodeBlock } from '~/components/ReactMarkdownComponents/CodeBlock';
  25. import { DrawioViewerWithEditButton } from '~/components/ReactMarkdownComponents/DrawioViewerWithEditButton';
  26. import { Header } from '~/components/ReactMarkdownComponents/Header';
  27. import { NextLink } from '~/components/ReactMarkdownComponents/NextLink';
  28. import { TableWithEditButton } from '~/components/ReactMarkdownComponents/TableWithEditButton';
  29. import { RehypeSanitizeOption } from '~/interfaces/rehype';
  30. import type { RendererConfig } from '~/interfaces/services/renderer';
  31. import { registerGrowiFacade } from '~/utils/growi-facade';
  32. import loggerFactory from '~/utils/logger';
  33. import * as addClass from './rehype-plugins/add-class';
  34. import * as addLineNumberAttribute from './rehype-plugins/add-line-number-attribute';
  35. import * as keywordHighlighter from './rehype-plugins/keyword-highlighter';
  36. import { relativeLinks } from './rehype-plugins/relative-links';
  37. import { relativeLinksByPukiwikiLikeLinker } from './rehype-plugins/relative-links-by-pukiwiki-like-linker';
  38. import * as relocateToc from './rehype-plugins/relocate-toc';
  39. import * as plantuml from './remark-plugins/plantuml';
  40. import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
  41. import * as xsvToTable from './remark-plugins/xsv-to-table';
  42. // import EasyGrid from './PreProcessor/EasyGrid';
  43. // import BlockdiagConfigurer from './markdown-it/blockdiag';
  44. const logger = loggerFactory('growi:util:GrowiRenderer');
  45. type SanitizePlugin = PluginTuple<[SanitizeOption]>;
  46. export type RendererOptions = Omit<ReactMarkdownOptions, 'remarkPlugins' | 'rehypePlugins' | 'components' | 'children'> & {
  47. remarkPlugins: PluggableList,
  48. rehypePlugins: PluggableList,
  49. components?:
  50. | Partial<
  51. Omit<NormalComponents, keyof SpecialComponents>
  52. & SpecialComponents
  53. & {
  54. [elem: string]: ComponentType<any>,
  55. }
  56. >
  57. | undefined
  58. };
  59. const baseSanitizeSchema = {
  60. tagNames: ['iframe', 'section'],
  61. attributes: {
  62. iframe: ['allow', 'referrerpolicy', 'sandbox', 'src', 'srcdoc'],
  63. // The special value 'data*' as a property name can be used to allow all data properties.
  64. // see: https://github.com/syntax-tree/hast-util-sanitize/
  65. '*': ['key', 'class', 'className', 'style', 'data*'],
  66. },
  67. };
  68. const commonSanitizeOption: SanitizeOption = deepmerge(
  69. rehypeSanitizeDefaultSchema,
  70. baseSanitizeSchema,
  71. {
  72. clobberPrefix: 'mdcont-',
  73. },
  74. );
  75. let isInjectedCustomSanitaizeOption = false;
  76. const injectCustomSanitizeOption = (config: RendererConfig) => {
  77. if (!isInjectedCustomSanitaizeOption && config.isEnabledXssPrevention && config.xssOption === RehypeSanitizeOption.CUSTOM) {
  78. commonSanitizeOption.tagNames = baseSanitizeSchema.tagNames.concat(config.tagWhiteList ?? []);
  79. commonSanitizeOption.attributes = deepmerge(baseSanitizeSchema.attributes, config.attrWhiteList ?? {});
  80. isInjectedCustomSanitaizeOption = true;
  81. }
  82. };
  83. const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
  84. if (!Array.isArray(pluggable) || pluggable.length < 2) {
  85. return false;
  86. }
  87. const sanitizeOption = pluggable[1];
  88. return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
  89. };
  90. const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
  91. const { rehypePlugins } = options;
  92. if (rehypePlugins == null || rehypePlugins.length === 0) {
  93. return false;
  94. }
  95. return shouldBeTheLastItem
  96. ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
  97. : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
  98. };
  99. const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
  100. if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
  101. return;
  102. }
  103. throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
  104. };
  105. const generateCommonOptions = (pagePath: string|undefined): RendererOptions => {
  106. return {
  107. remarkPlugins: [
  108. [toc, { maxDepth: 3, tight: true, prefix: 'mdcont-' }],
  109. gfm,
  110. emoji,
  111. pukiwikiLikeLinker,
  112. growiDirective,
  113. ],
  114. remarkRehypeOptions: {
  115. clobberPrefix: 'mdcont-',
  116. allowDangerousHtml: true,
  117. },
  118. rehypePlugins: [
  119. [relativeLinksByPukiwikiLikeLinker, { pagePath }],
  120. [relativeLinks, { pagePath }],
  121. raw,
  122. [addClass.rehypePlugin, {
  123. table: 'table table-bordered',
  124. }],
  125. ],
  126. components: {
  127. a: NextLink,
  128. code: CodeBlock,
  129. },
  130. };
  131. };
  132. export const generateViewOptions = (
  133. pagePath: string,
  134. config: RendererConfig,
  135. storeTocNode: (toc: HtmlElementNode) => void,
  136. ): RendererOptions => {
  137. const options = generateCommonOptions(pagePath);
  138. const { remarkPlugins, rehypePlugins, components } = options;
  139. // add remark plugins
  140. remarkPlugins.push(
  141. math,
  142. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  143. drawioPlugin.remarkPlugin,
  144. xsvToTable.remarkPlugin,
  145. lsxGrowiPlugin.remarkPlugin,
  146. );
  147. if (config.isEnabledLinebreaks) {
  148. remarkPlugins.push(breaks);
  149. }
  150. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  151. injectCustomSanitizeOption(config);
  152. }
  153. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  154. ? [sanitize, deepmerge(
  155. commonSanitizeOption,
  156. drawioPlugin.sanitizeOption,
  157. lsxGrowiPlugin.sanitizeOption,
  158. )]
  159. : () => {};
  160. // add rehype plugins
  161. rehypePlugins.push(
  162. slug,
  163. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  164. rehypeSanitizePlugin,
  165. katex,
  166. [relocateToc.rehypePluginStore, { storeTocNode }],
  167. );
  168. // add components
  169. if (components != null) {
  170. components.h1 = Header;
  171. components.h2 = Header;
  172. components.h3 = Header;
  173. components.h4 = Header;
  174. components.h5 = Header;
  175. components.h6 = Header;
  176. components.lsx = Lsx;
  177. components.drawio = DrawioViewerWithEditButton;
  178. components.table = TableWithEditButton;
  179. }
  180. if (config.isEnabledXssPrevention) {
  181. verifySanitizePlugin(options, false);
  182. }
  183. return options;
  184. };
  185. export const generateTocOptions = (config: RendererConfig, tocNode: HtmlElementNode | undefined): RendererOptions => {
  186. const options = generateCommonOptions(undefined);
  187. const { rehypePlugins } = options;
  188. // add remark plugins
  189. // remarkPlugins.push();
  190. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  191. injectCustomSanitizeOption(config);
  192. }
  193. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  194. ? [sanitize, deepmerge(
  195. commonSanitizeOption,
  196. )]
  197. : () => {};
  198. // add rehype plugins
  199. rehypePlugins.push(
  200. [relocateToc.rehypePluginRestore, { tocNode }],
  201. rehypeSanitizePlugin,
  202. );
  203. if (config.isEnabledXssPrevention) {
  204. verifySanitizePlugin(options);
  205. }
  206. return options;
  207. };
  208. export const generateSimpleViewOptions = (
  209. config: RendererConfig,
  210. pagePath: string,
  211. highlightKeywords?: string | string[],
  212. overrideIsEnabledLinebreaks?: boolean,
  213. ): RendererOptions => {
  214. const options = generateCommonOptions(pagePath);
  215. const { remarkPlugins, rehypePlugins, components } = options;
  216. // add remark plugins
  217. remarkPlugins.push(
  218. math,
  219. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  220. drawioPlugin.remarkPlugin,
  221. xsvToTable.remarkPlugin,
  222. lsxGrowiPlugin.remarkPlugin,
  223. // table.remarkPlugin,
  224. );
  225. const isEnabledLinebreaks = overrideIsEnabledLinebreaks ?? config.isEnabledLinebreaks;
  226. if (isEnabledLinebreaks) {
  227. remarkPlugins.push(breaks);
  228. }
  229. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  230. injectCustomSanitizeOption(config);
  231. }
  232. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  233. ? [sanitize, deepmerge(
  234. commonSanitizeOption,
  235. drawioPlugin.sanitizeOption,
  236. lsxGrowiPlugin.sanitizeOption,
  237. )]
  238. : () => {};
  239. // add rehype plugins
  240. rehypePlugins.push(
  241. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  242. [keywordHighlighter.rehypePlugin, { keywords: highlightKeywords }],
  243. rehypeSanitizePlugin,
  244. katex,
  245. );
  246. // add components
  247. if (components != null) {
  248. components.lsx = LsxImmutable;
  249. components.drawio = drawioPlugin.DrawioViewer;
  250. }
  251. if (config.isEnabledXssPrevention) {
  252. verifySanitizePlugin(options, false);
  253. }
  254. return options;
  255. };
  256. export const generatePresentationViewOptions = (
  257. config: RendererConfig,
  258. pagePath: string,
  259. ): RendererOptions => {
  260. // based on simple view options
  261. const options = generateSimpleViewOptions(config, pagePath);
  262. if (config.isEnabledXssPrevention) {
  263. verifySanitizePlugin(options, false);
  264. }
  265. return options;
  266. };
  267. export const generateSSRViewOptions = (
  268. config: RendererConfig,
  269. pagePath: string,
  270. ): RendererOptions => {
  271. const options = generateCommonOptions(pagePath);
  272. const { remarkPlugins, rehypePlugins, components } = options;
  273. // add remark plugins
  274. remarkPlugins.push(
  275. math,
  276. xsvToTable.remarkPlugin,
  277. lsxGrowiPlugin.remarkPlugin,
  278. // table.remarkPlugin,
  279. );
  280. const isEnabledLinebreaks = config.isEnabledLinebreaks;
  281. if (isEnabledLinebreaks) {
  282. remarkPlugins.push(breaks);
  283. }
  284. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  285. injectCustomSanitizeOption(config);
  286. }
  287. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  288. ? [sanitize, deepmerge(
  289. commonSanitizeOption,
  290. lsxGrowiPlugin.sanitizeOption,
  291. )]
  292. : () => {};
  293. // add rehype plugins
  294. rehypePlugins.push(
  295. slug,
  296. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  297. rehypeSanitizePlugin,
  298. katex,
  299. );
  300. // add components
  301. if (components != null) {
  302. components.lsx = LsxImmutable;
  303. }
  304. if (config.isEnabledXssPrevention) {
  305. verifySanitizePlugin(options, false);
  306. }
  307. return options;
  308. };
  309. export const generatePreviewOptions = (config: RendererConfig, pagePath: string): RendererOptions => {
  310. const options = generateCommonOptions(pagePath);
  311. const { remarkPlugins, rehypePlugins, components } = options;
  312. // add remark plugins
  313. remarkPlugins.push(
  314. math,
  315. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  316. drawioPlugin.remarkPlugin,
  317. xsvToTable.remarkPlugin,
  318. lsxGrowiPlugin.remarkPlugin,
  319. // table.remarkPlugin,
  320. );
  321. if (config.isEnabledLinebreaks) {
  322. remarkPlugins.push(breaks);
  323. }
  324. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  325. injectCustomSanitizeOption(config);
  326. }
  327. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  328. ? [sanitize, deepmerge(
  329. commonSanitizeOption,
  330. lsxGrowiPlugin.sanitizeOption,
  331. drawioPlugin.sanitizeOption,
  332. addLineNumberAttribute.sanitizeOption,
  333. )]
  334. : () => {};
  335. // add rehype plugins
  336. rehypePlugins.push(
  337. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  338. addLineNumberAttribute.rehypePlugin,
  339. rehypeSanitizePlugin,
  340. katex,
  341. );
  342. // add components
  343. if (components != null) {
  344. components.lsx = LsxImmutable;
  345. components.drawio = drawioPlugin.DrawioViewer;
  346. }
  347. if (config.isEnabledXssPrevention) {
  348. verifySanitizePlugin(options, false);
  349. }
  350. return options;
  351. };
  352. // register to facade
  353. if (isClient()) {
  354. registerGrowiFacade({
  355. markdownRenderer: {
  356. optionsGenerators: {
  357. generateViewOptions,
  358. generatePreviewOptions,
  359. },
  360. },
  361. });
  362. }