@aliens-syndicate/cli 0.1.6 → 0.1.8

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/tools/runtime.mjs CHANGED
@@ -1,28 +1,228 @@
1
- // The .logic reaches tags only by id: bind: lists each id with what a signal sets on it.
2
- const instances = new Map();
3
- for (const root of document.querySelectorAll('[data-element]')) {
4
- const entry = logic[root.dataset.element];
5
- if (!entry) continue;
6
- const element = id => {
7
- if (id && root.id === id) return root;
8
- for (const node of root.querySelectorAll('[id]')) {
9
- if (node.id === id && node.closest('[data-element]') === root) return node;
1
+ // Reactive core. Reading a signal or a computed inside a bind, computed, effect or watch records that reader; a write
2
+ // runs again only the readers of that value. Writes inside batch() wait for its end, and every action runs in one, so
3
+ // a click updates each tag once. Binds run before effects and watches. Writes outside a batch, like in a setTimeout,
4
+ // update the page at once.
5
+ let reader = null;
6
+ let batchDepth = 0;
7
+ const queues = [new Set(), new Set()];
8
+
9
+ function track(readers) {
10
+ if (!reader) return;
11
+ readers.add(reader);
12
+ reader.sources.add(readers);
13
+ }
14
+
15
+ function notify(readers) {
16
+ for (const dependent of [...readers]) dependent.stale();
17
+ if (!batchDepth) flush();
18
+ }
19
+
20
+ function tracked(self, read, target, ...args) {
21
+ for (const readers of self.sources) readers.delete(self);
22
+ self.sources.clear();
23
+ const previous = reader;
24
+ reader = self;
25
+ try { return read.apply(target, args); } finally { reader = previous; }
26
+ }
27
+
28
+ function untracked(read, target, ...args) {
29
+ const previous = reader;
30
+ reader = null;
31
+ try { return read.apply(target, args); } finally { reader = previous; }
32
+ }
33
+
34
+ function batch(update) {
35
+ batchDepth++;
36
+ try { return update(); } finally { if (--batchDepth === 0) flush(); }
37
+ }
38
+
39
+ function flush() {
40
+ batchDepth++;
41
+ const runs = new Map();
42
+ try {
43
+ for (let round = 0; queues[0].size || queues[1].size; round++) {
44
+ // Binds never write, so a loop comes from the effect or watch that ran the most.
45
+ if (round === 100) {
46
+ const [loop] = [...runs].filter(([effect]) => effect.priority).sort((left, right) => right[1] - left[1])[0];
47
+ throw new Error(`Aliens: ${loop.label} keeps changing the values it reads.`);
48
+ }
49
+ const queue = queues[0].size ? queues[0] : queues[1];
50
+ const current = [...queue];
51
+ queue.clear();
52
+ for (const effect of current) {
53
+ runs.set(effect, (runs.get(effect) ?? 0) + 1);
54
+ effect.execute();
55
+ }
56
+ }
57
+ } catch (error) {
58
+ for (const queue of queues) queue.clear();
59
+ throw error;
60
+ } finally {
61
+ batchDepth--;
62
+ }
63
+ }
64
+
65
+ function defineSignal(target, name) {
66
+ let value = target[name];
67
+ const readers = new Set();
68
+ Object.defineProperty(target, name, {
69
+ enumerable: true,
70
+ get() { track(readers); return value; },
71
+ set(next) {
72
+ if (Object.is(next, value)) return;
73
+ value = next;
74
+ notify(readers);
75
+ }
76
+ });
77
+ }
78
+
79
+ // A computed recalculates on the next read after one of its values changes, never on the write itself.
80
+ function defineComputed(target, name, read, label) {
81
+ const readers = new Set();
82
+ const self = {
83
+ sources: new Set(), dirty: true, running: false, value: undefined,
84
+ stale() {
85
+ if (self.dirty) return;
86
+ self.dirty = true;
87
+ for (const dependent of [...readers]) dependent.stale();
88
+ }
89
+ };
90
+ Object.defineProperty(target, name, {
91
+ enumerable: true,
92
+ get() {
93
+ if (self.running) throw new Error(`Aliens: ${label} reads itself.`);
94
+ if (self.dirty) {
95
+ self.running = true;
96
+ try { self.value = tracked(self, read, target); } finally { self.running = false; }
97
+ self.dirty = false;
98
+ }
99
+ track(readers);
100
+ return self.value;
101
+ },
102
+ set() { throw new Error(`Aliens: ${label} is computed; change the signals it reads.`); }
103
+ });
104
+ }
105
+
106
+ // priority 0 is a bind, 1 an effect or a watch. stop() forgets what it read, so it never runs again.
107
+ function createEffect(label, priority, execute) {
108
+ const self = {
109
+ label, priority, sources: new Set(), stopped: false,
110
+ stale() { if (!self.stopped) queues[priority].add(self); },
111
+ execute: () => { if (!self.stopped) execute(self); },
112
+ stop() {
113
+ self.stopped = true;
114
+ for (const readers of self.sources) readers.delete(self);
115
+ self.sources.clear();
116
+ queues[priority].delete(self);
10
117
  }
11
- throw new Error(`Aliens: ID "${id}" not found in Element "${root.dataset.element}".`);
12
118
  };
13
- const state = entry.create(element);
14
- instances.set(root, { state, actions: entry.actions, page: entry.page, binds: entry.bind.map(([id, name, read]) => ({ node: element(id), name, read })) });
119
+ self.execute();
120
+ return self;
15
121
  }
16
122
 
17
- // A .logic without .markup runs once for the whole page. Markup calls it with action="element.action".
18
- const standalone = new Map();
19
- for (const [name, entry] of Object.entries(logic)) {
20
- if (!entry.standalone) continue;
21
- const state = entry.create(id => { throw new Error(`Aliens: ${name} has no markup, so it has no tag "${id}".`); });
22
- const instance = { state, actions: entry.actions, page: entry.page, binds: [] };
23
- standalone.set(name, instance);
24
- instances.set(`logic:${name}`, instance);
123
+ // The hook that @aliens-syndicate/reactive receives: from(() => this.query) calls next now and on every change.
124
+ function observe(read, next) {
125
+ const effect = createEffect('stream from()', 1, self => {
126
+ const value = tracked(self, read);
127
+ untracked(next, null, value);
128
+ });
129
+ return () => effect.stop();
25
130
  }
131
+ const streamTools = typeof reactiveStreams === 'function' ? reactiveStreams(observe) : null;
132
+
133
+ // A stream member holds the latest value its stream emitted; it reads like a signal and can't be assigned.
134
+ function defineStream(target, name, create, label) {
135
+ let value;
136
+ const readers = new Set();
137
+ Object.defineProperty(target, name, {
138
+ enumerable: true,
139
+ get() { track(readers); return value; },
140
+ set() { throw new Error(`Aliens: ${label} comes from its stream; change what the stream reads.`); }
141
+ });
142
+ const stream = streamTools.from(create.call(target, streamTools));
143
+ stream.subscribe({
144
+ next(next) {
145
+ if (Object.is(next, value)) return;
146
+ value = next;
147
+ notify(readers);
148
+ },
149
+ error(error) {
150
+ reportError(new Error(`Aliens: ${label} failed: ${error?.message ?? error}`, { cause: error }));
151
+ }
152
+ });
153
+ }
154
+
155
+ function applyBind(node, name, value) {
156
+ if (name === 'text') node.textContent = String(value);
157
+ // toggleAttribute also reaches the svg of an icon tag, which has no hidden property.
158
+ if (name === 'show') node.toggleAttribute('hidden', !value);
159
+ if (name === 'pressed' || name === 'expanded') node.setAttribute('aria-' + name, String(Boolean(value)));
160
+ if (name.startsWith('_')) node.classList.toggle(node.id + name, Boolean(value));
161
+ }
162
+
163
+ // Turns what entry.create returns into a live instance: signals and computed become reactive properties, each bind
164
+ // updates its tag, an effect runs now and again when what it read changes, and a watch runs when its value changes.
165
+ function activate(name, entry, element) {
166
+ const { state, computed, streams, effects, watches } = entry.create(element);
167
+ for (const field of entry.signals) defineSignal(state, field);
168
+ for (const [field, read] of computed) defineComputed(state, field, read, `${name}.logic computed ${field}`);
169
+ for (const [field, create] of streams) defineStream(state, field, create, `${name}.logic stream ${field}`);
170
+ const binds = entry.bind.map(([id, kind, read]) => ({ node: element(id), kind, read }));
171
+ for (const { node, kind, read } of binds) {
172
+ createEffect(`${name}.logic bind ${node.id}`, 0, self => applyBind(node, kind, tracked(self, read, state)));
173
+ }
174
+ for (const [label, body, cleanup] of effects) {
175
+ let ran = false;
176
+ createEffect(`${name}.logic effect ${label}`, 1, self => {
177
+ if (ran && cleanup) untracked(cleanup, state);
178
+ ran = true;
179
+ tracked(self, body, state);
180
+ });
181
+ }
182
+ for (const [target, body, cleanup] of watches) {
183
+ let previous;
184
+ let ran = false;
185
+ createEffect(`${name}.logic watch ${target}`, 1, self => {
186
+ const value = tracked(self, () => state[target]);
187
+ if (!ran || Object.is(value, previous)) {
188
+ ran = true;
189
+ previous = value;
190
+ return;
191
+ }
192
+ if (cleanup) untracked(cleanup, state);
193
+ const before = previous;
194
+ previous = value;
195
+ untracked(body, state, before);
196
+ });
197
+ }
198
+ return { state, actions: entry.actions, page: entry.page };
199
+ }
200
+
201
+ // The .logic reaches tags only by id: bind: lists each id with what a signal sets on it.
202
+ const instances = new Map();
203
+ const standalone = new Map();
204
+ batch(() => {
205
+ for (const root of document.querySelectorAll('[data-element]')) {
206
+ const entry = logic[root.dataset.element];
207
+ if (!entry) continue;
208
+ const element = id => {
209
+ if (id && root.id === id) return root;
210
+ for (const node of root.querySelectorAll('[id]')) {
211
+ if (node.id === id && node.closest('[data-element]') === root) return node;
212
+ }
213
+ throw new Error(`Aliens: ID "${id}" not found in Element "${root.dataset.element}".`);
214
+ };
215
+ instances.set(root, activate(root.dataset.element, entry, element));
216
+ }
217
+
218
+ // A .logic without .markup runs once for the whole page. Markup calls it with action="element.action".
219
+ for (const [name, entry] of Object.entries(logic)) {
220
+ if (!entry.standalone) continue;
221
+ const instance = activate(name, entry, id => { throw new Error(`Aliens: ${name} has no markup, so it has no tag "${id}".`); });
222
+ standalone.set(name, instance);
223
+ instances.set(`logic:${name}`, instance);
224
+ }
225
+ });
26
226
 
27
227
  function owner(node, accepts) {
28
228
  let element = node.closest('[data-element]');
@@ -33,19 +233,6 @@ function owner(node, accepts) {
33
233
  }
34
234
  }
35
235
 
36
- function render(instance) {
37
- for (const current of instance ? [instance] : instances.values()) {
38
- for (const { node, name, read } of current.binds) {
39
- const value = read.call(current.state);
40
- if (name === 'text') node.textContent = String(value);
41
- // toggleAttribute also reaches the svg of an icon tag, which has no hidden property.
42
- if (name === 'show') node.toggleAttribute('hidden', !value);
43
- if (name === 'pressed' || name === 'expanded') node.setAttribute('aria-' + name, String(Boolean(value)));
44
- if (name.startsWith('_')) node.classList.toggle(node.id + name, Boolean(value));
45
- }
46
- }
47
- }
48
-
49
236
  const supported = Object.keys(languages);
50
237
  const localeKey = 'aliens-docs-locale';
51
238
  const themeKey = 'aliens-docs-theme';
@@ -145,16 +332,13 @@ function applyTheme(name, persist = false) {
145
332
  getComputedStyle(document.documentElement).getPropertyValue('--color-canvas').trim() ||
146
333
  (theme === 'dark' ? '#000000' : '#ffffff');
147
334
  for (const picker of themePickers) picker.value = theme;
148
- if (themeModel) {
149
- themeModel.state[themeField] = theme === 'dark';
150
- render(themeModel);
151
- }
335
+ if (themeModel) themeModel.state[themeField] = theme === 'dark';
152
336
  if (persist) savePreference(themeKey, theme);
153
337
  }
154
338
 
155
339
  // Short fragments from older links: #logic opens logic-guide, #mock opens type-index-mock.
156
340
  const shortViews = new Map([['home', 'home-guide'], ['logic', 'logic-guide'], ['markup', 'markup-reference'], ['search', 'site-search']]);
157
- const legacyViews = new Map([...shortViews, ['style-kit', 'kit-overview'], ['styles', 'type-index-style'], ['mockup', 'type-index-mock']]);
341
+ const legacyViews = new Map([...shortViews, ['style-kit', 'kit-overview'], ['style-docs', 'utilities-docs'], ['styles', 'type-index-style'], ['mockup', 'type-index-mock']]);
158
342
  // The search shows a view by its short name: type-index-agent is .agent, logic-guide is .logic.
159
343
  function shortName(id) {
160
344
  for (const [short, full] of shortViews) if (full === id) return short;
@@ -437,6 +621,7 @@ function resolveView(id) {
437
621
  return legacy ? document.getElementById(legacy) : direct;
438
622
  }
439
623
 
624
+ const consoleBadge = 'color: #fff; background: #111; padding: 1px 6px; border-radius: 4px';
440
625
  function showView({ scroll = false } = {}) {
441
626
  const fragment = location.hash.slice(1);
442
627
  let id = fragment;
@@ -444,6 +629,9 @@ function showView({ scroll = false } = {}) {
444
629
  const target = resolveView(id);
445
630
  const requested = target?.closest('[data-view]') ?? views[0];
446
631
  for (const view of views) view.hidden = view !== requested;
632
+ if (consoleCode && requested && consoleCode.views[requested.id]) {
633
+ console.log(`%cAliens%c ${location.href} → ${location.origin}/${consoleCode.views[requested.id]}`, consoleBadge, '');
634
+ }
447
635
  for (const link of navigation) {
448
636
  // A short fragment such as #search marks its link as current like the full view id does.
449
637
  if (link.hash === '#' + requested?.id || shortViews.get(link.hash.slice(1)) === requested?.id) link.setAttribute('aria-current', 'page');
@@ -479,8 +667,7 @@ document.addEventListener('click', event => {
479
667
  const [scope, method] = control.dataset.action.includes('.') ? control.dataset.action.split('.') : [null, control.dataset.action];
480
668
  const handler = scope ? standalone.get(scope) : owner(control, ({ actions }) => actions.includes(method));
481
669
  if (!handler?.actions.includes(method)) throw new Error(`Aliens: unbound action "${control.dataset.action}".`);
482
- handler.state[method]();
483
- render(handler);
670
+ batch(() => handler.state[method]());
484
671
  if (handler === localeModel && supported.includes(localeModel.state[localeField])) {
485
672
  const updatedLocale = localeModel.state[localeField];
486
673
  applyLocale(updatedLocale);
@@ -496,7 +683,31 @@ document.addEventListener('click', event => {
496
683
  const initialLocale = preferredLocale();
497
684
  if (localeModel) localeModel.state[localeField] = initialLocale;
498
685
  applyTheme(preference(themeKey) ?? 'light');
499
- render();
500
686
  applyLocale(initialLocale);
501
687
  showView({ scroll: Boolean(location.hash) });
502
688
  window.addEventListener('hashchange', () => showView({ scroll: true }));
689
+
690
+ // console: in .config (local: and dev:, true by default). Each Space file of the page becomes a file of the browser
691
+ // tools (Sources, searchable with Cmd+Option+F or Ctrl+Shift+F) at its project path, with the same line numbers; the
692
+ // console lists them, colored like the editor, and names the .markup of every view the address opens.
693
+ if (consoleCode) {
694
+ const colors = consoleCode.colors[matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'];
695
+ for (const [file, code] of consoleCode.files) {
696
+ // A script that is only a comment runs nothing; sourceURL gives it the path of the Space file.
697
+ (0, eval)(`/* ${code.replace(/[\uE000-\uE0FF]/g, '').replaceAll('*/', '*\\/')}\n*/\n//# sourceURL=${location.origin}/${file}`);
698
+ }
699
+ console.groupCollapsed(`%cAliens%c ${consoleCode.files.length} Space files · Sources > ${location.host}`, consoleBadge, '');
700
+ for (const [file, code] of consoleCode.files) {
701
+ // Each \uE001 + n in the code switches to colors[n] and \uE000 back to plain text (see consoleCode in build.mjs).
702
+ const styles = [];
703
+ const text = code.replaceAll('%', '%%').replace(/[\uE000-\uE0FF]/g, marker => {
704
+ const color = colors[marker.charCodeAt(0) - 0xE001];
705
+ styles.push(color ? `color: ${color}` : '');
706
+ return '%c';
707
+ });
708
+ console.groupCollapsed(file);
709
+ console.log(text, ...styles);
710
+ console.groupEnd();
711
+ }
712
+ console.groupEnd();
713
+ }
@@ -8,5 +8,5 @@ Rule Architecture
8
8
  # Compose atoms into molecules, organisms, and templates. A reusable Element does not depend on a page.
9
9
  # Keep the .markup, .logic, .style, and .test files of an Element together in its folder.
10
10
  # Use .style for element stylesheets and the global layers declared in project/styles/main.style.
11
- # In .style, write plain CSS as property: value. Utility class names, like flex gap-4 md:flex-row, need npm install @aliens-syndicate/utilities and utilities: from: @aliens-syndicate/utilities in .config.
12
- # Ready-made Elements, like ui-button and ui-card, need npm install @aliens-syndicate/elements and elements: from: @aliens-syndicate/elements in .config; ai/.map then lists them.
11
+ # In .style, write plain CSS as property: value. Utility class names, like flex gap-4 md:flex-row, need npm install @aliens-syndicate/utilities and devDependencies: utilities: from: @aliens-syndicate/utilities in .config.
12
+ # Ready-made Elements, like ui-button and ui-card, need npm install @aliens-syndicate/elements and dependencies: elements: from: @aliens-syndicate/elements in .config; ai/.map then lists them.