Plugins Plugin data

Source

A plugin can hand something back from the parse of a document, such as a table of contents or a reading time.

ctx.set(key, value) keeps one value under a key and ctx.add(key, value) adds an entry to a list. ctx.data reads what the plugin has written so far:

const reading_time = {
	name: 'reading_time',
	parse: {
		sequential: true,
		paragraph: {
			parse(node, ctx) {
				const words = (ctx.data.words ?? 0) + node.text_content.split(/\s+/).length;
				ctx.set('words', words);
				ctx.set('minutes', Math.ceil(words / 200));
			}
		}
	}
};

mdsvex({ plugins: [reading_time] });
You write
# A short post

It has two paragraphs.

This is the second one.
You get
Compiles to
<script module>
  export const plugin_data = {
    reading_time: {
      words: 9,
      minutes: 1,
    },
  };
</script>

<script>
  import { setContext as set_context_MDSVEX } from 'svelte';
  set_context_MDSVEX(
    Symbol.for('mdsvex.plugin_data'),
    { current: plugin_data },
  );
</script>

<h1>A short post</h1>
<p>It has two paragraphs.</p>
<p>This is the second one.</p>
  • A write belongs to the node whose handler made it. When the parser takes a node back, the writes its handlers made go too, so a handler can write as soon as it knows something.
  • Lists are in document order. An entry from ctx.add sorts by where its node is in the document, whatever order the handlers ran in. Of two nodes that ctx.set one key, the later one in the document wins.
  • ctx.data is read-only. Assigning to it throws a TypeError, and what it holds is frozen.
  • The values are JSON: plain objects, arrays, strings, finite numbers, booleans and null. Anything else, such as a Date, a Map, NaN or a function, throws a PluginDataError from the write, with the plugin, the key, the path of the value, headings[2].id, and where the node is. A key that holds undefined is left out.

The document exports what its plugins left as plugin_data, beside metadata, keyed by plugin name:

import Article, { metadata, plugin_data } from './article.svx';

plugin_data.reading_time; // { words: 420, minutes: 3 }
  • The document can read it too, as {plugin_data.reading_time.minutes} in its own markup.
  • A template gets it as its plugin_data prop.
  • A document whose plugins left nothing has no such export, and compiles exactly as it does without plugins. Import it from a document you know has some, or use ?data below, which always has the export.

To list documents with what their plugins left, import them with the ?data query:

src/routes/blog/+page.js
const posts = import.meta.glob('./*/+page.svx', { query: '?data', eager: true });

export function load() {
	return {
		posts: Object.entries(posts).map(([path, { metadata, plugin_data }]) => ({
			slug: path.split('/')[1],
			title: metadata?.title,
			minutes: plugin_data?.reading_time.minutes
		}))
	};
}

A ?data import parses the document and runs its plugins, and renders nothing, so the list does not load the component of every page. Its module exports metadata and plugin_data, each undefined when the document has none, and both in one object as its default export.

?data or ?metadata? A ?metadata import reads the frontmatter alone, so only an edit of the frontmatter reloads the pages that import it. A ?data import depends on the whole document: an edit of the body that changes what a plugin left reloads them, and a plugin that throws fails the import. Use ?metadata for a list of titles and dates, and ?data when the list shows something a plugin worked out.

For TypeScript, a plugin types its own key by adding to the PluginData interface, and mdsvex/globals in compilerOptions.types types direct ?data imports:

import 'mdsvex';

declare module 'mdsvex' {
	interface PluginData {
		reading_time: { words: number; minutes: number };
	}
}

The import makes the file a module, so the block adds to the types of mdsvex. Without it, in a .d.ts of its own, the block declares a module mdsvex that has only PluginData, and every other import from mdsvex fails.

mdsvex, markdown with Svelte in it. MIT licence.