renderer.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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/lib/ast-to-react';
  10. import type { NormalComponents } from 'react-markdown/lib/complex-types';
  11. import type { ReactMarkdownOptions } from 'react-markdown/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 deepmerge from 'ts-deepmerge';
  22. import type { PluggableList, Pluggable, PluginTuple } from 'unified';
  23. import { CodeBlock } from '~/components/ReactMarkdownComponents/CodeBlock';
  24. import { DrawioViewerWithEditButton } from '~/components/ReactMarkdownComponents/DrawioViewerWithEditButton';
  25. import { Header } from '~/components/ReactMarkdownComponents/Header';
  26. import { NextLink } from '~/components/ReactMarkdownComponents/NextLink';
  27. import { Table } from '~/components/ReactMarkdownComponents/Table';
  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 toc 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 table from './remark-plugins/table';
  42. import * as xsvToTable from './remark-plugins/xsv-to-table';
  43. // import EasyGrid from './PreProcessor/EasyGrid';
  44. // import BlockdiagConfigurer from './markdown-it/blockdiag';
  45. const logger = loggerFactory('growi:util:GrowiRenderer');
  46. type SanitizePlugin = PluginTuple<[SanitizeOption]>;
  47. export type RendererOptions = Omit<ReactMarkdownOptions, 'remarkPlugins' | 'rehypePlugins' | 'components' | 'children'> & {
  48. remarkPlugins: PluggableList,
  49. rehypePlugins: PluggableList,
  50. components?:
  51. | Partial<
  52. Omit<NormalComponents, keyof SpecialComponents>
  53. & SpecialComponents
  54. & {
  55. [elem: string]: ComponentType<any>,
  56. }
  57. >
  58. | undefined
  59. };
  60. const baseSanitizeSchema = {
  61. tagNames: ['iframe', 'section'],
  62. attributes: {
  63. iframe: ['allow', 'referrerpolicy', 'sandbox', 'src', 'srcdoc'],
  64. // The special value 'data*' as a property name can be used to allow all data properties.
  65. // see: https://github.com/syntax-tree/hast-util-sanitize/
  66. '*': ['class', 'className', 'style', 'data*'],
  67. },
  68. };
  69. const commonSanitizeOption: SanitizeOption = deepmerge(
  70. rehypeSanitizeDefaultSchema,
  71. baseSanitizeSchema,
  72. {
  73. clobberPrefix: 'mdcont-',
  74. },
  75. );
  76. let isInjectedCustomSanitaizeOption = false;
  77. const injectCustomSanitizeOption = (config: RendererConfig) => {
  78. if (!isInjectedCustomSanitaizeOption && config.isEnabledXssPrevention && config.xssOption === RehypeSanitizeOption.CUSTOM) {
  79. commonSanitizeOption.tagNames = baseSanitizeSchema.tagNames.concat(config.tagWhiteList ?? []);
  80. commonSanitizeOption.attributes = deepmerge(baseSanitizeSchema.attributes, config.attrWhiteList ?? {});
  81. isInjectedCustomSanitaizeOption = true;
  82. }
  83. };
  84. const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
  85. if (!Array.isArray(pluggable) || pluggable.length < 2) {
  86. return false;
  87. }
  88. const sanitizeOption = pluggable[1];
  89. return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
  90. };
  91. const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
  92. const { rehypePlugins } = options;
  93. if (rehypePlugins == null || rehypePlugins.length === 0) {
  94. return false;
  95. }
  96. return shouldBeTheLastItem
  97. ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
  98. : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
  99. };
  100. const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
  101. if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
  102. return;
  103. }
  104. throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
  105. };
  106. const generateCommonOptions = (pagePath: string|undefined): RendererOptions => {
  107. return {
  108. remarkPlugins: [
  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. [toc.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. [toc.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. components.table = Table;
  251. }
  252. if (config.isEnabledXssPrevention) {
  253. verifySanitizePlugin(options, false);
  254. }
  255. return options;
  256. };
  257. export const generatePresentationViewOptions = (
  258. config: RendererConfig,
  259. pagePath: string,
  260. ): RendererOptions => {
  261. // based on simple view options
  262. const options = generateSimpleViewOptions(config, pagePath);
  263. if (config.isEnabledXssPrevention) {
  264. verifySanitizePlugin(options, false);
  265. }
  266. return options;
  267. };
  268. export const generateSSRViewOptions = (
  269. config: RendererConfig,
  270. pagePath: string,
  271. ): RendererOptions => {
  272. const options = generateCommonOptions(pagePath);
  273. const { remarkPlugins, rehypePlugins, components } = options;
  274. // add remark plugins
  275. remarkPlugins.push(
  276. math,
  277. xsvToTable.remarkPlugin,
  278. lsxGrowiPlugin.remarkPlugin,
  279. table.remarkPlugin,
  280. );
  281. const isEnabledLinebreaks = config.isEnabledLinebreaks;
  282. if (isEnabledLinebreaks) {
  283. remarkPlugins.push(breaks);
  284. }
  285. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  286. injectCustomSanitizeOption(config);
  287. }
  288. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  289. ? [sanitize, deepmerge(
  290. commonSanitizeOption,
  291. lsxGrowiPlugin.sanitizeOption,
  292. )]
  293. : () => {};
  294. // add rehype plugins
  295. rehypePlugins.push(
  296. slug,
  297. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  298. rehypeSanitizePlugin,
  299. katex,
  300. );
  301. // add components
  302. if (components != null) {
  303. components.lsx = LsxImmutable;
  304. components.table = Table;
  305. }
  306. if (config.isEnabledXssPrevention) {
  307. verifySanitizePlugin(options, false);
  308. }
  309. return options;
  310. };
  311. export const generatePreviewOptions = (config: RendererConfig, pagePath: string): RendererOptions => {
  312. const options = generateCommonOptions(pagePath);
  313. const { remarkPlugins, rehypePlugins, components } = options;
  314. // add remark plugins
  315. remarkPlugins.push(
  316. math,
  317. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  318. drawioPlugin.remarkPlugin,
  319. xsvToTable.remarkPlugin,
  320. lsxGrowiPlugin.remarkPlugin,
  321. table.remarkPlugin,
  322. );
  323. if (config.isEnabledLinebreaks) {
  324. remarkPlugins.push(breaks);
  325. }
  326. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  327. injectCustomSanitizeOption(config);
  328. }
  329. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  330. ? [sanitize, deepmerge(
  331. commonSanitizeOption,
  332. lsxGrowiPlugin.sanitizeOption,
  333. drawioPlugin.sanitizeOption,
  334. addLineNumberAttribute.sanitizeOption,
  335. )]
  336. : () => {};
  337. // add rehype plugins
  338. rehypePlugins.push(
  339. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  340. addLineNumberAttribute.rehypePlugin,
  341. rehypeSanitizePlugin,
  342. katex,
  343. );
  344. // add components
  345. if (components != null) {
  346. components.lsx = LsxImmutable;
  347. components.drawio = drawioPlugin.DrawioViewer;
  348. components.table = Table;
  349. }
  350. if (config.isEnabledXssPrevention) {
  351. verifySanitizePlugin(options, false);
  352. }
  353. return options;
  354. };
  355. // register to facade
  356. if (isClient()) {
  357. registerGrowiFacade({
  358. markdownRenderer: {
  359. optionsGenerators: {
  360. generateViewOptions,
  361. generatePreviewOptions,
  362. },
  363. },
  364. });
  365. }