foldkit-primitives 0.2.1 → 0.4.0

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 (57) hide show
  1. package/README.md +514 -43
  2. package/dist/device/index.d.mts +11 -11
  3. package/dist/device/index.d.mts.map +1 -1
  4. package/dist/device/index.mjs +95 -87
  5. package/dist/device/index.mjs.map +1 -1
  6. package/dist/dom/index.d.mts +71 -1
  7. package/dist/dom/index.d.mts.map +1 -1
  8. package/dist/dom/index.mjs +303 -5
  9. package/dist/dom/index.mjs.map +1 -1
  10. package/dist/editable-text-CKkS_mWt.d.mts +235 -0
  11. package/dist/editable-text-CKkS_mWt.d.mts.map +1 -0
  12. package/dist/events/index.d.mts +10 -1
  13. package/dist/events/index.d.mts.map +1 -1
  14. package/dist/events/index.mjs +34 -18
  15. package/dist/events/index.mjs.map +1 -1
  16. package/dist/follow-tab-stop-DpxwLXvU.mjs +800 -0
  17. package/dist/follow-tab-stop-DpxwLXvU.mjs.map +1 -0
  18. package/dist/index-Cppf-lBx.d.mts +130 -0
  19. package/dist/index-Cppf-lBx.d.mts.map +1 -0
  20. package/dist/index.d.mts +8 -6
  21. package/dist/index.mjs +8 -6
  22. package/dist/input-modality-DGOhAknO.d.mts +26 -0
  23. package/dist/input-modality-DGOhAknO.d.mts.map +1 -0
  24. package/dist/input-modality-m6v7__Xs.mjs +43 -0
  25. package/dist/input-modality-m6v7__Xs.mjs.map +1 -0
  26. package/dist/interaction/index.d.mts +1017 -0
  27. package/dist/interaction/index.d.mts.map +1 -0
  28. package/dist/interaction/index.mjs +1647 -0
  29. package/dist/interaction/index.mjs.map +1 -0
  30. package/dist/internal-DP-xLKbT.mjs +37 -0
  31. package/dist/internal-DP-xLKbT.mjs.map +1 -0
  32. package/dist/media/index.d.mts.map +1 -1
  33. package/dist/media/index.mjs +3 -3
  34. package/dist/media/index.mjs.map +1 -1
  35. package/dist/motion/index.d.mts +2 -112
  36. package/dist/motion/index.mjs +2 -208
  37. package/dist/motion-DGGBZ0wt.mjs +240 -0
  38. package/dist/motion-DGGBZ0wt.mjs.map +1 -0
  39. package/dist/net/index.d.mts +68 -4
  40. package/dist/net/index.d.mts.map +1 -1
  41. package/dist/net/index.mjs +139 -56
  42. package/dist/net/index.mjs.map +1 -1
  43. package/dist/observers/index.d.mts +1 -1
  44. package/dist/observers/index.mjs +3 -0
  45. package/dist/observers/index.mjs.map +1 -1
  46. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  47. package/dist/state/index.d.mts +57 -15
  48. package/dist/state/index.d.mts.map +1 -1
  49. package/dist/state/index.mjs +198 -90
  50. package/dist/state/index.mjs.map +1 -1
  51. package/dist/time/index.d.mts +21 -1
  52. package/dist/time/index.d.mts.map +1 -1
  53. package/dist/time/index.mjs +48 -19
  54. package/dist/time/index.mjs.map +1 -1
  55. package/package.json +31 -8
  56. package/dist/motion/index.d.mts.map +0 -1
  57. package/dist/motion/index.mjs.map +0 -1
@@ -0,0 +1,800 @@
1
+ import { Effect, Queue, Schema, Stream } from "effect";
2
+ import * as Mount from "foldkit/mount";
3
+ import * as Dom from "foldkit/dom";
4
+ //#region src/dom/focus-scope.ts
5
+ /**
6
+ * A focus scope as a Mount: on insert it remembers what was focused, focuses
7
+ * an initial element inside, and with `contain` keeps Tab and Shift+Tab
8
+ * cycling inside; on unmount it gives focus back. Nothing crosses to the
9
+ * Model: which element had focus is a DOM fact, so this is element lifecycle,
10
+ * not state. It emits no Messages.
11
+ */
12
+ const FOCUSABLE = [
13
+ "a[href]",
14
+ "button:not([disabled])",
15
+ "input:not([disabled]):not([type=\"hidden\"])",
16
+ "select:not([disabled])",
17
+ "textarea:not([disabled])",
18
+ "[tabindex]",
19
+ "[contenteditable=\"true\"]"
20
+ ].join(", ");
21
+ const isVisible = (element) => {
22
+ const probe = element;
23
+ return element.closest("[hidden], [inert]") === null && (probe.checkVisibility?.() ?? true);
24
+ };
25
+ /** Tabbable descendants in DOM order: focusable, visible, and not `tabindex="-1"`. */
26
+ const tabbableWithin = (root) => Array.from(root.querySelectorAll(FOCUSABLE)).filter((element) => element.tabIndex >= 0 && isVisible(element));
27
+ const focusFirst = (elements) => {
28
+ const first = elements[0];
29
+ if (first === void 0) return false;
30
+ first.focus();
31
+ return true;
32
+ };
33
+ const FocusScope = Mount.defineStream("FocusScope", {
34
+ messages: [Schema.Never],
35
+ args: {
36
+ /** Keep Tab, Shift+Tab, and a stray focus inside. */
37
+ contain: Schema.Boolean,
38
+ /** Give focus back to what had it, on unmount. */
39
+ restore: Schema.Boolean,
40
+ /** A selector inside the element to focus first; else the first tabbable
41
+ * descendant, else the element itself when it is focusable. */
42
+ initialFocus: Schema.NullOr(Schema.String)
43
+ },
44
+ execute: ({ element, contain, restore, initialFocus }) => Stream.callback(() => Effect.acquireRelease(Effect.sync(() => {
45
+ const ownerDocument = element.ownerDocument;
46
+ const previous = ownerDocument.activeElement;
47
+ const initial = initialFocus === null ? null : element.querySelector(initialFocus);
48
+ if (initial !== null) initial.focus();
49
+ else if (!focusFirst(tabbableWithin(element)) && element instanceof HTMLElement) element.focus();
50
+ const onKeyDown = (event) => {
51
+ const key = event;
52
+ if (key.key !== "Tab") return;
53
+ const tabbable = tabbableWithin(element);
54
+ const first = tabbable[0];
55
+ const last = tabbable[tabbable.length - 1];
56
+ if (first === void 0 || last === void 0) {
57
+ key.preventDefault();
58
+ return;
59
+ }
60
+ const active = ownerDocument.activeElement;
61
+ if (key.shiftKey && (active === first || !element.contains(active))) {
62
+ key.preventDefault();
63
+ last.focus();
64
+ } else if (!key.shiftKey && (active === last || !element.contains(active))) {
65
+ key.preventDefault();
66
+ first.focus();
67
+ }
68
+ };
69
+ const onFocusIn = (event) => {
70
+ const target = event.target;
71
+ if (target instanceof Node && element.contains(target)) return;
72
+ focusFirst(tabbableWithin(element));
73
+ };
74
+ if (contain) {
75
+ element.addEventListener("keydown", onKeyDown);
76
+ ownerDocument.addEventListener("focusin", onFocusIn);
77
+ }
78
+ return {
79
+ previous,
80
+ onKeyDown,
81
+ onFocusIn,
82
+ ownerDocument
83
+ };
84
+ }), ({ previous, onKeyDown, onFocusIn, ownerDocument }) => Effect.sync(() => {
85
+ if (contain) {
86
+ element.removeEventListener("keydown", onKeyDown);
87
+ ownerDocument.removeEventListener("focusin", onFocusIn);
88
+ }
89
+ if (restore && previous instanceof HTMLElement && ownerDocument.contains(previous)) previous.focus();
90
+ })))
91
+ });
92
+ //#endregion
93
+ //#region src/dom/layers.ts
94
+ /**
95
+ * Two Mounts over Foldkit's own DOM helpers, for an overlay that is not a
96
+ * native `<dialog>` or `popover`:
97
+ *
98
+ * - `ScrollLock` locks the document's scroll while mounted. Foldkit's lock is
99
+ * refcounted, so nested overlays release it only when the last one goes.
100
+ * - `HideOutside` marks everything outside the element inert while mounted,
101
+ * through `Dom.inertOthers`, keyed by an id this Mount mints.
102
+ *
103
+ * Both emit no Messages; they are element lifecycle.
104
+ */
105
+ const ScrollLock = Mount.defineStream("ScrollLock", {
106
+ messages: [Schema.Never],
107
+ execute: () => Stream.callback(() => Effect.acquireRelease(Dom.lockScroll, () => Dom.unlockScroll))
108
+ });
109
+ const HIDE_OUTSIDE_ATTRIBUTE = "data-foldkit-plus-hide-outside";
110
+ let minted = 0;
111
+ const HideOutside = Mount.defineStream("HideOutside", {
112
+ messages: [Schema.Never],
113
+ execute: ({ element }) => Stream.callback(() => Effect.acquireRelease(Effect.gen(function* () {
114
+ const id = `hide-outside-${minted += 1}`;
115
+ element.setAttribute(HIDE_OUTSIDE_ATTRIBUTE, id);
116
+ yield* Dom.inertOthers(id, [`[${HIDE_OUTSIDE_ATTRIBUTE}="${id}"]`]);
117
+ return id;
118
+ }), (id) => Effect.andThen(Dom.restoreInert(id), () => Effect.sync(() => element.removeAttribute(HIDE_OUTSIDE_ATTRIBUTE)))))
119
+ });
120
+ //#endregion
121
+ //#region src/dom/move.ts
122
+ /**
123
+ * Pointer movement on an element as a Mount: a primary-button pointer down
124
+ * captures the pointer, each move reports the delta from where it started,
125
+ * and up, cancel, or lost capture ends it. Nothing is decided here: a drag
126
+ * threshold, a snap, or a constraint is the parent's `update`. Capture is
127
+ * released with the Mount.
128
+ */
129
+ const MoveStarted = Schema.TaggedStruct("MoveStarted", {
130
+ pointerId: Schema.Number,
131
+ pointerType: Schema.String
132
+ });
133
+ const Moved = Schema.TaggedStruct("Moved", {
134
+ pointerId: Schema.Number,
135
+ /** From where the pointer went down, in CSS pixels. */
136
+ deltaX: Schema.Number,
137
+ deltaY: Schema.Number,
138
+ pointerType: Schema.String
139
+ });
140
+ const MoveEnded = Schema.TaggedStruct("MoveEnded", {
141
+ pointerId: Schema.Number,
142
+ /** `false` when the pointer was cancelled or capture was lost. */
143
+ completed: Schema.Boolean
144
+ });
145
+ const Move = Mount.defineStream("Move", {
146
+ messages: [
147
+ MoveStarted,
148
+ Moved,
149
+ MoveEnded
150
+ ],
151
+ execute: ({ element }) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
152
+ const target = element;
153
+ let active = null;
154
+ const offer = (fact) => Queue.offerUnsafe(queue, fact);
155
+ const end = (pointerId, completed) => {
156
+ if (active === null || active.pointerId !== pointerId) return;
157
+ active = null;
158
+ try {
159
+ target.releasePointerCapture?.(pointerId);
160
+ } catch {}
161
+ offer(MoveEnded.make({
162
+ pointerId,
163
+ completed
164
+ }));
165
+ };
166
+ const listeners = [
167
+ ["pointerdown", (event) => {
168
+ const pointer = event;
169
+ if ((pointer.button ?? 0) !== 0 || active !== null) return;
170
+ const pointerId = pointer.pointerId ?? 0;
171
+ active = {
172
+ pointerId,
173
+ x: pointer.clientX ?? 0,
174
+ y: pointer.clientY ?? 0
175
+ };
176
+ try {
177
+ target.setPointerCapture?.(pointerId);
178
+ } catch {}
179
+ offer(MoveStarted.make({
180
+ pointerId,
181
+ pointerType: pointer.pointerType ?? "mouse"
182
+ }));
183
+ }],
184
+ ["pointermove", (event) => {
185
+ const pointer = event;
186
+ const pointerId = pointer.pointerId ?? 0;
187
+ if (active === null || active.pointerId !== pointerId) return;
188
+ offer(Moved.make({
189
+ pointerId,
190
+ deltaX: (pointer.clientX ?? 0) - active.x,
191
+ deltaY: (pointer.clientY ?? 0) - active.y,
192
+ pointerType: pointer.pointerType ?? "mouse"
193
+ }));
194
+ }],
195
+ ["pointerup", (event) => end(event.pointerId ?? 0, true)],
196
+ ["pointercancel", (event) => end(event.pointerId ?? 0, false)],
197
+ ["lostpointercapture", (event) => end(event.pointerId ?? 0, false)]
198
+ ];
199
+ for (const [type, listener] of listeners) element.addEventListener(type, listener);
200
+ return {
201
+ listeners,
202
+ current: () => active
203
+ };
204
+ }), ({ listeners, current }) => Effect.sync(() => {
205
+ for (const [type, listener] of listeners) element.removeEventListener(type, listener);
206
+ const pointer = current();
207
+ if (pointer !== null) try {
208
+ element.releasePointerCapture?.(pointer.pointerId);
209
+ } catch {}
210
+ })))
211
+ });
212
+ //#endregion
213
+ //#region src/dom/targets.ts
214
+ /**
215
+ * Which marked descendant of an element the pointer is over, and which one was
216
+ * pressed, as a Mount: one set of listeners on the container, not one per item.
217
+ * A descendant is marked by an attribute whose value is its id, such as a
218
+ * canvas's `data-composition-node` or a table's `data-row`. The nearest marked
219
+ * ancestor of the event's target, inside the container, is the one reported.
220
+ *
221
+ * What hovering or pressing means (a selection, an outline, a menu) is the
222
+ * parent's `update`.
223
+ */
224
+ const TargetHovered = Schema.TaggedStruct("TargetHovered", {
225
+ /** The marked descendant under the pointer, or `null` when there is none. */
226
+ id: Schema.NullOr(Schema.String) });
227
+ const TargetPressed = Schema.TaggedStruct("TargetPressed", {
228
+ id: Schema.String,
229
+ shiftKey: Schema.Boolean,
230
+ altKey: Schema.Boolean,
231
+ ctrlKey: Schema.Boolean,
232
+ metaKey: Schema.Boolean
233
+ });
234
+ /** The id of the nearest marked element at or above `from`, inside `container`. */
235
+ const targetOf = (container, from, attribute) => {
236
+ if (!(from instanceof Element)) return null;
237
+ const marked = from.closest(`[${attribute}]`);
238
+ return marked !== null && container.contains(marked) ? marked.getAttribute(attribute) : null;
239
+ };
240
+ const Targets = Mount.defineStream("Targets", {
241
+ messages: [TargetHovered, TargetPressed],
242
+ args: {
243
+ /** The attribute that marks a descendant, holding its id. */
244
+ attribute: Schema.String,
245
+ /** Prevent a press's default, such as a link navigating inside an editor's canvas. */
246
+ preventDefault: Schema.Boolean
247
+ },
248
+ execute: ({ element, attribute, preventDefault }) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
249
+ let hovered = null;
250
+ const hover = (id) => {
251
+ if (id === hovered) return;
252
+ hovered = id;
253
+ Queue.offerUnsafe(queue, TargetHovered.make({ id }));
254
+ };
255
+ const listeners = [
256
+ ["pointerover", (event) => hover(targetOf(element, event.target, attribute))],
257
+ ["pointerleave", () => hover(null)],
258
+ ["click", (event) => {
259
+ const id = targetOf(element, event.target, attribute);
260
+ if (id === null) return;
261
+ if (preventDefault) event.preventDefault();
262
+ const modified = event;
263
+ Queue.offerUnsafe(queue, TargetPressed.make({
264
+ id,
265
+ shiftKey: modified.shiftKey === true,
266
+ altKey: modified.altKey === true,
267
+ ctrlKey: modified.ctrlKey === true,
268
+ metaKey: modified.metaKey === true
269
+ }));
270
+ }]
271
+ ];
272
+ for (const [type, listener] of listeners) element.addEventListener(type, listener);
273
+ return listeners;
274
+ }), (listeners) => Effect.sync(() => {
275
+ for (const [type, listener] of listeners) element.removeEventListener(type, listener);
276
+ })))
277
+ });
278
+ //#endregion
279
+ //#region src/dom/pointer-drag.ts
280
+ /**
281
+ * Dragging one marked descendant of an element onto another, as a Mount. A
282
+ * descendant is marked by an attribute whose value is its id, as `Targets`
283
+ * marks them; a press on one that then moves past a threshold starts a drag,
284
+ * and the pointer's place over another marked descendant is reported with the
285
+ * zone of it the pointer is in: its first third (`before`), its middle
286
+ * (`inside`), or its last third (`after`). Releasing drops, and Escape or a
287
+ * cancelled pointer ends the drag with nothing dropped.
288
+ *
289
+ * It writes no roles, no `tabindex` and no key handling, so the marked
290
+ * elements can be anything: a tree's rows, a canvas's nodes. The keyboard's way
291
+ * to do what a drag does is the parent's to give. Geometry is measured when the
292
+ * pointer moves and never kept; what a drop means is the parent's `update`.
293
+ */
294
+ const DragZone = Schema.Literals([
295
+ "before",
296
+ "inside",
297
+ "after"
298
+ ]);
299
+ /** A marked descendant under the pointer, and the zone of it the pointer is in. */
300
+ const DragPlace = Schema.Struct({
301
+ id: Schema.String,
302
+ zone: DragZone
303
+ });
304
+ const DragStarted = Schema.TaggedStruct("DragStarted", {
305
+ /** The marked descendant being dragged. */
306
+ id: Schema.String });
307
+ const DraggedOver = Schema.TaggedStruct("DraggedOver", {
308
+ /** Where the pointer is, or `null` over nothing marked, or over what is dragged. */
309
+ over: Schema.NullOr(DragPlace),
310
+ /**
311
+ * For a drag onto `targets`: whether the pointer is inside the region they
312
+ * are in, so `over: null` with `region: true` is its empty space (an empty
313
+ * page, the space below the last node). Absent for a drag among its own.
314
+ */
315
+ region: Schema.optionalKey(Schema.Boolean)
316
+ });
317
+ const DragDropped = Schema.TaggedStruct("DragDropped", {
318
+ id: Schema.String,
319
+ over: Schema.NullOr(DragPlace),
320
+ /** As `DraggedOver`'s: released inside the `targets` region. */
321
+ region: Schema.optionalKey(Schema.Boolean)
322
+ });
323
+ const DragCancelled = Schema.TaggedStruct("DragCancelled", { id: Schema.String });
324
+ /** How far, in CSS pixels, a press moves before it is a drag rather than a click. */
325
+ const DRAG_THRESHOLD = 4;
326
+ /** The zone of a box a vertical position falls in, by thirds. */
327
+ const zoneOf = (box, y) => {
328
+ if (box.height <= 0) return "inside";
329
+ const at = (y - box.top) / box.height;
330
+ return at < 1 / 3 ? "before" : at > 2 / 3 ? "after" : "inside";
331
+ };
332
+ /**
333
+ * An element's box. An element drawn as `display: contents` has none, so its
334
+ * first child's stands for it, as an editor's node wrapper's does.
335
+ */
336
+ const boxOf = (element) => {
337
+ const own = element.getBoundingClientRect();
338
+ if (own.width > 0 || own.height > 0) return own;
339
+ const child = element.firstElementChild;
340
+ return child === null ? own : boxOf(child);
341
+ };
342
+ const PointerDrag = Mount.defineStream("PointerDrag", {
343
+ messages: [
344
+ DragStarted,
345
+ DraggedOver,
346
+ DragDropped,
347
+ DragCancelled
348
+ ],
349
+ args: {
350
+ /** The attribute that marks a descendant, holding its id. */
351
+ attribute: Schema.String,
352
+ /**
353
+ * Where a drag may land, when not on the element's own marked descendants:
354
+ * the elements marked by `attribute` inside the one `within` selects, such
355
+ * as a palette's Blocks dragged onto a page. A drop's `over` is then one of
356
+ * those; what is dragged is still one of the element's own. `within` is
357
+ * looked for nearest first, under the element's closest ancestor that holds
358
+ * a match, so two editors on one page each drop onto their own.
359
+ */
360
+ targets: Schema.optionalKey(Schema.Struct({
361
+ attribute: Schema.String,
362
+ within: Schema.String
363
+ }))
364
+ },
365
+ execute: ({ element, attribute, targets }) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
366
+ const owner = element.ownerDocument;
367
+ const landsOn = targets?.attribute ?? attribute;
368
+ const regionOf = (within) => {
369
+ for (let at = element.parentElement; at !== null; at = at.parentElement) {
370
+ const found = at.querySelector(within);
371
+ if (found !== null) return found;
372
+ }
373
+ return null;
374
+ };
375
+ const find = (from) => {
376
+ if (!(from instanceof Element)) return {
377
+ marked: null,
378
+ inRegion: false
379
+ };
380
+ const region = targets === void 0 ? element : regionOf(targets.within);
381
+ const marked = from.closest(`[${landsOn}]`);
382
+ return {
383
+ marked: marked !== null && region !== null && region.contains(marked) ? marked : null,
384
+ inRegion: targets !== void 0 && region !== null && region.contains(from)
385
+ };
386
+ };
387
+ let pressed = null;
388
+ let dragging = null;
389
+ let over = null;
390
+ let inRegion = false;
391
+ let swallowClick = false;
392
+ const placeAt = (event) => {
393
+ const under = typeof owner.elementFromPoint === "function" && event.clientX !== void 0 ? owner.elementFromPoint(event.clientX, event.clientY ?? 0) : null;
394
+ const { marked, inRegion: region } = find(under ?? event.target);
395
+ const id = marked?.getAttribute(landsOn) ?? null;
396
+ return {
397
+ place: marked === null || id === null || targets === void 0 && id === dragging ? null : {
398
+ id,
399
+ zone: zoneOf(boxOf(marked), event.clientY ?? 0)
400
+ },
401
+ region
402
+ };
403
+ };
404
+ /** The region flag a fact carries: only for a drag onto `targets`. */
405
+ const withRegion = (region) => targets === void 0 ? {} : { region };
406
+ const ours = (event) => pressed !== null && (pressed.pointer === void 0 || event.pointerId === pressed.pointer);
407
+ const end = (dropped, inside = false) => {
408
+ const id = dragging;
409
+ pressed = null;
410
+ dragging = null;
411
+ const last = over;
412
+ const lastRegion = inRegion;
413
+ over = null;
414
+ inRegion = false;
415
+ release();
416
+ if (id === null) return;
417
+ swallowClick = dropped && inside;
418
+ Queue.offerUnsafe(queue, dropped ? DragDropped.make({
419
+ id,
420
+ over: last,
421
+ ...withRegion(lastRegion)
422
+ }) : DragCancelled.make({ id }));
423
+ };
424
+ const onDocument = [
425
+ ["pointermove", (event) => {
426
+ const positioned = event;
427
+ if (!ours(positioned) || pressed === null) return;
428
+ if (positioned.buttons !== void 0 && (positioned.buttons & 1) === 0) return end(false);
429
+ if (dragging === null) {
430
+ if (Math.hypot((positioned.clientX ?? 0) - pressed.x, (positioned.clientY ?? 0) - pressed.y) < 4) return;
431
+ dragging = pressed.id;
432
+ owner.getSelection()?.removeAllRanges();
433
+ Queue.offerUnsafe(queue, DragStarted.make({ id: dragging }));
434
+ }
435
+ const { place, region } = placeAt(positioned);
436
+ if (place?.id === over?.id && place?.zone === over?.zone && region === inRegion) return;
437
+ over = place;
438
+ inRegion = region;
439
+ Queue.offerUnsafe(queue, DraggedOver.make({
440
+ over: place,
441
+ ...withRegion(region)
442
+ }));
443
+ }],
444
+ ["pointerup", (event) => {
445
+ if (!ours(event)) return;
446
+ if (dragging === null) end(false);
447
+ else end(true, event.target instanceof Node && element.contains(event.target));
448
+ }],
449
+ ["pointercancel", (event) => {
450
+ if (ours(event)) end(false);
451
+ }]
452
+ ];
453
+ const onEscape = (event) => {
454
+ if (pressed === null || event.key !== "Escape") return;
455
+ event.preventDefault();
456
+ event.stopPropagation();
457
+ end(false);
458
+ };
459
+ let listening = false;
460
+ const listen = () => {
461
+ if (listening) return;
462
+ listening = true;
463
+ for (const [type, listener] of onDocument) owner.addEventListener(type, listener);
464
+ owner.addEventListener("keydown", onEscape, true);
465
+ };
466
+ const release = () => {
467
+ if (!listening) return;
468
+ listening = false;
469
+ for (const [type, listener] of onDocument) owner.removeEventListener(type, listener);
470
+ owner.removeEventListener("keydown", onEscape, true);
471
+ };
472
+ const onElement = [
473
+ [
474
+ "pointerdown",
475
+ (event) => {
476
+ const positioned = event;
477
+ swallowClick = false;
478
+ if (pressed !== null) return;
479
+ if ((positioned.button ?? 0) !== 0) return;
480
+ if (event.target instanceof Element && event.target.closest("[contenteditable]:not([contenteditable=\"false\"])") !== null) return;
481
+ const id = targetOf(element, event.target, attribute);
482
+ if (id === null) return;
483
+ pressed = {
484
+ id,
485
+ pointer: positioned.pointerId,
486
+ x: positioned.clientX ?? 0,
487
+ y: positioned.clientY ?? 0
488
+ };
489
+ listen();
490
+ },
491
+ false
492
+ ],
493
+ [
494
+ "click",
495
+ (event) => {
496
+ if (!swallowClick) return;
497
+ swallowClick = false;
498
+ event.preventDefault();
499
+ event.stopImmediatePropagation();
500
+ },
501
+ true
502
+ ],
503
+ [
504
+ "dragstart",
505
+ (event) => event.preventDefault(),
506
+ false
507
+ ]
508
+ ];
509
+ for (const [type, listener, capture] of onElement) element.addEventListener(type, listener, capture);
510
+ return {
511
+ onElement,
512
+ release
513
+ };
514
+ }), ({ onElement, release }) => Effect.sync(() => {
515
+ for (const [type, listener, capture] of onElement) element.removeEventListener(type, listener, capture);
516
+ release();
517
+ })))
518
+ });
519
+ //#endregion
520
+ //#region src/dom/editable-text.ts
521
+ /**
522
+ * Text typed into an editable descendant of an element, as a Mount: one set of
523
+ * listeners on the container, like `Targets`. A field is a descendant marked
524
+ * by an attribute whose value names it, while it is `contenteditable`. The
525
+ * view decides which one is; the Mount focuses it as it becomes so (made
526
+ * editable, or drawn editable), with the caret at its end, and at no other
527
+ * time. When Enter or Escape ends an edit and the view then removes the field
528
+ * or makes it no longer editable, focus, left on nothing, comes back to the
529
+ * container, so the next key reaches it; give the container a `tabindex`. A double-click on a marked field that is not editable yet asks for it
530
+ * to be (`EditAsked`).
531
+ *
532
+ * It reads `innerText`, never `innerHTML`, so what arrives is text. A field is
533
+ * one line unless it carries `aria-multiline="true"`: in one line, a line
534
+ * break becomes a space. Nothing is reported while an input method composes;
535
+ * the composed text arrives once, when it is done.
536
+ *
537
+ * Enter commits (Shift+Enter breaks a line in a multiline field), and so does
538
+ * leaving the field. Escape cancels, and puts the text the field had when
539
+ * editing began back in the DOM, since a view that stopped redrawing the field
540
+ * while it was edited will not. Where the browser lacks `plaintext-only`, a
541
+ * paste is inserted as text. What an edit means is the parent's `update`.
542
+ */
543
+ const TextEdited = Schema.TaggedStruct("TextEdited", {
544
+ /** The field, by its marking attribute's value. */
545
+ field: Schema.String,
546
+ text: Schema.String
547
+ });
548
+ const TextCommitted = Schema.TaggedStruct("TextCommitted", {
549
+ field: Schema.String,
550
+ text: Schema.String
551
+ });
552
+ const TextCancelled = Schema.TaggedStruct("TextCancelled", {
553
+ field: Schema.String,
554
+ /** The text the field had when editing began, which the DOM shows again. */
555
+ initial: Schema.String
556
+ });
557
+ const EditAsked = Schema.TaggedStruct("EditAsked", {
558
+ /** A marked field, not editable yet, that was double-clicked. */
559
+ field: Schema.String });
560
+ /** Whether a field takes more than one line. */
561
+ const multiline = (element) => element.getAttribute("aria-multiline") === "true";
562
+ /**
563
+ * A field's text. A browser ends an edited element with a line break it adds
564
+ * itself, which is not the author's; in one line, the author's breaks are spaces.
565
+ */
566
+ const textOf = (element) => {
567
+ const text = element.innerText.replace(/\r\n?/g, "\n").replace(/\n$/, "");
568
+ return multiline(element) ? text : text.replace(/\n+/g, " ");
569
+ };
570
+ /** Puts the caret at the end of a field, which focuses it too. */
571
+ const caretAtEnd = (field) => {
572
+ field.focus();
573
+ const caret = document.createRange();
574
+ caret.selectNodeContents(field);
575
+ caret.collapse(false);
576
+ const selection = window.getSelection();
577
+ selection?.removeAllRanges();
578
+ selection?.addRange(caret);
579
+ };
580
+ /** Whether a key press belongs to an input method still composing, not to the field. */
581
+ const composing = (event) => event.isComposing || event.keyCode === 229;
582
+ const EditableText = Mount.defineStream("EditableText", {
583
+ messages: [
584
+ TextEdited,
585
+ TextCommitted,
586
+ TextCancelled,
587
+ EditAsked
588
+ ],
589
+ args: {
590
+ /** The attribute that marks a field, holding its name. */
591
+ attribute: Schema.String },
592
+ execute: ({ element, attribute }) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
593
+ /** The field being edited: its name, its text when editing began, and the last reported. */
594
+ let current;
595
+ let composingText = false;
596
+ let ending;
597
+ /** The marked field at or above an event's target, inside the container. */
598
+ const markedOf = (target) => {
599
+ if (!(target instanceof Element)) return void 0;
600
+ const field = target.closest(`[${attribute}]`);
601
+ return field instanceof HTMLElement && element.contains(field) ? field : void 0;
602
+ };
603
+ /** The same, while it is editable. */
604
+ const fieldOf = (target) => {
605
+ const field = markedOf(target);
606
+ return field?.isContentEditable === true ? field : void 0;
607
+ };
608
+ /** Begins an edit of `field`, unless one of it is under way: on focus, or typing. */
609
+ const begin = (field) => {
610
+ if (current?.field === field && !current.ended) return current;
611
+ const text = textOf(field);
612
+ current = {
613
+ field,
614
+ name: field.getAttribute(attribute) ?? "",
615
+ initial: text,
616
+ reported: text,
617
+ ended: false
618
+ };
619
+ return current;
620
+ };
621
+ /**
622
+ * The edit of `field`: the one under way or just ended, else one begun
623
+ * now, for a field focused before these listeners came. An ended edit
624
+ * reports nothing more, so the blur that follows a commit or a cancel
625
+ * does not commit again.
626
+ */
627
+ const editOf = (field) => current?.field === field ? current : begin(field);
628
+ const report = (field) => {
629
+ const edit = editOf(field);
630
+ if (edit.ended) return;
631
+ const text = textOf(field);
632
+ if (text === edit.reported) return;
633
+ edit.reported = text;
634
+ Queue.offerUnsafe(queue, TextEdited.make({
635
+ field: edit.name,
636
+ text
637
+ }));
638
+ };
639
+ const commit = (field) => {
640
+ const edit = editOf(field);
641
+ if (edit.ended) return;
642
+ edit.ended = true;
643
+ Queue.offerUnsafe(queue, TextCommitted.make({
644
+ field: edit.name,
645
+ text: textOf(field)
646
+ }));
647
+ };
648
+ const cancel = (field) => {
649
+ const edit = editOf(field);
650
+ if (edit.ended) return;
651
+ edit.ended = true;
652
+ field.innerText = edit.initial;
653
+ caretAtEnd(field);
654
+ Queue.offerUnsafe(queue, TextCancelled.make({
655
+ field: edit.name,
656
+ initial: edit.initial
657
+ }));
658
+ };
659
+ const listeners = [
660
+ ["dblclick", (event) => {
661
+ const field = markedOf(event.target);
662
+ if (field === void 0 || field.isContentEditable) return;
663
+ Queue.offerUnsafe(queue, EditAsked.make({ field: field.getAttribute(attribute) ?? "" }));
664
+ }],
665
+ ["focusin", (event) => {
666
+ composingText = false;
667
+ const field = fieldOf(event.target);
668
+ if (field !== void 0) begin(field);
669
+ }],
670
+ ["beforeinput", (event) => {
671
+ const field = fieldOf(event.target);
672
+ if (field !== void 0) begin(field);
673
+ }],
674
+ ["compositionstart", () => composingText = true],
675
+ ["compositionend", (event) => {
676
+ composingText = false;
677
+ const field = fieldOf(event.target);
678
+ if (field !== void 0) report(field);
679
+ }],
680
+ ["input", (event) => {
681
+ const field = fieldOf(event.target);
682
+ if (field !== void 0 && !composingText) report(field);
683
+ }],
684
+ ["keydown", (event) => {
685
+ const field = fieldOf(event.target);
686
+ const key = event;
687
+ if (field === void 0 || composing(key)) return;
688
+ if (key.key === "Escape") {
689
+ event.preventDefault();
690
+ ending = field;
691
+ cancel(field);
692
+ } else if (key.key === "Enter" && !(key.shiftKey && multiline(field))) {
693
+ event.preventDefault();
694
+ ending = field;
695
+ commit(field);
696
+ }
697
+ }],
698
+ ["focusout", (event) => {
699
+ const field = fieldOf(event.target);
700
+ if (field === void 0) return;
701
+ queueMicrotask(() => {
702
+ if (field === ending && field.isConnected && field.isContentEditable) ending = void 0;
703
+ });
704
+ commit(field);
705
+ }],
706
+ ["paste", (event) => {
707
+ const field = fieldOf(event.target);
708
+ if (field === void 0 || field.contentEditable === "plaintext-only") return;
709
+ const pasted = event.clipboardData?.getData("text/plain") ?? "";
710
+ event.preventDefault();
711
+ begin(field);
712
+ document.execCommand("insertText", false, pasted);
713
+ }]
714
+ ];
715
+ const editable = `[${attribute}][contenteditable]:not([contenteditable="false"])`;
716
+ const becoming = new MutationObserver((records) => {
717
+ if (ending !== void 0 && !(ending.isConnected && ending.isContentEditable)) {
718
+ ending = void 0;
719
+ const focused = document.activeElement;
720
+ if ((focused === null || focused === document.body) && element instanceof HTMLElement) element.focus({ preventScroll: true });
721
+ }
722
+ for (const record of records) {
723
+ const changed = record.type === "attributes" ? [record.target] : Array.from(record.addedNodes);
724
+ for (const node of changed) {
725
+ if (!(node instanceof HTMLElement)) continue;
726
+ const field = node.matches(editable) ? node : node.querySelector(editable);
727
+ if (field instanceof HTMLElement) return caretAtEnd(field);
728
+ }
729
+ }
730
+ });
731
+ for (const [type, listener] of listeners) element.addEventListener(type, listener);
732
+ becoming.observe(element, {
733
+ subtree: true,
734
+ childList: true,
735
+ attributes: true,
736
+ attributeFilter: ["contenteditable"]
737
+ });
738
+ return {
739
+ listeners,
740
+ becoming
741
+ };
742
+ }), ({ listeners, becoming }) => Effect.sync(() => {
743
+ becoming.disconnect();
744
+ for (const [type, listener] of listeners) element.removeEventListener(type, listener);
745
+ })))
746
+ });
747
+ //#endregion
748
+ //#region src/dom/follow-tab-stop.ts
749
+ /**
750
+ * Keeps focus that is inside a container of roving tab stops on its stop, as a
751
+ * Mount: when a transition moves the stop (a row made current by a command the
752
+ * container did not see, such as a duplicate) or removes the focused
753
+ * descendant (a deleted row), focus goes to the descendant with
754
+ * `tabindex="0"`. It sends no Message. Focus outside the container is never
755
+ * taken, and focus the user moved away stays where it went.
756
+ */
757
+ const FollowTabStop = Mount.defineStream("FollowTabStop", {
758
+ messages: [Schema.Never],
759
+ execute: ({ element }) => Stream.callback(() => Effect.acquireRelease(Effect.sync(() => {
760
+ let within = element.contains(document.activeElement);
761
+ const entered = () => {
762
+ within = true;
763
+ };
764
+ const left = (event) => {
765
+ const next = event.relatedTarget;
766
+ if (next instanceof Node && element.contains(next)) return;
767
+ const from = event.target;
768
+ queueMicrotask(() => {
769
+ if (!(from instanceof Node) || from.isConnected) within = false;
770
+ });
771
+ };
772
+ const follow = () => {
773
+ if (!within) return;
774
+ const stop = element.querySelector("[tabindex=\"0\"]");
775
+ const focused = document.activeElement;
776
+ if (!(stop instanceof HTMLElement) || stop === focused) return;
777
+ const lost = focused === null || focused === document.body;
778
+ const passed = focused !== null && element.contains(focused) && focused.getAttribute("tabindex") === "-1";
779
+ if (lost || passed) stop.focus();
780
+ };
781
+ const changes = new MutationObserver(follow);
782
+ element.addEventListener("focusin", entered);
783
+ element.addEventListener("focusout", left);
784
+ changes.observe(element, {
785
+ subtree: true,
786
+ childList: true,
787
+ attributes: true,
788
+ attributeFilter: ["tabindex"]
789
+ });
790
+ return () => {
791
+ changes.disconnect();
792
+ element.removeEventListener("focusin", entered);
793
+ element.removeEventListener("focusout", left);
794
+ };
795
+ }), (stop) => Effect.sync(stop)))
796
+ });
797
+ //#endregion
798
+ export { MoveEnded as C, ScrollLock as D, HideOutside as E, FocusScope as O, Move as S, Moved as T, zoneOf as _, TextCommitted as a, Targets as b, DRAG_THRESHOLD as c, DragPlace as d, DragStarted as f, boxOf as g, PointerDrag as h, TextCancelled as i, tabbableWithin as k, DragCancelled as l, DraggedOver as m, EditAsked as n, TextEdited as o, DragZone as p, EditableText as r, textOf as s, FollowTabStop as t, DragDropped as u, TargetHovered as v, MoveStarted as w, targetOf as x, TargetPressed as y };
799
+
800
+ //# sourceMappingURL=follow-tab-stop-DpxwLXvU.mjs.map