Просмотр исходного кода

Merge pull request #9388 from weseek/fix/echo-directive-as-is

fix: Output TextDirective and LeafDirective HTML
mergify[bot] 1 год назад
Родитель
Сommit
b05e68005f

+ 1 - 0
apps/app/package.json

@@ -126,6 +126,7 @@
     "graceful-fs": "^4.1.11",
     "hast-util-sanitize": "^5.0.1",
     "hast-util-select": "^6.0.2",
+    "hastscript": "^8.0.0",
     "helmet": "^4.6.0",
     "http-errors": "^2.0.0",
     "i18next": "^23.10.1",

+ 40 - 0
apps/app/src/services/renderer/remark-plugins/echo-directive.ts

@@ -0,0 +1,40 @@
+import type { ElementContent } from 'hast';
+import { h } from 'hastscript';
+import type { Text } from 'mdast';
+import type { LeafDirective, TextDirective } from 'mdast-util-directive';
+import type { Plugin } from 'unified';
+import { visit } from 'unist-util-visit';
+
+
+function echoDirective(node: TextDirective | LeafDirective): ElementContent[] {
+  const mark = node.type === 'textDirective' ? ':' : '::';
+
+  return [
+    h('span', `${mark}${node.name}`),
+    ...(node.children ?? []).map((child: Text) => h('span', `[${child.value}]`)),
+  ];
+}
+
+export const remarkPlugin: Plugin = () => {
+  return (tree) => {
+
+    visit(tree, 'textDirective', (node: TextDirective) => {
+      const tagName = 'span';
+
+      const data = node.data ?? (node.data = {});
+      data.hName = tagName;
+      data.hProperties = h(tagName, node.attributes ?? {}).properties;
+      data.hChildren = echoDirective(node);
+    });
+
+    visit(tree, 'leafDirective', (node: LeafDirective) => {
+      const tagName = 'div';
+
+      const data = node.data ?? (node.data = {});
+      data.hName = tagName;
+      data.hProperties = h(tagName, node.attributes ?? {}).properties;
+      data.hChildren = echoDirective(node);
+    });
+
+  };
+};

+ 2 - 0
apps/app/src/services/renderer/renderer.tsx

@@ -25,6 +25,7 @@ import * as addClass from './rehype-plugins/add-class';
 import { relativeLinks } from './rehype-plugins/relative-links';
 import { relativeLinksByPukiwikiLikeLinker } from './rehype-plugins/relative-links-by-pukiwiki-like-linker';
 import * as codeBlock from './remark-plugins/codeblock';
+import * as echoDirective from './remark-plugins/echo-directive';
 import * as emoji from './remark-plugins/emoji';
 import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
 import * as xsvToTable from './remark-plugins/xsv-to-table';
@@ -99,6 +100,7 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
       pukiwikiLikeLinker,
       growiDirective,
       remarkDirective,
+      echoDirective.remarkPlugin,
       remarkFrontmatter,
       codeBlock.remarkPlugin,
     ],

+ 3 - 0
pnpm-lock.yaml

@@ -378,6 +378,9 @@ importers:
       hast-util-select:
         specifier: ^6.0.2
         version: 6.0.2
+      hastscript:
+        specifier: ^8.0.0
+        version: 8.0.0
       helmet:
         specifier: ^4.6.0
         version: 4.6.0