growi-renderer.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { isClient } from '@growi/core';
  2. import MarkdownIt from 'markdown-it';
  3. import { Nullable } from '~/interfaces/common'; // TODO: Remove this asap when the ContextExtractor is removed
  4. import { CustomWindow } from '~/interfaces/global';
  5. import { GrowiRendererConfig, RendererSettings } from '~/interfaces/services/renderer';
  6. import loggerFactory from '~/utils/logger';
  7. import CsvToTable from './PreProcessor/CsvToTable';
  8. import EasyGrid from './PreProcessor/EasyGrid';
  9. import Linker from './PreProcessor/Linker';
  10. import XssFilter from './PreProcessor/XssFilter';
  11. import BlockdiagConfigurer from './markdown-it/blockdiag';
  12. import DrawioViewerConfigurer from './markdown-it/drawio-viewer';
  13. import EmojiConfigurer from './markdown-it/emoji';
  14. import FooternoteConfigurer from './markdown-it/footernote';
  15. import HeaderConfigurer from './markdown-it/header';
  16. import HeaderLineNumberConfigurer from './markdown-it/header-line-number';
  17. import HeaderWithEditLinkConfigurer from './markdown-it/header-with-edit-link';
  18. import LinkerByRelativePathConfigurer from './markdown-it/link-by-relative-path';
  19. import MathJaxConfigurer from './markdown-it/mathjax';
  20. import PlantUMLConfigurer from './markdown-it/plantuml';
  21. import TableConfigurer from './markdown-it/table';
  22. import TableWithHandsontableButtonConfigurer from './markdown-it/table-with-handsontable-button';
  23. import TaskListsConfigurer from './markdown-it/task-lists';
  24. import TocAndAnchorConfigurer from './markdown-it/toc-and-anchor';
  25. const logger = loggerFactory('growi:util:GrowiRenderer');
  26. declare const hljs;
  27. type MarkdownSettings = {
  28. breaks?: boolean,
  29. };
  30. export default class GrowiRenderer {
  31. preProcessors: any[];
  32. postProcessors: any[];
  33. md: any;
  34. isMarkdownItConfigured: boolean;
  35. markdownItConfigurers: any[];
  36. growiRendererConfig: GrowiRendererConfig;
  37. pagePath?: Nullable<string>;
  38. /**
  39. *
  40. * @param {string} mode
  41. */
  42. constructor(growiRendererConfig: GrowiRendererConfig, pagePath?: Nullable<string>) {
  43. this.growiRendererConfig = growiRendererConfig;
  44. this.pagePath = pagePath;
  45. if (isClient() && (window as CustomWindow).growiRenderer != null) {
  46. this.preProcessors = (window as CustomWindow).growiRenderer.preProcessors;
  47. this.postProcessors = (window as CustomWindow).growiRenderer.postProcessors;
  48. }
  49. else {
  50. this.preProcessors = [
  51. new EasyGrid(),
  52. new Linker(),
  53. new CsvToTable(),
  54. new XssFilter({
  55. isEnabledXssPrevention: this.growiRendererConfig.isEnabledXssPrevention,
  56. tagWhiteList: this.growiRendererConfig.tagWhiteList,
  57. attrWhiteList: this.growiRendererConfig.attrWhiteList,
  58. }),
  59. ];
  60. this.postProcessors = [
  61. ];
  62. }
  63. this.init = this.init.bind(this);
  64. this.addConfigurers = this.addConfigurers.bind(this);
  65. this.setMarkdownSettings = this.setMarkdownSettings.bind(this);
  66. this.configure = this.configure.bind(this);
  67. this.process = this.process.bind(this);
  68. this.codeRenderer = this.codeRenderer.bind(this);
  69. }
  70. init() {
  71. // init markdown-it
  72. this.md = new MarkdownIt({
  73. html: true,
  74. linkify: true,
  75. highlight: this.codeRenderer,
  76. });
  77. this.isMarkdownItConfigured = false;
  78. this.markdownItConfigurers = [
  79. new TaskListsConfigurer(),
  80. new HeaderConfigurer(),
  81. new EmojiConfigurer(),
  82. new MathJaxConfigurer(),
  83. new DrawioViewerConfigurer(),
  84. new PlantUMLConfigurer(this.growiRendererConfig),
  85. new BlockdiagConfigurer(this.growiRendererConfig),
  86. ];
  87. if (this.pagePath != null) {
  88. this.markdownItConfigurers.push(
  89. new LinkerByRelativePathConfigurer(this.pagePath),
  90. );
  91. }
  92. }
  93. addConfigurers(configurers: any[]): void {
  94. this.markdownItConfigurers.push(...configurers);
  95. }
  96. setMarkdownSettings(settings: MarkdownSettings): void {
  97. this.md.set(settings);
  98. }
  99. configure(): void {
  100. if (!this.isMarkdownItConfigured) {
  101. this.markdownItConfigurers.forEach((configurer) => {
  102. configurer.configure(this.md);
  103. });
  104. }
  105. }
  106. preProcess(markdown, context) {
  107. let processed = markdown;
  108. for (let i = 0; i < this.preProcessors.length; i++) {
  109. if (!this.preProcessors[i].process) {
  110. continue;
  111. }
  112. processed = this.preProcessors[i].process(processed, context);
  113. }
  114. return processed;
  115. }
  116. process(markdown, context) {
  117. return this.md.render(markdown, context);
  118. }
  119. postProcess(html, context) {
  120. let processed = html;
  121. for (let i = 0; i < this.postProcessors.length; i++) {
  122. if (!this.postProcessors[i].process) {
  123. continue;
  124. }
  125. processed = this.postProcessors[i].process(processed, context);
  126. }
  127. return processed;
  128. }
  129. codeRenderer(code, langExt) {
  130. const noborder = (!this.growiRendererConfig.highlightJsStyleBorder) ? 'hljs-no-border' : '';
  131. let citeTag = '';
  132. let hljsLang = 'plaintext';
  133. let showLinenumbers = false;
  134. if (langExt) {
  135. // https://regex101.com/r/qGs7eZ/3
  136. const match = langExt.match(/^([^:=\n]+)?(=([^:=\n]*))?(:([^:=\n]*))?(=([^:=\n]*))?$/);
  137. const lang = match[1];
  138. const fileName = match[5] || null;
  139. showLinenumbers = (match[2] != null) || (match[6] != null);
  140. if (fileName != null) {
  141. citeTag = `<cite>${fileName}</cite>`;
  142. }
  143. // if (hljs.getLanguage(lang)) {
  144. // hljsLang = lang;
  145. // }
  146. }
  147. let highlightCode = code;
  148. // try {
  149. // highlightCode = hljs.highlight(hljsLang, code, true).value;
  150. // // add line numbers
  151. // if (showLinenumbers) {
  152. // highlightCode = hljs.lineNumbersValue((highlightCode));
  153. // }
  154. // }
  155. // catch (err) {
  156. // logger.error(err);
  157. // }
  158. return `<pre class="hljs ${noborder}">${citeTag}<code>${highlightCode}</code></pre>`;
  159. }
  160. }
  161. export interface RendererGenerator {
  162. (growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings | null, pagePath?: Nullable<string>): GrowiRenderer
  163. }
  164. export const generateViewRenderer: RendererGenerator = (
  165. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  166. ): GrowiRenderer => {
  167. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  168. renderer.init();
  169. // Add configurers for viewer
  170. renderer.addConfigurers([
  171. new FooternoteConfigurer(),
  172. new TocAndAnchorConfigurer(),
  173. new HeaderLineNumberConfigurer(),
  174. new HeaderWithEditLinkConfigurer(),
  175. new TableWithHandsontableButtonConfigurer(),
  176. ]);
  177. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  178. renderer.configure();
  179. return renderer;
  180. };
  181. export const generatePreviewRenderer: RendererGenerator = (
  182. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings | null, pagePath?: Nullable<string>,
  183. ): GrowiRenderer => {
  184. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  185. renderer.init();
  186. // Add configurers for preview
  187. renderer.addConfigurers([
  188. new FooternoteConfigurer(),
  189. new HeaderLineNumberConfigurer(),
  190. new TableConfigurer(),
  191. ]);
  192. renderer.setMarkdownSettings({ breaks: rendererSettings?.isEnabledLinebreaks });
  193. renderer.configure();
  194. return renderer;
  195. };
  196. export const generateCommentPreviewRenderer: RendererGenerator = (
  197. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  198. ): GrowiRenderer => {
  199. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  200. renderer.init();
  201. renderer.addConfigurers([
  202. new TableConfigurer(),
  203. ]);
  204. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaksInComments });
  205. renderer.configure();
  206. return renderer;
  207. };
  208. export const generateOthersRenderer: RendererGenerator = (
  209. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  210. ): GrowiRenderer => {
  211. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  212. renderer.init();
  213. renderer.addConfigurers([
  214. new TableConfigurer(),
  215. ]);
  216. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  217. renderer.configure();
  218. return renderer;
  219. };