renderer.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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'],
  62. attributes: {
  63. iframe: ['allow', 'referrerpolicy', 'sandbox', 'src', 'srcdoc'],
  64. '*': ['class', 'className', 'style'],
  65. },
  66. };
  67. const commonSanitizeOption: SanitizeOption = deepmerge(
  68. rehypeSanitizeDefaultSchema,
  69. baseSanitizeSchema,
  70. {
  71. clobberPrefix: 'mdcont-',
  72. },
  73. );
  74. let isInjectedCustomSanitaizeOption = false;
  75. const injectCustomSanitizeOption = (config: RendererConfig) => {
  76. if (!isInjectedCustomSanitaizeOption && config.isEnabledXssPrevention && config.xssOption === RehypeSanitizeOption.CUSTOM) {
  77. commonSanitizeOption.tagNames = deepmerge(baseSanitizeSchema.tagNames, config.tagWhiteList ?? []);
  78. commonSanitizeOption.attributes = deepmerge(baseSanitizeSchema.attributes, config.attrWhiteList ?? {});
  79. isInjectedCustomSanitaizeOption = true;
  80. }
  81. };
  82. const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
  83. if (!Array.isArray(pluggable) || pluggable.length < 2) {
  84. return false;
  85. }
  86. const sanitizeOption = pluggable[1];
  87. return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
  88. };
  89. const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
  90. const { rehypePlugins } = options;
  91. if (rehypePlugins == null || rehypePlugins.length === 0) {
  92. return false;
  93. }
  94. return shouldBeTheLastItem
  95. ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
  96. : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
  97. };
  98. const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
  99. if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
  100. return;
  101. }
  102. throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
  103. };
  104. const generateCommonOptions = (pagePath: string|undefined): RendererOptions => {
  105. return {
  106. remarkPlugins: [
  107. gfm,
  108. emoji,
  109. pukiwikiLikeLinker,
  110. growiDirective,
  111. ],
  112. remarkRehypeOptions: {
  113. clobberPrefix: 'mdcont-',
  114. allowDangerousHtml: true,
  115. },
  116. rehypePlugins: [
  117. [relativeLinksByPukiwikiLikeLinker, { pagePath }],
  118. [relativeLinks, { pagePath }],
  119. raw,
  120. [addClass.rehypePlugin, {
  121. table: 'table table-bordered',
  122. }],
  123. ],
  124. components: {
  125. a: NextLink,
  126. code: CodeBlock,
  127. },
  128. };
  129. };
  130. export const generateViewOptions = (
  131. pagePath: string,
  132. config: RendererConfig,
  133. storeTocNode: (toc: HtmlElementNode) => void,
  134. ): RendererOptions => {
  135. const options = generateCommonOptions(pagePath);
  136. const { remarkPlugins, rehypePlugins, components } = options;
  137. // add remark plugins
  138. remarkPlugins.push(
  139. math,
  140. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  141. drawioPlugin.remarkPlugin,
  142. xsvToTable.remarkPlugin,
  143. lsxGrowiPlugin.remarkPlugin,
  144. );
  145. if (config.isEnabledLinebreaks) {
  146. remarkPlugins.push(breaks);
  147. }
  148. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  149. injectCustomSanitizeOption(config);
  150. }
  151. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  152. ? [sanitize, deepmerge(
  153. commonSanitizeOption,
  154. drawioPlugin.sanitizeOption,
  155. lsxGrowiPlugin.sanitizeOption,
  156. )]
  157. : () => {};
  158. // add rehype plugins
  159. rehypePlugins.push(
  160. slug,
  161. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  162. rehypeSanitizePlugin,
  163. katex,
  164. [toc.rehypePluginStore, { storeTocNode }],
  165. );
  166. // add components
  167. if (components != null) {
  168. components.h1 = Header;
  169. components.h2 = Header;
  170. components.h3 = Header;
  171. components.lsx = Lsx;
  172. components.drawio = DrawioViewerWithEditButton;
  173. components.table = TableWithEditButton;
  174. }
  175. if (config.isEnabledXssPrevention) {
  176. verifySanitizePlugin(options, false);
  177. }
  178. return options;
  179. };
  180. export const generateTocOptions = (config: RendererConfig, tocNode: HtmlElementNode | undefined): RendererOptions => {
  181. const options = generateCommonOptions(undefined);
  182. const { rehypePlugins } = options;
  183. // add remark plugins
  184. // remarkPlugins.push();
  185. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  186. injectCustomSanitizeOption(config);
  187. }
  188. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  189. ? [sanitize, deepmerge(
  190. commonSanitizeOption,
  191. )]
  192. : () => {};
  193. // add rehype plugins
  194. rehypePlugins.push(
  195. [toc.rehypePluginRestore, { tocNode }],
  196. rehypeSanitizePlugin,
  197. );
  198. if (config.isEnabledXssPrevention) {
  199. verifySanitizePlugin(options);
  200. }
  201. return options;
  202. };
  203. export const generateSimpleViewOptions = (
  204. config: RendererConfig,
  205. pagePath: string,
  206. highlightKeywords?: string | string[],
  207. overrideIsEnabledLinebreaks?: boolean,
  208. ): RendererOptions => {
  209. const options = generateCommonOptions(pagePath);
  210. const { remarkPlugins, rehypePlugins, components } = options;
  211. // add remark plugins
  212. remarkPlugins.push(
  213. math,
  214. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  215. drawioPlugin.remarkPlugin,
  216. xsvToTable.remarkPlugin,
  217. lsxGrowiPlugin.remarkPlugin,
  218. table.remarkPlugin,
  219. );
  220. const isEnabledLinebreaks = overrideIsEnabledLinebreaks ?? config.isEnabledLinebreaks;
  221. if (isEnabledLinebreaks) {
  222. remarkPlugins.push(breaks);
  223. }
  224. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  225. injectCustomSanitizeOption(config);
  226. }
  227. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  228. ? [sanitize, deepmerge(
  229. commonSanitizeOption,
  230. drawioPlugin.sanitizeOption,
  231. lsxGrowiPlugin.sanitizeOption,
  232. )]
  233. : () => {};
  234. // add rehype plugins
  235. rehypePlugins.push(
  236. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  237. [keywordHighlighter.rehypePlugin, { keywords: highlightKeywords }],
  238. rehypeSanitizePlugin,
  239. katex,
  240. );
  241. // add components
  242. if (components != null) {
  243. components.lsx = LsxImmutable;
  244. components.drawio = drawioPlugin.DrawioViewer;
  245. components.table = Table;
  246. }
  247. if (config.isEnabledXssPrevention) {
  248. verifySanitizePlugin(options, false);
  249. }
  250. return options;
  251. };
  252. export const generateSSRViewOptions = (
  253. config: RendererConfig,
  254. pagePath: string,
  255. ): RendererOptions => {
  256. const options = generateCommonOptions(pagePath);
  257. const { remarkPlugins, rehypePlugins, components } = options;
  258. // add remark plugins
  259. remarkPlugins.push(
  260. math,
  261. xsvToTable.remarkPlugin,
  262. lsxGrowiPlugin.remarkPlugin,
  263. table.remarkPlugin,
  264. );
  265. const isEnabledLinebreaks = config.isEnabledLinebreaks;
  266. if (isEnabledLinebreaks) {
  267. remarkPlugins.push(breaks);
  268. }
  269. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  270. injectCustomSanitizeOption(config);
  271. }
  272. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  273. ? [sanitize, deepmerge(
  274. commonSanitizeOption,
  275. lsxGrowiPlugin.sanitizeOption,
  276. )]
  277. : () => {};
  278. // add rehype plugins
  279. rehypePlugins.push(
  280. slug,
  281. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  282. rehypeSanitizePlugin,
  283. katex,
  284. );
  285. // add components
  286. if (components != null) {
  287. components.lsx = LsxImmutable;
  288. components.table = Table;
  289. }
  290. if (config.isEnabledXssPrevention) {
  291. verifySanitizePlugin(options, false);
  292. }
  293. return options;
  294. };
  295. export const generatePreviewOptions = (config: RendererConfig, pagePath: string): RendererOptions => {
  296. const options = generateCommonOptions(pagePath);
  297. const { remarkPlugins, rehypePlugins, components } = options;
  298. // add remark plugins
  299. remarkPlugins.push(
  300. math,
  301. [plantuml.remarkPlugin, { plantumlUri: config.plantumlUri }],
  302. drawioPlugin.remarkPlugin,
  303. xsvToTable.remarkPlugin,
  304. lsxGrowiPlugin.remarkPlugin,
  305. table.remarkPlugin,
  306. );
  307. if (config.isEnabledLinebreaks) {
  308. remarkPlugins.push(breaks);
  309. }
  310. if (config.xssOption === RehypeSanitizeOption.CUSTOM) {
  311. injectCustomSanitizeOption(config);
  312. }
  313. const rehypeSanitizePlugin: Pluggable<any[]> | (() => void) = config.isEnabledXssPrevention
  314. ? [sanitize, deepmerge(
  315. commonSanitizeOption,
  316. lsxGrowiPlugin.sanitizeOption,
  317. drawioPlugin.sanitizeOption,
  318. addLineNumberAttribute.sanitizeOption,
  319. )]
  320. : () => {};
  321. // add rehype plugins
  322. rehypePlugins.push(
  323. [lsxGrowiPlugin.rehypePlugin, { pagePath, isSharedPage: config.isSharedPage }],
  324. addLineNumberAttribute.rehypePlugin,
  325. rehypeSanitizePlugin,
  326. katex,
  327. );
  328. // add components
  329. if (components != null) {
  330. components.lsx = LsxImmutable;
  331. components.drawio = drawioPlugin.DrawioViewer;
  332. components.table = Table;
  333. }
  334. if (config.isEnabledXssPrevention) {
  335. verifySanitizePlugin(options, false);
  336. }
  337. return options;
  338. };
  339. // register to facade
  340. if (isClient()) {
  341. registerGrowiFacade({
  342. markdownRenderer: {
  343. optionsGenerators: {
  344. generateViewOptions,
  345. generatePreviewOptions,
  346. },
  347. },
  348. });
  349. }