Plugins Bundles

Source
plugins: Bundle[];

A plugin brings directives: the components that render them and the handlers that reshape what is written inside them. A package exports a function that returns one, and you call it:

import { steps } from '@acme/steps';

mdsvex({ plugins: [steps()] });
:::steps

## Install

```sh
pnpm add mdsvex
```

## Configure

Add it to the config.
:::

Here each heading inside :::steps starts a step. The plugin wraps the heading and what follows it in a step directive with the heading as its label, so the page renders the plugin's steps and step components.

The first-party plugins are listed under Plugins.

A plugin is an object:

export function steps() {
	return {
		name: 'steps',
		// exports a component for each directive below, under its name
		module: '@acme/steps/directives',
		directives: {
			steps: {
				children: {
					heading(node, ctx) {
						ctx.state.step?.close();
						ctx.state.step = node.wrap_from('directive_container', { name: 'step' });
						node.wrap_from('directive_label').close();
					}
				}
			},
			step: {}
		}
	};
}

mdsvex({ plugins: [steps()] });
You write
:::steps

## Install

Run `pnpm add mdsvex`.

## Configure

Add it to the config.
:::
You get
Compiles to
<script>
  import {
    steps as Steps_MDSVEX_D_G,
    step as Step_MDSVEX_D_G,
  } from '@acme/steps/directives';
</script>

<Steps_MDSVEX_D_G>
  <Step_MDSVEX_D_G
    >{#snippet label()}<h2>
        Install
      </h2>{/snippet}
    <p>
      Run <code>pnpm add mdsvex</code>.
    </p>
  </Step_MDSVEX_D_G><Step_MDSVEX_D_G
    >{#snippet label()}<h2>
        Configure
      </h2>{/snippet}
    <p>Add it to the config.</p>
  </Step_MDSVEX_D_G>
</Steps_MDSVEX_D_G>
keywhat it is
namenames the plugin in errors and in the editor manifest
modulethe module that exports the directive components. It resolves as an import from the Vite root would
directivesone entry per directive name the plugin owns
parsea parse plugin for the whole document, the same object an entry of parse_plugins is
componentselement replacements, as { specifier, names }
fencesthe fence languages the plugin renders itself, such as ['mermaid'], which the highlighter never sees

compile() takes plugins as well. It writes module as the import specifier exactly as given.

An entry of directives can hold handlers. They are bound to that directive, so they never run anywhere else in the document:

keycalled for
childrennodes written directly inside a container directive of this name, by node type
descendantsnodes at any depth inside it, by node type
parsethe directive itself, in any of its three forms

An entry can also say what its directive reads as in the text of a page, with text.

  • Your own export wins. A directives export of the same name from a components module or a template replaces the plugin's component. The plugin's handlers still run, so your step gets the same label and children.
  • Other plugins still see the nodes. A heading inside :::steps reaches the heading handlers of parse_plugins too, after the bound handler ran. A plugin's parse runs ahead of parse_plugins.
  • A nested blockquote or list is not a child. children means written directly inside the directive. Use descendants for every node of a type at any depth.
  • Only containers have children. The bracket text of a leaf or inline directive is not passed to children or descendants handlers. Their own parse still runs, though an inline directive gets its args after it, so read them in the function parse returns.
  • A directive has one owner. Two plugins with an entry for the same directive throw a DirectiveOwnerError when the config loads, naming both. Another plugin reads the directive by observing it, below.

Each handler gets the node and a context:

  • ctx.directive is the directive it is bound to.
  • ctx.index counts the calls of this handler in this directive, from 0.
  • ctx.state is an empty object, new for each directive in the document. Keep what a handler needs between calls there, such as the step it opened last.
  • ctx.scratch is the plugin's, one for the whole document and shared with its other handlers and its document hook, see plugin handlers.

A handler can return a function, which runs when the node closes. The directive's own parse can read its args when it opens and write them when it closes:

mdsvex({
	plugins: [
		{
			name: 'tabs',
			module: '@acme/tabs/directives',
			directives: {
				tabs: {
					parse(tabs, ctx) {
						return () => {
							tabs.attrs.args = { ...tabs.attrs.args, count: String(ctx.state.count ?? 0) };
						};
					},
					children: {
						heading(node, ctx) {
							ctx.state.count = ctx.index + 1;
						}
					}
				}
			}
		}
	]
});
You write
:::tabs

## macOS

## Windows

:::
You get
Compiles to
<script>
  import { tabs as Tabs_MDSVEX_D_G } from '@acme/tabs/directives';
</script>

<Tabs_MDSVEX_D_G count="2">
  <h2>macOS</h2>
  <h2>Windows</h2>
</Tabs_MDSVEX_D_G>

Args are always strings, since they reach the component as string props.

A plugin that wants to read a directive another plugin owns observes it, with observe in its parse, or in an entry of parse_plugins. This numbers the figures of a figure plugin and leaves what it finds as plugin data, which the figure's component can read:

import { figures } from '@mdsvex/plugin-figures';

export function numbering() {
	return {
		name: 'numbering',
		parse: {
			observe: {
				figure: {
					parse(figure, ctx) {
						const number = (ctx.scratch.figures = (ctx.scratch.figures ?? 0) + 1);
						const id = figure.attrs.args?.id;
						if (id === undefined) return;
						return () => {
							const label = figure.first_child;
							ctx.set('target:' + id, {
								number,
								caption: label?.type === 'directive_label' ? label.text_content : null
							});
						};
					}
				}
			}
		}
	};
}

mdsvex({ plugins: [figures(), numbering()] });
You write
:::figure[Sales by month](id=sales)
![A bar chart](./sales.png)
:::
You get
Compiles to
<script module>
  export const plugin_data = {
    numbering: {
      'target:sales': {
        number: 1,
        caption: 'Sales by month',
      },
    },
  };
</script>

<script>
  import { figure as Figure_MDSVEX_D_G } from '@mdsvex/plugin-figures/directives';
  import { setContext as set_context_MDSVEX } from 'svelte';
  set_context_MDSVEX(
    Symbol.for('mdsvex.plugin_data'),
    { current: plugin_data },
  );
  import __mdsvex_img_0 from './sales.png';
</script>

<Figure_MDSVEX_D_G id="sales"
  >{#snippet label()}Sales by month{/snippet}
  <p>
    <img
      src={__mdsvex_img_0}
      alt="A bar chart"
    />
  </p>
</Figure_MDSVEX_D_G>
  • It takes the same entries as a plugin's own directives: parse, children and descendants, with a ctx.state and ctx.index of its own.
  • It runs after the owner, at the open and at the close, so it sees the args and the children as the owner left them.
  • It runs whoever renders the directive: a plugin, your own component, or nothing yet.
  • It changes no node. It writes data, warns, and reads the tree. Writing to a node, the directive or anything else, throws a TypeError that names the plugin that owns the directive.

A plugin that renders the fences of a language itself claims them with fences. @mdsvex/plugin-diagram draws each mermaid fence and keeps its code as the diagram's source:

import { fence_meta } from 'mdsvex/compile';

export function diagram() {
	return {
		name: 'diagram',
		module: '@acme/diagram/directives',
		directives: { diagram: {} },
		fences: ['mermaid'],
		parse: {
			code_fence: {
				parse(node) {
					if (fence_meta(node.info).lang !== 'mermaid') return;
					node.wrap_from('directive_container', { name: 'diagram' }).close();
				}
			}
		}
	};
}

mdsvex({ plugins: [diagram()] });
You write
```mermaid
graph LR
  A --> B
```
You get
Compiles to
<script>
  import { diagram as Diagram_MDSVEX_D_G } from '@acme/diagram/directives';
</script>

<Diagram_MDSVEX_D_G>
  <pre><code class="language-mermaid"
      >graph LR
  A --&gt; B</code
    ></pre>
</Diagram_MDSVEX_D_G>
  • The highlighter never sees a claimed fence. It renders as plain code, as with highlight: false, and there is no unknown_language warning for it. That holds for twinkleplop and for a highlighter function, and saves the work of highlighting code the plugin replaces. It still goes to a replaced pre, with its lang, title and the rest.
  • The editor knows. The manifest lists the claimed languages, so the language server does not warn of them either.
  • A language has one owner. Two plugins that claim the same language throw a FenceOwnerError when the config loads, with language and both plugin names as plugins.
  • Only fences. A code span with a hint, `#!mermaid A --> B`, is highlighted as before.
  • The language as written, the first word of the info string, so Mermaid is not mermaid. Claim what your handler matches.
  • math fences are rendered by the math option before any highlighter, so claiming math changes nothing while it is on.

What a handler gets and can do is under plugin handlers.

mdsvex, markdown with Svelte in it. MIT licence.