@docfy/ember-vite
Version:
Vite plugin for Docfy Ember integration with @embroider/vite
82 lines (81 loc) • 3.26 kB
JavaScript
import plugin from '@docfy/core/lib/plugin.js';
import visit from 'unist-util-visit';
import u from 'unist-builder';
function visitor(page) {
visit(page.ast, 'link', (node, index, parent) => {
// Only process internal links that start with '/'
if (node.url && node.url[0] === '/') {
const data = node.data || (node.data = {});
const props = (data.hProperties || (data.hProperties = {}));
const urlParts = node.url.split('#');
const attributes = Object.keys(props)
.map((key) => {
return `${key}="${String(props[key])}"`;
})
.join(' ');
const toInsert = [
u('html', `<DocfyLink @to="${urlParts[0]}" ${urlParts[1] ? `@anchor="${urlParts[1]}"` : ''} ${attributes}>`),
...node.children,
u('html', `</DocfyLink>`)
];
if (parent && parent.children) {
parent.children.splice(index, 1, ...toInsert);
}
}
});
}
/**
* This plugin finds all the links starting with `/` and replaces them with
* the `DocfyLink` component. It also adds the DocfyLink component to the
* page imports metadata.
*
* For example:
* [Getting Started](/docs/getting-started) -> <DocfyLink @to="/docs/getting-started">Getting Started</DocfyLink>
* [API Reference](/docs/api#configuration) -> <DocfyLink @to="/docs/api" @anchor="configuration">API Reference</DocfyLink>
*/
export default plugin({
runWithMdast(ctx) {
ctx.pages.forEach((page) => {
let hasInternalLinks = false;
// Check if page has internal links
visit(page.ast, 'link', (node) => {
if (node.url && node.url[0] === '/') {
hasInternalLinks = true;
}
});
// Also check demos for internal links
if (Array.isArray(page.demos)) {
page.demos.forEach((demo) => {
visit(demo.ast, 'link', (node) => {
if (node.url && node.url[0] === '/') {
hasInternalLinks = true;
}
});
});
}
// If page has internal links, add DocfyLink to imports and transform the links
if (hasInternalLinks) {
// Add DocfyLink to page imports
const pluginData = page.pluginData;
if (!pluginData.imports) {
pluginData.imports = [];
}
const existingImport = pluginData.imports.find((imp) => imp.name === 'DocfyLink');
if (!existingImport) {
pluginData.imports.push({
name: 'DocfyLink',
path: 'test-app-vite/components/docfy-link'
});
}
// Transform the links
visitor(page);
// Also process links in demos
if (Array.isArray(page.demos)) {
page.demos.forEach((demo) => {
visitor(demo);
});
}
}
});
}
});