@yaks/render 0.0.0-stage → 0.2.36

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 (53) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +396 -2
  3. package/_dist/archetype.d.ts +3 -0
  4. package/_dist/archetype.d.ts.map +1 -0
  5. package/_dist/component.d.ts +15 -0
  6. package/_dist/component.d.ts.map +1 -0
  7. package/_dist/edit.d.ts +17 -0
  8. package/_dist/edit.d.ts.map +1 -0
  9. package/_dist/host.d.ts +59 -0
  10. package/_dist/host.d.ts.map +1 -0
  11. package/_dist/mod.d.ts +72 -0
  12. package/_dist/mod.d.ts.map +1 -0
  13. package/_dist/namespace.d.ts +12 -0
  14. package/_dist/namespace.d.ts.map +1 -0
  15. package/_dist/prepare.d.ts +11 -0
  16. package/_dist/prepare.d.ts.map +1 -0
  17. package/_dist/types.d.ts +66 -0
  18. package/_dist/types.d.ts.map +1 -0
  19. package/_dist/views.d.ts +88 -0
  20. package/_dist/views.d.ts.map +1 -0
  21. package/archetype.js +56 -0
  22. package/archetype.js.map +1 -0
  23. package/archetype.ts +76 -0
  24. package/component.js +39 -0
  25. package/component.js.map +1 -0
  26. package/component.ts +84 -0
  27. package/deno.json +1 -0
  28. package/edit.js +88 -0
  29. package/edit.js.map +1 -0
  30. package/edit.ts +113 -0
  31. package/host.js +191 -0
  32. package/host.js.map +1 -0
  33. package/host.ts +277 -0
  34. package/mod.js +158 -0
  35. package/mod.js.map +1 -0
  36. package/mod.ts +328 -0
  37. package/namespace.js +90 -0
  38. package/namespace.js.map +1 -0
  39. package/namespace.ts +121 -0
  40. package/package.json +31 -4
  41. package/prepare.js +32 -0
  42. package/prepare.js.map +1 -0
  43. package/prepare.ts +55 -0
  44. package/prop.js +37 -0
  45. package/prop.js.map +1 -0
  46. package/prop.ts +46 -0
  47. package/types.js +7 -0
  48. package/types.js.map +1 -0
  49. package/types.ts +116 -0
  50. package/views.js +333 -0
  51. package/views.js.map +1 -0
  52. package/views.ts +389 -0
  53. package/vocab.json +29 -0
package/edit.js ADDED
@@ -0,0 +1,88 @@
1
+ /** Property actions parse input without touching a store or a rendering
2
+ * backend. */ import { declared, writable } from "./prop.js";
3
+ let fail = (c, expected)=>{
4
+ throw new Error(`${c.comp}.${c.prop} needs ${expected}`);
5
+ };
6
+ let decimal = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
7
+ let parse = (input, c)=>{
8
+ if (input == null) return null;
9
+ let type = c.category == 'scalar' ? c.scalar : c.category;
10
+ // Empty text remains text; an empty optional scalar clears its property.
11
+ if (input === '' && ![
12
+ 'text',
13
+ 'url',
14
+ 'query',
15
+ 'json'
16
+ ].includes(type) && !(type == 'enum' && c.values.includes(''))) {
17
+ return null;
18
+ }
19
+ if (type == 'number' || type == 'priority') {
20
+ let text = typeof input == 'string' || typeof input == 'number' ? String(input).trim() : '';
21
+ if (type == 'priority') text = text.replace(/^p/i, '');
22
+ return decimal.test(text) && Number.isFinite(Number(text)) ? Number(text) : fail(c, 'a finite decimal number');
23
+ }
24
+ if (type == 'bool') {
25
+ if (input === true || input === 1 || input === 'true' || input === '1') {
26
+ return true;
27
+ }
28
+ if (input === false || input === 0 || input === 'false' || input === '0') {
29
+ return false;
30
+ }
31
+ return fail(c, 'a boolean');
32
+ }
33
+ // A JSON value is edited as its JSON text, and a value already parsed
34
+ // passes as it is; `check` holds it to the declared types.
35
+ if (type == 'jsonb') {
36
+ if (typeof input != 'string') return input;
37
+ try {
38
+ return JSON.parse(input);
39
+ } catch {
40
+ return fail(c, 'JSON');
41
+ }
42
+ }
43
+ if (typeof input != 'string') return fail(c, 'text');
44
+ if (type == 'enum') {
45
+ if (c.values.includes(input)) return input;
46
+ let text = input.trim().toLowerCase();
47
+ let alias = Object.entries(c.aliases ?? {}).find(([key])=>key.toLowerCase() == text)?.[1];
48
+ return c.values.find((v)=>String(v).toLowerCase() == (alias ?? text).toLowerCase()) ?? fail(c, `one of ${c.values.join(', ')}`);
49
+ }
50
+ if (type == 'ref') return input.trim() || fail(c, 'an entity id');
51
+ if (type == 'time') {
52
+ // Explicit offsets keep the instant from shifting with the local timezone.
53
+ let text = input.trim();
54
+ let stamp = /^\d{4}-\d\d-\d\dT(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|[+-]\d\d:\d\d)$/i;
55
+ let time = Date.parse(text);
56
+ let day = text.slice(0, 10);
57
+ // Date.parse normalizes February 31 into March; a timestamp must name an
58
+ // existing calendar day before its timezone offset is applied.
59
+ return stamp.test(text) && Number.isFinite(time) && new Date(`${day}T00:00:00Z`).toISOString().slice(0, 10) == day ? new Date(time).toISOString() : fail(c, 'an ISO timestamp with a timezone');
60
+ }
61
+ return input;
62
+ };
63
+ /**
64
+ * Offer a single-property patch. Construction is inert; run parses, validates
65
+ * and returns only that property. The caller decides whether to apply the patch.
66
+ */ export let edit = (vocab, address, options = {})=>{
67
+ let c = declared(vocab, address);
68
+ return {
69
+ name: `set ${c.comp}.${c.prop}`,
70
+ run: (bundle, input)=>{
71
+ if (!writable(vocab, c)) {
72
+ throw new Error(`${c.comp}.${c.prop} is read-only`);
73
+ }
74
+ let value = (options.parse ?? parse)(input, c, bundle);
75
+ let errors = vocab.check(c.comp, {
76
+ [c.prop]: value
77
+ });
78
+ if (errors.length) throw new Error(errors.join('; '));
79
+ options.validate?.(value, c, bundle);
80
+ return {
81
+ [c.comp]: {
82
+ [c.prop]: value
83
+ }
84
+ };
85
+ }
86
+ };
87
+ };
88
+ //# sourceMappingURL=edit.js.map
package/edit.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edit.js","sources":["./edit.ts"],"names":[],"mappings":"AAAA;YACY,GAIZ,SAAS,QAAQ,EAAE,QAAQ,oBAAmB;AAW9C,IAAI,OAAO,CAAC,GAAS;EACnB,MAAM,IAAI,MAAM,GAAG,EAAE,IAAI,CAAC,CAAC,EAAE,EAAE,IAAI,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IAAI,EAAE;QAAE,CAAC,EAAE,IAAI,CAAC,EAAE;MAAM;MACnD,IAAI,OAAO,MAAM,EAAE,MAAM,IAAI,MAAM,OAAO,IAAI,CAAC;MAC/C,QAAQ,QAAQ,GAAG,OAAO,GAAG;MAC7B,OAAO;QAAE,CAAC,EAAE,IAAI,CAAC,EAAE;UAAE,CAAC,EAAE,IAAI,CAAC,EAAE;QAAM;MAAE;IACzC;EACF;AACF,EAAC"}
package/edit.ts ADDED
@@ -0,0 +1,113 @@
1
+ /** Property actions parse input without touching a store or a rendering
2
+ * backend. */
3
+
4
+ import type { Bundle } from 'jsr:@yaks/match@0.2.36'
5
+ import type { Prop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
6
+ import { declared, writable } from './prop.js'
7
+ import type { Action } from './types.ts'
8
+
9
+ /** Applications may supply their value language and additional validation. */
10
+ export type EditOptions = {
11
+ parse?: (input: unknown, prop: Prop, bundle: Bundle) => unknown
12
+ validate?: (value: unknown, prop: Prop, bundle: Bundle) => void
13
+ }
14
+
15
+ type Address = { comp: string; prop: string }
16
+
17
+ let fail = (c: Prop, expected: string): never => {
18
+ throw new Error(`${c.comp}.${c.prop} needs ${expected}`)
19
+ }
20
+
21
+ let decimal = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i
22
+
23
+ let parse = (input: unknown, c: Prop): unknown => {
24
+ if (input == null) return null
25
+ let type = c.category == 'scalar' ? c.scalar : c.category
26
+ // Empty text remains text; an empty optional scalar clears its property.
27
+ if (
28
+ input === '' && !['text', 'url', 'query', 'json'].includes(type!) &&
29
+ !(type == 'enum' && c.values!.includes(''))
30
+ ) {
31
+ return null
32
+ }
33
+ if (type == 'number' || type == 'priority') {
34
+ let text = typeof input == 'string' || typeof input == 'number'
35
+ ? String(input).trim()
36
+ : ''
37
+ if (type == 'priority') text = text.replace(/^p/i, '')
38
+ return decimal.test(text) && Number.isFinite(Number(text))
39
+ ? Number(text)
40
+ : fail(c, 'a finite decimal number')
41
+ }
42
+ if (type == 'bool') {
43
+ if (input === true || input === 1 || input === 'true' || input === '1') {
44
+ return true
45
+ }
46
+ if (input === false || input === 0 || input === 'false' || input === '0') {
47
+ return false
48
+ }
49
+ return fail(c, 'a boolean')
50
+ }
51
+ // A JSON value is edited as its JSON text, and a value already parsed
52
+ // passes as it is; `check` holds it to the declared types.
53
+ if (type == 'jsonb') {
54
+ if (typeof input != 'string') return input
55
+ try {
56
+ return JSON.parse(input)
57
+ } catch {
58
+ return fail(c, 'JSON')
59
+ }
60
+ }
61
+ if (typeof input != 'string') return fail(c, 'text')
62
+ if (type == 'enum') {
63
+ if (c.values!.includes(input)) return input
64
+ let text = input.trim().toLowerCase()
65
+ let alias = Object.entries(c.aliases ?? {})
66
+ .find(([key]) => key.toLowerCase() == text)?.[1]
67
+ return c.values!.find((v) =>
68
+ String(v).toLowerCase() == (alias ?? text).toLowerCase()
69
+ ) ??
70
+ fail(c, `one of ${c.values!.join(', ')}`)
71
+ }
72
+ if (type == 'ref') return input.trim() || fail(c, 'an entity id')
73
+ if (type == 'time') {
74
+ // Explicit offsets keep the instant from shifting with the local timezone.
75
+ let text = input.trim()
76
+ let stamp =
77
+ /^\d{4}-\d\d-\d\dT(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|[+-]\d\d:\d\d)$/i
78
+ let time = Date.parse(text)
79
+ let day = text.slice(0, 10)
80
+ // Date.parse normalizes February 31 into March; a timestamp must name an
81
+ // existing calendar day before its timezone offset is applied.
82
+ return stamp.test(text) && Number.isFinite(time) &&
83
+ new Date(`${day}T00:00:00Z`).toISOString().slice(0, 10) == day
84
+ ? new Date(time).toISOString()
85
+ : fail(c, 'an ISO timestamp with a timezone')
86
+ }
87
+ return input
88
+ }
89
+
90
+ /**
91
+ * Offer a single-property patch. Construction is inert; run parses, validates
92
+ * and returns only that property. The caller decides whether to apply the patch.
93
+ */
94
+ export let edit = (
95
+ vocab: Vocab,
96
+ address: Address,
97
+ options: EditOptions = {},
98
+ ): Action => {
99
+ let c = declared(vocab, address)
100
+ return {
101
+ name: `set ${c.comp}.${c.prop}`,
102
+ run: (bundle, input) => {
103
+ if (!writable(vocab, c)) {
104
+ throw new Error(`${c.comp}.${c.prop} is read-only`)
105
+ }
106
+ let value = (options.parse ?? parse)(input, c, bundle)
107
+ let errors = vocab.check(c.comp, { [c.prop]: value })
108
+ if (errors.length) throw new Error(errors.join('; '))
109
+ options.validate?.(value, c, bundle)
110
+ return { [c.comp]: { [c.prop]: value } }
111
+ },
112
+ }
113
+ }
package/host.js ADDED
@@ -0,0 +1,191 @@
1
+ import { loadVocab } from "@yaks/vocab";
2
+ let path = (url)=>new URL(url).pathname;
3
+ /** The sha of the views module a write brings when the write is that module
4
+ * alone; else null, and the page takes the write its own way (a stylesheet
5
+ * swapped, or a reload). */ export let taken = (news, views)=>{
6
+ let files = Array.isArray(news?.files) ? news.files : [];
7
+ let ours = files.length > 0 && files.every((f)=>f.sha && (f.entries?.length ? f.entries.every((entry)=>path(entry) == path(views)) : f.url && path(f.url) == path(views)));
8
+ return ours ? files.at(-1).sha : null;
9
+ };
10
+ /** Where the module a write brought is imported from: a new address for each
11
+ * sha, so the browser imports it again. */ export let addressed = (views, sha)=>{
12
+ let url = new URL(views);
13
+ url.searchParams.set('yak-draft', sha);
14
+ return String(url);
15
+ };
16
+ let registryOf = (module)=>{
17
+ let views = module?.views;
18
+ if (!Array.isArray(views?.renderers)) {
19
+ throw new Error('A views module exports `views`, a @yaks/render registry');
20
+ }
21
+ return views;
22
+ };
23
+ let placeOf = (root, el)=>{
24
+ if (el.id) return el.id;
25
+ let steps = [];
26
+ for(let at = el; at != root && at.parentElement; at = at.parentElement){
27
+ steps.unshift([
28
+ ...at.parentElement.children
29
+ ].indexOf(at));
30
+ }
31
+ return steps;
32
+ };
33
+ let found = (root, place)=>typeof place == 'string' ? root.ownerDocument.getElementById(place) : place.reduce((at, i)=>at?.children[i], root);
34
+ // What a redraw may move, read before it: the window's scroll, each scrolled
35
+ // element's, and the focused element and its caret. The answer puts back
36
+ // whatever the redraw lost.
37
+ let kept = (root)=>{
38
+ let doc = root.ownerDocument;
39
+ let win = doc.defaultView;
40
+ let [x, y] = [
41
+ win?.scrollX ?? 0,
42
+ win?.scrollY ?? 0
43
+ ];
44
+ let scrolled = [
45
+ ...root.querySelectorAll('*')
46
+ ].filter((el)=>el.scrollTop || el.scrollLeft).map((el)=>[
47
+ placeOf(root, el),
48
+ el.scrollTop,
49
+ el.scrollLeft
50
+ ]);
51
+ let active = doc.activeElement;
52
+ let focus = active && active != root && root.contains(active) ? placeOf(root, active) : null;
53
+ let caret = active && typeof active.selectionStart == 'number' ? [
54
+ active.selectionStart,
55
+ active.selectionEnd
56
+ ] : null;
57
+ return ()=>{
58
+ for (let [place, top, left] of scrolled){
59
+ let el = found(root, place);
60
+ if (el && (el.scrollTop != top || el.scrollLeft != left)) {
61
+ el.scrollTop = top;
62
+ el.scrollLeft = left;
63
+ }
64
+ }
65
+ if (focus != null && !active.isConnected) {
66
+ let el = found(root, focus);
67
+ el?.focus?.({
68
+ preventScroll: true
69
+ });
70
+ if (caret && el?.setSelectionRange) el.setSelectionRange(...caret);
71
+ }
72
+ if (win && (win.scrollX != x || win.scrollY != y)) win.scrollTo?.(x, y);
73
+ };
74
+ };
75
+ let binding = (page)=>{
76
+ if (!('client' in page)) return page;
77
+ let { client } = page;
78
+ return {
79
+ vocab: client.vocab,
80
+ store: client.ent,
81
+ extend: client.extend,
82
+ subscribe: (eid, notify)=>{
83
+ let watch = client.watch(`.entity.eid="${eid}"`);
84
+ let off = watch.subscribe(notify);
85
+ return ()=>{
86
+ off();
87
+ watch.close();
88
+ };
89
+ }
90
+ };
91
+ };
92
+ /** Draw a page and follow its draft using the supplied renderer. */ export let host = async (page, mount)=>{
93
+ let { root, draw, load = (url)=>import(url) } = page;
94
+ let views = String(new URL(page.views, root.ownerDocument.baseURI));
95
+ let bound = binding(page);
96
+ let words = bound.vocab;
97
+ let source = String(new URL(page.vocabulary ?? 'api/vocab.json', root.ownerDocument.baseURI));
98
+ let file = String(new URL('vocab.json', root.ownerDocument.baseURI));
99
+ let current = registryOf(await load(views));
100
+ let surface = mount(root, bound, current, draw);
101
+ let drawn = ()=>surface.draw(current, words);
102
+ try {
103
+ drawn();
104
+ } catch (error) {
105
+ surface.close();
106
+ throw error;
107
+ }
108
+ // Writes can land faster than their modules import; only the newest draws.
109
+ let newest = 0;
110
+ let closed = false;
111
+ let last = Promise.resolve();
112
+ let swap = async (sha, n)=>{
113
+ let next;
114
+ try {
115
+ next = registryOf(await load(addressed(views, sha)));
116
+ } catch (e) {
117
+ if (n == newest) throw e;
118
+ return;
119
+ }
120
+ if (n != newest) return;
121
+ let old = current;
122
+ let restore = kept(root);
123
+ current = next;
124
+ try {
125
+ drawn();
126
+ } catch (e) {
127
+ current = old;
128
+ drawn();
129
+ throw e;
130
+ } finally{
131
+ restore();
132
+ }
133
+ };
134
+ let heard = (event)=>{
135
+ let news = event.detail;
136
+ let files = Array.isArray(news?.files) ? news.files : [];
137
+ let vocab = files.filter((f)=>f.url && path(f.url) == path(file));
138
+ let modules = files.filter((f)=>!vocab.includes(f));
139
+ let sha = taken({
140
+ files: modules
141
+ }, views);
142
+ if (!vocab.length && !sha || modules.length && !sha) return;
143
+ if (vocab.length && (!bound.extend || vocab.some((f)=>!f.sha))) return;
144
+ event.preventDefault();
145
+ let reload = event.reload;
146
+ let n = sha ? ++newest : newest;
147
+ // A views write may follow a vocabulary write before its fetch finishes.
148
+ // Keep their order so a new renderer always meets its new components.
149
+ last = last.then(async ()=>{
150
+ if (closed) return;
151
+ if (vocab.length) {
152
+ let response = await (page.fetch ?? globalThis.fetch)(addressed(source, vocab.at(-1).sha));
153
+ if (!response.ok) {
154
+ throw new Error(`Vocabulary fetch: ${response.status}`);
155
+ }
156
+ let next = loadVocab(await response.json(), words.keywords);
157
+ if (closed) return;
158
+ if (!bound.extend(next)) {
159
+ reload?.();
160
+ return;
161
+ }
162
+ words = next;
163
+ }
164
+ if (sha) await swap(sha, n);
165
+ else if (n == newest) {
166
+ let restore = kept(root);
167
+ try {
168
+ drawn();
169
+ } finally{
170
+ restore();
171
+ }
172
+ }
173
+ }).catch((e)=>{
174
+ console.error(e);
175
+ reload?.();
176
+ });
177
+ };
178
+ let win = root.ownerDocument.defaultView ?? globalThis;
179
+ win.addEventListener('yak-draft', heard);
180
+ return {
181
+ registry: ()=>current,
182
+ settled: ()=>last,
183
+ close: ()=>{
184
+ closed = true;
185
+ newest++;
186
+ win.removeEventListener('yak-draft', heard);
187
+ surface.close();
188
+ }
189
+ };
190
+ };
191
+ //# sourceMappingURL=host.js.map
package/host.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sources":["./host.ts"],"names":[],"mappings":"AAAA,SAAS,SAAS,2BAA4C;AA+D9D,IAAI,OAAO,CAAC,MAAgB,IAAI,IAAI,KAAK,QAAQ;AAEjD;;0BAE0B,GAC1B,OAAO,IAAI,QAAQ,CAAC,MAAa;EAC/B,IAAI,QAAQ,MAAM,OAAO,CAAC,MAAM,SAAS,KAAK,KAAK,GAAG,EAAE;EACxD,IAAI,OAAO,MAAM,MAAM,GAAG,KACxB,MAAM,KAAK,CAAC,CAAC,IACX,EAAE,GAAG,IAAI,CACP,EAAE,OAAO,EAAE,SACP,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,QAAU,KAAK,UAAU,KAAK,UAC/C,EAAE,GAAG,IAAI,KAAK,EAAE,GAAG,KAAK,KAAK,MACnC;EAEJ,OAAO,OAAO,MAAM,EAAE,CAAC,CAAC,GAAI,GAAG,GAAG;AACpC,EAAC;AAED;yCACyC,GACzC,OAAO,IAAI,YAAY,CAAC,OAAe;EACrC,IAAI,MAAM,IAAI,IAAI;EAClB,IAAI,YAAY,CAAC,GAAG,CAAC,aAAa;EAClC,OAAO,OAAO;AAChB,EAAC;AAED,IAAI,aAAa,CACf;EAEA,IAAI,QAAQ,QAAQ;EACpB,IAAI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IAAI,SAAS,AAAC,MAA0C,MAAM;IAC9D,IAAI,IAAI,MAAM,EAAE,SAAS;IACzB,yEAAyE;IACzE,sEAAsE;IACtE,OAAO,KAAK,IAAI,CAAC;MACf,IAAI,QAAQ;MACZ,IAAI,MAAM,MAAM,EAAE;QAChB,IAAI,WAAW,MAAM,CAAC,KAAK,KAAK,IAAI,WAAW,KAAK,EAClD,UAAU,QAAQ,MAAM,EAAE,CAAC,CAAC,GAAI,GAAG;QAErC,IAAI,CAAC,SAAS,EAAE,EAAE;UAChB,MAAM,IAAI,MAAM,CAAC,kBAAkB,EAAE,SAAS,MAAM,EAAE;QACxD;QACA,IAAI,OAAO,UAAU,MAAM,SAAS,IAAI,IAAI,MAAM,QAAQ;QAC1D,IAAI,QAAQ;QACZ,IAAI,CAAC,MAAM,MAAM,CAAE,OAAO;UACxB;UACA;QACF;QACA,QAAQ;MACV;MACA,IAAI,KAAK,MAAM,KAAK,KAAK;WACpB,IAAI,KAAK,QAAQ;QACpB,IAAI,UAAU,KAAK;QACnB,IAAI;UACF;QACF,SAAU;UACR;QACF;MACF;IACF,GAAG,KAAK,CAAC,CAAC;MACR,QAAQ,KAAK,CAAC;MACd;IACF;EACF;EACA,IAAI,MAAM,KAAK,aAAa,CAAC,WAAW,IAAI;EAC5C,IAAI,gBAAgB,CAAC,aAAa;EAClC,OAAO;IACL,UAAU,IAAM;IAChB,SAAS,IAAM;IACf,OAAO;MACL,SAAS;MACT;MACA,IAAI,mBAAmB,CAAC,aAAa;MACrC,QAAQ,KAAK;IACf;EACF;AACF,EAAC"}
package/host.ts ADDED
@@ -0,0 +1,277 @@
1
+ import { loadVocab, type Vocab } from '@yaks/vocab'
2
+ import type { Store, Subscribe } from './component.ts'
3
+
4
+ /** What a views module exports: its registry, named as a package's `/views`
5
+ * facet names it. */
6
+ export type Views<R> = { views: R }
7
+
8
+ /** A write to the draft a preview page follows, as `yak-draft` tells it:
9
+ * each file's path, the address it serves at, and its sha (null when the
10
+ * write deleted it). */
11
+ export type Draft = {
12
+ files: {
13
+ path: string
14
+ sha: string | null
15
+ url?: string
16
+ entries?: string[]
17
+ }[]
18
+ }
19
+
20
+ /** What the page supplies: everything `entity` binds but the registry, the
21
+ * element the page draws into, the address of its views module, and what to
22
+ * draw there given the bound `Entity`. */
23
+ export type Binding = {
24
+ vocab: Vocab
25
+ store: Store
26
+ subscribe?: Subscribe
27
+ extend?: (next: Vocab) => boolean
28
+ }
29
+
30
+ export type Page<R, Render> =
31
+ & (Binding | {
32
+ client: {
33
+ vocab: Vocab
34
+ ent: Store
35
+ extend: (next: Vocab) => boolean
36
+ watch: (query: string) => {
37
+ subscribe: (notify: () => void) => () => void
38
+ close: () => void
39
+ }
40
+ }
41
+ })
42
+ & {
43
+ root: Element
44
+ views: string | URL
45
+ draw: Render
46
+ /** how a module is imported; `import()` by default */
47
+ load?: (url: string) => Promise<Views<R>>
48
+ /** The page vocabulary endpoint, relative to its base URI (default: api/vocab.json). */
49
+ vocabulary?: string | URL
50
+ /** How the vocabulary is fetched; the page's fetch by default. */
51
+ fetch?: (url: string) => Promise<Response>
52
+ }
53
+
54
+ /** A drawn page. */
55
+ export type Host<R> = {
56
+ /** the registry drawn now */
57
+ registry: () => R
58
+ /** resolves once the newest write the host took is drawn, or given up */
59
+ settled: () => Promise<void>
60
+ /** stop following writes and empty the root */
61
+ close: () => void
62
+ }
63
+
64
+ let path = (url: string) => new URL(url).pathname
65
+
66
+ /** The sha of the views module a write brings when the write is that module
67
+ * alone; else null, and the page takes the write its own way (a stylesheet
68
+ * swapped, or a reload). */
69
+ export let taken = (news: Draft, views: string): string | null => {
70
+ let files = Array.isArray(news?.files) ? news.files : []
71
+ let ours = files.length > 0 &&
72
+ files.every((f) =>
73
+ f.sha && (
74
+ f.entries?.length
75
+ ? f.entries.every((entry) => path(entry) == path(views))
76
+ : f.url && path(f.url) == path(views)
77
+ )
78
+ )
79
+ return ours ? files.at(-1)!.sha : null
80
+ }
81
+
82
+ /** Where the module a write brought is imported from: a new address for each
83
+ * sha, so the browser imports it again. */
84
+ export let addressed = (views: string, sha: string): string => {
85
+ let url = new URL(views)
86
+ url.searchParams.set('yak-draft', sha)
87
+ return String(url)
88
+ }
89
+
90
+ let registryOf = <R extends { renderers: readonly unknown[] }>(
91
+ module: Views<R>,
92
+ ) => {
93
+ let views = module?.views
94
+ if (!Array.isArray(views?.renderers)) {
95
+ throw new Error('A views module exports `views`, a @yaks/render registry')
96
+ }
97
+ return views
98
+ }
99
+
100
+ // An element's place under the root: its id, or the child indices leading
101
+ // to it, which a redraw of the same shape gives back.
102
+ type Place = string | number[]
103
+ let placeOf = (root: Element, el: Element): Place => {
104
+ if (el.id) return el.id
105
+ let steps = []
106
+ for (let at = el; at != root && at.parentElement; at = at.parentElement) {
107
+ steps.unshift([...at.parentElement.children].indexOf(at))
108
+ }
109
+ return steps
110
+ }
111
+ let found = (root: Element, place: Place) =>
112
+ typeof place == 'string'
113
+ ? root.ownerDocument.getElementById(place)
114
+ : place.reduce<Element | undefined>((at, i) => at?.children[i], root)
115
+
116
+ type Field = HTMLInputElement | HTMLTextAreaElement
117
+
118
+ // What a redraw may move, read before it: the window's scroll, each scrolled
119
+ // element's, and the focused element and its caret. The answer puts back
120
+ // whatever the redraw lost.
121
+ let kept = (root: Element) => {
122
+ let doc = root.ownerDocument
123
+ let win = doc.defaultView
124
+ let [x, y] = [win?.scrollX ?? 0, win?.scrollY ?? 0]
125
+ let scrolled = [...root.querySelectorAll('*')]
126
+ .filter((el) => el.scrollTop || el.scrollLeft)
127
+ .map((el) => [placeOf(root, el), el.scrollTop, el.scrollLeft] as const)
128
+ let active = doc.activeElement as Field | null
129
+ let focus = active && active != root && root.contains(active)
130
+ ? placeOf(root, active)
131
+ : null
132
+ let caret = active && typeof active.selectionStart == 'number'
133
+ ? [active.selectionStart, active.selectionEnd] as const
134
+ : null
135
+ return () => {
136
+ for (let [place, top, left] of scrolled) {
137
+ let el = found(root, place)
138
+ if (el && (el.scrollTop != top || el.scrollLeft != left)) {
139
+ el.scrollTop = top
140
+ el.scrollLeft = left
141
+ }
142
+ }
143
+ if (focus != null && !active!.isConnected) {
144
+ let el = found(root, focus) as Field | null
145
+ el?.focus?.({ preventScroll: true })
146
+ if (caret && el?.setSelectionRange) el.setSelectionRange(...caret)
147
+ }
148
+ if (win && (win.scrollX != x || win.scrollY != y)) win.scrollTo?.(x, y)
149
+ }
150
+ }
151
+
152
+ let binding = <R, Render>(page: Page<R, Render>): Binding => {
153
+ if (!('client' in page)) return page
154
+ let { client } = page
155
+ return {
156
+ vocab: client.vocab,
157
+ store: client.ent,
158
+ extend: client.extend,
159
+ subscribe: (eid, notify) => {
160
+ let watch = client.watch(`.entity.eid="${eid}"`)
161
+ let off = watch.subscribe(notify)
162
+ return () => {
163
+ off()
164
+ watch.close()
165
+ }
166
+ },
167
+ }
168
+ }
169
+
170
+ /** Draw a page and follow its draft using the supplied renderer. */
171
+ export let host = async <R extends { renderers: readonly unknown[] }, Render>(
172
+ page: Page<R, Render>,
173
+ mount: (root: Element, binding: Binding, initial: R, view: Render) => {
174
+ draw: (registry: R, vocab: Vocab) => void
175
+ close: () => void
176
+ },
177
+ ): Promise<Host<R>> => {
178
+ let { root, draw, load = (url) => import(url) } = page
179
+ let views = String(new URL(page.views, root.ownerDocument.baseURI))
180
+ let bound = binding(page)
181
+ let words = bound.vocab
182
+ let source = String(
183
+ new URL(page.vocabulary ?? 'api/vocab.json', root.ownerDocument.baseURI),
184
+ )
185
+ let file = String(new URL('vocab.json', root.ownerDocument.baseURI))
186
+ let current = registryOf<R>(await load(views))
187
+ let surface = mount(root, bound, current, draw)
188
+ let drawn = () => surface.draw(current, words)
189
+ try {
190
+ drawn()
191
+ } catch (error) {
192
+ surface.close()
193
+ throw error
194
+ }
195
+ // Writes can land faster than their modules import; only the newest draws.
196
+ let newest = 0
197
+ let closed = false
198
+ let last = Promise.resolve()
199
+ let swap = async (sha: string, n: number) => {
200
+ let next
201
+ try {
202
+ next = registryOf<R>(await load(addressed(views, sha)))
203
+ } catch (e) {
204
+ if (n == newest) throw e
205
+ return
206
+ }
207
+ if (n != newest) return
208
+ let old = current
209
+ let restore = kept(root)
210
+ current = next
211
+ try {
212
+ drawn()
213
+ } catch (e) {
214
+ current = old
215
+ drawn()
216
+ throw e
217
+ } finally {
218
+ restore()
219
+ }
220
+ }
221
+ let heard = (event: Event) => {
222
+ let news = (event as CustomEvent<Draft>).detail
223
+ let files = Array.isArray(news?.files) ? news.files : []
224
+ let vocab = files.filter((f) => f.url && path(f.url) == path(file))
225
+ let modules = files.filter((f) => !vocab.includes(f))
226
+ let sha = taken({ files: modules }, views)
227
+ if ((!vocab.length && !sha) || (modules.length && !sha)) return
228
+ if (vocab.length && (!bound.extend || vocab.some((f) => !f.sha))) return
229
+ event.preventDefault()
230
+ let reload = (event as Event & { reload?: () => void }).reload
231
+ let n = sha ? ++newest : newest
232
+ // A views write may follow a vocabulary write before its fetch finishes.
233
+ // Keep their order so a new renderer always meets its new components.
234
+ last = last.then(async () => {
235
+ if (closed) return
236
+ if (vocab.length) {
237
+ let response = await (page.fetch ?? globalThis.fetch)(
238
+ addressed(source, vocab.at(-1)!.sha!),
239
+ )
240
+ if (!response.ok) {
241
+ throw new Error(`Vocabulary fetch: ${response.status}`)
242
+ }
243
+ let next = loadVocab(await response.json(), words.keywords)
244
+ if (closed) return
245
+ if (!bound.extend!(next)) {
246
+ reload?.()
247
+ return
248
+ }
249
+ words = next
250
+ }
251
+ if (sha) await swap(sha, n)
252
+ else if (n == newest) {
253
+ let restore = kept(root)
254
+ try {
255
+ drawn()
256
+ } finally {
257
+ restore()
258
+ }
259
+ }
260
+ }).catch((e) => {
261
+ console.error(e)
262
+ reload?.()
263
+ })
264
+ }
265
+ let win = root.ownerDocument.defaultView ?? globalThis
266
+ win.addEventListener('yak-draft', heard)
267
+ return {
268
+ registry: () => current,
269
+ settled: () => last,
270
+ close: () => {
271
+ closed = true
272
+ newest++
273
+ win.removeEventListener('yak-draft', heard)
274
+ surface.close()
275
+ },
276
+ }
277
+ }