diff options
Diffstat (limited to 'packages/integrations/markdoc/src/heading-ids.ts')
-rw-r--r-- | packages/integrations/markdoc/src/heading-ids.ts | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/packages/integrations/markdoc/src/heading-ids.ts b/packages/integrations/markdoc/src/heading-ids.ts new file mode 100644 index 000000000..57b84d059 --- /dev/null +++ b/packages/integrations/markdoc/src/heading-ids.ts @@ -0,0 +1,73 @@ +import Markdoc, { type ConfigType, type RenderableTreeNode, type Schema } from '@markdoc/markdoc'; +import Slugger from 'github-slugger'; +import { getTextContent } from './runtime.js'; +import type { AstroMarkdocConfig } from './config.js'; +import { MarkdocError } from './utils.js'; + +function getSlug( + attributes: Record<string, any>, + children: RenderableTreeNode[], + headingSlugger: Slugger +): string { + if (attributes.id && typeof attributes.id === 'string') { + return attributes.id; + } + const textContent = attributes.content ?? getTextContent(children); + let slug = headingSlugger.slug(textContent); + + if (slug.endsWith('-')) slug = slug.slice(0, -1); + return slug; +} + +type HeadingIdConfig = AstroMarkdocConfig<{ + headingSlugger: Slugger; +}>; + +/* + Expose standalone node for users to import in their config. + Allows users to apply a custom `render: AstroComponent` + and spread our default heading attributes. +*/ +export const heading: Schema = { + children: ['inline'], + attributes: { + id: { type: String }, + level: { type: Number, required: true, default: 1 }, + }, + transform(node, config: HeadingIdConfig) { + const { level, ...attributes } = node.transformAttributes(config); + const children = node.transformChildren(config); + + if (!config.ctx?.headingSlugger) { + throw new MarkdocError({ + message: + 'Unexpected problem adding heading IDs to Markdoc file. Did you modify the `ctx.headingSlugger` property in your Markdoc config?', + }); + } + const slug = getSlug(attributes, children, config.ctx.headingSlugger); + + const render = config.nodes?.heading?.render ?? `h${level}`; + const tagProps = + // For components, pass down `level` as a prop, + // alongside `__collectHeading` for our `headings` collector. + // Avoid accidentally rendering `level` as an HTML attribute otherwise! + typeof render === 'function' + ? { ...attributes, id: slug, __collectHeading: true, level } + : { ...attributes, id: slug }; + + return new Markdoc.Tag(render, tagProps, children); + }, +}; + +// Called internally to ensure `ctx` is generated per-file, instead of per-build. +export function setupHeadingConfig(): HeadingIdConfig { + const headingSlugger = new Slugger(); + return { + ctx: { + headingSlugger, + }, + nodes: { + heading, + }, + }; +} |