@skeudo/html 0.0.0-stage → 0.2.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.
@@ -0,0 +1,340 @@
1
+ import { CHANGE_KINDS, formatLocation, HIDDEN_KINDS, rollup, } 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', 'fold', 'danger', 'unsure', 'untrusted', 'secret', ...CHANGE_KINDS]);
6
+ /** Tags a renderer hides: `::src` and `::repo` become links, `::doc` shows on hover, and `::fold` folds its block. */
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
+ /**
166
+ * The `sk-fit-*` class for a line whose trailing tags (given as widths) may not fit in the tag column, if
167
+ * any. `prefix` names the class: `sk-fit-90` and `sk-under`, or for a folded line `sk-ffit-90` and `sk-funder`.
168
+ */
169
+ function fitClass(widths, before, prefix = '') {
170
+ if (!widths.length)
171
+ return undefined;
172
+ const column = TAG_COLUMN_PADDING + widths.reduce((a, b) => a + b, 0) + TAG_GAP * (widths.length - 1);
173
+ if (column <= TAG_COLUMN_MIN)
174
+ return undefined;
175
+ const need = Math.ceil((before + column) / FIT_STEP) * FIT_STEP;
176
+ if (need < FIT_MIN)
177
+ return undefined;
178
+ return need > FIT_MAX ? `sk-${prefix}under` : `sk-${prefix}fit-${need}`;
179
+ }
180
+ /** Text for the lines a rolled-up tag comes from: `On line 5`, `On lines 5 and 9`, `On lines 5, 7 and 9`. */
181
+ function onLines(lines) {
182
+ const list = [...new Set(lines)];
183
+ if (list.length === 1)
184
+ return `On line ${list[0]}`;
185
+ return `On lines ${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
186
+ }
187
+ /** The tag a rolled-up tag shows as: the first of them, with their danger notes as its note and no other. */
188
+ function rolledTag(rolled) {
189
+ const { tag, dangers } = rolled;
190
+ // A ::danger tag is amber already, so its note isn't marked again.
191
+ const note = dangers.length ? { text: dangers.join('; '), danger: tag.kind !== 'danger' } : undefined;
192
+ return { ...tag, note };
193
+ }
194
+ /**
195
+ * A rolled-up tag as a pill, with a count when several lines carry it. The labeled variables that reach it
196
+ * follow, as `← body`, underlined like their other uses, since the line that shows it is folded away.
197
+ */
198
+ function rolledHast(rolled, sketch, opts) {
199
+ const el = tagHast(rolledTag(rolled), opts);
200
+ el.properties.className.push('sk-rolled');
201
+ if (rolled.removed)
202
+ el.properties.className.push('sk-rolled-removed');
203
+ el.properties.title = `${onLines(rolled.lines)}${rolled.removed ? ', removed by the change' : ''}`;
204
+ if (rolled.lines.length > 1) {
205
+ const pill = el.children[0];
206
+ pill.children.push(h('span', { className: ['sk-count'] }, text(`×${rolled.lines.length}`)));
207
+ }
208
+ if (rolled.flows.length) {
209
+ const names = rolled.flows.flatMap((name, i) => [...(i ? text(', ') : []), varHast(sketch, name, name, false)]);
210
+ const reach = rolled.flows.map((name) => `${name} (${sketch.variables[name]?.labels.join(', ')})`).join(', ');
211
+ el.children.push(h('span', { className: ['sk-flow'], title: `${reach} reaches this effect` }, [h('span', { className: ['sk-arrow'] }, text('← ')), ...names]));
212
+ }
213
+ return el;
214
+ }
215
+ /** Estimated width of a rolled-up tag, with its count and the variables that reach it. */
216
+ function rolledWidth(rolled) {
217
+ const count = rolled.lines.length > 1 ? (0.35 * EM + textWidth(`×${rolled.lines.length}`)) * TAG_SCALE : 0;
218
+ const flows = rolled.flows.length ? (0.4 * EM + textWidth(`← ${rolled.flows.join(', ')}`)) * TAG_SCALE : 0;
219
+ return tagWidth(rolledTag(rolled)) + count + flows;
220
+ }
221
+ /** The ⋯ that starts a folded line's summary, and the padding around it, in `ch`. */
222
+ const ROLLUP_MARK_WIDTH = 2 + 0.9 * EM * TAG_SCALE;
223
+ /**
224
+ * The summary a folded line shows in its tag column, after its own tags: a ⋯, then the tags of the lines
225
+ * under it. Clicking it unfolds the block.
226
+ */
227
+ function rollupHast(r, sketch, opts) {
228
+ const folded = `${r.lines} line${r.lines === 1 ? '' : 's'} folded`;
229
+ const warnings = r.diagnostics.length ? `, ${r.diagnostics.length} with a warning` : '';
230
+ return h('span', { className: ['sk-rollup'], title: `${folded}${warnings}. Click to unfold.` }, [
231
+ h('span', { className: ['sk-more'], ariaHidden: 'true' }, text('⋯')),
232
+ ...r.tags.map((t) => rolledHast(t, sketch, opts)),
233
+ ]);
234
+ }
235
+ /** A line can fold when it is a block header other than the signature. */
236
+ const canFold = (line) => line.header && !line.signature;
237
+ /**
238
+ * The lines hidden at first: the lines of every block tagged `::fold`. A blank line takes the depth of
239
+ * the shallower line around it, so a blank line inside a block is hidden with it. enhance() does the same
240
+ * each time a block is folded or unfolded.
241
+ */
242
+ function hiddenAtFirst(lines) {
243
+ const hidden = new Set();
244
+ let foldDepth = -1;
245
+ for (const line of lines) {
246
+ if (foldDepth >= 0 && line.depth > foldDepth) {
247
+ hidden.add(line.number);
248
+ continue;
249
+ }
250
+ foldDepth = line.fold && canFold(line) ? line.depth : -1;
251
+ }
252
+ return hidden;
253
+ }
254
+ /** A file path that can break after each slash. */
255
+ function breakablePath(path) {
256
+ const parts = path.split('/');
257
+ return parts.flatMap((part, i) => (i < parts.length - 1 ? [...text(`${part}/`), h('wbr', {})] : text(part)));
258
+ }
259
+ function lineHast(line, sketch, opts, gutter, before, fold) {
260
+ const indent = ' '.repeat(line.depth * (sketch.indentUnit ?? 4));
261
+ const cls = ['sk-row'];
262
+ if (line.blank)
263
+ cls.push('sk-blank');
264
+ if (line.signature)
265
+ cls.push('sk-sig');
266
+ if (line.header)
267
+ cls.push('sk-header');
268
+ if (line.change)
269
+ cls.push('sk-ch', `sk-ch-${line.change.kind}`);
270
+ const diags = sketch.diagnostics.filter((d) => d.line === line.number);
271
+ if (diags.length)
272
+ cls.push('sk-has-diag');
273
+ const { rollup: summary } = fold;
274
+ if (summary) {
275
+ cls.push('sk-foldable');
276
+ if (line.fold)
277
+ cls.push('sk-folded');
278
+ if (summary.changes.length)
279
+ cls.push('sk-ch-in', `sk-ch-in-${summary.changes[0]}`);
280
+ if (summary.diagnostics.length)
281
+ cls.push('sk-diag-in');
282
+ }
283
+ if (fold.hidden)
284
+ cls.push('sk-hide');
285
+ let code = line.segments.flatMap((s) => segmentHast(s, sketch, opts));
286
+ // Wrapped so the strike-through of a removed line skips its indentation.
287
+ if (code.length && line.change?.kind === 'removed')
288
+ code = [h('span', { className: ['sk-struck'] }, code)];
289
+ const trailing = line.tags.filter((t) => t.trailing && !isHiddenTag(t));
290
+ const tags = trailing.map((t) => tagHast(t, opts));
291
+ const widths = trailing.map(tagWidth);
292
+ if (line.signature && line.src && sketch.file) {
293
+ // Set at 0.78em. It can also break after a slash, when even the line under the code is too narrow.
294
+ tags.push(srcLink(['sk-file'], line.src, sketch, opts, formatLocation(line.src), breakablePath(sketch.file)));
295
+ widths.push(textWidth(sketch.file) * 0.78);
296
+ }
297
+ const fit = fitClass(widths, before);
298
+ if (fit)
299
+ cls.push(fit);
300
+ if (summary) {
301
+ tags.push(rollupHast(summary, sketch, opts));
302
+ const ffit = fitClass([...widths, ROLLUP_MARK_WIDTH + summary.tags.reduce((w, t) => w + rolledWidth(t) + TAG_GAP, 0)], before, 'f');
303
+ if (ffit)
304
+ cls.push(ffit);
305
+ }
306
+ const title = diags.length ? { title: diags.map((d) => d.message).join('\n') } : {};
307
+ // A line with an explanation gets a marker after its code. Its circle is drawn by code.css, so it isn't copied.
308
+ const mark = line.doc ? [h('span', { className: ['sk-doc-mark'], ariaHidden: 'true' })] : [];
309
+ // The indentation is an element with a width, not bare spaces, since some hosts drop whitespace-only
310
+ // text: VitePress compiles Markdown pages as Vue templates, and Vue does.
311
+ const ind = indent ? [h('span', { className: ['sk-ind'] }, text(indent))] : [];
312
+ // The chevron that folds the block. code.css draws it, so copying the code leaves it out, and shows it
313
+ // only once enhance() runs, since nothing could fold the block without it.
314
+ const chevron = summary
315
+ ? [h('button', { type: 'button', className: ['sk-fold'], ariaExpanded: line.fold ? 'false' : 'true', ariaLabel: line.fold ? 'Unfold block' : 'Fold block' })]
316
+ : [];
317
+ return h('div', { className: cls, style: `--d:${line.depth}`, dataLine: line.number, ...title }, [
318
+ h('span', { className: ['sk-gut'] }, gutter ? gutterHast(line.src, sketch, opts) : []),
319
+ withDoc(h('span', { className: ['sk-code'] }, [...ind, ...(code.length ? code : text('​')), ...mark, ...chevron]), line.doc),
320
+ h('span', { className: ['sk-tags'] }, tags),
321
+ ]);
322
+ }
323
+ /** Builds a code sketch as a hast tree: one `div.sketch` element. */
324
+ export function codeToHast(sketch, opts = {}) {
325
+ const firstContent = sketch.lines.findIndex((l) => !l.blank);
326
+ const lines = firstContent === -1 ? [] : sketch.lines.slice(firstContent).filter((l) => !l.hidden);
327
+ const gutter = lines.some((l) => l.src);
328
+ // Everything left of the tag column: the gutter and the widest line of code.
329
+ const unit = sketch.indentUnit ?? 4;
330
+ const before = gutterWidth(lines, gutter) + Math.max(0, ...lines.map((l) => codeWidth(l, unit)));
331
+ const hidden = hiddenAtFirst(lines);
332
+ const rows = lines.map((l) => {
333
+ // A block of lines the renderer drops, such as ::src tags, has nothing to fold.
334
+ const summary = canFold(l) ? rollup(sketch, l) : undefined;
335
+ return lineHast(l, sketch, opts, gutter, before, { rollup: summary?.lines ? summary : undefined, hidden: hidden.has(l.number) });
336
+ });
337
+ return h('div', { className: gutter ? ['sketch', 'sk-gutter'] : ['sketch'], style: `--sk-indent:${unit}ch`, dataSketch: true }, [
338
+ h('div', { className: ['sk-lines'] }, rows),
339
+ ]);
340
+ }
@@ -0,0 +1 @@
1
+ export declare function enhanceData(root: HTMLElement | Document): () => void;