@yaks/native 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,555 @@
1
+ /**
2
+ * @yaks/native: the kits' component tree, painted as native views. The host
3
+ * renders into @yaks/dom's in-memory DOM, as it does for a terminal; `paint`
4
+ * reads that tree into plain nodes a native host draws with its own widgets:
5
+ * a box, a run of text, a press, a field, a toggle, a pick, a drawing, an
6
+ * image, and what only a browser draws (`web`). It holds no widget and
7
+ * imports no platform, so it runs and is tested anywhere; the host (the iOS
8
+ * shell's `native/kit.tsx`) maps each node to a React Native view.
9
+ *
10
+ * A node's look is the merge of its tag's defaults and the native style of
11
+ * each class it wears, read from a {@link Look} (look.ts). What a press or a
12
+ * typed character means stays the app's: the node carries the act that
13
+ * delivers it to the element, as a browser's event would.
14
+ *
15
+ * @module
16
+ */
17
+
18
+ /* @ts-types="npm:@types/react@19.3.0" */ import { Component, createElement as h, type ReactNode } from 'react'
19
+ import { draw } from '@yaks/react/draw'
20
+ import {
21
+ dispatch,
22
+ install,
23
+ onNavigate,
24
+ onPaint,
25
+ type TElement,
26
+ type TNode,
27
+ TText,
28
+ } from '@yaks/dom'
29
+
30
+ /** A native style: a React Native style object's keys and values. */
31
+ export type Style = Record<string, string | number>
32
+
33
+ /** The native look: each class's style, and each tag's. */
34
+ export type Look = {
35
+ classes: Record<string, Style>
36
+ tags: Record<string, Style>
37
+ }
38
+
39
+ /** One run of text inside a text node: words, or a styled inline element. */
40
+ export type Run = string | Text
41
+
42
+ /** Words, drawn in one native text view; nested runs keep their style. */
43
+ export type Text = {
44
+ kind: 'text'
45
+ key: number
46
+ style: Style
47
+ runs: Run[]
48
+ press?: () => void
49
+ }
50
+
51
+ /** A box laid out by flex, holding other nodes. */
52
+ export type Box = {
53
+ kind: 'box'
54
+ key: number
55
+ style: Style
56
+ children: Node[]
57
+ press?: () => void
58
+ }
59
+
60
+ /** How a field's keyboard behaves, in React Native's `TextInput` terms,
61
+ * read from what the element says it takes (`type`, `inputmode`,
62
+ * `enterkeyhint`, `autocomplete`, `autocapitalize`, `autofocus`). */
63
+ export type Traits = {
64
+ keyboardType?:
65
+ | 'email-address'
66
+ | 'numeric'
67
+ | 'decimal-pad'
68
+ | 'phone-pad'
69
+ | 'url'
70
+ | 'web-search'
71
+ secureTextEntry?: boolean
72
+ returnKeyType: 'done' | 'go' | 'next' | 'search' | 'send'
73
+ autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters'
74
+ autoCorrect?: boolean
75
+ autoComplete?: string
76
+ autoFocus?: boolean
77
+ editable?: boolean
78
+ /** whether submitting keeps the keyboard up: a form that takes one entry
79
+ * after another (a list's "add") does, a lone field does not */
80
+ submitBehavior: 'submit' | 'blurAndSubmit' | 'newline'
81
+ }
82
+
83
+ /** A text field: what it shows, how its keyboard behaves, and the acts
84
+ * typing and submitting are. */
85
+ export type Field = {
86
+ kind: 'field'
87
+ key: number
88
+ style: Style
89
+ value: string
90
+ placeholder: string
91
+ lines: boolean
92
+ traits: Traits
93
+ type: (text: string) => void
94
+ submit: () => void
95
+ }
96
+
97
+ /** A choice of one among options (a `select`): the chosen value, what each
98
+ * option says, and the act of choosing one. */
99
+ export type Pick = {
100
+ kind: 'pick'
101
+ key: number
102
+ style: Style
103
+ value: string
104
+ options: { value: string; label: string }[]
105
+ disabled: boolean
106
+ choose: (value: string) => void
107
+ }
108
+
109
+ /** One shape of a drawing: its tag (`path`, `circle`, `rect`, …), its
110
+ * attributes, the look its classes give it (`fill`, `stroke`), and the
111
+ * shapes it holds. */
112
+ export type Shape = {
113
+ tag: string
114
+ attrs: Record<string, string>
115
+ style: Style
116
+ shapes: Shape[]
117
+ }
118
+
119
+ /** Lines and shapes (an `svg`, as an icon or a chart is), drawn in its
120
+ * words' colour where it says `currentColor`. */
121
+ export type Drawing = {
122
+ kind: 'drawing'
123
+ key: number
124
+ style: Style
125
+ attrs: Record<string, string>
126
+ shapes: Shape[]
127
+ }
128
+
129
+ /** A picture from an address. */
130
+ export type Picture = {
131
+ kind: 'image'
132
+ key: number
133
+ style: Style
134
+ uri: string
135
+ alt: string
136
+ }
137
+
138
+ /** What only a browser draws (a canvas, a frame, a video), or a view that
139
+ * broke: shown as a notice that it is on the app's web page. */
140
+ export type Web = {
141
+ kind: 'web'
142
+ key: number
143
+ style: Style
144
+ tag: string
145
+ words: string
146
+ }
147
+
148
+ /** A check box: whether it is on, and the act of flipping it. */
149
+ export type Toggle = {
150
+ kind: 'toggle'
151
+ key: number
152
+ style: Style
153
+ on: boolean
154
+ label: Run[]
155
+ flip: () => void
156
+ }
157
+
158
+ /** What a native host draws. */
159
+ export type Node = Text | Box | Field | Toggle | Pick | Drawing | Picture | Web
160
+
161
+ // Elements whose words run inline with their neighbours'.
162
+ let INLINE = new Set([
163
+ 'a',
164
+ 'abbr',
165
+ 'b',
166
+ 'br',
167
+ 'code',
168
+ 'em',
169
+ 'i',
170
+ 'kbd',
171
+ 'mark',
172
+ 'small',
173
+ 'span',
174
+ 'strong',
175
+ 'time',
176
+ ])
177
+
178
+ // Elements that are never drawn.
179
+ let UNSEEN = new Set([
180
+ 'head',
181
+ 'link',
182
+ 'meta',
183
+ 'noscript',
184
+ 'script',
185
+ 'style',
186
+ 'template',
187
+ ])
188
+
189
+ // Elements only a browser draws.
190
+ let WEB = new Set([
191
+ 'audio',
192
+ 'canvas',
193
+ 'embed',
194
+ 'iframe',
195
+ 'math',
196
+ 'object',
197
+ 'video',
198
+ ])
199
+
200
+ let keys = new WeakMap<TNode, number>()
201
+ let next = 0
202
+ let keyOf = (n: TNode) => {
203
+ let k = keys.get(n)
204
+ if (k == null) keys.set(n, k = ++next)
205
+ return k
206
+ }
207
+
208
+ let elements = (n: TElement) =>
209
+ n.childNodes.filter((c): c is TElement => !(c instanceof TText))
210
+
211
+ let styleOf = (el: TElement, look: Look): Style =>
212
+ Object.assign(
213
+ {},
214
+ look.tags[el.localName],
215
+ ...el.className.split(' ').filter(Boolean).map((c) => look.classes[c]),
216
+ )
217
+
218
+ // The style words take from the boxes around them, as a browser's text
219
+ // inherits its ink and size; a native box passes none on by itself.
220
+ let WORDS = [
221
+ 'color',
222
+ 'fontFamily',
223
+ 'fontSize',
224
+ 'fontStyle',
225
+ 'fontWeight',
226
+ 'letterSpacing',
227
+ 'lineHeight',
228
+ 'textAlign',
229
+ ]
230
+
231
+ let worn = (style: Style): Style =>
232
+ Object.fromEntries(Object.entries(style).filter(([k]) => WORDS.includes(k)))
233
+
234
+ // Whether an element takes a press: a button, a link, a summary (which opens
235
+ // its details), or anything the app listens to clicks on.
236
+ let pressable = (el: TElement) =>
237
+ el.localName == 'button' || el.localName == 'summary' ||
238
+ el.hasAttribute('href') || el.hasAttribute('data-href') ||
239
+ el.handlers.has('click')
240
+
241
+ // What a closed `details` shows of what it holds: its summary alone.
242
+ let shut = (el: TElement, c: TNode) =>
243
+ el.localName == 'details' && !el.hasAttribute('open') &&
244
+ (c instanceof TText || (c as TElement).localName != 'summary')
245
+
246
+ // A press clicks it, which submits a submit button's form and flips a box,
247
+ // as a browser's click does (@yaks/dom).
248
+ let pressOf = (el: TElement) =>
249
+ pressable(el) && !el.hasAttribute('disabled') ? () => el.click() : undefined
250
+
251
+ // Whether everything inside is words: text nodes and inline elements only.
252
+ let worded = (el: TElement): boolean =>
253
+ el.childNodes.every((c) =>
254
+ c instanceof TText ||
255
+ INLINE.has((c as TElement).localName) && worded(c as TElement)
256
+ )
257
+
258
+ let runs = (el: TElement, look: Look): Run[] =>
259
+ el.childNodes.map((c) =>
260
+ c instanceof TText
261
+ ? c.data
262
+ : (c as TElement).localName == 'br'
263
+ ? '\n'
264
+ : text(c as TElement, look, {})
265
+ )
266
+
267
+ let text = (el: TElement, look: Look, around: Style): Text => ({
268
+ kind: 'text',
269
+ key: keyOf(el),
270
+ style: { ...around, ...styleOf(el, look) },
271
+ runs: runs(el, look),
272
+ ...pressOf(el) && { press: pressOf(el) },
273
+ })
274
+
275
+ let event = (type: string, cancelable = false) =>
276
+ new Event(type, { bubbles: true, cancelable })
277
+
278
+ // Whether pressing it submits its form, as a button does unless it says
279
+ // otherwise.
280
+ let submits = (el: TElement) =>
281
+ (el.getAttribute('type') ?? (el.localName == 'button' ? 'submit' : '')) ==
282
+ 'submit'
283
+
284
+ // The keyboard each kind of entry brings up, by its `inputmode` or `type`.
285
+ let KEYBOARDS: Record<string, Traits['keyboardType']> = {
286
+ email: 'email-address',
287
+ numeric: 'numeric',
288
+ number: 'decimal-pad',
289
+ decimal: 'decimal-pad',
290
+ tel: 'phone-pad',
291
+ url: 'url',
292
+ search: 'web-search',
293
+ }
294
+
295
+ // The return key each `enterkeyhint` names; `enter` and `previous` have no
296
+ // iOS key of their own.
297
+ let RETURNS: Record<string, Traits['returnKeyType']> = {
298
+ done: 'done',
299
+ go: 'go',
300
+ next: 'next',
301
+ search: 'search',
302
+ send: 'send',
303
+ }
304
+
305
+ // Entries a person types exactly, which take no capital and no correction.
306
+ let EXACT = new Set(['email', 'url', 'password', 'tel', 'number'])
307
+
308
+ /** How a field's keyboard behaves: what it takes, as its attributes say,
309
+ * and whether submitting keeps it up (a form with a submit button does, so
310
+ * one entry follows another, as a list's "add" field does on iOS). */
311
+ export let traits = (el: TElement): Traits => {
312
+ let a = (k: string) => el.getAttribute(k) ?? undefined
313
+ let type = el.localName == 'textarea' ? 'textarea' : a('type') ?? 'text'
314
+ let keyboard = KEYBOARDS[a('inputmode') ?? ''] ?? KEYBOARDS[type]
315
+ let form = el.closest('form')
316
+ let exact = EXACT.has(type) || EXACT.has(a('inputmode') ?? '')
317
+ let caps = a('autocapitalize') as Traits['autoCapitalize'] | undefined
318
+ return {
319
+ ...keyboard && { keyboardType: keyboard },
320
+ ...type == 'password' && { secureTextEntry: true },
321
+ returnKeyType: RETURNS[a('enterkeyhint') ?? ''] ??
322
+ (type == 'search' ? 'search' : 'done'),
323
+ ...(caps ?? exact) && { autoCapitalize: caps ?? 'none' },
324
+ ...exact && { autoCorrect: false },
325
+ ...a('autocomplete') && { autoComplete: a('autocomplete') },
326
+ ...el.hasAttribute('autofocus') && { autoFocus: true },
327
+ ...(el.hasAttribute('disabled') || el.hasAttribute('readonly')) &&
328
+ { editable: false },
329
+ submitBehavior: type == 'textarea'
330
+ ? 'newline'
331
+ : form?.querySelectorAll('button,input').some(submits)
332
+ ? 'submit'
333
+ : 'blurAndSubmit',
334
+ }
335
+ }
336
+
337
+ let field = (el: TElement, look: Look): Field => ({
338
+ kind: 'field',
339
+ key: keyOf(el),
340
+ style: styleOf(el, look),
341
+ value: el.value,
342
+ placeholder: el.getAttribute('placeholder') ?? '',
343
+ lines: el.localName == 'textarea',
344
+ traits: traits(el),
345
+ type: (typed) => {
346
+ el.value = typed
347
+ dispatch(el, event('input'))
348
+ },
349
+ submit: () => {
350
+ let form = el.closest('form')
351
+ if (form) dispatch(form, event('submit', true))
352
+ else {
353
+ dispatch(
354
+ el,
355
+ Object.assign(event('keydown', true), { key: 'Enter' }),
356
+ )
357
+ }
358
+ },
359
+ })
360
+
361
+ let toggle = (el: TElement, label: Run[], look: Look): Toggle => ({
362
+ kind: 'toggle',
363
+ key: keyOf(el),
364
+ style: styleOf(el, look),
365
+ on: el.checked,
366
+ label,
367
+ flip: () => el.click(),
368
+ })
369
+
370
+ let words = (n: TNode): string =>
371
+ n instanceof TText ? n.data : (n as TElement).childNodes.map(words).join('')
372
+
373
+ let options = (el: TElement): TElement[] =>
374
+ elements(el).flatMap((k) => k.localName == 'optgroup' ? elements(k) : [k])
375
+ .filter((k) => k.localName == 'option')
376
+
377
+ let pick = (el: TElement, look: Look): Pick => {
378
+ let all = options(el).map((o) => ({
379
+ value: o.getAttribute('value') ?? words(o),
380
+ label: words(o).trim(),
381
+ selected: o.hasAttribute('selected'),
382
+ }))
383
+ let value = el.getAttribute('value')
384
+ let chosen = all.find((o) => o.value == value) ??
385
+ all.find((o) => o.selected) ?? all[0]
386
+ return {
387
+ kind: 'pick',
388
+ key: keyOf(el),
389
+ style: styleOf(el, look),
390
+ value: chosen?.value ?? '',
391
+ options: all.map(({ value, label }) => ({ value, label })),
392
+ disabled: el.hasAttribute('disabled'),
393
+ choose: (v) => {
394
+ el.value = v
395
+ dispatch(el, event('input'))
396
+ dispatch(el, event('change'))
397
+ },
398
+ }
399
+ }
400
+
401
+ let attrsOf = (el: TElement): Record<string, string> =>
402
+ Object.fromEntries(
403
+ el.getAttributeNames().map((k) => [k, el.getAttribute(k) ?? '']),
404
+ )
405
+
406
+ let shape = (el: TElement, look: Look): Shape => ({
407
+ tag: el.localName,
408
+ attrs: attrsOf(el),
409
+ style: styleOf(el, look),
410
+ shapes: elements(el).map((c) => shape(c, look)),
411
+ })
412
+
413
+ let drawing = (el: TElement, look: Look, around: Style): Drawing => ({
414
+ kind: 'drawing',
415
+ key: keyOf(el),
416
+ style: { ...worn(around), ...styleOf(el, look) },
417
+ attrs: attrsOf(el),
418
+ shapes: elements(el).map((c) => shape(c, look)),
419
+ })
420
+
421
+ let isBox = (el: TElement, type: string) =>
422
+ el.localName == 'input' && (el.getAttribute('type') ?? 'text') == type
423
+
424
+ /** Paint one element and what it holds as native nodes; a text node beside
425
+ * elements becomes a text of its own, since a native box holds no bare
426
+ * words. */
427
+ export let paint = (
428
+ el: TElement,
429
+ look: Look,
430
+ around: Style = {},
431
+ ): Node | null => {
432
+ // A popover is closed until a press opens it, which a paint never is.
433
+ if (
434
+ UNSEEN.has(el.localName) || el.hasAttribute('hidden') ||
435
+ el.hasAttribute('popover')
436
+ ) return null
437
+ if (WEB.has(el.localName)) {
438
+ return {
439
+ kind: 'web',
440
+ key: keyOf(el),
441
+ style: styleOf(el, look),
442
+ tag: el.localName,
443
+ words: el.getAttribute('aria-label') ?? el.getAttribute('title') ??
444
+ words(el).trim(),
445
+ }
446
+ }
447
+ if (el.localName == 'svg') return drawing(el, look, around)
448
+ if (el.localName == 'img') {
449
+ return {
450
+ kind: 'image',
451
+ key: keyOf(el),
452
+ style: styleOf(el, look),
453
+ uri: el.getAttribute('src') ?? '',
454
+ alt: el.getAttribute('alt') ?? '',
455
+ }
456
+ }
457
+ if (el.localName == 'select') return pick(el, look)
458
+ if (isBox(el, 'checkbox') || isBox(el, 'radio')) return toggle(el, [], look)
459
+ if (el.localName == 'input' || el.localName == 'textarea') {
460
+ return field(el, look)
461
+ }
462
+ // A label around a box and its words is one toggle, its words the label.
463
+ let box = elements(el).find((c) => isBox(c, 'checkbox') || isBox(c, 'radio'))
464
+ if (el.localName == 'label' && box) {
465
+ let words = el.childNodes.filter((c) => c != box) as TNode[]
466
+ return {
467
+ ...toggle(box, [], look),
468
+ style: { ...around, ...styleOf(el, look) },
469
+ label: words.map((c) =>
470
+ c instanceof TText ? c.data : text(c as TElement, look, {})
471
+ ),
472
+ }
473
+ }
474
+ if (el.childNodes.length && worded(el)) return text(el, look, around)
475
+ let style = styleOf(el, look)
476
+ let inner = { ...around, ...worn(style) }
477
+ return {
478
+ kind: 'box',
479
+ key: keyOf(el),
480
+ style,
481
+ children: el.childNodes.flatMap((c): Node[] => {
482
+ if (shut(el, c)) return []
483
+ if (c instanceof TText) {
484
+ return c.data.trim()
485
+ ? [{ kind: 'text', key: keyOf(c), style: inner, runs: [c.data] }]
486
+ : []
487
+ }
488
+ let n = paint(c as TElement, look, inner)
489
+ return n ? [n] : []
490
+ }),
491
+ ...pressOf(el) && { press: pressOf(el) },
492
+ }
493
+ }
494
+
495
+ // What a view that threw paints: a notice that it is on the app's web page,
496
+ // with what went wrong.
497
+ let broken = (e: unknown): Web => ({
498
+ kind: 'web',
499
+ key: 0,
500
+ style: {},
501
+ tag: 'error',
502
+ words: String((e as Error)?.message ?? e),
503
+ })
504
+
505
+ // Catches what the tree throws while rendering, so a view that breaks shows
506
+ // its notice instead of taking the host down with it.
507
+ class Kept
508
+ extends Component<{ fell: (e: unknown) => void; children?: ReactNode }> {
509
+ override componentDidCatch(e: unknown) {
510
+ this.props.fell(e)
511
+ }
512
+ override render() {
513
+ return this.props.children
514
+ }
515
+ }
516
+
517
+ /** Render a tree into the in-memory DOM and hand `drawn` its painted nodes
518
+ * after every change, as a terminal repaints; the answer unmounts it. The
519
+ * DOM is one per process, so one tree is mounted at a time. A tree that
520
+ * throws while it renders paints as a {@link Web} notice saying so, and
521
+ * `fell` hears what it threw; a pressed link no listener took is `follow`ed,
522
+ * as a browser loads it. */
523
+ export let mount = (
524
+ node: ReactNode,
525
+ look: Look,
526
+ drawn: (painted: Node | null) => void,
527
+ { fell = console.error, follow = () => {} }: {
528
+ fell?: (e: unknown) => void
529
+ follow?: (href: string) => void
530
+ } = {},
531
+ ): () => void => {
532
+ let { root, free } = install()
533
+ let stop: (() => void) | undefined
534
+ let fault: Web | null = null
535
+ let fall = (e: unknown) => {
536
+ fault = broken(e)
537
+ fell(e)
538
+ drawn(fault)
539
+ }
540
+ onPaint(() => drawn(fault ?? paint(root, look)))
541
+ onNavigate(follow)
542
+ try {
543
+ stop = draw(h(Kept, { fell: fall }, node), root as unknown as Element)
544
+ } catch (e) {
545
+ fall(e)
546
+ }
547
+ return () => {
548
+ stop?.()
549
+ onPaint(() => {})
550
+ onNavigate(() => {})
551
+ free()
552
+ }
553
+ }
554
+
555
+ export { type Colors, look } from './look.js'
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@yaks/native",
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/native",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./remote": {
12
+ "types": "./_dist/remote.d.ts",
13
+ "default": "./remote.js"
14
+ }
15
+ },
16
+ "license": "Apache-2.0",
17
+ "dependencies": {
18
+ "@yaks/dom": "0.2.36",
19
+ "@yaks/react": "0.2.36",
20
+ "@yaks/ui": "0.2.36",
21
+ "@types/react": "19.3.0",
22
+ "react": "19.3.0",
23
+ "sucrase": "3.35.1"
24
+ },
25
+ "description": "Loads a kit-built app's view and store outside a browser and turns its Preact tree into native nodes that a host draws with its own widgets.",
26
+ "repository": "https://github.com/yak-sh/yak.git"
27
+ }