diff --git a/astro.config.mjs b/astro.config.mjs index e847b0f..ce4188e 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -15,7 +15,7 @@ }), preact(), mdx({ - remarkPlugins: [remarkToc], + remarkPlugins: [remarkToc, remarkCodeFile], }), ], markdown: { diff --git a/src/pages/js/02-js-with-html.mdx b/src/pages/js/02-js-with-html.mdx new file mode 100644 index 0000000..0939f67 --- /dev/null +++ b/src/pages/js/02-js-with-html.mdx @@ -0,0 +1,18 @@ +--- +layout: "@/layouts/MarkdownLayout.astro" +--- + +import RenderFile from "@/components/RenderFile"; +import RenderHtml from "@/components/RenderHtml"; + +export const title = "HTMLとJavaScript"; + +# {title} + +## とりあえず書いてみよう + +```html file=src/sample/js/button.html +内容を取得できませんでした +``` + + diff --git a/src/playground/html/.gitkeep b/src/playground/html/.gitkeep new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/playground/html/.gitkeep diff --git a/src/playground/js/.gitkeep b/src/playground/js/.gitkeep new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/src/playground/js/.gitkeep diff --git a/src/plugins/remarkCodeFile.ts b/src/plugins/remarkCodeFile.ts index f0c43dd..2cffaee 100644 --- a/src/plugins/remarkCodeFile.ts +++ b/src/plugins/remarkCodeFile.ts @@ -1,27 +1,32 @@ import fs from "node:fs"; -import path from "node:path"; +import { resolve } from "node:path"; import { visit } from "unist-util-visit"; export default function remarkCodeFile() { - return (tree: any, file: any) => { - visit(tree, "code", (node) => { - console.log("Processing code node with meta:", node.meta); + return (tree: any, _file: any) => { + visit(tree, "code", (node) => { + if (!node.meta) return; - if (!node.meta) return; + const metaList = node.meta.split(" "); - const match = node.meta.match(/file=(.+)/); - if (!match) return; + const path = metaList + .find((meta: string) => meta.startsWith("file=")) + ?.slice(5); - const relativePath = match[1].trim(); - const fullPath = path.resolve(process.cwd(), relativePath); + if (!path) return; - if (!fs.existsSync(fullPath)) { - node.value = `Error: File not found - ${relativePath}`; - return; - } + const fullPath = resolve(process.cwd(), path); - node.value = fs.readFileSync(fullPath, "utf8"); - node.meta = undefined; // meta は消しておく(任意) - }); - }; + if (!fs.existsSync(fullPath)) { + node.value = `Error: File not found - ${path}`; + return; + } + + node.value = fs.readFileSync(fullPath, "utf8"); + + if (!node.meta.includes("title=")) { + node.meta += ` title=${path}`; + } + }); + }; } diff --git a/src/sample/js/button.html b/src/sample/js/button.html new file mode 100644 index 0000000..26a1713 --- /dev/null +++ b/src/sample/js/button.html @@ -0,0 +1,8 @@ + + +