growi-renderer.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import MarkdownIt from 'markdown-it';
  2. import { Nullable } from '~/interfaces/common'; // TODO: Remove this asap when the ContextExtractor is removed
  3. import { CustomWindow } from '~/interfaces/global';
  4. import { GrowiRendererConfig, RendererSettings } from '~/interfaces/services/renderer';
  5. import loggerFactory from '~/utils/logger';
  6. import CsvToTable from './PreProcessor/CsvToTable';
  7. import EasyGrid from './PreProcessor/EasyGrid';
  8. import Linker from './PreProcessor/Linker';
  9. import XssFilter from './PreProcessor/XssFilter';
  10. import BlockdiagConfigurer from './markdown-it/blockdiag';
  11. import DrawioViewerConfigurer from './markdown-it/drawio-viewer';
  12. import EmojiConfigurer from './markdown-it/emoji';
  13. import FooternoteConfigurer from './markdown-it/footernote';
  14. import HeaderConfigurer from './markdown-it/header';
  15. import HeaderLineNumberConfigurer from './markdown-it/header-line-number';
  16. import HeaderWithEditLinkConfigurer from './markdown-it/header-with-edit-link';
  17. import LinkerByRelativePathConfigurer from './markdown-it/link-by-relative-path';
  18. import OrderedListConfigurer from './markdown-it/list';
  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 ((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(this.growiRendererConfig),
  83. new DrawioViewerConfigurer(),
  84. new PlantUMLConfigurer(this.growiRendererConfig),
  85. new BlockdiagConfigurer(this.growiRendererConfig),
  86. new OrderedListConfigurer(),
  87. ];
  88. if (this.pagePath != null) {
  89. this.markdownItConfigurers.push(
  90. new LinkerByRelativePathConfigurer(this.pagePath),
  91. );
  92. }
  93. }
  94. addConfigurers(configurers: any[]): void {
  95. this.markdownItConfigurers.push(...configurers);
  96. }
  97. setMarkdownSettings(settings: MarkdownSettings): void {
  98. this.md.set(settings);
  99. }
  100. configure(): void {
  101. if (!this.isMarkdownItConfigured) {
  102. this.markdownItConfigurers.forEach((configurer) => {
  103. configurer.configure(this.md);
  104. });
  105. }
  106. }
  107. preProcess(markdown, context) {
  108. let processed = markdown;
  109. for (let i = 0; i < this.preProcessors.length; i++) {
  110. if (!this.preProcessors[i].process) {
  111. continue;
  112. }
  113. processed = this.preProcessors[i].process(processed, context);
  114. }
  115. return processed;
  116. }
  117. process(markdown, context) {
  118. return this.md.render(markdown, context);
  119. }
  120. postProcess(html, context) {
  121. let processed = html;
  122. for (let i = 0; i < this.postProcessors.length; i++) {
  123. if (!this.postProcessors[i].process) {
  124. continue;
  125. }
  126. processed = this.postProcessors[i].process(processed, context);
  127. }
  128. return processed;
  129. }
  130. codeRenderer(code, langExt) {
  131. const noborder = (!this.growiRendererConfig.highlightJsStyleBorder) ? 'hljs-no-border' : '';
  132. let citeTag = '';
  133. let hljsLang = 'plaintext';
  134. let showLinenumbers = false;
  135. if (langExt) {
  136. // https://regex101.com/r/qGs7eZ/3
  137. const match = langExt.match(/^([^:=\n]+)?(=([^:=\n]*))?(:([^:=\n]*))?(=([^:=\n]*))?$/);
  138. const lang = match[1];
  139. const fileName = match[5] || null;
  140. showLinenumbers = (match[2] != null) || (match[6] != null);
  141. if (fileName != null) {
  142. citeTag = `<cite>${fileName}</cite>`;
  143. }
  144. if (hljs.getLanguage(lang)) {
  145. hljsLang = lang;
  146. }
  147. }
  148. let highlightCode = code;
  149. try {
  150. highlightCode = hljs.highlight(hljsLang, code, true).value;
  151. // add line numbers
  152. if (showLinenumbers) {
  153. highlightCode = hljs.lineNumbersValue((highlightCode));
  154. }
  155. }
  156. catch (err) {
  157. logger.error(err);
  158. }
  159. return `<pre class="hljs ${noborder}">${citeTag}<code>${highlightCode}</code></pre>`;
  160. }
  161. }
  162. export interface RendererGenerator {
  163. (growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings | null, pagePath?: Nullable<string>): GrowiRenderer
  164. }
  165. export const generateViewRenderer: RendererGenerator = (
  166. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  167. ): GrowiRenderer => {
  168. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  169. renderer.init();
  170. // Add configurers for viewer
  171. renderer.addConfigurers([
  172. new FooternoteConfigurer(),
  173. new TocAndAnchorConfigurer(),
  174. new HeaderLineNumberConfigurer(),
  175. new HeaderWithEditLinkConfigurer(),
  176. new TableWithHandsontableButtonConfigurer(),
  177. ]);
  178. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  179. renderer.configure();
  180. return renderer;
  181. };
  182. export const generatePreviewRenderer: RendererGenerator = (
  183. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings | null, pagePath?: Nullable<string>,
  184. ): GrowiRenderer => {
  185. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  186. renderer.init();
  187. // Add configurers for preview
  188. renderer.addConfigurers([
  189. new FooternoteConfigurer(),
  190. new HeaderLineNumberConfigurer(),
  191. new TableConfigurer(),
  192. ]);
  193. renderer.setMarkdownSettings({ breaks: rendererSettings?.isEnabledLinebreaks });
  194. renderer.configure();
  195. return renderer;
  196. };
  197. export const generateCommentPreviewRenderer: RendererGenerator = (
  198. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  199. ): GrowiRenderer => {
  200. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  201. renderer.init();
  202. renderer.addConfigurers([
  203. new TableConfigurer(),
  204. ]);
  205. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaksInComments });
  206. renderer.configure();
  207. return renderer;
  208. };
  209. export const generateOthersRenderer: RendererGenerator = (
  210. growiRendererConfig: GrowiRendererConfig, rendererSettings: RendererSettings, pagePath?: Nullable<string>,
  211. ): GrowiRenderer => {
  212. const renderer = new GrowiRenderer(growiRendererConfig, pagePath);
  213. renderer.init();
  214. renderer.addConfigurers([
  215. new TableConfigurer(),
  216. ]);
  217. renderer.setMarkdownSettings({ breaks: rendererSettings.isEnabledLinebreaks });
  218. renderer.configure();
  219. return renderer;
  220. };