@ng-native/web 0.0.1 → 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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -1
  3. package/dist/browser-engine.d.ts +146 -0
  4. package/dist/browser-engine.js +585 -0
  5. package/dist/browser-engine.js.map +1 -0
  6. package/dist/browser-renderer.d.ts +87 -0
  7. package/dist/browser-renderer.js +295 -0
  8. package/dist/browser-renderer.js.map +1 -0
  9. package/dist/css-units.d.ts +9 -0
  10. package/dist/css-units.js +98 -0
  11. package/dist/css-units.js.map +1 -0
  12. package/dist/device-sources.d.ts +53 -0
  13. package/dist/device-sources.js +96 -0
  14. package/dist/device-sources.js.map +1 -0
  15. package/dist/dom-node.d.ts +63 -0
  16. package/dist/dom-node.js +103 -0
  17. package/dist/dom-node.js.map +1 -0
  18. package/dist/elements.d.ts +79 -0
  19. package/dist/elements.js +53 -0
  20. package/dist/elements.js.map +1 -0
  21. package/dist/index.d.ts +17 -0
  22. package/dist/index.js +18 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/island.d.ts +46 -0
  25. package/dist/island.js +109 -0
  26. package/dist/island.js.map +1 -0
  27. package/dist/jsdom-env.d.ts +4 -0
  28. package/dist/jsdom-env.js +67 -0
  29. package/dist/jsdom-env.js.map +1 -0
  30. package/dist/mount.d.ts +88 -0
  31. package/dist/mount.js +240 -0
  32. package/dist/mount.js.map +1 -0
  33. package/dist/native-style.d.ts +8 -0
  34. package/dist/native-style.js +108 -0
  35. package/dist/native-style.js.map +1 -0
  36. package/dist/props.d.ts +54 -0
  37. package/dist/props.js +608 -0
  38. package/dist/props.js.map +1 -0
  39. package/dist/reset-css.d.ts +26 -0
  40. package/dist/reset-css.js +163 -0
  41. package/dist/reset-css.js.map +1 -0
  42. package/dist/reset.css +282 -0
  43. package/dist/responder.d.ts +55 -0
  44. package/dist/responder.js +137 -0
  45. package/dist/responder.js.map +1 -0
  46. package/dist/web-view.d.ts +46 -0
  47. package/dist/web-view.js +93 -0
  48. package/dist/web-view.js.map +1 -0
  49. package/package.json +92 -3
  50. package/vite.d.mts +11 -0
  51. package/vite.mjs +41 -0
@@ -0,0 +1,585 @@
1
+ /**
2
+ * `HostEngine` over real DOM APIs: the browser counterpart to `packages/fabric/src/engine.ts`'s
3
+ * `Engine`.
4
+ *
5
+ * One instance per `mount()` call. It owns the prop/DOM translation (`props.ts`), the element
6
+ * mapping (`elements.ts`), and the responder negotiation (`responder.ts`); this file is mostly
7
+ * the wiring between them and the handful of DOM event listeners the whole tree shares - one
8
+ * `pointerdown`/`pointermove`/`pointerup`/`pointercancel` set on `document` for the responder
9
+ * system, one `focusin`/`focusout` set for `:focus` tracking, because both need to see every
10
+ * node's events rather than each node installing its own (Fabric's own engine is exactly this
11
+ * shape: one `registerEventHandler` callback for the whole tree, not one per view).
12
+ *
13
+ * `dispatchEvent` mirrors `engine.ts`'s method of the same name step for step: run the responder
14
+ * negotiation first, then propagate to whatever `(eventName)` bindings are listening, in the
15
+ * same two-phase order a real touch would arrive in on native.
16
+ */
17
+ import { HostEngine, SyntheticEvent, } from '@ng-native/fabric';
18
+ import { makeAnchorNode, makeElementNode, makeTextNode, nearestNodeOf, nodeOf, } from "./dom-node.js";
19
+ import { createDomElement } from "./elements.js";
20
+ import { applyProp } from "./props.js";
21
+ import { ResponderSystem } from "./responder.js";
22
+ /**
23
+ * Events that reach only their target, never its ancestors. Ported from `engine.ts`'s own
24
+ * `DIRECT_EVENTS`: a layout, a load, a scroll offset or a content size is meaningless to
25
+ * anything but the view it happened on, so bubbling it would let an ancestor's same-named
26
+ * listener - a scroll view inside a scroll view - fire for the wrong one.
27
+ */
28
+ const DIRECT_EVENTS = new Set([
29
+ 'topScroll',
30
+ 'topScrollBeginDrag',
31
+ 'topScrollEndDrag',
32
+ 'topMomentumScrollBegin',
33
+ 'topMomentumScrollEnd',
34
+ 'topContentSizeChange',
35
+ 'topLayout',
36
+ 'topLoad',
37
+ 'topLoadStart',
38
+ 'topLoadEnd',
39
+ 'topError',
40
+ 'topProgress',
41
+ 'topRefresh',
42
+ ]);
43
+ const TOUCH_EVENT_NAMES = {
44
+ pointerdown: 'topTouchStart',
45
+ pointermove: 'topTouchMove',
46
+ pointerup: 'topTouchEnd',
47
+ pointercancel: 'topTouchCancel',
48
+ };
49
+ function scrollToEnd(el, args) {
50
+ const [animated = true] = args;
51
+ const horizontal = el.scrollWidth > el.clientWidth && el.scrollHeight <= el.clientHeight;
52
+ el.scrollTo(horizontal
53
+ ? { left: el.scrollWidth, behavior: animated ? 'smooth' : 'auto' }
54
+ : { top: el.scrollHeight, behavior: animated ? 'smooth' : 'auto' });
55
+ }
56
+ function setTextAndSelection(el, args) {
57
+ const [, text, start, end] = args;
58
+ const textarea = el;
59
+ if (text !== null && text !== undefined)
60
+ textarea.value = text;
61
+ if (start !== -1)
62
+ textarea.setSelectionRange(start, end === -1 ? start : end);
63
+ }
64
+ /**
65
+ * View commands, by name. A lookup table for the same reason `props.ts`'s tables are one: it is
66
+ * where a review sees which commands do something and which do not, in one place, rather than
67
+ * spread across a `switch`'s branches.
68
+ *
69
+ * `flashScrollIndicators`, `zoomToRect`, `hotspotUpdate`, `setPressed`, `setNativeRefreshing`:
70
+ * no web equivalent (a browser's scrollbar has no imperative "flash", pinch-zoom is not
71
+ * scriptable, and there is no Android ripple to drive) - absent rather than a `noop` entry,
72
+ * because unlike a prop there is no generic fallback for a command name to fall through to; an
73
+ * absent command is already silently ignored below.
74
+ */
75
+ const COMMANDS = {
76
+ focus: (el) => el.focus(),
77
+ blur: (el) => el.blur(),
78
+ scrollTo: (el, args) => {
79
+ const [x = 0, y = 0, animated = true] = args;
80
+ el.scrollTo({ left: x, top: y, behavior: animated ? 'smooth' : 'auto' });
81
+ },
82
+ scrollToEnd,
83
+ setTextAndSelection,
84
+ // `<switch>` putting back a flip the app refused; the checkbox is what the user clicked.
85
+ setValue: (el, [value]) => {
86
+ el.checked = value === true;
87
+ },
88
+ };
89
+ /**
90
+ * The events this engine owns, which are React Native's rather than the DOM's.
91
+ *
92
+ * Each is either synthesised here from something else - `topLayout` from a `ResizeObserver`,
93
+ * `topTouch*` from pointer events, `topFocus` from `focusin` - or not implemented yet. Either way
94
+ * a handler bound to one expects React Native's `{ nativeEvent }` payload with React Native's own
95
+ * fields in it, so they must not be wired straight to the DOM event of the same name: a
96
+ * `scroll-view`'s `(scroll)` reads `nativeEvent.contentOffset`, and handing it a raw DOM `Event`
97
+ * would turn a binding that quietly does nothing into one that throws on the first scroll.
98
+ *
99
+ * The list is the events `@ng-native/components` actually binds, found by
100
+ * reading their host and template bindings rather than guessed. Anything outside it is a plain
101
+ * DOM event and is bound as one.
102
+ *
103
+ * `topLoad` and `topError` are deliberately *not* here, though an `<image>` binds both. A
104
+ * background image fires neither on its own, so `props.ts` loads the URL with a detached `Image()`
105
+ * and dispatches a real DOM `load` or `error` on the element - which means there is a genuine DOM
106
+ * event of each name to bind, and the general path is the right one. Reserving them was what left
107
+ * a broken image URL blank rather than showing a fallback.
108
+ */
109
+ const ENGINE_EVENTS = new Set([
110
+ 'topLayout',
111
+ 'topChange',
112
+ 'topContentSizeChange',
113
+ 'topRefresh',
114
+ 'topScroll',
115
+ 'topEndReached',
116
+ 'topSelectionChange',
117
+ 'topMomentumScrollBegin',
118
+ 'topMomentumScrollEnd',
119
+ 'topTouchStart',
120
+ 'topTouchMove',
121
+ 'topTouchEnd',
122
+ 'topTouchCancel',
123
+ 'topFocus',
124
+ 'topBlur',
125
+ 'topPointerEnter',
126
+ 'topPointerLeave',
127
+ ]);
128
+ export class BrowserEngine extends HostEngine {
129
+ document;
130
+ responders = new ResponderSystem();
131
+ focusedNode = null;
132
+ /** `TextInput`'s echo protocol: a change count that only ever goes up. One counter per field. */
133
+ eventCounts = new WeakMap();
134
+ /** Mount points `wrapRoot` wrapped; see `isRoot`. */
135
+ roots = new WeakSet();
136
+ /**
137
+ * The node each in-progress gesture began on, by `pointerId`, so `pointermove`/`pointerup`
138
+ * resolve to the same node however far the finger has travelled - `setPointerCapture` keeps
139
+ * the browser routing them there; this is what this class trusts instead of re-reading
140
+ * `event.target`. Keyed by `pointerId` rather than holding just one, so two fingers on two
141
+ * different controls (a phone reports multi-touch) do not clobber each other.
142
+ */
143
+ activeTouches = new Map();
144
+ /**
145
+ * The element nodes this engine made, and so the only ones its document listeners act for.
146
+ *
147
+ * Every engine listens on the one `document`, and a page can hold several - one per island, or
148
+ * the documentation site's three roots - while `nearestNodeOf` finds a node whichever engine
149
+ * made it. Without this, each engine delivered every focus, blur and touch in any root on the
150
+ * page, so a text field's `(blur)` ran once per island.
151
+ */
152
+ owned = new WeakSet();
153
+ /** Removes the document listeners, once the app they served is gone; see `dispose`. */
154
+ listening;
155
+ constructor(document) {
156
+ super();
157
+ this.document = document;
158
+ // The document's own, so the signal is one its `addEventListener` recognises.
159
+ this.listening = new (document.defaultView?.AbortController ?? AbortController)();
160
+ this.installGlobalListeners();
161
+ }
162
+ /** Stop listening to the document. `mount` calls this as its app is destroyed. */
163
+ dispose() {
164
+ this.listening.abort();
165
+ this.activeTouches.clear();
166
+ }
167
+ // --- element creation, called from BrowserRenderer ----------------------------------------
168
+ createElementNode(name) {
169
+ const el = createDomElement(this.document, name);
170
+ const node = makeElementNode(name, el);
171
+ this.owned.add(node);
172
+ this.wireAlwaysOnListeners(node);
173
+ return node;
174
+ }
175
+ createTextNode(value) {
176
+ return makeTextNode(this.document.createTextNode(value));
177
+ }
178
+ createAnchorNode() {
179
+ return makeAnchorNode(this.document.createComment(''));
180
+ }
181
+ /** Wrap an existing real element - the app's own mount point - as the tree's root node. */
182
+ wrapRoot(el) {
183
+ const node = makeElementNode(el.tagName.toLowerCase(), el);
184
+ el.setAttribute('data-rn', 'root');
185
+ this.roots.add(node);
186
+ this.owned.add(node);
187
+ return node;
188
+ }
189
+ /**
190
+ * Whether `node` is a mount point `wrapRoot` wrapped. It belongs to whoever called `mount`, not
191
+ * to the app rendered into it, so the renderer empties it rather than removing it.
192
+ */
193
+ isRoot(node) {
194
+ return this.roots.has(node);
195
+ }
196
+ // --- HostEngine -----------------------------------------------------------------------------
197
+ setProp(node, key, value) {
198
+ const clear = value === undefined || value === null;
199
+ if (clear) {
200
+ if (!(key in node.props))
201
+ return;
202
+ delete node.props[key];
203
+ }
204
+ else {
205
+ if (node.props[key] === value)
206
+ return;
207
+ node.props[key] = value;
208
+ }
209
+ applyProp(node, key, value, clear);
210
+ }
211
+ setEventListener(node, topLevelType, fn) {
212
+ const listeners = (node.listeners ??= new Map());
213
+ let set = listeners.get(topLevelType);
214
+ if (!set)
215
+ listeners.set(topLevelType, (set = new Set()));
216
+ set.add(fn);
217
+ this.wireOptIn(node, topLevelType);
218
+ return () => set.delete(fn);
219
+ }
220
+ setResponder(node, handlers) {
221
+ return this.responders.setResponder(node, handlers);
222
+ }
223
+ /**
224
+ * Where a node is, relative to the mount root rather than to the viewport.
225
+ *
226
+ * `measureInWindow` on native answers in window coordinates, and the overlay host is a
227
+ * full-screen absolutely positioned view at the window's origin, so the two agree and an
228
+ * anchored overlay can use one as the other. `getBoundingClientRect` answers in *viewport*
229
+ * coordinates, and `<overlay-host>` is absolutely positioned inside the mount root - so
230
+ * those two agree only when the root sits at the top left of an unscrolled viewport.
231
+ *
232
+ * That is true of a full-page app, which is why every popover in the gallery lands correctly
233
+ * and this went unnoticed. It is false in the two cases that matter: an app mounted into a box
234
+ * partway down a page, where every overlay is offset by the box's own position, and a document
235
+ * that scrolls, where the offset changes as you scroll. Subtracting the root's own rect from a
236
+ * viewport-relative one cancels the scroll term as well as the offset, since both rects move
237
+ * together as the page scrolls - so one subtraction fixes both cases at once.
238
+ *
239
+ * `closest`, not `querySelector`: a page can hold more than one mounted root at a time (the
240
+ * documentation site's own home page does, three of them), and `querySelector` always answers
241
+ * the first one in document order regardless of which root's own tree `node` actually lives in.
242
+ * That made every root after the first measure its overlays against someone else's box.
243
+ * `closest` walks up from the node itself, so each root only ever measures against its own.
244
+ */
245
+ measure(node, into) {
246
+ const el = node.el;
247
+ const rect = el.getBoundingClientRect();
248
+ const root = el.closest('[data-rn-root]');
249
+ const origin = root ? root.getBoundingClientRect() : { x: 0, y: 0 };
250
+ into({ x: rect.x - origin.x, y: rect.y - origin.y, width: rect.width, height: rect.height });
251
+ }
252
+ dispatchCommand(node, name, args = []) {
253
+ COMMANDS[name]?.(node.el, args);
254
+ }
255
+ commit() {
256
+ // Every write above already reached the DOM synchronously; there is nothing batched to flush.
257
+ return false;
258
+ }
259
+ get focused() {
260
+ if (this.focusedNode && !this.isAttached(this.focusedNode))
261
+ this.focusedNode = null;
262
+ return this.focusedNode;
263
+ }
264
+ isAttached(node) {
265
+ return node.el.isConnected;
266
+ }
267
+ /**
268
+ * A `require()`d numeric asset has no web analogue - there is no bundler-provided asset
269
+ * registry this package can read at runtime - so it resolves to nothing rather than a guess.
270
+ * A `{uri}` source, or an array of them, passes through unchanged: `props.ts`'s image handler
271
+ * reads it directly.
272
+ */
273
+ resolveAsset(value) {
274
+ if (typeof value === 'number')
275
+ return undefined;
276
+ return value;
277
+ }
278
+ /**
279
+ * A colour the app wrote is passed straight through: CSS accepts the same hex/rgb/named
280
+ * strings RN does. `platform-color(...)`'s semantic iOS/Android names have no web colour
281
+ * system to resolve against, so they resolve to nothing rather than to a wrong guess.
282
+ */
283
+ color(value) {
284
+ if (value === undefined)
285
+ return undefined;
286
+ if (typeof value === 'object' && value !== null && 'platformColor' in value)
287
+ return undefined;
288
+ return value;
289
+ }
290
+ // --- event dispatch, mirrors engine.ts's `dispatchEvent` -----------------------------------
291
+ dispatchEvent(target, topLevelType, nativeEvent) {
292
+ const event = new SyntheticEvent(nativeEvent);
293
+ if (topLevelType.startsWith('topTouch'))
294
+ this.responders.runResponder(target, topLevelType, event);
295
+ this.propagate(target, topLevelType, event);
296
+ }
297
+ /** As on native: a listener that stops the event ends the bubble after its own node. */
298
+ propagate(target, topLevelType, event) {
299
+ for (let node = target; node && !event.isPropagationStopped(); node = DIRECT_EVENTS.has(topLevelType) ? null : node.parent) {
300
+ const listeners = node.listeners?.get(topLevelType);
301
+ if (listeners)
302
+ for (const fn of [...listeners])
303
+ fn(event);
304
+ }
305
+ }
306
+ // --- always-on listeners, installed once per element at creation ---------------------------
307
+ wireAlwaysOnListeners(node) {
308
+ if (node.name === 'scroll-view' || node.name === 'virtual-list')
309
+ this.wireScroll(node);
310
+ if (node.name === 'text-input')
311
+ this.wireTextInput(node);
312
+ if (node.name === 'switch')
313
+ this.wireSwitch(node);
314
+ }
315
+ /**
316
+ * `scroll` does not bubble, so this is a real per-node listener rather than a document one.
317
+ *
318
+ * `scrollend` is the browser saying the scroll has come to rest, whatever moved it: a wheel's
319
+ * or a trackpad's glide, a flick, or an animated `scrollTo`. That is the moment a device reports
320
+ * as `(momentumScrollEnd)` - iOS sends it after an animated `scrollTo` as well as after a fling -
321
+ * and the event a paging carousel reads its page from, which never arrived here at all.
322
+ */
323
+ wireScroll(node) {
324
+ const el = node.el;
325
+ const offsets = () => ({
326
+ contentOffset: { x: el.scrollLeft, y: el.scrollTop },
327
+ contentSize: { width: el.scrollWidth, height: el.scrollHeight },
328
+ layoutMeasurement: { width: el.clientWidth, height: el.clientHeight },
329
+ contentInset: { top: 0, left: 0, bottom: 0, right: 0 },
330
+ zoomScale: 1,
331
+ });
332
+ el.addEventListener('scroll', () => {
333
+ this.responders.notifyScroll(node);
334
+ this.dispatchEvent(node, 'topScroll', offsets());
335
+ });
336
+ el.addEventListener('scrollend', () => {
337
+ this.dispatchEvent(node, 'topMomentumScrollEnd', offsets());
338
+ });
339
+ }
340
+ wireTextInput(node) {
341
+ const el = node.el;
342
+ const nextCount = () => {
343
+ const count = (this.eventCounts.get(node) ?? 0) + 1;
344
+ this.eventCounts.set(node, count);
345
+ return count;
346
+ };
347
+ el.addEventListener('input', () => {
348
+ this.dispatchEvent(node, 'topChange', { text: el.value, eventCount: nextCount(), target: 0 });
349
+ });
350
+ el.addEventListener('focus', () => {
351
+ if (el.hasAttribute('data-select-on-focus'))
352
+ el.select();
353
+ });
354
+ el.addEventListener('blur', () => {
355
+ this.dispatchEvent(node, 'topEndEditing', {
356
+ text: el.value,
357
+ eventCount: nextCount(),
358
+ target: 0,
359
+ });
360
+ });
361
+ // `Enter` does what `submitBehavior` says, as on a device: `newline` inserts one, `submit`
362
+ // submits and keeps focus, and `blurAndSubmit` submits and then lets go of the field. The
363
+ // component resolves the default, `blurAndSubmit` on one line and `newline` on many; the
364
+ // fallback here is the same rule, for a field whose binding has not landed yet. An `Enter`
365
+ // that confirms an IME composition belongs to the composition, not to the field.
366
+ el.addEventListener('keydown', (event) => {
367
+ if (event.key !== 'Enter' || event.isComposing)
368
+ return;
369
+ const behavior = node.props['submitBehavior'] ??
370
+ (el.hasAttribute('data-multiline') ? 'newline' : 'blurAndSubmit');
371
+ if (behavior === 'newline')
372
+ return;
373
+ event.preventDefault();
374
+ this.dispatchEvent(node, 'topSubmitEditing', {
375
+ text: el.value,
376
+ eventCount: nextCount(),
377
+ target: 0,
378
+ });
379
+ if (behavior === 'blurAndSubmit')
380
+ el.blur();
381
+ });
382
+ }
383
+ wireSwitch(node) {
384
+ const el = node.el;
385
+ el.addEventListener('change', () => {
386
+ this.dispatchEvent(node, 'topChange', { value: el.checked, target: 0 });
387
+ });
388
+ }
389
+ /**
390
+ * `topLayout` and hover, opted into once per node the first time something listens for them -
391
+ * never torn down again, exactly as `engine.ts`'s own `EVENT_OPT_IN_PROPS` never unsets the
392
+ * native prop it wrote either. A second listener for the same type on the same node (unusual,
393
+ * but not forbidden) shares the one observer rather than getting a duplicate.
394
+ */
395
+ wireOptIn(node, topLevelType) {
396
+ const optedIn = (node.optedIn ??= new Set());
397
+ if (optedIn.has(topLevelType))
398
+ return;
399
+ optedIn.add(topLevelType);
400
+ if (topLevelType === 'topLayout') {
401
+ /*
402
+ * The observer says *when*, and the bounding rect says *how big*. The size deliberately
403
+ * does not come from the entry's `contentBoxSize`, which is what it used to come from.
404
+ *
405
+ * Yoga lays out border-box: a React Native view styled `width: 192` with `padding: 16` and
406
+ * a hairline border is 192 wide, and `onLayout` reports 192. `contentBoxSize` is the CSS
407
+ * *content* box, so the same element in a browser reported 158 - the padding and the border
408
+ * subtracted. Every `(layout)` consumer in the library was therefore being handed a size
409
+ * smaller than its native counterpart by however much padding the element happened to have,
410
+ * and each one used it for something different: an accordion animated to a height that cut
411
+ * its own padding off, and an anchored overlay both centred itself on a width it did not
412
+ * have and decided it had room on a side where it did not, because `fits()` was asked about
413
+ * a shorter card than the one about to be painted.
414
+ *
415
+ * `measure()` in this same file has always answered from `getBoundingClientRect()`, which
416
+ * is the border box - so the engine was reporting two different sizes for one element
417
+ * depending on which way you asked. This is the half that was wrong.
418
+ *
419
+ * `x`/`y` are the other half, and a different frame from `measure()`'s: `engine.ts`'s own
420
+ * doc comment for `measure()` says it plainly - "`(layout)` reports a frame in the parent's
421
+ * coordinates" - because a layout tells a view how big it is and where it sits inside
422
+ * whatever it is stacked in, not where it is on screen. Reporting the raw viewport rect here
423
+ * answered a question nothing asked: a consumer that reads `layout.y` as an item's offset
424
+ * within its scrolling parent compares it against a scroll position in that same space, so
425
+ * a viewport-relative `y` was wrong by the scroll container's own position on the page - right only for a scroll view
426
+ * pinned at the top of an unscrolled full-page app, wrong the moment it sits lower on the
427
+ * page or the page itself scrolls. Subtracting the immediate DOM parent's rect - never an
428
+ * anchor comment; `browser-renderer.ts`'s `appendChild`/`insertBefore` only ever set
429
+ * `child.parent` to a node backed by a real element - puts it back in the parent's frame.
430
+ */
431
+ const observer = new ResizeObserver(() => {
432
+ const rect = node.el.getBoundingClientRect();
433
+ const parent = node.parent?.el;
434
+ const origin = parent ? parent.getBoundingClientRect() : { x: 0, y: 0 };
435
+ this.dispatchEvent(node, 'topLayout', {
436
+ layout: {
437
+ x: rect.x - origin.x,
438
+ y: rect.y - origin.y,
439
+ width: rect.width,
440
+ height: rect.height,
441
+ },
442
+ });
443
+ });
444
+ observer.observe(node.el);
445
+ return;
446
+ }
447
+ if (topLevelType === 'topPointerEnter' || topLevelType === 'topPointerLeave') {
448
+ const domName = topLevelType === 'topPointerEnter' ? 'pointerenter' : 'pointerleave';
449
+ node.el.addEventListener(domName, () => this.dispatchEvent(node, topLevelType, {}));
450
+ return;
451
+ }
452
+ /*
453
+ * Anything else is an ordinary DOM event, bound for real.
454
+ *
455
+ * Without this, `renderer.listen` put the callback in the node's map and stopped: the map is
456
+ * only ever read by `dispatchEvent`, and nothing dispatches a `topClick`. So `(click)`,
457
+ * `(keydown)`, `(input)` and every other plain binding registered successfully and never
458
+ * fired - including Angular's own `RouterLink`, which is why no link in the gallery navigated
459
+ * and no `(click)` anywhere in an app would have worked.
460
+ *
461
+ * The name maps straight down: DOM event types are lowercase, so `topClick` is `click` and
462
+ * `topKeyDown` is `keydown`.
463
+ *
464
+ * The event reaches the handler raw, not wrapped in `{ nativeEvent }`, because that is what a
465
+ * handler written for a browser expects - `RouterLink` reads `button`, `ctrlKey` and
466
+ * `metaKey` off it and calls `preventDefault` itself. Returning `false` from a binding
467
+ * prevents the default, as it does in any Angular app.
468
+ *
469
+ * Delivered only to this node's own listeners rather than through `propagate`, and that is
470
+ * the subtle half. `propagate` walks this package's retained tree to emulate the bubbling
471
+ * React Native does in JavaScript. The DOM already bubbles, so a click on a child arrives at
472
+ * an ancestor's listener by itself, and running both would call every ancestor handler twice.
473
+ */
474
+ if (ENGINE_EVENTS.has(topLevelType))
475
+ return;
476
+ node.el.addEventListener(topLevelType.slice(3).toLowerCase(), (event) => {
477
+ for (const listener of [...(node.listeners?.get(topLevelType) ?? [])]) {
478
+ if (listener(event) === false)
479
+ event.preventDefault();
480
+ }
481
+ });
482
+ }
483
+ // --- document-level listeners, shared by the whole tree ------------------------------------
484
+ installGlobalListeners() {
485
+ const on = (type, listener) => this.document.addEventListener(type, listener, { signal: this.listening.signal });
486
+ for (const type of ['pointerdown', 'pointermove', 'pointerup', 'pointercancel']) {
487
+ on(type, (event) => this.onPointer(event, type));
488
+ }
489
+ on('focusin', (event) => this.onFocusChange(event, true));
490
+ on('focusout', (event) => this.onFocusChange(event, false));
491
+ on('keydown', (event) => this.onKey(event, true));
492
+ on('keyup', (event) => this.onKey(event, false));
493
+ }
494
+ /** The control a held Space is pressing, released on the matching `keyup`. */
495
+ keyPress = null;
496
+ /**
497
+ * Enter and Space press the focused control, as they press a `<button>`.
498
+ *
499
+ * A pressable is focusable and announces itself as a button, but it presses through the
500
+ * responder negotiation, which only pointer events drove - so a keyboard user could tab to it
501
+ * and do nothing with it. The key becomes the same touch a finger would make, on the control
502
+ * itself, so `pressIn`, `press` and `pressOut` all fire, in order, through the same code.
503
+ *
504
+ * Enter presses on the way down and Space on the way up, which is the browser's own rule for a
505
+ * button; Space is also kept from scrolling the page. A text field and a switch are left alone,
506
+ * because the browser's own control already does the right thing with both keys.
507
+ */
508
+ onKey(event, down) {
509
+ if (event.key !== 'Enter' && event.key !== ' ')
510
+ return;
511
+ const space = event.key === ' ';
512
+ if (!down) {
513
+ const node = this.keyPress;
514
+ if (!space || !node)
515
+ return;
516
+ this.keyPress = null;
517
+ this.dispatchEvent(node, 'topTouchEnd', this.keyTouch(node));
518
+ return;
519
+ }
520
+ const node = this.keyTarget(event);
521
+ if (!node)
522
+ return;
523
+ event.preventDefault();
524
+ if (event.repeat || this.keyPress)
525
+ return;
526
+ this.dispatchEvent(node, 'topTouchStart', this.keyTouch(node));
527
+ if (space)
528
+ this.keyPress = node;
529
+ else
530
+ this.dispatchEvent(node, 'topTouchEnd', this.keyTouch(node));
531
+ }
532
+ /** The focused control a key would press, or null where the key belongs to something else. */
533
+ keyTarget(event) {
534
+ if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey)
535
+ return null;
536
+ const node = nodeOf(event.target);
537
+ if (!node || node.name === 'text-input' || node.name === 'switch')
538
+ return null;
539
+ return this.responders.responds(node) ? node : null;
540
+ }
541
+ /** A touch at the control's centre, so nothing downstream mistakes it for a drag. */
542
+ keyTouch(node) {
543
+ const rect = node.el.getBoundingClientRect();
544
+ return { pageX: rect.x + rect.width / 2, pageY: rect.y + rect.height / 2, identifier: -1 };
545
+ }
546
+ onPointer(event, domType) {
547
+ let target;
548
+ if (domType === 'pointerdown') {
549
+ // A right or middle click opens a menu or a tab; only the primary button presses.
550
+ if (event.button > 0)
551
+ return;
552
+ target = nearestNodeOf(event.target) ?? undefined;
553
+ if (!target || !this.owned.has(target))
554
+ return;
555
+ this.activeTouches.set(event.pointerId, target);
556
+ // Pins every later event in this gesture to the element the finger actually landed on,
557
+ // regardless of where it wanders - what makes the negotiation's `target` mean the same
558
+ // thing `topTouchMove`/`topTouchEnd` that Fabric's continuous per-finger delivery does.
559
+ event.target.setPointerCapture?.(event.pointerId);
560
+ }
561
+ else {
562
+ target = this.activeTouches.get(event.pointerId);
563
+ if (!target)
564
+ return;
565
+ if (domType === 'pointerup' || domType === 'pointercancel')
566
+ this.activeTouches.delete(event.pointerId);
567
+ }
568
+ this.dispatchEvent(target, TOUCH_EVENT_NAMES[domType], {
569
+ pageX: event.pageX,
570
+ pageY: event.pageY,
571
+ identifier: event.pointerId,
572
+ });
573
+ }
574
+ onFocusChange(event, focused) {
575
+ const node = nearestNodeOf(event.target);
576
+ if (!node || !this.owned.has(node))
577
+ return;
578
+ if (focused)
579
+ this.focusedNode = node;
580
+ else if (this.focusedNode === node)
581
+ this.focusedNode = null;
582
+ this.dispatchEvent(node, focused ? 'topFocus' : 'topBlur', { target: 0 });
583
+ }
584
+ }
585
+ //# sourceMappingURL=browser-engine.js.map