@yaks/dom 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.
package/mod.ts ADDED
@@ -0,0 +1,571 @@
1
+ /**
2
+ * @yaks/dom: a just-enough DOM for Preact to render against outside a browser
3
+ * (the undom trick): elements are plain objects, every mutation marks the tree
4
+ * dirty, and whoever owns the screen paints on the next microtask. A painter is
5
+ * a small reader of this tree: @yaks/tui paints it to a terminal, @yaks/native
6
+ * to native views, so a kit-built app is one tree on both. `install()` swaps
7
+ * `globalThis.document` for this one and hands back the render root plus the
8
+ * restore, so a process that also holds a browser document (a test suite) keeps
9
+ * its own.
10
+ *
11
+ * @module
12
+ */
13
+
14
+ let paint = { fn: () => {} }
15
+
16
+ /** Register the repaint the next dirty tree asks for. */
17
+ export let onPaint = (fn: () => void): void => {
18
+ paint.fn = fn
19
+ }
20
+
21
+ // Exported because not every change to the screen is a change to the tree: a
22
+ // scroll and a resize move no nodes and still owe a repaint.
23
+ let dirty = false
24
+
25
+ /** Ask for a repaint; many touches in one turn coalesce into one paint. */
26
+ export let touch = (): void => {
27
+ if (dirty) return
28
+ dirty = true
29
+ queueMicrotask(() => {
30
+ dirty = false
31
+ paint.fn()
32
+ })
33
+ }
34
+
35
+ /** A rectangle of cells: columns left to right, rows top to bottom, the
36
+ * right and bottom edges just past the last. */
37
+ export type Box = { left: number; top: number; right: number; bottom: number }
38
+
39
+ let none: Box = { left: 0, top: 0, right: 0, bottom: 0 }
40
+ let union = (a: Box, b: Box): Box => ({
41
+ left: Math.min(a.left, b.left),
42
+ top: Math.min(a.top, b.top),
43
+ right: Math.max(a.right, b.right),
44
+ bottom: Math.max(a.bottom, b.bottom),
45
+ })
46
+
47
+ // What the last paint did: the cells each element painted itself, and the
48
+ // elements its sheet hid.
49
+ let placed = new Map<TElement, Box>()
50
+ let hidden = new Set<TElement>()
51
+ let revealed: TElement | undefined
52
+ let follow = (_href: string) => {}
53
+
54
+ /** Say how a pressed link is followed: the app's own navigation, since a
55
+ * painter outside a browser has no location to load. */
56
+ export let onNavigate = (fn: (href: string) => void): void => {
57
+ follow = fn
58
+ }
59
+
60
+ /** Record a paint: the screen's lines, each segment's owner the element that
61
+ * painted it, and the elements the sheet hid. Elements measure themselves by
62
+ * it (`getBoundingClientRect`, `checkVisibility`). */
63
+ export let place = (
64
+ lines: { text: string; owner?: TElement }[][],
65
+ hid: Set<TElement> = new Set(),
66
+ ): void => {
67
+ placed = new Map()
68
+ hidden = hid
69
+ lines.forEach((line, top) => {
70
+ let left = 0
71
+ for (let { text, owner } of line) {
72
+ let cells = { left, top, right: left + text.length, bottom: top + 1 }
73
+ let had = owner && placed.get(owner)
74
+ if (owner && text) placed.set(owner, had ? union(had, cells) : cells)
75
+ left = cells.right
76
+ }
77
+ })
78
+ }
79
+
80
+ /** The base node: parent link, sibling walk, and self-removal. */
81
+ export class TNode {
82
+ /** The element this node hangs from, or null when detached. */
83
+ parentNode: TElement | null = null
84
+ /** The node after this one under the same parent. */
85
+ get nextSibling(): TNode | null {
86
+ let sibs = this.parentNode?.childNodes
87
+ return sibs ? sibs[sibs.indexOf(this) + 1] ?? null : null
88
+ }
89
+ /** Whether it hangs under a screen's root, as a browser's node hangs in
90
+ * its document. */
91
+ get isConnected(): boolean {
92
+ return this.parentNode?.isConnected ??
93
+ (this as { localName?: string }).localName == 'root'
94
+ }
95
+ /** Detach this node from its parent. */
96
+ remove() {
97
+ this.parentNode?.removeChild(this)
98
+ }
99
+ }
100
+
101
+ /** A text node; writing `data` dirties the tree. */
102
+ export class TText extends TNode {
103
+ /** DOM node type, as Preact expects to read it. */
104
+ nodeType = 3
105
+ private text: string
106
+ constructor(text: unknown) { // preact passes numbers through raw
107
+ super()
108
+ this.text = String(text)
109
+ }
110
+ /** The characters this node holds. */
111
+ get data(): string {
112
+ return this.text
113
+ }
114
+ set data(v: string) {
115
+ this.text = String(v)
116
+ touch()
117
+ }
118
+ }
119
+
120
+ /** An element: children, class, attributes, listeners. */
121
+ export class TElement extends TNode {
122
+ // Preact uses native property presence to normalize event names to lowercase.
123
+ onwheel = null
124
+ onclick = null
125
+ onmousedown = null
126
+ onmouseup = null
127
+ onmousemove = null
128
+ oninput = null
129
+ onchange = null
130
+ onkeydown = null
131
+ onsubmit = null
132
+ onfocus = null
133
+ onblur = null
134
+ onselect = null
135
+ onkeyup = null
136
+ ondblclick = null
137
+ oncancel = null
138
+ selectionStart = 0
139
+ selectionEnd = 0
140
+ /** Forms share their value and selection with browser components. */
141
+ get value(): string {
142
+ return this.attr('value') ?? ''
143
+ }
144
+ set value(text: string) {
145
+ this.setAttribute('value', text)
146
+ }
147
+ /** Whether a check box or radio is on, kept as its attribute, which the
148
+ * painter reads. */
149
+ get checked(): boolean {
150
+ return this.attrs.has('checked')
151
+ }
152
+ set checked(on: boolean) {
153
+ if (on) this.setAttribute('checked', '')
154
+ else this.removeAttribute('checked')
155
+ }
156
+ get ownerDocument(): typeof doc {
157
+ return doc
158
+ }
159
+ /** Take the focus from whatever held it; the painter shows where it is. */
160
+ focus() {
161
+ if (doc.activeElement && doc.activeElement != this) {
162
+ doc.activeElement.blur()
163
+ }
164
+ doc.activeElement = this
165
+ // Text typed over in place takes the caret at its end, where a browser
166
+ // page puts it (a terminal has no selection to put it by).
167
+ if (this.isContentEditable) {
168
+ this.selectionStart = this.selectionEnd = this.textContent.length
169
+ }
170
+ if (this.matches('input,textarea') || this.isContentEditable) {
171
+ this.setAttribute('data-caret', this.selectionStart)
172
+ }
173
+ this.dispatchEvent(new Event('focus'))
174
+ this.dispatchEvent(new Event('focusin', { bubbles: true }))
175
+ touch()
176
+ }
177
+ blur() {
178
+ let held = doc.activeElement == this
179
+ if (held) doc.activeElement = null
180
+ this.removeAttribute('data-caret')
181
+ this.dispatchEvent(new Event('blur'))
182
+ if (held) this.dispatchEvent(new Event('focusout', { bubbles: true }))
183
+ touch()
184
+ }
185
+ /** Press it, as a primary-button click does: a check box flips and a
186
+ * radio turns on (back again when a listener cancels the click, else
187
+ * telling its `input` and `change`), a submit button submits its form, a
188
+ * `details`' summary opens or closes it, and a link no listener took is
189
+ * followed (`onNavigate`). */
190
+ click() {
191
+ let mark = this.matches('input') && this.attr('type')
192
+ let was = this.checked
193
+ let group = mark == 'radio' ? radios(this) : []
194
+ let on = group.find((r) => r.checked)
195
+ if (mark == 'checkbox') this.checked = !was
196
+ if (mark == 'radio') {
197
+ for (let r of group) r.checked = false
198
+ this.checked = true
199
+ }
200
+ let e = Object.assign(
201
+ new Event('click', { bubbles: true, cancelable: true }),
202
+ {
203
+ button: 0,
204
+ detail: 0,
205
+ metaKey: false,
206
+ ctrlKey: false,
207
+ shiftKey: false,
208
+ altKey: false,
209
+ },
210
+ )
211
+ let taken = dispatch(this, e)
212
+ if (mark == 'checkbox' || mark == 'radio') {
213
+ if (!taken) {
214
+ this.checked = was
215
+ if (on) on.checked = true
216
+ } else if (this.checked != was) {
217
+ for (let type of ['input', 'change']) {
218
+ dispatch(this, new Event(type, { bubbles: true }))
219
+ }
220
+ }
221
+ }
222
+ if (!taken) return
223
+ let details = this.localName == 'summary' && this.parentNode
224
+ if (details && details.localName == 'details') {
225
+ if (details.hasAttribute('open')) details.removeAttribute('open')
226
+ else details.setAttribute('open', '')
227
+ }
228
+ let form = submits(this) && this.closest('form')
229
+ if (form) {
230
+ dispatch(form, new Event('submit', { bubbles: true, cancelable: true }))
231
+ }
232
+ let href = this.closest('a')?.attr('href') ?? this.attr('data-href')
233
+ if (href) follow(href)
234
+ }
235
+ /** Keep it in sight: the scroll region around it shows it on the next
236
+ * paint, until another element asks. */
237
+ scrollIntoView() {
238
+ if (revealed == this) return
239
+ revealed?.removeAttribute('reveal')
240
+ revealed = this
241
+ this.setAttribute('reveal', '')
242
+ }
243
+ /** Where the last paint put it, in cells: every cell it or anything inside
244
+ * it painted. Nothing painted, out of a window's sight or hidden, is an
245
+ * empty box at the origin. */
246
+ getBoundingClientRect(): Box & {
247
+ x: number
248
+ y: number
249
+ width: number
250
+ height: number
251
+ } {
252
+ let at: Box | undefined
253
+ let add = (n: TElement) => {
254
+ let b = placed.get(n)
255
+ if (b) at = at ? union(at, b) : b
256
+ for (let k of n.childNodes) if (k instanceof TElement) add(k)
257
+ }
258
+ add(this)
259
+ let { left, top, right, bottom } = at ?? none
260
+ return {
261
+ left,
262
+ top,
263
+ right,
264
+ bottom,
265
+ x: left,
266
+ y: top,
267
+ width: right - left,
268
+ height: bottom - top,
269
+ }
270
+ }
271
+ /** Whether it shows: false where the last paint's sheet hid it or what
272
+ * holds it, true out of a window's sight. */
273
+ checkVisibility(): boolean {
274
+ return !hidden.has(this) && (this.parentNode?.checkVisibility() ?? true)
275
+ }
276
+ setSelectionRange(start: number, end: number) {
277
+ this.selectionStart = start
278
+ this.selectionEnd = end
279
+ if (doc.activeElement == this) this.setAttribute('data-caret', start)
280
+ }
281
+ /** DOM node type, as Preact expects to read it. */
282
+ nodeType = 1
283
+ /** Children in document order. */
284
+ childNodes: TNode[] = []
285
+ /** The element children in document order. */
286
+ get children(): TElement[] {
287
+ return this.childNodes.filter((node) => node instanceof TElement)
288
+ }
289
+ /** Present because Preact writes to it, a custom property through
290
+ * `setProperty`; the painter reads none of it. */
291
+ style: Record<string, unknown> & {
292
+ setProperty: (k: string, v: string) => void
293
+ } = {
294
+ setProperty(k, v) {
295
+ this[k] = v
296
+ },
297
+ }
298
+ get textContent(): string {
299
+ return this.childNodes.map((n) =>
300
+ n instanceof TText ? n.data : (n as TElement).textContent
301
+ ).join('')
302
+ }
303
+ /** Its children become one text node holding `text`, or none. */
304
+ set textContent(text: string) {
305
+ for (let n of this.childNodes) n.parentNode = null
306
+ this.childNodes = []
307
+ if (text) this.appendChild(new TText(text))
308
+ touch()
309
+ }
310
+ getAttribute(k: string): string | null {
311
+ return this.attr(k.toLowerCase()) ?? null
312
+ }
313
+ hasAttribute(k: string): boolean {
314
+ return this.attr(k.toLowerCase()) != null
315
+ }
316
+ get tagName(): string {
317
+ return this.localName.toUpperCase()
318
+ }
319
+ get parentElement(): TElement | null {
320
+ return this.parentNode
321
+ }
322
+ /** `contenteditable`, as a browser's element reads and sets it. */
323
+ get contentEditable(): string {
324
+ return this.attr('contenteditable') ?? 'inherit'
325
+ }
326
+ set contentEditable(v: string) {
327
+ if (v == 'inherit') this.removeAttribute('contenteditable')
328
+ else this.setAttribute('contenteditable', v)
329
+ }
330
+ /** Whether it is typed into in place: its own `contenteditable`, or its
331
+ * parent's. */
332
+ get isContentEditable(): boolean {
333
+ let v = this.attr('contenteditable')
334
+ return v == null || v == 'inherit'
335
+ ? !!this.parentNode?.isContentEditable
336
+ : v != 'false'
337
+ }
338
+ get href(): string {
339
+ return this.attr('href') ?? ''
340
+ }
341
+ get target(): string {
342
+ return this.attr('target') ?? ''
343
+ }
344
+ contains(n: TNode | null): boolean {
345
+ for (; n; n = n.parentNode) if (n == this) return true
346
+ return false
347
+ }
348
+ matches(selector: string): boolean {
349
+ return selector.split(',').some((s) => {
350
+ s = s.trim()
351
+ let m = s.match(/^([\w-]+)?(?:\[([\w-]+)(?:=["']?([^"'\]]+)["']?)?\])?$/)
352
+ if (m && (m[1] || m[2])) {
353
+ return (!m[1] || m[1] == this.localName) &&
354
+ (!m[2] ||
355
+ (m[3] == null ? this.hasAttribute(m[2]) : this.attr(m[2]) == m[3]))
356
+ }
357
+ if (s.startsWith('.')) {
358
+ return this.className.split(' ').includes(s.slice(1))
359
+ }
360
+ if (s.startsWith('#')) return this.attr('id') == s.slice(1)
361
+ return s == '*'
362
+ })
363
+ }
364
+ closest(selector: string): TElement | null {
365
+ return this.matches(selector)
366
+ ? this
367
+ : this.parentNode?.closest(selector) ?? null
368
+ }
369
+ querySelectorAll(selector: string): TElement[] {
370
+ return this.childNodes.filter((n) => n instanceof TElement).flatMap((n) => {
371
+ let el = n as TElement
372
+ return [
373
+ ...el.matches(selector) ? [el] : [],
374
+ ...el.querySelectorAll(selector),
375
+ ]
376
+ })
377
+ }
378
+ querySelector(selector: string): TElement | null {
379
+ return this.querySelectorAll(selector)[0] ?? null
380
+ }
381
+ dispatchEvent(event: Event): boolean {
382
+ return dispatch(this, event)
383
+ }
384
+ private attrs = new Map<string, string>()
385
+ handlers: Map<string, unknown> = new Map()
386
+ listeners: Map<string, Set<EventListener>> = new Map<
387
+ string,
388
+ Set<EventListener>
389
+ >()
390
+ constructor(public localName: string) {
391
+ super()
392
+ }
393
+ /** The first child, or null. */
394
+ get firstChild(): TNode | null {
395
+ return this.childNodes[0] ?? null
396
+ }
397
+ /** Read one attribute; undefined when unset. */
398
+ attr(k: string): string | undefined {
399
+ return this.attrs.get(k)
400
+ }
401
+ /** The names of the attributes it has, as a browser lists them. */
402
+ getAttributeNames(): string[] {
403
+ return [...this.attrs.keys()]
404
+ }
405
+ /** The class attribute, as Preact names it. */
406
+ get className(): string {
407
+ return this.attrs.get('class') ?? ''
408
+ }
409
+ set className(v: string) {
410
+ this.setAttribute('class', v)
411
+ }
412
+ /** Append a child; it is returned, as a browser returns it. */
413
+ appendChild<N extends TNode>(c: N): N {
414
+ return this.insertBefore(c, null)
415
+ }
416
+ /** Insert a child before `ref`, or at the end when ref is null. */
417
+ insertBefore<N extends TNode>(c: N, ref: TNode | null): N {
418
+ c.parentNode?.removeChild(c)
419
+ let i = ref ? this.childNodes.indexOf(ref) : -1
420
+ this.childNodes.splice(i < 0 ? this.childNodes.length : i, 0, c)
421
+ c.parentNode = this
422
+ touch()
423
+ return c
424
+ }
425
+ /** Remove a child. */
426
+ removeChild(c: TNode) {
427
+ let i = this.childNodes.indexOf(c)
428
+ if (i >= 0) this.childNodes.splice(i, 1)
429
+ c.parentNode = null
430
+ touch()
431
+ }
432
+ /** Set an attribute; its name lowercased and its value stringified, as an
433
+ * HTML document does (Preact writes `tabIndex`, a selector reads
434
+ * `[tabindex]`). */
435
+ setAttribute(k: string, v: unknown) {
436
+ this.attrs.set(k.toLowerCase(), String(v))
437
+ touch()
438
+ }
439
+ /** Remove an attribute. */
440
+ removeAttribute(k: string) {
441
+ this.attrs.delete(k.toLowerCase())
442
+ touch()
443
+ }
444
+ /** Record a listener. Pointer events bubble here; keys go through `screen`. */
445
+ addEventListener(t: string, fn: unknown) {
446
+ let set = this.listeners.get(t) ?? new Set<EventListener>()
447
+ set.add(fn as EventListener)
448
+ this.listeners.set(t, set)
449
+ this.handlers.set(t, (e: Event) => {
450
+ let consumed = false
451
+ for (let handler of [...this.listeners.get(t) ?? []].reverse()) {
452
+ if (
453
+ (handler as unknown as (e: Event) => unknown).call(this, e) === true
454
+ ) consumed = true
455
+ if (e.cancelBubble) break
456
+ }
457
+ return consumed
458
+ })
459
+ }
460
+ /** Forget a listener. */
461
+ removeEventListener(t: string, fn?: unknown) {
462
+ if (fn) this.listeners.get(t)?.delete(fn as EventListener)
463
+ else this.listeners.delete(t)
464
+ if (!this.listeners.get(t)?.size) this.handlers.delete(t)
465
+ }
466
+ }
467
+
468
+ // The radios a radio turns off when it turns on: those of its name in its
469
+ // form, or under the same root when it has none.
470
+ let radios = (el: TElement): TElement[] => {
471
+ let name = el.attr('name')
472
+ if (!name) return [el]
473
+ let top: TElement = el
474
+ while (top.parentNode && top.localName != 'form') top = top.parentNode
475
+ return top.querySelectorAll('input')
476
+ .filter((r) => r.attr('type') == 'radio' && r.attr('name') == name)
477
+ }
478
+
479
+ // Whether pressing it submits its form, as a browser's button does.
480
+ let submits = (el: TElement) =>
481
+ el.attr('disabled') == null && (
482
+ el.localName == 'button' && (el.attr('type') ?? 'submit') == 'submit' ||
483
+ el.matches('input') && el.attr('type') == 'submit'
484
+ )
485
+
486
+ /** Deliver DOM events through capture, target, bubble and the host window. */
487
+ export let dispatch = (target: TElement, event: Event): boolean => {
488
+ Object.defineProperty(event, 'target', { value: target, configurable: true })
489
+ let path: TElement[] = []
490
+ for (let n: TElement | null = target; n; n = n.parentNode) path.push(n)
491
+ let call = (node: TElement, capture = false) => {
492
+ Object.defineProperty(event, 'currentTarget', {
493
+ value: node,
494
+ configurable: true,
495
+ })
496
+ let handler = node.handlers.get(event.type + (capture ? 'Capture' : ''))
497
+ if (typeof handler == 'function') handler.call(node, event)
498
+ }
499
+ for (let n of [...path].reverse()) {
500
+ call(n, true)
501
+ if (event.cancelBubble) return !event.defaultPrevented
502
+ }
503
+ for (let n of path) {
504
+ call(n)
505
+ if (event.cancelBubble) return !event.defaultPrevented
506
+ }
507
+ Object.defineProperty(event, 'currentTarget', {
508
+ value: null,
509
+ configurable: true,
510
+ })
511
+ globalThis.dispatchEvent(event)
512
+ return !event.defaultPrevented
513
+ }
514
+
515
+ /** The document Preact reaches for globally, over these node types. */
516
+ export let doc: {
517
+ createElement: (t: string) => TElement
518
+ createElementNS: (ns: string, t: string) => TElement
519
+ createTextNode: (d: string) => TText
520
+ activeElement: TElement | null
521
+ addEventListener: typeof globalThis.addEventListener
522
+ removeEventListener: typeof globalThis.removeEventListener
523
+ getSelection: () => null
524
+ querySelector: (s: string) => null
525
+ } = {
526
+ createElement: (t: string): TElement => new TElement(t),
527
+ createElementNS: (_ns: string, t: string): TElement => new TElement(t),
528
+ createTextNode: (d: string): TText => new TText(d),
529
+ activeElement: null as TElement | null,
530
+ addEventListener: globalThis.addEventListener.bind(globalThis),
531
+ removeEventListener: globalThis.removeEventListener.bind(globalThis),
532
+ getSelection: () => null,
533
+ querySelector: (_s: string) => null,
534
+ }
535
+
536
+ /** Install that document, returning a fresh render root and the restore. */
537
+ export let install = (): { root: TElement; free: () => void } => {
538
+ let priorElement = Object.getOwnPropertyDescriptor(globalThis, 'Element')
539
+ let priorHtml = Object.getOwnPropertyDescriptor(globalThis, 'HTMLElement')
540
+ Object.defineProperty(globalThis, 'Element', {
541
+ value: TElement,
542
+ configurable: true,
543
+ })
544
+ Object.defineProperty(globalThis, 'HTMLElement', {
545
+ value: TElement,
546
+ configurable: true,
547
+ })
548
+ let prior = Object.getOwnPropertyDescriptor(globalThis, 'document')
549
+ Object.defineProperty(globalThis, 'document', {
550
+ value: doc,
551
+ configurable: true,
552
+ })
553
+ return {
554
+ root: new TElement('root'),
555
+ free: () => {
556
+ for (
557
+ let [name, descriptor] of [['Element', priorElement], [
558
+ 'HTMLElement',
559
+ priorHtml,
560
+ ]] as const
561
+ ) {
562
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor)
563
+ else Reflect.deleteProperty(globalThis, name)
564
+ }
565
+ if (prior) Object.defineProperty(globalThis, 'document', prior)
566
+ else delete (globalThis as { document?: unknown }).document
567
+ // The tree is gone, and with it whatever held the focus.
568
+ doc.activeElement = null
569
+ },
570
+ }
571
+ }
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "@yaks/dom",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/dom",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ }
11
+ },
12
+ "license": "Apache-2.0",
13
+ "dependencies": {},
14
+ "description": "A just-enough in-memory DOM for Preact to render against outside a browser, which a terminal painter (@yaks/tui) and a native painter (@yaks/native) each paint.",
15
+ "repository": "https://github.com/yak-sh/yak.git"
16
+ }