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,80 @@
1
+ // The rows of a table or list: their fields, the heads and feet of groups
2
+ // among them, and the order a sortable table puts them in. No DOM here, so
3
+ // the tests run it in Node.
4
+ import { K, NONE, ctxFind, canon, intern, spell, text, compare, } from "../core/index.js";
5
+ /** A field of a map! or object! row; map keys may be words or strings. */
6
+ export function rowField(row, sym) {
7
+ if (row.t === K.Object) {
8
+ const i = ctxFind(row.ctx, sym);
9
+ return i < 0 ? NONE : row.ctx.vals[i];
10
+ }
11
+ if (row.t === K.Map) {
12
+ const d = row.s.data;
13
+ const c = canon(sym);
14
+ for (let i = 0; i + 1 < d.length; i += 2) {
15
+ const k = d[i];
16
+ if (k.t === K.Word || k.t === K.SetWord || k.t === K.LitWord) {
17
+ if (canon(k.sym) === c)
18
+ return d[i + 1];
19
+ }
20
+ else if (k.t === K.String && canon(intern(text(k))) === c) {
21
+ return d[i + 1];
22
+ }
23
+ }
24
+ }
25
+ return NONE;
26
+ }
27
+ /**
28
+ * A row of data that heads or closes a group: [head 1 "Title"], whose title may
29
+ * be a text per language, or [foot 1 #(amount: ...)], whose row is shown as the
30
+ * totals are. The level is 1 or 2; 2 is indented.
31
+ */
32
+ export function groupRow(c) {
33
+ if (c.t !== K.Block)
34
+ return null;
35
+ const [w, n, v] = c.s.data.slice(c.i);
36
+ if (w === undefined || n === undefined || v === undefined || w.t !== K.Word || n.t !== K.Integer)
37
+ return null;
38
+ const kind = spell(w.sym).toLowerCase();
39
+ if (kind !== 'head' && kind !== 'foot')
40
+ return null;
41
+ return { kind, level: Number(n.v) >= 2 ? 2 : 1, value: v };
42
+ }
43
+ /** Sorts the rows between the heads and feet of groups, each run on its own; those stay where they are. */
44
+ export function sortGroups(rows, col, desc, language, shows) {
45
+ const out = [];
46
+ let run = [];
47
+ for (const r of rows) {
48
+ if (groupRow(r) === null) {
49
+ run.push(r);
50
+ continue;
51
+ }
52
+ out.push(...sortRows(run, col, desc, language, shows), r);
53
+ run = [];
54
+ }
55
+ return out.concat(sortRows(run, col, desc, language, shows));
56
+ }
57
+ /**
58
+ * Rows by the native value of a column: numbers, amounts and dates by value, texts as
59
+ * the language orders them; empty cells go last either way. Ties keep their order.
60
+ */
61
+ function sortRows(rows, col, desc, language, shows) {
62
+ const collator = new Intl.Collator(language, { numeric: true });
63
+ const blank = (v) => v.t === K.None || (v.t === K.String && text(v) === '');
64
+ const order = (a, b) => {
65
+ if (a.t === K.String && b.t === K.String)
66
+ return collator.compare(text(a), text(b));
67
+ // values that cannot be ordered together (a text and a number) go by what they show
68
+ return compare(a, b) ?? collator.compare(shows(a), shows(b));
69
+ };
70
+ return rows
71
+ .map(row => ({ row, v: rowField(row, col) }))
72
+ .sort((a, b) => {
73
+ const ea = blank(a.v);
74
+ const eb = blank(b.v);
75
+ if (ea || eb)
76
+ return ea === eb ? 0 : ea ? 1 : -1;
77
+ return desc ? order(b.v, a.v) : order(a.v, b.v);
78
+ })
79
+ .map(x => x.row);
80
+ }
@@ -0,0 +1,45 @@
1
+ import { type Cell, type BlockCell, type ObjectCell, type Runtime, type Task, type Series } from '../core/index.ts';
2
+ /** Steps a task runs before the scheduler yields to the host. */
3
+ export declare const SLICE = 10000;
4
+ export interface HostTask {
5
+ readonly id: number;
6
+ readonly task: Task;
7
+ state: 'ready' | 'waiting' | 'done' | 'failed' | 'cancelled';
8
+ result: Cell;
9
+ error: ObjectCell | null;
10
+ /** Aborts the operation the task is waiting on, if any. */
11
+ abort: (() => void) | null;
12
+ /** Called when the task finishes, fails or is cancelled. */
13
+ readonly watchers: Array<(t: HostTask) => void>;
14
+ }
15
+ export interface Scheduler {
16
+ readonly rt: Runtime;
17
+ readonly ready: HostTask[];
18
+ readonly byTask: WeakMap<Task, HostTask>;
19
+ /** Reports errors of tasks nobody waits for. */
20
+ onError: (e: ObjectCell, t: HostTask) => void;
21
+ pumping: boolean;
22
+ live: number;
23
+ /** Called after each round of slices: the browser host syncs the DOM here. */
24
+ afterPump: (() => void) | null;
25
+ }
26
+ /** Stores a host object and returns a handle! cell for it. */
27
+ export declare function makeHandle(kind: string, obj: unknown): Cell;
28
+ export declare function handleOf<T>(c: Cell, kind: string): T | null;
29
+ export declare function dropHandle(c: Cell): void;
30
+ export declare function makeScheduler(rt: Runtime, onError: Scheduler['onError']): Scheduler;
31
+ /** The scheduler running a task's runtime. */
32
+ export declare function schedulerOf(t: Task): Scheduler;
33
+ /** Starts a task for `code` (a block bound to the user context or deeper). */
34
+ export declare function spawn(sch: Scheduler, s: Series<Cell>, i?: number): HostTask;
35
+ /**
36
+ * Runs a handler block as a new task with some words bound to values, e.g.
37
+ * `value` for a message. The block is copied, so handlers never share state.
38
+ */
39
+ export declare function spawnHandler(sch: Scheduler, body: BlockCell, words: Record<string, Cell>): HostTask;
40
+ /** A rejected promise's reason as a Trebol error!. */
41
+ export declare function asError(e: unknown): ObjectCell;
42
+ /** Cancels a task: aborts what it waits on; watchers see a `cancelled` error. */
43
+ export declare function cancelTask(sch: Scheduler, ht: HostTask): void;
44
+ /** A promise for the task's result; rejects with its error. */
45
+ export declare function taskResult(ht: HostTask): Promise<Cell>;
@@ -0,0 +1,173 @@
1
+ // The task scheduler: runs Trebol tasks cooperatively on the JS event loop.
2
+ //
3
+ // Each task runs for a slice of steps, then the scheduler gives control back
4
+ // to the host (browser rendering, network callbacks) before continuing. A
5
+ // task that returns `await` is parked until its promise settles. Event
6
+ // handlers, `spawn` and timers all create new tasks here.
7
+ //
8
+ // Host resources (tasks, sockets, timers) are exposed to Trebol as handle!
9
+ // cells holding only a kind and a numeric id; the objects live in a table
10
+ // here, so no JS object is stored inside a Trebol value.
11
+ import { K, UNSET, intern, newTask, run, resume, resumeError, makeError, bindSeries, copyDeep, context, } from "../core/index.js";
12
+ /** Steps a task runs before the scheduler yields to the host. */
13
+ export const SLICE = 10_000;
14
+ let nextId = 1;
15
+ const resources = new Map();
16
+ /** Stores a host object and returns a handle! cell for it. */
17
+ export function makeHandle(kind, obj) {
18
+ const id = nextId++;
19
+ resources.set(id, obj);
20
+ return { t: K.Handle, p: { kind, id } };
21
+ }
22
+ export function handleOf(c, kind) {
23
+ if (c.t !== K.Handle)
24
+ return null;
25
+ const h = c.p;
26
+ return h.kind === kind ? resources.get(h.id) ?? null : null;
27
+ }
28
+ export function dropHandle(c) {
29
+ if (c.t === K.Handle)
30
+ resources.delete(c.p.id);
31
+ }
32
+ const schedulers = new WeakMap();
33
+ export function makeScheduler(rt, onError) {
34
+ const sch = { rt, ready: [], byTask: new WeakMap(), onError, pumping: false, live: 0, afterPump: null };
35
+ schedulers.set(rt, sch);
36
+ return sch;
37
+ }
38
+ /** The scheduler running a task's runtime. */
39
+ export function schedulerOf(t) {
40
+ const sch = schedulers.get(t.rt);
41
+ // Host natives only run inside a scheduler; anything else is a host bug.
42
+ if (sch === undefined)
43
+ throw new Error('no scheduler for this runtime');
44
+ return sch;
45
+ }
46
+ /** Starts a task for `code` (a block bound to the user context or deeper). */
47
+ export function spawn(sch, s, i = 0) {
48
+ const task = newTask(sch.rt, s, i);
49
+ const ht = { id: nextId++, task, state: 'ready', result: UNSET, error: null, abort: null, watchers: [] };
50
+ sch.byTask.set(task, ht);
51
+ sch.live++;
52
+ sch.ready.push(ht);
53
+ schedule(sch);
54
+ return ht;
55
+ }
56
+ /**
57
+ * Runs a handler block as a new task with some words bound to values, e.g.
58
+ * `value` for a message. The block is copied, so handlers never share state.
59
+ */
60
+ export function spawnHandler(sch, body, words) {
61
+ const names = Object.keys(words);
62
+ const s = copyDeep(body.s, body.i);
63
+ if (names.length > 0) {
64
+ const ctx = context(names.map(n => intern(n)), names.map(n => words[n]));
65
+ bindSeries(s, ctx);
66
+ }
67
+ return spawn(sch, s, 0);
68
+ }
69
+ /**
70
+ * Runs `fn` after the host had a chance to do its own work (render, I/O).
71
+ * setImmediate where it exists (Node); a MessageChannel in browsers, which
72
+ * unlike setTimeout(0) is not clamped to 4 ms.
73
+ */
74
+ const defer = (() => {
75
+ const g = globalThis;
76
+ if (typeof g.setImmediate === 'function')
77
+ return (fn) => void g.setImmediate(fn);
78
+ if (typeof MessageChannel === 'undefined')
79
+ return (fn) => void setTimeout(fn, 0);
80
+ const ch = new MessageChannel();
81
+ const queue = [];
82
+ ch.port1.onmessage = () => queue.shift()?.();
83
+ return (fn) => {
84
+ queue.push(fn);
85
+ ch.port2.postMessage(null);
86
+ };
87
+ })();
88
+ function schedule(sch) {
89
+ if (sch.pumping)
90
+ return;
91
+ sch.pumping = true;
92
+ defer(() => pump(sch));
93
+ }
94
+ function finish(sch, ht, state) {
95
+ ht.state = state;
96
+ ht.abort = null;
97
+ sch.live--;
98
+ if (state === 'failed' && ht.watchers.length === 0)
99
+ sch.onError(ht.error, ht);
100
+ for (const w of ht.watchers.splice(0))
101
+ w(ht);
102
+ }
103
+ /** Runs ready tasks, one slice each, until none is ready; then yields. */
104
+ function pump(sch) {
105
+ sch.pumping = false;
106
+ const batch = sch.ready.splice(0);
107
+ for (const ht of batch) {
108
+ if (ht.state !== 'ready')
109
+ continue;
110
+ const r = run(ht.task, SLICE);
111
+ switch (r.k) {
112
+ case 'done':
113
+ ht.result = r.v;
114
+ finish(sch, ht, 'done');
115
+ break;
116
+ case 'error':
117
+ ht.error = r.e;
118
+ finish(sch, ht, 'failed');
119
+ break;
120
+ case 'yield':
121
+ sch.ready.push(ht);
122
+ break;
123
+ case 'await':
124
+ ht.state = 'waiting';
125
+ r.p.then(v => {
126
+ if (ht.state !== 'waiting')
127
+ return;
128
+ ht.abort = null;
129
+ resume(ht.task, v);
130
+ ht.state = 'ready';
131
+ sch.ready.push(ht);
132
+ schedule(sch);
133
+ }, (e) => {
134
+ if (ht.state !== 'waiting')
135
+ return;
136
+ ht.abort = null;
137
+ resumeError(ht.task, asError(e));
138
+ ht.state = 'ready';
139
+ sch.ready.push(ht);
140
+ schedule(sch);
141
+ });
142
+ break;
143
+ }
144
+ }
145
+ sch.afterPump?.();
146
+ if (sch.ready.length > 0)
147
+ schedule(sch);
148
+ }
149
+ /** A rejected promise's reason as a Trebol error!. */
150
+ export function asError(e) {
151
+ if (typeof e === 'object' && e !== null && e.t === K.Error)
152
+ return e;
153
+ const msg = e instanceof Error ? e.message : String(e);
154
+ return makeError('access', 'host', msg);
155
+ }
156
+ /** Cancels a task: aborts what it waits on; watchers see a `cancelled` error. */
157
+ export function cancelTask(sch, ht) {
158
+ if (ht.state === 'done' || ht.state === 'failed' || ht.state === 'cancelled')
159
+ return;
160
+ ht.abort?.();
161
+ ht.error = makeError('access', 'cancelled', 'the task was cancelled');
162
+ finish(sch, ht, 'cancelled');
163
+ }
164
+ /** A promise for the task's result; rejects with its error. */
165
+ export function taskResult(ht) {
166
+ return new Promise((resolve, reject) => {
167
+ const settle = (t) => (t.state === 'done' ? resolve(t.result) : reject(t.error ?? makeError('access', 'cancelled', 'the task was cancelled')));
168
+ if (ht.state === 'done' || ht.state === 'failed' || ht.state === 'cancelled')
169
+ settle(ht);
170
+ else
171
+ ht.watchers.push(settle);
172
+ });
173
+ }
@@ -0,0 +1,58 @@
1
+ /** modern: today's flat controls; classic recalls Rebol/View, cupertino the Mac, fusion Qt, fluent Windows 11. */
2
+ export type Skin = 'modern' | 'classic' | 'cupertino' | 'fusion' | 'fluent';
3
+ export interface ThemeParams {
4
+ /** Hue of the primary color, 0-360. */
5
+ base: number;
6
+ /** Hue of the accent color, 0-360. */
7
+ accent: number;
8
+ neutral: 'cool' | 'neutral' | 'warm';
9
+ density: 'compact' | 'normal' | 'comfortable';
10
+ radius: 'sharp' | 'soft' | 'round';
11
+ font: string;
12
+ /** Font of titles and headings; the same as `font` if it is not given. */
13
+ headings: string | null;
14
+ mode: 'light' | 'dark' | 'auto';
15
+ /** How much color the primary and accent have, 0-1; 0 is black and white. */
16
+ color: number;
17
+ /** Thickness of borders, in px. */
18
+ line: 1 | 2;
19
+ /** Whether panels and buttons cast a shadow. */
20
+ depth: 'flat' | 'soft' | 'lifted';
21
+ /** How the same icons are drawn. */
22
+ icons: 'fine' | 'round' | 'sharp' | 'bold';
23
+ /** How the controls are built: see SKINS. */
24
+ skin: Skin;
25
+ }
26
+ export declare const DEFAULT_THEME: ThemeParams;
27
+ /** The theme parameters that take a word, and the words each takes. */
28
+ export declare const THEME_WORDS: Record<string, readonly string[]>;
29
+ /** The looks: complete sets of parameters with a name. `theme [look: civic base: 200]` starts from one. */
30
+ export declare const LOOKS: Record<string, Partial<ThemeParams>>;
31
+ export interface Oklch {
32
+ l: number;
33
+ c: number;
34
+ h: number;
35
+ }
36
+ /** Roles every theme defines, for both modes. */
37
+ export declare const ROLES: readonly ["bg", "surface", "raised", "border", "border-strong", "text", "muted", "primary", "primary-hover", "on-primary", "accent", "on-accent", "danger", "on-danger", "success", "warning", "focus"];
38
+ export type Role = (typeof ROLES)[number];
39
+ /** Text/background pairs that must reach WCAG AA (4.5:1). */
40
+ export declare const CONTRAST_PAIRS: ReadonlyArray<[Role, Role]>;
41
+ /** The palette for one mode. Lightness values are fixed; hues come from the theme. */
42
+ export declare function palette(t: ThemeParams, dark: boolean): Record<Role, Oklch>;
43
+ /** Linear sRGB of an OKLCH color, clamped to the gamut. */
44
+ export declare function toLinearRgb({ l, c, h }: Oklch): [number, number, number];
45
+ export declare function luminance(c: Oklch): number;
46
+ /** WCAG contrast ratio between two colors. */
47
+ export declare function contrast(x: Oklch, y: Oklch): number;
48
+ /** Luminance of `c` at `alpha` over a pixel of gray `px` (0 black, 1 white), blended as browsers do. */
49
+ export declare function luminanceOver(c: Oklch, alpha: number, px: number): number;
50
+ /** The worst contrast of `fg` on the background at `alpha` over any image: a black or a white one. */
51
+ export declare function contrastOverImage(fg: Oklch, bg: Oklch, alpha: number): number;
52
+ /**
53
+ * The alpha of the veil over a backdrop: the least that keeps text AA on any image. Muted text would
54
+ * need a veil almost opaque, so on a backdrop it takes the color of the text.
55
+ */
56
+ export declare function scrimAlpha(p: Record<Role, Oklch>): number;
57
+ /** The full stylesheet for a theme: tokens, then the fixed component rules. */
58
+ export declare function themeCss(t: ThemeParams): string;