Skip to content

Commit

Permalink
Improve local link transform plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
Taucher2003 committed Dec 26, 2023
1 parent 5c6e711 commit 01a700e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 22 deletions.
23 changes: 1 addition & 22 deletions astro.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import transformLocalLinks from "./src/plugins/transformLocalLinks.js";

const defaultConfig = {
title: 'Code0 Documentation'
Expand All @@ -9,28 +10,6 @@ const config = process.env.SRC_DIR
? (await import(/* @vite-ignore */`${process.env.SRC_DIR}/docs/starlight.json`)).default
: defaultConfig;

const transformLocalLinks = () => {
return {
name: 'transform-local-links',

transform(src, id) {
if (id.endsWith('.md') || id.endsWith('.mdx')) {
const directory = id.endsWith('index.md') || id.endsWith('index.mdx') ? '' : '../';

const code = src
.replaceAll(/\[([^\]]+?)]\(([^)]+?)\.mdx?\)/g, `[$1](${directory}$2/)`)
.replaceAll(/href=\\"([^"]+?)\.mdx?\\"/g, `href=\\"${directory}$1/\\"`)
.replaceAll(/href: "([^"]+?)\.mdx?"/g, `href: "${directory}$1/"`);

return {
code: code,
map: null, // provide source map if available
}
}
},
}
}

// https://astro.build/config
export default defineConfig({
base: process.env.BASE_URL,
Expand Down
35 changes: 35 additions & 0 deletions src/plugins/transformLocalLinks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const replaceUrl = (directoryPrefix) => (match, fullUrl, matchedUrl) => {
if(new URL(fullUrl, 'https://docs.code0.tech').origin !== 'https://docs.code0.tech') {
// not a relative url
return match;
}

let replacementUrl = matchedUrl;

if(/(?:^|\/)index$/.test(matchedUrl)) {
replacementUrl = matchedUrl === 'index' ? '' : matchedUrl.replace(/\/index/, '');
}

return match.replace(fullUrl, `${directoryPrefix}${replacementUrl}/`.replace('//', ''))
}

export default () => ({
name: 'transform-local-links',

transform(src, id) {
if (id.endsWith('.md') || id.endsWith('.mdx')) {
const directory = id.endsWith('index.md') || id.endsWith('index.mdx') ? '' : '../';

const regexes = [
/\[[^\]]+?]\((([^)]+?)\.mdx?)\)/g,
/href=\\"(([^"]+?)\.mdx?)\\"/g,
/href: "(([^"]+?)\.mdx?)"/g
]

return {
code: regexes.reduce((acc, regex) => acc.replaceAll(regex, replaceUrl(directory)), src),
map: null
}
}
},
})

0 comments on commit 01a700e

Please sign in to comment.