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

output TextDirective and LeafDirective as HTML

Yuki Takei 1 год назад
Родитель
Сommit
9168acbb9d

+ 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

@@ -26,6 +26,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';
@@ -101,6 +102,7 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
       pukiwikiLikeLinker,
       growiDirective,
       remarkDirective,
+      echoDirective.remarkPlugin,
       remarkFrontmatter,
       codeBlock.remarkPlugin,
     ],