| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import type { Schema as SanitizeOption } from 'hast-util-sanitize';
- import type { Root } from 'mdast';
- import { frontmatterToMarkdown } from 'mdast-util-frontmatter';
- import { gfmToMarkdown } from 'mdast-util-gfm';
- import { toMarkdown } from 'mdast-util-to-markdown';
- import type { Plugin } from 'unified';
- import type { Node } from 'unist';
- import { visit } from 'unist-util-visit';
- const SUPPORTED_ATTRIBUTES = ['children', 'marp'];
- const rewriteNode = (tree: Node, node: Node) => {
- let slide = false;
- let marp = false;
- const lines = (node.value as string).split('\n');
- lines.forEach((line) => {
- const [key, value] = line.split(':').map(part => part.trim());
- if (key === 'slide' && value === 'true') {
- slide = true;
- }
- else if (key === 'marp' && value === 'true') {
- marp = true;
- }
- });
- if (marp || slide) {
- let markdown = '';
- const createMarkdownParent = new Set<Node>([tree]);
- visit(tree, (node, index, parent: Node) => {
- try {
- if (createMarkdownParent.has(parent)) {
- const tmp = toMarkdown(node as Root, {
- extensions: [
- frontmatterToMarkdown(['yaml']),
- gfmToMarkdown(),
- ],
- });
- if (node.type === 'heading') {
- markdown += '\n';
- }
- markdown += tmp;
- }
- }
- catch (err) {
- createMarkdownParent.add(node);
- if (node?.children == null) {
- markdown += ' ';
- }
- }
- });
- console.log(markdown);
- console.log(createMarkdownParent);
- const newNode: Node = {
- type: 'root',
- data: {},
- position: tree.position,
- children: tree.children,
- };
- const data = newNode.data ?? (newNode.data = {});
- tree.children = [newNode];
- data.hName = 'slide';
- data.hProperties = {
- marp: marp ? 'marp' : '',
- children: markdown,
- };
- }
- };
- export const remarkPlugin: Plugin = function() {
- return (tree) => {
- visit(tree, (node) => {
- if (node.type === 'yaml' && node.value != null) {
- rewriteNode(tree, node);
- }
- });
- };
- };
- export const sanitizeOption: SanitizeOption = {
- tagNames: ['slide'],
- attributes: {
- slide: SUPPORTED_ATTRIBUTES,
- },
- };
|