histoire
Version:
A fast story book powered by Vite
133 lines (132 loc) • 6.43 kB
JavaScript
import MarkdownIt from 'markdown-it';
import anchor from 'markdown-it-anchor';
import attrs from 'markdown-it-attrs';
import { full as emoji } from 'markdown-it-emoji';
import path from 'pathe';
import pc from 'picocolors';
import { hashContent } from '../runtime/content/hash.js';
import { captureInlineDocs } from '../runtime/content/inline.js';
import { readStorySource } from '../story-source.js';
import { slugify } from '../util/slugify.js';
import { assertMarkdownActive, getMarkdownHighlighter } from './highlighter.js';
import { renderMarkdown } from './render.js';
/** Creates existing Markdown renderer and story-aware relative link handling. */
export async function createMarkdownRenderer(ctx) {
const highlighter = getMarkdownHighlighter(ctx);
const md = new MarkdownIt({
highlight: (code, lang) => highlighter.highlight(code, lang),
linkify: true,
html: true,
breaks: false,
});
// MarkdownIt recognizes Shiki's leading <pre> and skips its own <pre><code>.
// Wrap the completed fence so the label stays outside selectable code content.
const renderFence = md.renderer.rules.fence;
md.renderer.rules.fence = (tokens, index, options, env, self) => {
const language = md.utils.unescapeAll(tokens[index].info).trim().split(/\s+/)[0];
const label = language ? `<span class="__histoire-code-language">${md.utils.escapeHtml(language)}</span>` : '';
return `<div class="__histoire-code">${label}${renderFence(tokens, index, options, env, self)}</div>\n`;
};
md.use(anchor, {
slugify,
permalink: anchor.permalink.ariaHidden({}),
})
.use(attrs)
.use(emoji);
// External links
{
const defaultRender = md.renderer.rules.link_open || function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const token = tokens[idx];
const hrefIndex = token.attrIndex('href');
const classIndex = token.attrIndex('class');
if (hrefIndex >= 0) {
const href = token.attrs[hrefIndex][1];
if (href.startsWith('.')) {
const suffixIndex = href.search(/[?#]/);
const pathname = suffixIndex >= 0 ? href.slice(0, suffixIndex) : href;
const suffix = suffixIndex >= 0 ? href.slice(suffixIndex) : '';
// File lookup
const file = path.resolve(path.dirname(env.file), decodeURIComponent(pathname));
const storyFile = ctx.storyFiles.find(f => f.path === file);
const mdFile = ctx.markdownFiles.find(f => f.absolutePath === file);
if (!storyFile && !mdFile?.storyFile) {
throw new Error(pc.red(`[md] Cannot find story file: ${pathname} from ${env.file}`));
}
// Add attributes
const newHref = `${ctx.resolvedViteConfig.base}story/${encodeURIComponent(storyFile?.id ?? mdFile.storyFile.id)}${suffix}`;
token.attrSet('href', newHref);
token.attrSet('data-route', 'true');
// Markdown can render before custom story IDs finish collection.
// Native consumers resolve this exact portable catalog label; legacy
// standalone href remains compatible with its file-route adapter.
token.attrSet('data-histoire-story-path', (storyFile ?? mdFile.storyFile).relativePath);
}
else if (!href.startsWith('/') && !href.startsWith('#') && (classIndex < 0 || !token.attrs[classIndex][1].includes('header-anchor'))) {
// Add target="_blank" to external links
const aIndex = token.attrIndex('target');
if (aIndex < 0) {
token.attrPush(['target', '_blank']); // add new attribute
}
else {
token.attrs[aIndex][1] = '_blank'; // replace value of existing attr
}
}
}
// pass token to default renderer.
return defaultRender(tokens, idx, options, env, self);
};
}
return md;
}
/** Applies configured Markdown plugin hook once to the shared renderer. */
export async function createMarkdownRendererWithPlugins(ctx) {
let md = await createMarkdownRenderer(ctx);
if (ctx.config.markdown) {
const result = await ctx.config.markdown(md);
if (result) {
md = result;
}
}
return md;
}
/** Creates Vue inline documentation transform using the shared renderer. */
export async function createMarkdownPlugins(ctx) {
const plugins = [];
const md = await createMarkdownRendererWithPlugins(ctx);
plugins.push({
name: 'histoire-vue-docs-block',
async transform(code, id) {
if (!id.includes('?vue&type=docs'))
return;
if (!id.includes('lang.md'))
return;
const file = id.substring(0, id.indexOf('?vue'));
const registered = ctx.storyFiles.find(story => story.path === file || story.moduleId === file);
const sourceFile = registered ?? { path: file };
let capturedSource;
try {
capturedSource = await readStorySource(sourceFile);
}
catch { /* Synthetic transforms can lack readable source. */ }
const html = await renderMarkdown(ctx, md, code, { file });
try {
const source = await readStorySource(sourceFile);
assertMarkdownActive(ctx);
if (source != null && source === capturedSource)
captureInlineDocs(ctx, file, { html, text: code, sourceSha256: hashContent(source) });
}
catch {
// Some custom Vue transforms use synthetic IDs without registered raw
// source. Preserve their existing rendered docs and omit fresh capture.
}
assertMarkdownActive(ctx);
return `export default Comp => {
Comp.doc = ${JSON.stringify(html)}
}`;
},
});
return plugins;
}