@skeudo/html 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Skeudo authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @skeudo/html
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Experimental, 0.x: the format and this API can change in any minor version. [CHANGELOG.md](https://github.com/wlezzar/skeudo/blob/main/CHANGELOG.md) lists the changes.
4
+
5
+ Renders [Skeudo](https://github.com/wlezzar/skeudo) sketches as HTML. A sketch is pseudocode for code review where every outside effect is tagged, or, when it starts with a `data` line, a data model drawn as tables and a story of how their rows change. The format is defined in [spec/spec.md](https://github.com/wlezzar/skeudo/blob/main/spec/spec.md).
6
+
7
+ For Markdown, use [`markdown-it-skeudo`](https://www.npmjs.com/package/markdown-it-skeudo) or [`remark-skeudo`](https://www.npmjs.com/package/remark-skeudo), which call this package. To render whole pages from the command line, use the [`skeudo`](https://www.npmjs.com/package/skeudo) CLI.
8
+
9
+ ```sh
10
+ npm install @skeudo/html
11
+ ```
12
+
13
+ ## Use
14
+
15
+ ```js
16
+ import { toHtml } from '@skeudo/html';
17
+
18
+ const html = toHtml(`get_user(id):
19
+ row = find(id) ::read:postgres.users
20
+ return row
21
+ `);
22
+ ```
23
+
24
+ `toHtml` takes a sketch's source text or a sketch parsed by [`@skeudo/core`](https://www.npmjs.com/package/@skeudo/core), and returns one element: `div.sketch` for a code sketch, `div.skd` for a data sketch. `toHast` returns the same element as a [hast](https://github.com/syntax-tree/hast) tree, for unified pipelines and MDX. Neither touches the DOM, so both run in Node and in the browser.
25
+
26
+ The page needs two more things:
27
+
28
+ - **The stylesheet**, `@skeudo/html/skeudo.css`. Import it from a bundler (`import '@skeudo/html/skeudo.css'`), or copy `node_modules/@skeudo/html/dist/skeudo.css` next to your page.
29
+ - **`enhance()`**, called once in the browser. It wires the interaction: hovering a name highlights its other uses and clicking pins them, explanations from `::doc` show in a popover, and data sketches step through their story by click or with the arrow keys. It watches the page, so sketches added later, as when a single-page site changes page, work too. Without it, explanations are the browser's tooltips and a data sketch shows its last step.
30
+
31
+ ```js
32
+ import { enhance } from '@skeudo/html';
33
+
34
+ enhance(document); // returns a function that removes its listeners
35
+ ```
36
+
37
+ Sketches follow the reader's light or dark mode. A page with a theme switch sets `data-theme="light"` or `data-theme="dark"` on its `html` element, as Docusaurus and Starlight do.
38
+
39
+ ## Options
40
+
41
+ `toHtml(source, options)` and `toHast(source, options)` take:
42
+
43
+ | Option | Default | |
44
+ | --- | --- | --- |
45
+ | `srcHref` | links to `::repo` | Builds a link for a `::src` location, from `{ path, start, end }` and the parsed sketch. `srcBaseHref(base)` builds one for a base URL, such as `https://github.com/org/repo/blob/a1b2c3d/`. Without it, a sketch that names its repository with `::repo` links to the file there, on GitHub, GitLab or Bitbucket, and other locations are tooltips. |
46
+ | `gitHosts` | `{}` | Other GitHub, GitLab or Bitbucket servers, such as `{ 'git.example.com': 'gitlab' }`, so `::repo` links reach them too. |
47
+ | `kindColors` | `{}` | CSS colors for tag kinds, such as `{ todo: '#8b5cf6' }`. |
48
+ | `labelKinds` | `['untrusted', 'secret']` | Tag kinds whose value labels a variable. Every later use of a labeled variable is marked. |
49
+
50
+ The data view takes no options.
51
+
52
+ ## Other exports
53
+
54
+ - `tagHtml(tag, options)` and `tagHast(tag, options)` render one tag as a pill, as the Markdown plugins do for inline code such as `` `::read:postgres.users` ``.
55
+ - `repoHref(repo, location, gitHosts)` is the default link for a `::src` location in a sketch with `::repo`.
56
+ - `escapeHtml(text)`.
57
+
58
+ ## License
59
+
60
+ MIT
@@ -0,0 +1,2 @@
1
+ /** Variable highlighting and explanations for the code sketches under `root`. */
2
+ export declare function enhanceCode(root: HTMLElement | Document): () => void;
@@ -0,0 +1,175 @@
1
+ /*
2
+ * Interaction for rendered code sketches, wired by enhance() in index.ts.
3
+ */
4
+ import { Popover, POPOVER_DELAY } from '../shared/popover.js';
5
+ /** Variable highlighting and explanations for the code sketches under `root`. */
6
+ export function enhanceCode(root) {
7
+ const off = [highlightVariables(root), showDocs(root)];
8
+ return () => off.forEach((remove) => remove());
9
+ }
10
+ function highlightVariables(root) {
11
+ const target = (e) => e.target?.closest?.('[data-var]') ?? null;
12
+ const mark = (el, cls, on) => {
13
+ const name = el.getAttribute('data-var');
14
+ const scope = el.closest('[data-sketch], [data-sketch-scope]') ?? root;
15
+ scope.querySelectorAll(`[data-var="${CSS.escape(name)}"]`).forEach((n) => n.classList.toggle(cls, on));
16
+ };
17
+ const over = (e) => {
18
+ const el = target(e);
19
+ if (el)
20
+ mark(el, 'sk-hl', true);
21
+ };
22
+ const out = (e) => {
23
+ const el = target(e);
24
+ if (el)
25
+ mark(el, 'sk-hl', false);
26
+ };
27
+ const click = (e) => {
28
+ const el = target(e);
29
+ if (el && !el.closest('a'))
30
+ mark(el, 'sk-pin', !el.classList.contains('sk-pin'));
31
+ };
32
+ root.addEventListener('mouseover', over);
33
+ root.addEventListener('mouseout', out);
34
+ root.addEventListener('click', click);
35
+ return () => {
36
+ root.removeEventListener('mouseover', over);
37
+ root.removeEventListener('mouseout', out);
38
+ root.removeEventListener('click', click);
39
+ };
40
+ }
41
+ /** A sketch row's depth, from the `--d` its style sets. */
42
+ const rowDepth = (row) => Number(row.style.getPropertyValue('--d')) || 0;
43
+ /**
44
+ * Shows the explanation of a call or a line in a popover. The popover sits on the page's body with a
45
+ * fixed position, since the sketch's box scrolls and would cut it off. It stands in for the element's
46
+ * tooltip, which is removed while the pointer or focus is on the element and put back after.
47
+ */
48
+ function showDocs(root) {
49
+ const doc = root instanceof Document ? root : root.ownerDocument;
50
+ const win = doc.defaultView;
51
+ const pop = new Popover(doc);
52
+ /** The element whose explanation is shown, or is about to be. */
53
+ let anchor;
54
+ /** The anchor's tooltip, while it is removed. */
55
+ let title = null;
56
+ let timer;
57
+ const target = (e) => e.target?.closest?.('[data-doc]') ?? null;
58
+ /** The rows a line's explanation covers: the line, and the lines of its block when it is a header. */
59
+ function scope(el) {
60
+ const row = el.classList.contains('sk-code') ? el.closest('.sk-row') : null;
61
+ if (!row?.classList.contains('sk-header'))
62
+ return [];
63
+ const rows = [row];
64
+ const depth = rowDepth(row);
65
+ for (let r = row.nextElementSibling; r && rowDepth(r) > depth; r = r.nextElementSibling)
66
+ rows.push(r);
67
+ return rows;
68
+ }
69
+ /** Under the line, so it doesn't cover it. A call's explanation starts at the call, a line's where its text starts. */
70
+ function place(el) {
71
+ const start = el.classList.contains('sk-code')
72
+ ? ([...el.children].find((c) => !c.classList.contains('sk-x') && !c.classList.contains('sk-doc-mark')) ?? el)
73
+ : el;
74
+ pop.below((el.closest('.sk-row') ?? el).getBoundingClientRect(), start.getBoundingClientRect().left);
75
+ }
76
+ function show() {
77
+ clearTimeout(timer);
78
+ timer = undefined;
79
+ if (!anchor)
80
+ return;
81
+ const text = anchor.getAttribute('data-doc') ?? '';
82
+ // The rest of the tooltip, such as where a call is defined, goes under the explanation.
83
+ const rest = title?.startsWith(text) ? title.slice(text.length).trim() : '';
84
+ const main = doc.createElement('div');
85
+ main.className = 'sk-doc-text';
86
+ main.textContent = text;
87
+ const content = [main];
88
+ if (rest) {
89
+ const info = doc.createElement('div');
90
+ info.className = 'sk-doc-info';
91
+ info.textContent = rest;
92
+ content.push(info);
93
+ }
94
+ pop.show(content);
95
+ place(anchor);
96
+ anchor.setAttribute('aria-describedby', pop.id);
97
+ for (const row of scope(anchor))
98
+ row.classList.add('sk-doc-scope');
99
+ }
100
+ function hide() {
101
+ clearTimeout(timer);
102
+ timer = undefined;
103
+ if (anchor) {
104
+ if (title !== null)
105
+ anchor.setAttribute('title', title);
106
+ anchor.removeAttribute('aria-describedby');
107
+ for (const row of scope(anchor))
108
+ row.classList.remove('sk-doc-scope');
109
+ }
110
+ anchor = undefined;
111
+ title = null;
112
+ pop.hide();
113
+ }
114
+ function start(el, delay) {
115
+ if (el === anchor) {
116
+ // Focus on an element the pointer is resting on shows its explanation without waiting.
117
+ if (timer !== undefined && !delay)
118
+ show();
119
+ return;
120
+ }
121
+ hide();
122
+ anchor = el;
123
+ // Removed now, so the browser never shows the tooltip as well.
124
+ title = el.getAttribute('title');
125
+ el.removeAttribute('title');
126
+ if (delay)
127
+ timer = setTimeout(show, delay);
128
+ else
129
+ show();
130
+ }
131
+ const over = (e) => {
132
+ const el = target(e);
133
+ if (el)
134
+ start(el, POPOVER_DELAY);
135
+ // The sketch was rendered again under the pointer, as VS Code's preview does on each edit.
136
+ else if (anchor && !anchor.isConnected)
137
+ hide();
138
+ };
139
+ const out = (e) => {
140
+ if (anchor && !anchor.contains(e.relatedTarget))
141
+ hide();
142
+ };
143
+ const focusIn = (e) => {
144
+ const el = target(e);
145
+ if (el)
146
+ start(el, 0);
147
+ };
148
+ const focusOut = (e) => {
149
+ if (anchor && anchor.contains(e.target))
150
+ hide();
151
+ };
152
+ const key = (e) => {
153
+ if (e.key === 'Escape')
154
+ hide();
155
+ };
156
+ root.addEventListener('mouseover', over);
157
+ root.addEventListener('mouseout', out);
158
+ root.addEventListener('focusin', focusIn);
159
+ root.addEventListener('focusout', focusOut);
160
+ root.addEventListener('keydown', key);
161
+ // The popover doesn't move with the page, so it goes away when anything scrolls.
162
+ win?.addEventListener('scroll', hide, true);
163
+ win?.addEventListener('resize', hide);
164
+ return () => {
165
+ hide();
166
+ pop.remove();
167
+ root.removeEventListener('mouseover', over);
168
+ root.removeEventListener('mouseout', out);
169
+ root.removeEventListener('focusin', focusIn);
170
+ root.removeEventListener('focusout', focusOut);
171
+ root.removeEventListener('keydown', key);
172
+ win?.removeEventListener('scroll', hide, true);
173
+ win?.removeEventListener('resize', hide);
174
+ };
175
+ }
@@ -0,0 +1,20 @@
1
+ import type { Repo, ResolvedSrc } from '@skeudo/core';
2
+ /** A link for a source location, with a note for its tooltip, such as a warning that the lines may have moved. */
3
+ export interface SrcLink {
4
+ href: string;
5
+ note?: string;
6
+ }
7
+ /** The kinds of code hosts repoHref can link to. */
8
+ export type GitHost = 'github' | 'gitlab' | 'bitbucket';
9
+ /**
10
+ * A `srcHref` that links source locations under a base URL, such as a GitHub blob URL at a commit
11
+ * (`https://github.com/org/repo/blob/a1b2c3d/`). Lines become a fragment, as in `#L88-L94`.
12
+ */
13
+ export declare function srcBaseHref(base: string): (loc: ResolvedSrc) => string | undefined;
14
+ /**
15
+ * Links a source location to the repository a sketch names with `::repo`. A remote on GitHub, GitLab or
16
+ * Bitbucket links to the file on that host at the revision, or at the default branch without one; give
17
+ * other servers of those kinds in `hosts`. A `git+file://` folder links with a `file://` URL, and any
18
+ * other URL is a base that the path is added to. Returns undefined for a host it doesn't know.
19
+ */
20
+ export declare function repoHref(repo: Repo, loc: ResolvedSrc, hosts?: Record<string, GitHost>): string | undefined;
@@ -0,0 +1,45 @@
1
+ /** A path in a URL, each part escaped. */
2
+ const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');
3
+ /** A location's path, without a leading `./`. */
4
+ const relativePath = (loc) => loc.path.replace(/^(\.?\/)+/, '');
5
+ /** The lines of a location as a URL fragment, in the form each host reads: `#L88-L94`, `#L88-94` or `#lines-88:94`. */
6
+ function linesFragment(loc, host = 'github') {
7
+ if (loc.start === undefined)
8
+ return '';
9
+ const end = loc.end !== undefined && loc.end !== loc.start ? loc.end : undefined;
10
+ if (host === 'bitbucket')
11
+ return `#lines-${loc.start}${end === undefined ? '' : `:${end}`}`;
12
+ return `#L${loc.start}${end === undefined ? '' : host === 'gitlab' ? `-${end}` : `-L${end}`}`;
13
+ }
14
+ /**
15
+ * A `srcHref` that links source locations under a base URL, such as a GitHub blob URL at a commit
16
+ * (`https://github.com/org/repo/blob/a1b2c3d/`). Lines become a fragment, as in `#L88-L94`.
17
+ */
18
+ export function srcBaseHref(base) {
19
+ const root = base.endsWith('/') ? base : `${base}/`;
20
+ return (loc) => (loc.path ? root + encodePath(relativePath(loc)) + linesFragment(loc) : undefined);
21
+ }
22
+ const KNOWN_HOSTS = { 'github.com': 'github', 'gitlab.com': 'gitlab', 'bitbucket.org': 'bitbucket' };
23
+ /**
24
+ * Links a source location to the repository a sketch names with `::repo`. A remote on GitHub, GitLab or
25
+ * Bitbucket links to the file on that host at the revision, or at the default branch without one; give
26
+ * other servers of those kinds in `hosts`. A `git+file://` folder links with a `file://` URL, and any
27
+ * other URL is a base that the path is added to. Returns undefined for a host it doesn't know.
28
+ */
29
+ export function repoHref(repo, loc, hosts = {}) {
30
+ if (!loc.path)
31
+ return undefined;
32
+ if (repo.type === 'base')
33
+ return srcBaseHref(repo.url)(loc);
34
+ if (repo.type === 'local') {
35
+ // Keep a Windows drive, as in `file:///C:/code`, unescaped.
36
+ const folder = repo.path.split('/').map((part, i) => (i === 0 && /^[a-z]:$/i.test(part) ? part : encodeURIComponent(part)));
37
+ return srcBaseHref(`file://${repo.path.startsWith('/') ? '' : '/'}${folder.join('/')}`)(loc);
38
+ }
39
+ const host = hosts[repo.host] ?? KNOWN_HOSTS[repo.host];
40
+ if (!host)
41
+ return undefined;
42
+ const rev = encodePath(repo.rev ?? 'HEAD');
43
+ const view = host === 'github' ? 'blob' : host === 'gitlab' ? '-/blob' : 'src';
44
+ return `https://${repo.host}/${encodePath(repo.path)}/${view}/${rev}/${encodePath(relativePath(loc))}${linesFragment(loc, host)}`;
45
+ }
@@ -0,0 +1,21 @@
1
+ import { type CodeSketch, type ParseOptions, type ResolvedSrc, type Tag } from '@skeudo/core';
2
+ import type { Element as HastElement } from 'hast';
3
+ import { type GitHost, type SrcLink } from './links.ts';
4
+ /** Options for rendering code sketches. */
5
+ export interface CodeHtmlOptions extends ParseOptions {
6
+ /**
7
+ * Builds a link for a source location in a sketch. Return undefined to show the location as a tooltip
8
+ * only. Defaults to repoHref, which links to the repository the sketch names with `::repo`.
9
+ */
10
+ srcHref?: (loc: ResolvedSrc, sketch: CodeSketch) => string | SrcLink | undefined;
11
+ /** Hosts of other GitHub, GitLab or Bitbucket servers, such as `{ 'git.example.com': 'gitlab' }`, for repoHref. */
12
+ gitHosts?: Record<string, GitHost>;
13
+ /** CSS colors for tag kinds, such as `{ todo: '#8b5cf6' }`. Overrides the defaults. */
14
+ kindColors?: Record<string, string>;
15
+ }
16
+ /** Builds one tag as a pill followed by its note, as a hast element. */
17
+ export declare function tagHast(tag: Tag, opts?: CodeHtmlOptions): HastElement;
18
+ /** Renders one tag as a pill, followed by its note. */
19
+ export declare function tagHtml(tag: Tag, opts?: CodeHtmlOptions): string;
20
+ /** Builds a code sketch as a hast tree: one `div.sketch` element. */
21
+ export declare function codeToHast(sketch: CodeSketch, opts?: CodeHtmlOptions): HastElement;
@@ -0,0 +1,235 @@
1
+ import { CHANGE_KINDS, formatLocation, HIDDEN_KINDS, } from '@skeudo/core';
2
+ import { classSafe, h, link, serialize, text } from '../shared/hast.js';
3
+ import { textWidth } from '../shared/width.js';
4
+ import { repoHref } from './links.js';
5
+ const KNOWN_KINDS = new Set(['read', 'write', 'fail', 'src', 'repo', 'doc', 'danger', 'unsure', 'untrusted', 'secret', ...CHANGE_KINDS]);
6
+ /** Tags a renderer hides: `::src` and `::repo` become links, and `::doc` shows on hover. */
7
+ const isHiddenTag = (tag) => HIDDEN_KINDS.has(tag.kind);
8
+ const DEFAULT_LABEL_KINDS = ['untrusted', 'secret'];
9
+ /** Text that is copied with the sketch but not shown, such as the `::` of a tag. */
10
+ const hiddenText = (s) => h('span', { className: ['sk-x'] }, text(s));
11
+ /** A link to a source location, through `srcHref`, with its note added to the tooltip. */
12
+ function srcLink(cls, loc, sketch, opts, title, children) {
13
+ const found = (opts.srcHref ?? ((l, s) => (s.repo ? repoHref(s.repo, l, opts.gitHosts) : undefined)))(loc, sketch);
14
+ const { href, note } = typeof found === 'string' ? { href: found, note: undefined } : (found ?? {});
15
+ return link(note ? [...cls, 'sk-src-note'] : cls, href, note ? `${title}\n${note}` : title, children);
16
+ }
17
+ /**
18
+ * Gives a call or a line's code an explanation, from `::doc`. enhance() shows it in a popover on hover
19
+ * or focus; without enhance() it is the element's tooltip, before what the tooltip already said.
20
+ */
21
+ function withDoc(el, doc) {
22
+ if (!doc)
23
+ return el;
24
+ const { title } = el.properties;
25
+ el.properties.className.push('sk-has-doc');
26
+ el.properties.title = title ? `${doc}\n\n${title}` : doc;
27
+ el.properties.dataDoc = doc;
28
+ // A link already takes focus. Anything else needs to, so the explanation can be reached with the keyboard.
29
+ if (el.tagName !== 'a')
30
+ el.properties.tabIndex = 0;
31
+ return el;
32
+ }
33
+ /** The `?` and `~` modifiers as written. */
34
+ const tagMods = (tag) => /^::[^?~:[]*([?~]*)/u.exec(tag.raw)?.[1] ?? '';
35
+ /** Builds one tag as a pill followed by its note, as a hast element. */
36
+ export function tagHast(tag, opts = {}) {
37
+ const labelKinds = opts.labelKinds ?? DEFAULT_LABEL_KINDS;
38
+ const cls = ['sk-tag', `sk-k-${classSafe(tag.kind)}`];
39
+ if (!KNOWN_KINDS.has(tag.kind))
40
+ cls.push('sk-other');
41
+ if (tag.conditional)
42
+ cls.push('sk-cond');
43
+ if (tag.unverified)
44
+ cls.push('sk-unv');
45
+ if (tag.value === '*')
46
+ cls.push('sk-rt');
47
+ const color = opts.kindColors?.[tag.kind];
48
+ const mods = tagMods(tag);
49
+ const pill = [hiddenText('::'), h('span', { className: ['sk-kind'] }, text(tag.kind))];
50
+ if (mods)
51
+ pill.push(h('span', { className: ['sk-mod'] }, text(mods)));
52
+ if (tag.value) {
53
+ const isLabel = labelKinds.includes(tag.kind);
54
+ pill.push(hiddenText(':'), h('span', { className: ['sk-val'], ...(isLabel ? { dataVar: tag.value } : {}) }, text(tag.value)));
55
+ }
56
+ const children = [h('span', { className: cls, ...(color ? { style: `--sk-c:${color}` } : {}) }, pill)];
57
+ if (tag.note) {
58
+ const { text: note, danger } = tag.note;
59
+ children.push(h('span', { className: danger ? ['sk-note', 'sk-note-danger'] : ['sk-note'] }, [
60
+ hiddenText('['),
61
+ ...(danger ? [h('span', { className: ['sk-bang'] }, text('!'))] : []),
62
+ ...text(note),
63
+ hiddenText(']'),
64
+ ]));
65
+ }
66
+ return h('span', { className: ['sk-tagw'], title: tag.raw }, children);
67
+ }
68
+ /** Renders one tag as a pill, followed by its note. */
69
+ export function tagHtml(tag, opts = {}) {
70
+ return serialize(tagHast(tag, opts));
71
+ }
72
+ function varHast(sketch, name, value, definition) {
73
+ const labels = sketch.variables[name]?.labels ?? [];
74
+ const cls = ['sk-var'];
75
+ if (definition)
76
+ cls.push('sk-def');
77
+ for (const l of labels)
78
+ cls.push('sk-lbl', `sk-lbl-${classSafe(l)}`);
79
+ const title = labels.length ? { title: labels.join(', ') } : {};
80
+ return h('span', { className: cls, dataVar: name, ...title }, text(value));
81
+ }
82
+ function segmentHast(seg, sketch, opts) {
83
+ switch (seg.type) {
84
+ case 'text':
85
+ return text(seg.text);
86
+ case 'word':
87
+ return [h('span', { className: ['sk-word'] }, text(seg.text))];
88
+ case 'fn':
89
+ return [h('span', { className: ['sk-fn'] }, text(seg.text))];
90
+ case 'var':
91
+ return [varHast(sketch, seg.name, seg.text, seg.definition)];
92
+ case 'call': {
93
+ const loc = sketch.callSources[seg.name];
94
+ const doc = sketch.callDocs[seg.name];
95
+ const children = seg.head
96
+ ? [varHast(sketch, seg.head, seg.head, false), ...text(seg.text.slice(seg.head.length))]
97
+ : text(seg.text);
98
+ if (!loc)
99
+ return [withDoc(link(['sk-call'], undefined, '', children), doc)];
100
+ return [withDoc(srcLink(['sk-call', 'sk-linked'], loc, sketch, opts, `Defined at ${formatLocation(loc)}`, children), doc)];
101
+ }
102
+ case 'tag':
103
+ return isHiddenTag(seg.tag) ? [] : [tagHast(seg.tag, opts)];
104
+ }
105
+ }
106
+ function gutterHast(src, sketch, opts) {
107
+ if (!src)
108
+ return [];
109
+ const where = formatLocation(src);
110
+ if (src.inherited) {
111
+ return [srcLink(['sk-src', 'sk-src-inherited'], src, sketch, opts, `${where} (from the enclosing block)`, text('·'))];
112
+ }
113
+ const label = src.start !== undefined ? String(src.start) : '↗';
114
+ return [srcLink(['sk-src'], src, sketch, opts, where, text(label))];
115
+ }
116
+ /*
117
+ * Tag column fit. The renderer can't measure the page, but a sketch is set in a monospace font, so it
118
+ * can estimate widths in `ch`. For each line with trailing tags it works out how wide the box must be
119
+ * for those tags to fit on one line in the tag column, and marks the line with that width rounded up
120
+ * to a step (`sk-fit-90` means 90ch). code.css moves a marked line's tags under its code when the
121
+ * box is narrower. The constants mirror code.css.
122
+ */
123
+ const FIT_STEP = 10;
124
+ const FIT_MIN = 60;
125
+ const FIT_MAX = 250;
126
+ /** One `em` in `ch`, for a monospace font about 0.6em wide. */
127
+ const EM = 5 / 3;
128
+ /** Tags and notes are set at 0.8em. */
129
+ const TAG_SCALE = 0.8;
130
+ /** Gap between tags (0.45rem), and the tag column's padding (3ch on the left, 1rem on the right). */
131
+ const TAG_GAP = 0.9;
132
+ const TAG_COLUMN_PADDING = 5;
133
+ /** The tag column never gets narrower than this (`minmax(22ch, 1fr)`). */
134
+ const TAG_COLUMN_MIN = 22;
135
+ /** Estimated width of a rendered tag and its note, in `ch` of the sketch font. */
136
+ function tagWidth(tag) {
137
+ let w = EM + textWidth(tag.kind) + tagMods(tag).length; // 0.5em of padding on each side
138
+ if (tag.value)
139
+ w += 0.8 * EM + textWidth(tag.value); // 0.4em of margin and 0.4em of padding around the divider
140
+ if (tag.note)
141
+ w += 0.4 * EM + textWidth(tag.note.text) + (tag.note.danger ? 1 + 0.25 * EM : 0);
142
+ return w * TAG_SCALE + 0.25; // plus the pill's border
143
+ }
144
+ /** The marker after the code of a line with a `::doc`: 1ch of margin, then a circle 1.5em across at 0.72em. */
145
+ const DOC_MARK_WIDTH = 1 + 1.5 * 0.72 * EM;
146
+ function codeWidth(line, unit) {
147
+ let w = line.depth * unit;
148
+ for (const seg of line.segments) {
149
+ if (seg.type !== 'tag')
150
+ w += textWidth(seg.text);
151
+ else if (!isHiddenTag(seg.tag))
152
+ w += tagWidth(seg.tag);
153
+ }
154
+ if (line.doc)
155
+ w += DOC_MARK_WIDTH;
156
+ return w;
157
+ }
158
+ /** Estimated width of the gutter column (`.sk-gut`: 1rem of padding, then numbers at 0.78em). */
159
+ function gutterWidth(lines, gutter) {
160
+ if (!gutter)
161
+ return 2;
162
+ const digits = Math.max(1, ...lines.map((l) => (l.src?.start !== undefined && !l.src.inherited ? String(l.src.start).length : 1)));
163
+ return 2 + 0.78 * Math.max(4.5, 1.5 + digits);
164
+ }
165
+ /** The `sk-fit-*` class for a line whose trailing tags (given as widths) may not fit in the tag column, if any. */
166
+ function fitClass(widths, before) {
167
+ if (!widths.length)
168
+ return undefined;
169
+ const column = TAG_COLUMN_PADDING + widths.reduce((a, b) => a + b, 0) + TAG_GAP * (widths.length - 1);
170
+ if (column <= TAG_COLUMN_MIN)
171
+ return undefined;
172
+ const need = Math.ceil((before + column) / FIT_STEP) * FIT_STEP;
173
+ if (need < FIT_MIN)
174
+ return undefined;
175
+ return need > FIT_MAX ? 'sk-under' : `sk-fit-${need}`;
176
+ }
177
+ /** A file path that can break after each slash. */
178
+ function breakablePath(path) {
179
+ const parts = path.split('/');
180
+ return parts.flatMap((part, i) => (i < parts.length - 1 ? [...text(`${part}/`), h('wbr', {})] : text(part)));
181
+ }
182
+ function lineHast(line, sketch, opts, gutter, before) {
183
+ const indent = ' '.repeat(line.depth * (sketch.indentUnit ?? 4));
184
+ const cls = ['sk-row'];
185
+ if (line.blank)
186
+ cls.push('sk-blank');
187
+ if (line.signature)
188
+ cls.push('sk-sig');
189
+ if (line.header)
190
+ cls.push('sk-header');
191
+ if (line.change)
192
+ cls.push('sk-ch', `sk-ch-${line.change.kind}`);
193
+ const diags = sketch.diagnostics.filter((d) => d.line === line.number);
194
+ if (diags.length)
195
+ cls.push('sk-has-diag');
196
+ let code = line.segments.flatMap((s) => segmentHast(s, sketch, opts));
197
+ // Wrapped so the strike-through of a removed line skips its indentation.
198
+ if (code.length && line.change?.kind === 'removed')
199
+ code = [h('span', { className: ['sk-struck'] }, code)];
200
+ const trailing = line.tags.filter((t) => t.trailing && !isHiddenTag(t));
201
+ const tags = trailing.map((t) => tagHast(t, opts));
202
+ const widths = trailing.map(tagWidth);
203
+ if (line.signature && line.src && sketch.file) {
204
+ // Set at 0.78em. It can also break after a slash, when even the line under the code is too narrow.
205
+ tags.push(srcLink(['sk-file'], line.src, sketch, opts, formatLocation(line.src), breakablePath(sketch.file)));
206
+ widths.push(textWidth(sketch.file) * 0.78);
207
+ }
208
+ const fit = fitClass(widths, before);
209
+ if (fit)
210
+ cls.push(fit);
211
+ const title = diags.length ? { title: diags.map((d) => d.message).join('\n') } : {};
212
+ // A line with an explanation gets a marker after its code. Its circle is drawn by code.css, so it isn't copied.
213
+ const mark = line.doc ? [h('span', { className: ['sk-doc-mark'], ariaHidden: 'true' })] : [];
214
+ // The indentation is an element with a width, not bare spaces, since some hosts drop whitespace-only
215
+ // text: VitePress compiles Markdown pages as Vue templates, and Vue does.
216
+ const ind = indent ? [h('span', { className: ['sk-ind'] }, text(indent))] : [];
217
+ return h('div', { className: cls, style: `--d:${line.depth}`, dataLine: line.number, ...title }, [
218
+ h('span', { className: ['sk-gut'] }, gutter ? gutterHast(line.src, sketch, opts) : []),
219
+ withDoc(h('span', { className: ['sk-code'] }, [...ind, ...(code.length ? code : text('​')), ...mark]), line.doc),
220
+ h('span', { className: ['sk-tags'] }, tags),
221
+ ]);
222
+ }
223
+ /** Builds a code sketch as a hast tree: one `div.sketch` element. */
224
+ export function codeToHast(sketch, opts = {}) {
225
+ const firstContent = sketch.lines.findIndex((l) => !l.blank);
226
+ const lines = firstContent === -1 ? [] : sketch.lines.slice(firstContent).filter((l) => !l.hidden);
227
+ const gutter = lines.some((l) => l.src);
228
+ // Everything left of the tag column: the gutter and the widest line of code.
229
+ const unit = sketch.indentUnit ?? 4;
230
+ const before = gutterWidth(lines, gutter) + Math.max(0, ...lines.map((l) => codeWidth(l, unit)));
231
+ const rows = lines.map((l) => lineHast(l, sketch, opts, gutter, before));
232
+ return h('div', { className: gutter ? ['sketch', 'sk-gutter'] : ['sketch'], style: `--sk-indent:${unit}ch`, dataSketch: true }, [
233
+ h('div', { className: ['sk-lines'] }, rows),
234
+ ]);
235
+ }
@@ -0,0 +1 @@
1
+ export declare function enhanceData(root: HTMLElement | Document): () => void;