trebol 0.1.0 → 0.1.1

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.
Files changed (106) hide show
  1. package/README.md +8 -2
  2. package/dist/cli.js +55 -20
  3. package/dist/lib/core/access.d.ts +10 -0
  4. package/dist/lib/core/access.js +210 -0
  5. package/dist/lib/core/base.d.ts +4 -0
  6. package/dist/lib/core/base.js +50 -0
  7. package/dist/lib/core/bitset.d.ts +9 -0
  8. package/dist/lib/core/bitset.js +75 -0
  9. package/dist/lib/core/boot.d.ts +18 -0
  10. package/dist/lib/core/boot.js +72 -0
  11. package/dist/lib/core/compare.d.ts +9 -0
  12. package/dist/lib/core/compare.js +156 -0
  13. package/dist/lib/core/ctx.d.ts +36 -0
  14. package/dist/lib/core/ctx.js +251 -0
  15. package/dist/lib/core/dec.d.ts +28 -0
  16. package/dist/lib/core/dec.js +158 -0
  17. package/dist/lib/core/errors.d.ts +15 -0
  18. package/dist/lib/core/errors.js +44 -0
  19. package/dist/lib/core/escapes.d.ts +14 -0
  20. package/dist/lib/core/escapes.js +80 -0
  21. package/dist/lib/core/eval.d.ts +220 -0
  22. package/dist/lib/core/eval.js +666 -0
  23. package/dist/lib/core/func.d.ts +64 -0
  24. package/dist/lib/core/func.js +129 -0
  25. package/dist/lib/core/hash.d.ts +5 -0
  26. package/dist/lib/core/hash.js +155 -0
  27. package/dist/lib/core/index.d.ts +18 -0
  28. package/dist/lib/core/index.js +20 -0
  29. package/dist/lib/core/int64.d.ts +22 -0
  30. package/dist/lib/core/int64.js +113 -0
  31. package/dist/lib/core/kinds.d.ts +67 -0
  32. package/dist/lib/core/kinds.js +134 -0
  33. package/dist/lib/core/lexer.d.ts +13 -0
  34. package/dist/lib/core/lexer.js +702 -0
  35. package/dist/lib/core/mezz.d.ts +1 -0
  36. package/dist/lib/core/mezz.js +360 -0
  37. package/dist/lib/core/mold.d.ts +20 -0
  38. package/dist/lib/core/mold.js +434 -0
  39. package/dist/lib/core/natives/control.d.ts +1 -0
  40. package/dist/lib/core/natives/control.js +374 -0
  41. package/dist/lib/core/natives/csv.d.ts +15 -0
  42. package/dist/lib/core/natives/csv.js +315 -0
  43. package/dist/lib/core/natives/data.d.ts +11 -0
  44. package/dist/lib/core/natives/data.js +367 -0
  45. package/dist/lib/core/natives/define.d.ts +17 -0
  46. package/dist/lib/core/natives/define.js +47 -0
  47. package/dist/lib/core/natives/encode.d.ts +3 -0
  48. package/dist/lib/core/natives/encode.js +187 -0
  49. package/dist/lib/core/natives/json.d.ts +5 -0
  50. package/dist/lib/core/natives/json.js +273 -0
  51. package/dist/lib/core/natives/math.d.ts +3 -0
  52. package/dist/lib/core/natives/math.js +500 -0
  53. package/dist/lib/core/natives/parse.d.ts +1 -0
  54. package/dist/lib/core/natives/parse.js +600 -0
  55. package/dist/lib/core/natives/series.d.ts +4 -0
  56. package/dist/lib/core/natives/series.js +509 -0
  57. package/dist/lib/core/natives/text.d.ts +1 -0
  58. package/dist/lib/core/natives/text.js +484 -0
  59. package/dist/lib/core/natives/xml.d.ts +9 -0
  60. package/dist/lib/core/natives/xml.js +242 -0
  61. package/dist/lib/core/series.d.ts +26 -0
  62. package/dist/lib/core/series.js +73 -0
  63. package/dist/lib/core/symbols.d.ts +9 -0
  64. package/dist/lib/core/symbols.js +44 -0
  65. package/dist/lib/core/values.d.ts +206 -0
  66. package/dist/lib/core/values.js +223 -0
  67. package/dist/lib/host/browser.d.ts +4 -0
  68. package/dist/lib/host/browser.js +4081 -0
  69. package/dist/lib/host/chart.d.ts +26 -0
  70. package/dist/lib/host/chart.js +158 -0
  71. package/dist/lib/host/compress.d.ts +1 -0
  72. package/dist/lib/host/compress.js +37 -0
  73. package/dist/lib/host/draw.d.ts +31 -0
  74. package/dist/lib/host/draw.js +348 -0
  75. package/dist/lib/host/icons.d.ts +3 -0
  76. package/dist/lib/host/icons.js +97 -0
  77. package/dist/lib/host/index.d.ts +38 -0
  78. package/dist/lib/host/index.js +190 -0
  79. package/dist/lib/host/locale.d.ts +40 -0
  80. package/dist/lib/host/locale.js +241 -0
  81. package/dist/lib/host/markdown.d.ts +28 -0
  82. package/dist/lib/host/markdown.js +151 -0
  83. package/dist/lib/host/modules.d.ts +10 -0
  84. package/dist/lib/host/modules.js +262 -0
  85. package/dist/lib/host/natives.d.ts +6 -0
  86. package/dist/lib/host/natives.js +98 -0
  87. package/dist/lib/host/net.d.ts +12 -0
  88. package/dist/lib/host/net.js +541 -0
  89. package/dist/lib/host/page.d.ts +9 -0
  90. package/dist/lib/host/page.js +55 -0
  91. package/dist/lib/host/rows.d.ts +15 -0
  92. package/dist/lib/host/rows.js +80 -0
  93. package/dist/lib/host/scheduler.d.ts +45 -0
  94. package/dist/lib/host/scheduler.js +173 -0
  95. package/dist/lib/host/theme.d.ts +58 -0
  96. package/dist/lib/host/theme.js +1462 -0
  97. package/dist/lib/ui/i18n.trb +111 -0
  98. package/dist/lib/ui/ui.trb +1237 -0
  99. package/dist/trebol.js +123 -56
  100. package/package.json +17 -5
  101. package/src/host/browser.ts +274 -33
  102. package/src/host/index.ts +2 -2
  103. package/src/host/modules.ts +8 -1
  104. package/src/host/theme.ts +63 -4
  105. package/src/ui/i18n.trb +4 -0
  106. package/src/ui/ui.trb +48 -15
@@ -0,0 +1,26 @@
1
+ import { type El } from './draw.ts';
2
+ export type ChartKind = 'bar' | 'line' | 'area' | 'pie';
3
+ export interface Series {
4
+ name: string;
5
+ /** One per label; null where a row has no number. */
6
+ values: Array<number | null>;
7
+ color: string;
8
+ }
9
+ export interface ChartSpec {
10
+ kind: ChartKind;
11
+ labels: string[];
12
+ series: Series[];
13
+ stacked: boolean;
14
+ width: number;
15
+ height: number;
16
+ /** A number as it shows on screen: as the values it stands for (money, percent) in the active language. */
17
+ format: (n: number) => string;
18
+ }
19
+ /** The colors series take in turn: the theme's own two, then Red's color words. */
20
+ export declare const SERIES_COLORS: string[];
21
+ /** The elements of a chart, to go in an SVG of spec.width by spec.height. */
22
+ export declare function chartSvg(spec: ChartSpec): El[];
23
+ /** Round steps for an axis from lo to hi: 0, 250, 500...; whole numbers only, when the values are. */
24
+ export declare function ticks(lo: number, hi: number, whole?: boolean, most?: number): number[];
25
+ /** The color of slice i of a pie: each label its own. */
26
+ export declare function pieColor(i: number): string;
@@ -0,0 +1,158 @@
1
+ // Charts: bar, line, area and pie, drawn as SVG at the width they are given.
2
+ //
3
+ // chart bar income [month "Month" repairs "Repairs" parts "Parts"]
4
+ //
5
+ // The first column labels each point; the others are the series. The host
6
+ // reads the rows and the theme, and redraws when the width changes, so text
7
+ // stays the size of the rest of the page instead of scaling with the chart.
8
+ // Like draw.ts, this builds plain elements and knows nothing of the DOM.
9
+ import { svgEl } from "./draw.js";
10
+ /** The colors series take in turn: the theme's own two, then Red's color words. */
11
+ export const SERIES_COLORS = [
12
+ 'var(--tb-primary)', 'var(--tb-accent)', 'var(--tb-c-teal)', 'var(--tb-c-orange)',
13
+ 'var(--tb-c-purple)', 'var(--tb-c-green)', 'var(--tb-c-pink)', 'var(--tb-c-gold)',
14
+ ];
15
+ const FONT = 12;
16
+ const LABEL = { fill: 'var(--tb-muted)', 'font-size': FONT, 'font-family': 'var(--tb-font)' };
17
+ /** The elements of a chart, to go in an SVG of spec.width by spec.height. */
18
+ export function chartSvg(spec) {
19
+ if (spec.labels.length === 0 || spec.series.length === 0)
20
+ return [];
21
+ return spec.kind === 'pie' ? pie(spec) : axes(spec);
22
+ }
23
+ /** Round steps for an axis from lo to hi: 0, 250, 500...; whole numbers only, when the values are. */
24
+ export function ticks(lo, hi, whole = false, most = 5) {
25
+ if (hi === lo)
26
+ hi = lo + 1;
27
+ const raw = (hi - lo) / most;
28
+ const mag = 10 ** Math.floor(Math.log10(raw));
29
+ const step = Math.max(whole ? 1 : 0, [1, 2, 2.5, 5, 10].map(m => m * mag).find(s => s >= raw && (!whole || Number.isInteger(s))));
30
+ const out = [];
31
+ // each step from its count, cut to 12 digits, so 0.6 is not 0.6000000000000001
32
+ for (let k = Math.floor(lo / step); k * step <= hi + step * 1e-9; k++)
33
+ out.push(Number((k * step).toPrecision(12)));
34
+ if (out[out.length - 1] < hi)
35
+ out.push(out[out.length - 1] + step);
36
+ return out;
37
+ }
38
+ function axes(spec) {
39
+ const { labels, series, width, height, stacked, format } = spec;
40
+ const n = labels.length;
41
+ const stack = stacked && spec.kind !== 'line';
42
+ // the top of each point: its own value, or the sum below it when stacked
43
+ const tops = series.map(() => []);
44
+ const bases = series.map(() => []);
45
+ for (let i = 0; i < n; i++) {
46
+ let up = 0;
47
+ let down = 0;
48
+ series.forEach((s, k) => {
49
+ const v = s.values[i] ?? 0;
50
+ const base = stack ? (v >= 0 ? up : down) : 0;
51
+ bases[k][i] = base;
52
+ tops[k][i] = base + v;
53
+ if (stack)
54
+ v >= 0 ? (up += v) : (down += v);
55
+ });
56
+ }
57
+ const all = tops.flat().concat(bases.flat(), [0]);
58
+ const steps = ticks(Math.min(...all), Math.max(...all), all.every(Number.isInteger));
59
+ const lo = steps[0];
60
+ const hi = steps[steps.length - 1];
61
+ const left = Math.max(...steps.map(t => format(t).length)) * FONT * 0.6 + 8;
62
+ const right = 8;
63
+ const top = FONT;
64
+ const bottom = FONT * 2 + 4;
65
+ const plotW = Math.max(1, width - left - right);
66
+ const plotH = Math.max(1, height - top - bottom);
67
+ const y = (v) => top + plotH - ((v - lo) / (hi - lo)) * plotH;
68
+ const out = [];
69
+ for (const t of steps) {
70
+ out.push(svgEl('line', { x1: left, x2: left + plotW, y1: y(t), y2: y(t), stroke: 'var(--tb-border)', 'stroke-width': t === 0 ? 1.5 : 1 }));
71
+ out.push(svgEl('text', { ...LABEL, x: left - 6, y: y(t), 'text-anchor': 'end', 'dominant-baseline': 'middle' }, [], format(t)));
72
+ }
73
+ // each label gets a band; bars sit inside it, points in its middle
74
+ const band = plotW / n;
75
+ const x = (i) => left + band * (i + 0.5);
76
+ // as many labels as fit, evenly spread
77
+ const room = Math.max(1, Math.floor(plotW / (Math.max(...labels.map(l => l.length)) * FONT * 0.6 + 12)));
78
+ const every = Math.ceil(n / room);
79
+ labels.forEach((l, i) => {
80
+ if (i % every === 0)
81
+ out.push(svgEl('text', { ...LABEL, x: x(i), y: top + plotH + FONT + 4, 'text-anchor': 'middle', 'dominant-baseline': 'middle' }, [], l));
82
+ });
83
+ const tip = (i, s) => svgEl('title', {}, [], `${labels[i]}, ${s.name}: ${s.values[i] === null ? '' : format(s.values[i])}`);
84
+ if (spec.kind === 'bar') {
85
+ const groups = stack ? 1 : series.length;
86
+ const inner = band * 0.7;
87
+ const w = inner / groups;
88
+ series.forEach((s, k) => {
89
+ for (let i = 0; i < n; i++) {
90
+ if (s.values[i] === null)
91
+ continue;
92
+ const x0 = left + band * i + (band - inner) / 2 + (stack ? 0 : w * k);
93
+ const a = y(Math.max(bases[k][i], tops[k][i]));
94
+ const b = y(Math.min(bases[k][i], tops[k][i]));
95
+ out.push(svgEl('rect', { x: x0 + 1, y: a, width: Math.max(1, w - 2), height: Math.max(0, b - a), fill: s.color, rx: 2 }, [tip(i, s)]));
96
+ }
97
+ });
98
+ return out;
99
+ }
100
+ // line and area: the area first, so the lines go over every one of them
101
+ const marks = [];
102
+ series.forEach((s, k) => {
103
+ const pts = [];
104
+ for (let i = 0; i < n; i++)
105
+ if (s.values[i] !== null)
106
+ pts.push(`${x(i)},${y(tops[k][i])}`);
107
+ if (spec.kind === 'area') {
108
+ const under = [];
109
+ for (let i = n - 1; i >= 0; i--)
110
+ if (s.values[i] !== null)
111
+ under.push(`${x(i)},${y(bases[k][i])}`);
112
+ out.push(svgEl('polygon', { points: [...pts, ...under].join(' '), fill: s.color, 'fill-opacity': 0.18, stroke: 'none' }));
113
+ }
114
+ marks.push(svgEl('polyline', { points: pts.join(' '), fill: 'none', stroke: s.color, 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }));
115
+ for (let i = 0; i < n; i++) {
116
+ if (s.values[i] === null)
117
+ continue;
118
+ marks.push(svgEl('circle', { cx: x(i), cy: y(tops[k][i]), r: 3.5, fill: s.color, stroke: 'var(--tb-surface)', 'stroke-width': 1.5 }, [tip(i, s)]));
119
+ }
120
+ });
121
+ return out.concat(marks);
122
+ }
123
+ /** A pie of the first series: one slice per label, the ones with nothing to show left out. */
124
+ function pie(spec) {
125
+ const s = spec.series[0];
126
+ const vals = s.values.map(v => (v === null || v < 0 ? 0 : v));
127
+ const total = vals.reduce((a, b) => a + b, 0);
128
+ if (total === 0)
129
+ return [];
130
+ const r = Math.max(1, Math.min(spec.width, spec.height) / 2 - 4);
131
+ const cx = spec.width / 2;
132
+ const cy = spec.height / 2;
133
+ const out = [];
134
+ let at = -90;
135
+ vals.forEach((v, i) => {
136
+ if (v === 0)
137
+ return;
138
+ const sweep = (v / total) * 360;
139
+ const tip = svgEl('title', {}, [], `${spec.labels[i]}: ${spec.format(v)} (${Math.round((v / total) * 100)}%)`);
140
+ const paint = { fill: pieColor(i), stroke: 'var(--tb-surface)', 'stroke-width': 2 };
141
+ if (sweep >= 359.999) {
142
+ out.push(svgEl('circle', { cx, cy, r, ...paint }, [tip]));
143
+ }
144
+ else {
145
+ const p = (deg) => [cx + r * Math.cos((deg * Math.PI) / 180), cy + r * Math.sin((deg * Math.PI) / 180)];
146
+ const [x0, y0] = p(at);
147
+ const [x1, y1] = p(at + sweep);
148
+ const d = `M${cx},${cy} L${x0},${y0} A${r},${r} 0 ${sweep > 180 ? 1 : 0} 1 ${x1},${y1} Z`;
149
+ out.push(svgEl('path', { d, ...paint }, [tip]));
150
+ }
151
+ at += sweep;
152
+ });
153
+ return out;
154
+ }
155
+ /** The color of slice i of a pie: each label its own. */
156
+ export function pieColor(i) {
157
+ return SERIES_COLORS[i % SERIES_COLORS.length];
158
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ // compress and decompress, as in R3 and Red: gzip, zlib or raw deflate, done
2
+ // by the platform's CompressionStream (browsers and Node have it). It works
3
+ // on a stream, so both wait for the result as a fetch does.
4
+ import { K, native, value, binary, text, spell, canon, makeError, throwError, } from "../core/index.js";
5
+ const FORMATS = { gzip: 'gzip', zlib: 'deflate', deflate: 'deflate-raw' };
6
+ function format(method) {
7
+ return FORMATS[spell(canon(method.sym)).toLowerCase()] ?? null;
8
+ }
9
+ const bytesOf = (v) => v.t === K.Binary
10
+ ? new Uint8Array(v.s.data.slice(v.i))
11
+ : new TextEncoder().encode(text(v));
12
+ async function through(bytes, stream) {
13
+ const out = await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer();
14
+ return binary([...new Uint8Array(out)]);
15
+ }
16
+ native('compress', '["Compresses bytes, or text as UTF-8, into a binary." data [binary! string!] method [word!] "gzip, zlib or deflate"]', (_t, f, v) => {
17
+ if (f.phase === 1)
18
+ return value(v);
19
+ const fmt = format(f.args[1]);
20
+ if (fmt === null)
21
+ return throwError('script', 'bad-method', 'compress takes gzip, zlib or deflate');
22
+ f.phase = 1;
23
+ return { k: 'await', p: through(bytesOf(f.args[0]), new CompressionStream(fmt)) };
24
+ });
25
+ native('decompress', '["The bytes that compress was given." data [binary!] method [word!] "gzip, zlib or deflate"]', (_t, f, v) => {
26
+ if (f.phase === 1)
27
+ return value(v);
28
+ const fmt = format(f.args[1]);
29
+ if (fmt === null)
30
+ return throwError('script', 'bad-method', 'decompress takes gzip, zlib or deflate');
31
+ f.phase = 1;
32
+ const name = spell(f.args[1].sym);
33
+ const p = through(bytesOf(f.args[0]), new DecompressionStream(fmt)).catch(() => {
34
+ throw makeError('script', 'bad-compression', `the data is not ${name} compressed`);
35
+ });
36
+ return { k: 'await', p };
37
+ });
@@ -0,0 +1,31 @@
1
+ import { type Cell } from '../core/index.ts';
2
+ /** An SVG element to make: its tag, attributes, children and text. */
3
+ export interface El {
4
+ tag: string;
5
+ attrs: Record<string, string>;
6
+ kids: El[];
7
+ text?: string;
8
+ }
9
+ export declare const svgEl: (tag: string, attrs?: Record<string, string | number>, kids?: El[], txt?: string) => El;
10
+ /** Theme roles a drawing may use as colors. */
11
+ export declare const DRAW_ROLES: readonly ["primary", "accent", "danger", "success", "warning", "muted", "text", "border", "surface", "bg"];
12
+ /**
13
+ * Red's color words Trebol knows, as OKLCH hue and chroma with a lightness for
14
+ * light and one for dark mode, so each one reads on the background of either.
15
+ * black and white stay what they say in both.
16
+ */
17
+ export declare const DRAW_COLORS: Record<string, {
18
+ h: number;
19
+ c: number;
20
+ light: number;
21
+ dark: number;
22
+ }>;
23
+ /** The commands of the dialect, and how each is written. */
24
+ export declare const DRAW_COMMANDS: Record<string, string>;
25
+ /** A color word as CSS; null for off, undefined when it is no color. */
26
+ export declare function drawColor(w: string): string | null | undefined;
27
+ /** The SVG elements of a draw block, and what was wrong with it, if anything. Drawing stops at the first error. */
28
+ export declare function drawSvg(block: Cell): {
29
+ kids: El[];
30
+ error: string | null;
31
+ };
@@ -0,0 +1,348 @@
1
+ // The draw dialect: a block of drawing commands, as in Red, drawn as SVG.
2
+ //
3
+ // canvas 120x120 [fill-pen primary circle 60x60 50 pen text line 30x60 90x60]
4
+ //
5
+ // Coordinates are in the canvas's own space (its extent); the SVG scales to
6
+ // the room it gets. Colors are the theme's roles or Red's color words, which
7
+ // the theme works out for light and dark (`--tb-c-red` and so on), never RGB.
8
+ // This module builds a tree of plain elements and knows nothing of the DOM,
9
+ // so the tests run it in Node; the browser host turns the tree into nodes.
10
+ import { K, I64, spell, text } from "../core/index.js";
11
+ export const svgEl = (tag, attrs = {}, kids = [], txt) => {
12
+ const a = {};
13
+ for (const [k, v] of Object.entries(attrs))
14
+ a[k] = typeof v === 'number' ? round(v) : v;
15
+ return txt === undefined ? { tag, attrs: a, kids } : { tag, attrs: a, kids, text: txt };
16
+ };
17
+ const round = (n) => String(Math.round(n * 100) / 100);
18
+ /** Theme roles a drawing may use as colors. */
19
+ export const DRAW_ROLES = ['primary', 'accent', 'danger', 'success', 'warning', 'muted', 'text', 'border', 'surface', 'bg'];
20
+ /**
21
+ * Red's color words Trebol knows, as OKLCH hue and chroma with a lightness for
22
+ * light and one for dark mode, so each one reads on the background of either.
23
+ * black and white stay what they say in both.
24
+ */
25
+ export const DRAW_COLORS = {
26
+ red: { h: 27, c: 0.2, light: 0.58, dark: 0.7 },
27
+ maroon: { h: 15, c: 0.13, light: 0.38, dark: 0.58 },
28
+ orange: { h: 55, c: 0.17, light: 0.68, dark: 0.76 },
29
+ brown: { h: 50, c: 0.1, light: 0.45, dark: 0.62 },
30
+ gold: { h: 85, c: 0.15, light: 0.76, dark: 0.8 },
31
+ yellow: { h: 100, c: 0.17, light: 0.86, dark: 0.88 },
32
+ olive: { h: 115, c: 0.12, light: 0.5, dark: 0.68 },
33
+ green: { h: 145, c: 0.17, light: 0.6, dark: 0.74 },
34
+ teal: { h: 185, c: 0.11, light: 0.58, dark: 0.72 },
35
+ aqua: { h: 195, c: 0.12, light: 0.78, dark: 0.82 },
36
+ cyan: { h: 210, c: 0.12, light: 0.72, dark: 0.8 },
37
+ sky: { h: 235, c: 0.1, light: 0.75, dark: 0.8 },
38
+ blue: { h: 260, c: 0.19, light: 0.55, dark: 0.7 },
39
+ navy: { h: 265, c: 0.14, light: 0.32, dark: 0.55 },
40
+ violet: { h: 290, c: 0.15, light: 0.62, dark: 0.75 },
41
+ purple: { h: 305, c: 0.18, light: 0.5, dark: 0.68 },
42
+ magenta: { h: 330, c: 0.24, light: 0.6, dark: 0.72 },
43
+ pink: { h: 350, c: 0.13, light: 0.75, dark: 0.8 },
44
+ silver: { h: 0, c: 0, light: 0.8, dark: 0.75 },
45
+ gray: { h: 0, c: 0, light: 0.6, dark: 0.62 },
46
+ black: { h: 0, c: 0, light: 0.15, dark: 0.15 },
47
+ white: { h: 0, c: 0, light: 1, dark: 1 },
48
+ };
49
+ /** The commands of the dialect, and how each is written. */
50
+ export const DRAW_COMMANDS = {
51
+ pen: 'pen color',
52
+ 'fill-pen': 'fill-pen color',
53
+ 'line-width': 'line-width number',
54
+ 'line-cap': 'line-cap flat | square | round',
55
+ 'line-join': 'line-join miter | round | bevel',
56
+ font: 'font [size: number bold italic]',
57
+ line: 'line point point ...',
58
+ box: 'box top-left bottom-right [corner-radius]',
59
+ triangle: 'triangle point point point',
60
+ polygon: 'polygon point point point ...',
61
+ circle: 'circle center radius [radius-y]',
62
+ ellipse: 'ellipse top-left size',
63
+ arc: 'arc center radius begin sweep [closed]',
64
+ curve: 'curve start control end, or curve start control control end',
65
+ text: 'text top-left string',
66
+ translate: 'translate offset',
67
+ rotate: 'rotate angle [center]',
68
+ scale: 'scale x y',
69
+ push: 'push [commands]',
70
+ };
71
+ const START = { pen: 'var(--tb-text)', fill: null, width: 1, cap: 'butt', join: 'miter', size: 15, bold: false, italic: false };
72
+ /** A color word as CSS; null for off, undefined when it is no color. */
73
+ export function drawColor(w) {
74
+ if (w === 'off' || w === 'none' || w === 'transparent')
75
+ return null;
76
+ if (DRAW_ROLES.includes(w))
77
+ return `var(--tb-${w})`;
78
+ if (DRAW_COLORS[w] !== undefined)
79
+ return `var(--tb-c-${w})`;
80
+ return undefined;
81
+ }
82
+ class DrawError extends Error {
83
+ }
84
+ /** The SVG elements of a draw block, and what was wrong with it, if anything. Drawing stops at the first error. */
85
+ export function drawSvg(block) {
86
+ const out = [];
87
+ if (block.t !== K.Block)
88
+ return { kids: out, error: block.t === K.None ? null : 'draw takes a block' };
89
+ try {
90
+ run(block, { ...START }, out);
91
+ return { kids: out, error: null };
92
+ }
93
+ catch (e) {
94
+ if (e instanceof DrawError)
95
+ return { kids: out, error: e.message };
96
+ throw e;
97
+ }
98
+ }
99
+ function run(b, st, out) {
100
+ const d = b.s.data;
101
+ let i = b.i;
102
+ let into = out;
103
+ const word = (c) => c !== undefined && (c.t === K.Word || c.t === K.LitWord) ? spell(c.sym).toLowerCase() : null;
104
+ const num = (c) => c === undefined ? null : c.t === K.Integer ? I64.toNumber(c.v) : c.t === K.Decimal ? c.v : null;
105
+ const fail = (cmd) => {
106
+ throw new DrawError(`draw: ${cmd} is written ${DRAW_COMMANDS[cmd]}`);
107
+ };
108
+ const point = (cmd) => {
109
+ const c = d[i];
110
+ if (c === undefined || c.t !== K.Pair)
111
+ return fail(cmd);
112
+ i++;
113
+ return [c.x, c.y];
114
+ };
115
+ const optPoint = () => {
116
+ const c = d[i];
117
+ if (c === undefined || c.t !== K.Pair)
118
+ return null;
119
+ i++;
120
+ return [c.x, c.y];
121
+ };
122
+ const number = (cmd) => {
123
+ const n = num(d[i]);
124
+ if (n === null)
125
+ return fail(cmd);
126
+ i++;
127
+ return n;
128
+ };
129
+ const optNumber = () => {
130
+ const n = num(d[i]);
131
+ if (n !== null)
132
+ i++;
133
+ return n;
134
+ };
135
+ const points = (cmd, least) => {
136
+ const ps = [];
137
+ for (let p = optPoint(); p !== null; p = optPoint())
138
+ ps.push(p);
139
+ if (ps.length < least)
140
+ fail(cmd);
141
+ return ps;
142
+ };
143
+ const paint = (closed) => ({
144
+ fill: closed && st.fill !== null ? st.fill : 'none',
145
+ stroke: st.pen ?? 'none',
146
+ 'stroke-width': st.width,
147
+ 'stroke-linecap': st.cap,
148
+ 'stroke-linejoin': st.join,
149
+ });
150
+ const pts = (ps) => ps.map(([x, y]) => `${round(x)},${round(y)}`).join(' ');
151
+ while (i < d.length) {
152
+ const c = d[i];
153
+ const cmd = word(c);
154
+ if (cmd === null || DRAW_COMMANDS[cmd] === undefined) {
155
+ throw new DrawError(cmd === null ? `draw: a command was expected, not ${kindOf(c)}` : `draw: unknown command ${cmd}`);
156
+ }
157
+ i++;
158
+ switch (cmd) {
159
+ case 'pen':
160
+ case 'fill-pen': {
161
+ const w = word(d[i]);
162
+ const color = w === null ? undefined : drawColor(w);
163
+ if (color === undefined) {
164
+ throw new DrawError(`draw: ${cmd} takes a role (${DRAW_ROLES.join(' ')}), a color (${Object.keys(DRAW_COLORS).join(' ')}) or off`);
165
+ }
166
+ i++;
167
+ if (cmd === 'pen')
168
+ st.pen = color;
169
+ else
170
+ st.fill = color;
171
+ break;
172
+ }
173
+ case 'line-width':
174
+ st.width = Math.max(0, number(cmd));
175
+ break;
176
+ case 'line-cap': {
177
+ const w = word(d[i]);
178
+ if (w !== 'flat' && w !== 'square' && w !== 'round')
179
+ fail(cmd);
180
+ i++;
181
+ st.cap = w === 'flat' ? 'butt' : w;
182
+ break;
183
+ }
184
+ case 'line-join': {
185
+ const w = word(d[i]);
186
+ if (w !== 'miter' && w !== 'round' && w !== 'bevel')
187
+ fail(cmd);
188
+ i++;
189
+ st.join = w;
190
+ break;
191
+ }
192
+ case 'font': {
193
+ const spec = d[i];
194
+ if (spec === undefined || spec.t !== K.Block)
195
+ fail(cmd);
196
+ i++;
197
+ const fd = spec.s.data.slice(spec.i);
198
+ for (let j = 0; j < fd.length; j++) {
199
+ const f = fd[j];
200
+ if (f.t === K.SetWord && spell(f.sym).toLowerCase() === 'size' && num(fd[j + 1]) !== null) {
201
+ st.size = num(fd[++j]);
202
+ }
203
+ else if (word(f) === 'bold')
204
+ st.bold = true;
205
+ else if (word(f) === 'italic')
206
+ st.italic = true;
207
+ else if (word(f) === 'plain')
208
+ st.bold = st.italic = false;
209
+ else
210
+ fail(cmd);
211
+ }
212
+ break;
213
+ }
214
+ case 'line':
215
+ into.push(svgEl('polyline', { points: pts(points(cmd, 2)), ...paint(false) }));
216
+ break;
217
+ case 'triangle': {
218
+ const ps = points(cmd, 3);
219
+ if (ps.length !== 3)
220
+ fail(cmd);
221
+ into.push(svgEl('polygon', { points: pts(ps), ...paint(true) }));
222
+ break;
223
+ }
224
+ case 'polygon':
225
+ into.push(svgEl('polygon', { points: pts(points(cmd, 3)), ...paint(true) }));
226
+ break;
227
+ case 'box': {
228
+ const [x1, y1] = point(cmd);
229
+ const [x2, y2] = point(cmd);
230
+ const r = optNumber();
231
+ const a = {
232
+ x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1), ...paint(true),
233
+ };
234
+ if (r !== null)
235
+ a['rx'] = r;
236
+ into.push(svgEl('rect', a));
237
+ break;
238
+ }
239
+ case 'circle': {
240
+ const [cx, cy] = point(cmd);
241
+ const r = number(cmd);
242
+ const ry = optNumber();
243
+ into.push(ry === null
244
+ ? svgEl('circle', { cx, cy, r, ...paint(true) })
245
+ : svgEl('ellipse', { cx, cy, rx: r, ry, ...paint(true) }));
246
+ break;
247
+ }
248
+ case 'ellipse': {
249
+ const [x, y] = point(cmd);
250
+ const [w, h] = point(cmd);
251
+ into.push(svgEl('ellipse', { cx: x + w / 2, cy: y + h / 2, rx: w / 2, ry: h / 2, ...paint(true) }));
252
+ break;
253
+ }
254
+ case 'arc': {
255
+ const [cx, cy] = point(cmd);
256
+ const [rx, ry] = point(cmd);
257
+ const begin = number(cmd);
258
+ const sweep = number(cmd);
259
+ const closed = word(d[i]) === 'closed';
260
+ if (closed)
261
+ i++;
262
+ into.push(svgEl('path', { d: arcPath(cx, cy, rx, ry, begin, sweep, closed), ...paint(closed) }));
263
+ break;
264
+ }
265
+ case 'curve': {
266
+ const ps = points(cmd, 3);
267
+ if (ps.length > 4)
268
+ fail(cmd);
269
+ const [p0, ...rest] = ps;
270
+ const path = `M${round(p0[0])},${round(p0[1])} ${rest.length === 2 ? 'Q' : 'C'}${pts(rest)}`;
271
+ into.push(svgEl('path', { d: path, ...paint(false) }));
272
+ break;
273
+ }
274
+ case 'text': {
275
+ const [x, y] = point(cmd);
276
+ const s = d[i];
277
+ if (s === undefined || s.t !== K.String)
278
+ fail(cmd);
279
+ i++;
280
+ const a = {
281
+ x, y, 'dominant-baseline': 'hanging', fill: st.pen ?? 'none', 'font-size': st.size, 'font-family': 'var(--tb-font)',
282
+ };
283
+ if (st.bold)
284
+ a['font-weight'] = 'bold';
285
+ if (st.italic)
286
+ a['font-style'] = 'italic';
287
+ into.push(svgEl('text', a, [], text(s)));
288
+ break;
289
+ }
290
+ case 'translate':
291
+ case 'rotate':
292
+ case 'scale': {
293
+ let t;
294
+ if (cmd === 'translate') {
295
+ const [x, y] = point(cmd);
296
+ t = `translate(${round(x)} ${round(y)})`;
297
+ }
298
+ else if (cmd === 'rotate') {
299
+ const a = number(cmd);
300
+ const c = optPoint();
301
+ t = c === null ? `rotate(${round(a)})` : `rotate(${round(a)} ${round(c[0])} ${round(c[1])})`;
302
+ }
303
+ else {
304
+ const x = number(cmd);
305
+ const y = optNumber() ?? x;
306
+ t = `scale(${round(x)} ${round(y)})`;
307
+ }
308
+ // the rest of this block is drawn inside the transform
309
+ const g = svgEl('g', { transform: t });
310
+ into.push(g);
311
+ into = g.kids;
312
+ break;
313
+ }
314
+ case 'push': {
315
+ const inner = d[i];
316
+ if (inner === undefined || inner.t !== K.Block)
317
+ fail(cmd);
318
+ i++;
319
+ const g = svgEl('g');
320
+ into.push(g);
321
+ run(inner, { ...st }, g.kids);
322
+ break;
323
+ }
324
+ }
325
+ }
326
+ }
327
+ /** The SVG path of an arc: angles in degrees, 0 at three o'clock, going clockwise, as in Red. */
328
+ function arcPath(cx, cy, rx, ry, begin, sweep, closed) {
329
+ const at = (deg) => {
330
+ const r = (deg * Math.PI) / 180;
331
+ return [cx + rx * Math.cos(r), cy + ry * Math.sin(r)];
332
+ };
333
+ // a full turn is two halves: one arc cannot start and end at the same point
334
+ if (Math.abs(sweep) >= 360) {
335
+ const [x0, y0] = at(begin);
336
+ const [x1, y1] = at(begin + 180);
337
+ return `M${round(x0)},${round(y0)} A${round(rx)},${round(ry)} 0 1 1 ${round(x1)},${round(y1)} A${round(rx)},${round(ry)} 0 1 1 ${round(x0)},${round(y0)}${closed ? ' Z' : ''}`;
338
+ }
339
+ const [x0, y0] = at(begin);
340
+ const [x1, y1] = at(begin + sweep);
341
+ const large = Math.abs(sweep) > 180 ? 1 : 0;
342
+ const dir = sweep >= 0 ? 1 : 0;
343
+ const arc = `A${round(rx)},${round(ry)} 0 ${large} ${dir} ${round(x1)},${round(y1)}`;
344
+ return closed ? `M${round(cx)},${round(cy)} L${round(x0)},${round(y0)} ${arc} Z` : `M${round(x0)},${round(y0)} ${arc}`;
345
+ }
346
+ function kindOf(c) {
347
+ return c.t === K.String ? 'a string' : c.t === K.Pair ? 'a pair' : c.t === K.Integer || c.t === K.Decimal ? 'a number' : 'that';
348
+ }
@@ -0,0 +1,3 @@
1
+ export declare const ICONS: readonly string[];
2
+ /** An icon element, or null when the name is unknown. Icons are decorative unless labelled. */
3
+ export declare function iconNode(name: string, label?: string | null): SVGSVGElement | null;