diff --git a/docusaurus.config.js b/docusaurus.config.js index e15cf2b65..d7a8cb855 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -1,3 +1,4 @@ +const { execSync } = require("node:child_process"); const math = require("remark-math"); const katex = require("rehype-katex"); @@ -18,6 +19,9 @@ module.exports = { markdown: { mermaid: true, }, + customFields: { + commitRef: execSync("git rev-parse HEAD").toString().trim(), + }, themes: ["@docusaurus/theme-mermaid"], presets: [ [ diff --git a/src/components/ViewSource/index.jsx b/src/components/ViewSource/index.jsx index 37689d492..8fa96f3f2 100644 --- a/src/components/ViewSource/index.jsx +++ b/src/components/ViewSource/index.jsx @@ -2,28 +2,36 @@ import React from "react"; import clsx from "clsx"; import { BiLinkExternal } from "react-icons/bi"; import { SiGithub } from "react-icons/si"; +import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; import styles from "./styles.module.css"; +const repositoryRootPathLength = + import.meta.url.split("/").slice(0, -4).join("/").length + 1; + /** * @param {Object} props + * @param {string} props.url * @param {boolean} props.path * @param {boolean} props.noCodeSandbox */ export default function ViewSource({ url, path, noCodeSandbox }) { - const fullPathSplit = url.split("/"); - const docsIndex = fullPathSplit.indexOf("docs"); - const srcIndex = fullPathSplit.indexOf("src"); - const baseIndex = docsIndex !== -1 ? docsIndex : srcIndex; - const pathFromBase = fullPathSplit.slice(baseIndex); - const dirPath = pathFromBase.slice(0, pathFromBase.length - 1); - const relativePath = `${dirPath.join("/")}/${path}`; + const basePath = url.slice(repositoryRootPathLength); + const commitRef = useDocusaurusContext()?.siteConfig.customFields.commitRef; + const gitHubUrl = new URL( + path, + `https://github.com/ut-code/utcode-learn/tree/${commitRef}/${basePath}` + ); + const codeSandboxUrl = new URL( + path, + `https://githubbox.com/ut-code/utcode-learn/tree/${commitRef}/${basePath}` + ); return (
GitHub で表示 @@ -33,7 +41,7 @@ export default function ViewSource({ url, path, noCodeSandbox }) { className={clsx("button button--primary", styles.button)} target="_blank" rel="noopener" - href={`https://githubbox.com/ut-code/utcode-learn/tree/master/${relativePath}`} + href={codeSandboxUrl.toString()} > このプログラムを実行する