@grafctory/clay 0.0.0-stage → 0.4.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.
@@ -0,0 +1,732 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * Item transfers.
18
+ *
19
+ * Lets the components of an interface move items between sources and targets, wherever they sit in the page: a card
20
+ * into another column, a row to a new place in its list, files from the desktop into an upload zone. Drag and drop is
21
+ * one way of moving an item; a menu listing the targets that take it is the other, so every move a pointer makes is
22
+ * open to the keyboard and to a single tap as well.
23
+ *
24
+ * The module carries state and behaviour only. Each component draws its own items, grips, menus and drop indicators,
25
+ * reading the state the hooks return, so a board, a list and a tree look the way each needs:
26
+ *
27
+ * ```tsx
28
+ * function Card({ card }: { card: Card }) {
29
+ *
30
+ * const element = useId();
31
+ * const { dragging, targets, move } = useTransferSource({
32
+ * id: card.id, name: card.title, element, type: "application/x-card"
33
+ * });
34
+ *
35
+ * return <article id={element} data-dragging={dragging || undefined}>
36
+ * {card.title}
37
+ * <Menu items={targets.map(target => ({ label: target.name, action: () => move(target.id) }))}/>
38
+ * </article>;
39
+ *
40
+ * }
41
+ *
42
+ * function Column({ column }: { column: Column }) {
43
+ *
44
+ * const element = useId();
45
+ * const { target } = useTransferTarget({
46
+ * id: column.id, name: column.title, element, accept: ["application/x-card"],
47
+ * onDrop: drop => drop.source ? store.move(drop.source.id, column.id) : false
48
+ * });
49
+ *
50
+ * return <section id={element} data-target={target || undefined}>…</section>;
51
+ *
52
+ * }
53
+ * ```
54
+ *
55
+ * Sources and targets meet by MIME type: a source states the type of what it carries, and a target the types it
56
+ * takes, its own items and outside content such as `Files` or `text/uri-list` alike. Types are compared regardless of
57
+ * case.
58
+ *
59
+ * Elements are reached by their DOM id rather than by a ref, so a component states the id it renders its element
60
+ * under and hands the same id to the hook binding it.
61
+ *
62
+ * Every move ends with an announcement to screen readers, in English, telling where the item went or that the move was
63
+ * refused. A moved item glides to its new place over the design system's normal duration, or at once if the reader
64
+ * prefers reduced motion, and the focus follows it wherever it is drawn afresh.
65
+ *
66
+ * # Design
67
+ *
68
+ * - **Moves, not keyboard drags**: a reader without a pointer moves an item through a menu of plain buttons rather
69
+ * than by steering it with the arrow keys; every screen reader handles a menu, and a menu meets WCAG 2.5.7, which
70
+ * asks a single-pointer alternative to every drag and which a keyboard drag mode leaves unmet
71
+ * - **Native drag and drop**: the browser performs drags, so files and links dropped from other apps are taken as
72
+ * readily as items of the page, with no third-party engine; touch drags are added where the browser leaves them out
73
+ * - **Targets settle their own drops**: a column knows what taking a card means and an upload zone what to do with
74
+ * files, so each target answers its drops and the context carries no handlers of its own
75
+ * - **Types, not scopes**: sources and targets meet by MIME type across the whole app, since the browser runs a single
76
+ * drag at a time anyway; two boards kept apart take distinct types, and their move menus list only their own
77
+ * - **Visuals in each widget**: the module draws nothing but the off-screen status region, so a board, a list and a
78
+ * tree each draw their items and indicators with the design system roles they need
79
+ *
80
+ * The approach follows Atlassian's Pragmatic drag and drop and its
81
+ * [accessibility guidelines](https://atlassian.design/components/pragmatic-drag-and-drop/accessibility-guidelines),
82
+ * which take menus rather than keyboard drags as the way a reader moves items without a pointer.
83
+ *
84
+ * # Accessibility
85
+ *
86
+ * Measured against WCAG 2.2 AA, the module guarantees the parts every widget would otherwise get wrong alike:
87
+ *
88
+ * - a path for every move needing no drag (2.5.7, 2.1.1), through the `targets` and `move` of {@link useTransferSource}
89
+ * - the focus following a moved item (2.4.3), and the announcement closing each move (4.1.3)
90
+ * - drops settled on release, a drop outside any target or `Escape` cancelling (2.5.2)
91
+ * - the glide skipped where the reader prefers reduced motion (2.3.3)
92
+ *
93
+ * Each widget still owes the parts that depend on how it is drawn:
94
+ *
95
+ * - a visible control opening the moves: the grip doubling as the menu button where moving is the item's sole action,
96
+ * or an overflow (⋯) menu button where the item is dragged by its whole surface, never both (2.5.7)
97
+ * - a native file input beside a zone taking files (2.5.7)
98
+ * - controls named after their item, with `aria-haspopup` and `aria-expanded` on menu buttons (4.1.2), menus closing
99
+ * on `Escape` and handing the focus back (2.1.2), and visible focus rings (2.4.7)
100
+ * - grips and buttons at least 24 by 24 CSS pixels (2.5.8), and menus and previews never covering the focus (2.4.11)
101
+ * - drag states and drop targets told by shape or outline rather than colour alone (1.4.1), with marks holding 3:1
102
+ * against their background (1.4.11), as the selected role of the design system does
103
+ *
104
+ * @module
105
+ */
106
+ import { isPromiseLike } from "@grafctory/core";
107
+ import { immutable } from "@grafctory/core/values";
108
+ import { createContext, createElement } from "preact";
109
+ import { useContext, useEffect, useLayoutEffect, useState } from "preact/hooks";
110
+ import { isReserved } from "./index.js";
111
+ /**
112
+ * How long a finger rests on a draggable element before a drag starts, in milliseconds; a shorter press is left to the
113
+ * scroll or the tap the reader meant, so lists stay scrollable under the finger.
114
+ */
115
+ const Hold = 350;
116
+ /**
117
+ * How far a finger may wander while held before the press is taken as a scroll, in CSS pixels.
118
+ */
119
+ const Slop = 8;
120
+ /**
121
+ * How close to the edge of a scrolling container a drag comes before the container scrolls, in CSS pixels.
122
+ */
123
+ const Margin = 32;
124
+ /**
125
+ * How far a scrolling container scrolls on each move of a drag near its edge, in CSS pixels.
126
+ */
127
+ const Step = 12;
128
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
129
+ /**
130
+ * The service of the enclosing {@link Transfer} context; undefined outside any, leaving sources and targets inert.
131
+ */
132
+ const TransferContext = createContext(undefined);
133
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
134
+ /**
135
+ * Offers item transfers to nested components.
136
+ *
137
+ * Mounted once, at the root of an app: every source and target inside it meets every other one by type, the browser
138
+ * running a single drag at a time across the page anyway. A source or a target outside any stays inert.
139
+ *
140
+ * Draws a status region announcing how each move ended, and lets touch readers drag on the browsers that fire no drag
141
+ * events from a finger. Only the `@grafctory/skin` stylesheet keeps the region from sight while leaving it to screen
142
+ * readers: an app running without that stylesheet must hide `[data-offscreen]` elements with a rule of its own.
143
+ *
144
+ * @param options The components transfers are offered to
145
+ *
146
+ * @returns The nested components, with transfers offered to them
147
+ */
148
+ export function Transfer({ children }) {
149
+ const [message, setMessage] = useState("");
150
+ const [service] = useState(() => {
151
+ /*
152
+ * The registry, the drag under way and the state of each pending or gliding item are held by the service, a
153
+ * lifetime spanning every component inside the context; components follow it through its subscriptions.
154
+ */
155
+ let targets = [];
156
+ let sources = new Map();
157
+ let dragged;
158
+ let phases = new Map();
159
+ const listeners = new Set();
160
+ function notify() {
161
+ listeners.forEach(listener => listener());
162
+ }
163
+ function mark(ids, phase) {
164
+ phases = new Map([
165
+ ...[...phases].filter(([id]) => !ids.includes(id)),
166
+ ...(phase === undefined ? [] : ids.map((id) => [id, phase]))
167
+ ]);
168
+ notify();
169
+ }
170
+ /**
171
+ * Reads a message out through the status region.
172
+ *
173
+ * The region is emptied first, so a message repeating the last one is still read out.
174
+ *
175
+ * @param message The message to read out
176
+ */
177
+ function announce(message) {
178
+ setMessage("");
179
+ requestAnimationFrame(() => setMessage(message));
180
+ }
181
+ /**
182
+ * Follows a moved source to where it is drawn afresh.
183
+ *
184
+ * Once the components have rendered the move, the element glides from where the move started to where it now
185
+ * stands. It takes back the focus if the move left the focus on the page, and never takes it from anywhere
186
+ * else. A component drawn afresh may bind the item under new DOM ids, so the source is found again by item id.
187
+ *
188
+ * @param moved The source as it stood when the move started
189
+ * @param from The box the glide starts from; the element takes its new place at once if omitted
190
+ */
191
+ function follow(moved, from) {
192
+ requestAnimationFrame(() => requestAnimationFrame(() => {
193
+ const source = sources.get(moved.id) ?? moved;
194
+ const element = document.getElementById(source.element);
195
+ const focusable = document.getElementById(source.focus ?? source.handle ?? source.element);
196
+ if (document.activeElement === null || document.activeElement === document.body) {
197
+ focusable?.focus();
198
+ }
199
+ const to = element?.getBoundingClientRect();
200
+ const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
201
+ const styles = element ? getComputedStyle(element) : undefined;
202
+ const duration = milliseconds(styles?.getPropertyValue("--skin--duration-normal") ?? "");
203
+ const easing = styles?.getPropertyValue("--skin--easing-standard").trim() || "ease";
204
+ const shifted = from && to && (from.left !== to.left || from.top !== to.top);
205
+ if (element && shifted && !reduced && duration > 0) {
206
+ mark([source.id], "dropping");
207
+ element.animate([
208
+ { translate: `${from.left - to.left}px ${from.top - to.top}px` },
209
+ { translate: "0 0" }
210
+ ], { duration, easing }).finished.finally(() => mark([source.id], undefined));
211
+ }
212
+ }));
213
+ }
214
+ return {
215
+ targets: () => targets,
216
+ addTarget: entry => {
217
+ targets = [...targets, entry];
218
+ notify();
219
+ return () => {
220
+ targets = targets.filter(target => target !== entry);
221
+ notify();
222
+ };
223
+ },
224
+ /*
225
+ * A source is held by its identifier, the last component bound under it winning: a component drawn afresh
226
+ * after a move, under DOM ids of its own, takes the place of the one it replaces.
227
+ */
228
+ addSource: entry => {
229
+ sources = new Map([...sources, [entry.id, entry]]);
230
+ return () => {
231
+ sources = new Map([...sources].filter(([, source]) => source !== entry));
232
+ };
233
+ },
234
+ dragged: () => dragged,
235
+ begin: source => { dragged = source; },
236
+ end: () => { dragged = undefined; },
237
+ phase: id => phases.get(id),
238
+ subscribe: listener => {
239
+ listeners.add(listener);
240
+ return () => listeners.delete(listener);
241
+ },
242
+ drop: ({ target, side }, load) => {
243
+ const { source, from, item, content } = load.source ? {
244
+ source: load.source,
245
+ from: load.from,
246
+ item: load.source.name,
247
+ content: { source: { id: load.source.id, type: load.source.type, data: load.source.data } }
248
+ } : {
249
+ source: undefined,
250
+ from: undefined,
251
+ item: describe(load.files),
252
+ content: { files: load.files, strings: load.strings }
253
+ };
254
+ const drop = immutable({
255
+ ...content,
256
+ target: { id: target.id, name: target.name, data: target.data },
257
+ ...(side === undefined || !target.sides ? {} : { side })
258
+ });
259
+ const outcome = target.onDrop?.(drop);
260
+ const waiting = isPromiseLike(outcome);
261
+ const ids = [target.id, ...(source ? [source.id] : [])];
262
+ if (waiting) {
263
+ mark(ids, "pending");
264
+ }
265
+ return settle(outcome).then(taken => {
266
+ if (waiting) {
267
+ mark(ids, undefined);
268
+ }
269
+ announce(announcement(item, target.name, taken, drop.side));
270
+ if (source) {
271
+ follow(source, taken ? from : undefined);
272
+ }
273
+ return taken;
274
+ });
275
+ }
276
+ };
277
+ });
278
+ useEffect(() => lacking() ? touch() : undefined, []);
279
+ useEffect(() => scroll(), []);
280
+ return createElement(TransferContext.Provider, { value: service }, children, createElement("p", { role: "status", "data-offscreen": "" }, message));
281
+ }
282
+ /**
283
+ * Makes an element an item that can be moved.
284
+ *
285
+ * The item is dragged by its handle or, with no handle, by its whole surface. Presses {@link isReserved | reserved}
286
+ * for a field inside the item stay with that field. The item is also moved without dragging, through the
287
+ * {@link TargetBinding | targets} taking its type and the `move` transition, which a component offers as a move menu.
288
+ *
289
+ * Renders the component again whenever the item starts or stops being dragged or waiting for a move to settle, glides
290
+ * into a new place, or the targets taking its type change, so a move menu always lists the current ones.
291
+ *
292
+ * @param options The source configuration
293
+ *
294
+ * @returns The state of the item and the moves open to it
295
+ */
296
+ export function useTransferSource({ id, name, element, handle, focus, type, data, payload }) {
297
+ const service = useContext(TransferContext);
298
+ const entry = useTransferEntry(service, {
299
+ id,
300
+ name,
301
+ element,
302
+ handle,
303
+ focus,
304
+ type,
305
+ data,
306
+ payload
307
+ }, service => service.addSource);
308
+ const [dragging, setDragging] = useState(false);
309
+ useEffect(() => {
310
+ const root = document.getElementById(element);
311
+ const grip = handle === undefined ? root : document.getElementById(handle);
312
+ return service && root && grip ? bind(service, entry, root, grip, setDragging) : undefined;
313
+ }, [service, element, handle]);
314
+ const phase = service?.phase(id);
315
+ function takes(target) {
316
+ return target.id !== id && accepts(target.accept, [type]);
317
+ }
318
+ return immutable({
319
+ dragging,
320
+ dropping: phase === "dropping",
321
+ pending: phase === "pending",
322
+ targets: (service?.targets() ?? []).filter(takes).map(target => ({
323
+ id: target.id,
324
+ name: target.name,
325
+ data: target.data
326
+ })),
327
+ move: (target, side) => {
328
+ const $target = service?.targets().find(candidate => candidate.id === target && takes(candidate));
329
+ return service && $target
330
+ ? service.drop({ target: $target, side }, {
331
+ source: entry,
332
+ from: document.getElementById(element)?.getBoundingClientRect()
333
+ })
334
+ : Promise.resolve(false);
335
+ }
336
+ });
337
+ }
338
+ /**
339
+ * Makes an element a target items can be moved to.
340
+ *
341
+ * The target takes the items of the page whose type it accepts, by drag or by menu, and the outside content offered
342
+ * as one of those types; the innermost target taking a drag under the pointer is the one meeting it.
343
+ *
344
+ * Renders the component again whenever an item it takes starts or stops being dragged over it, the side the pointer
345
+ * stands nearest changes, or a drop onto it starts or stops waiting to be settled.
346
+ *
347
+ * @param options The target configuration
348
+ *
349
+ * @returns The state of the target
350
+ */
351
+ export function useTransferTarget({ sides = false, id, name, element, accept, data, onDrop }) {
352
+ const service = useContext(TransferContext);
353
+ const entry = useTransferEntry(service, {
354
+ sides,
355
+ id,
356
+ name,
357
+ accept,
358
+ data,
359
+ onDrop
360
+ }, service => service.addTarget);
361
+ const [target, setTarget] = useState(false);
362
+ const [side, setSide] = useState(undefined);
363
+ useEffect(() => {
364
+ const root = document.getElementById(element);
365
+ return service && root ? listen(service, entry, root, setTarget, setSide) : undefined;
366
+ }, [service, element]);
367
+ return immutable({
368
+ target,
369
+ side,
370
+ pending: service?.phase(id) === "pending"
371
+ });
372
+ }
373
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
374
+ /**
375
+ * Checks whether the browser leaves touch drags undone.
376
+ *
377
+ * Firefox for Android and Samsung Internet fire no drag events from a finger; other touch browsers drag natively.
378
+ *
379
+ * @returns `true` if the page runs on a touch device whose browser fires no drag events from a finger
380
+ */
381
+ function lacking() {
382
+ const { userAgent, maxTouchPoints } = navigator;
383
+ return maxTouchPoints > 0 && /Android/.test(userAgent) && /Firefox|SamsungBrowser/.test(userAgent);
384
+ }
385
+ /**
386
+ * Follows touch gestures on the draggable elements of the page, dispatching the drag events they stand for: a long
387
+ * press on a draggable element starts a drag, and the native drag events follow as the finger moves and lifts, so
388
+ * sources and targets need no touch code of their own, the drag reaching them as a pointer drag would.
389
+ *
390
+ * @returns A function removing the touch listeners and cancelling any drag under way
391
+ */
392
+ function touch() {
393
+ /*
394
+ * The gesture is a foreign lifetime spanning several events, so its state is held in two locals the listeners
395
+ * share, the press while the finger rests and the drag once it moves, both reset as either one ends.
396
+ */
397
+ let press;
398
+ let drag;
399
+ function dispatch(type, target, x, y) {
400
+ return target.dispatchEvent(new DragEvent(type, {
401
+ bubbles: true,
402
+ cancelable: true,
403
+ clientX: x,
404
+ clientY: y,
405
+ dataTransfer: drag?.data ?? null
406
+ }));
407
+ }
408
+ function start() {
409
+ if (press !== undefined) {
410
+ const { source, x, y } = press;
411
+ const box = source.getBoundingClientRect();
412
+ /*
413
+ * The preview stands for the item to the eye alone: hidden from assistive technology, out of reach of the
414
+ * focus, and stripped of the ids it copied, which the item still answers to and its references still point at.
415
+ */
416
+ const ghost = source.cloneNode(true); // ;(cast) cloneNode is typed as Node, but a clone
417
+ // keeps the element type
418
+ [ghost, ...ghost.querySelectorAll("[id]")].forEach(element => element.removeAttribute("id"));
419
+ ghost.setAttribute("aria-hidden", "true");
420
+ ghost.inert = true;
421
+ Object.assign(ghost.style, {
422
+ position: "fixed", left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`,
423
+ pointerEvents: "none", opacity: "0.8", zIndex: "2147483647"
424
+ });
425
+ press = undefined;
426
+ drag = { source, data: new DataTransfer(), ghost, box, over: undefined, accepted: false };
427
+ document.body.append(ghost);
428
+ dispatch("dragstart", source, x, y);
429
+ }
430
+ }
431
+ function move(x, y) {
432
+ if (drag !== undefined) {
433
+ const { ghost, box, over } = drag;
434
+ // translated from the box the preview was placed at, which its own box would carry along
435
+ ghost.style.translate = `${x - box.left - box.width / 2}px ${y - box.top - box.height / 2}px`;
436
+ const under = document.elementFromPoint(x, y) ?? undefined;
437
+ if (under !== over) {
438
+ if (over) {
439
+ dispatch("dragleave", over, x, y);
440
+ }
441
+ if (under) {
442
+ dispatch("dragenter", under, x, y);
443
+ }
444
+ }
445
+ drag = { ...drag, over: under, accepted: under !== undefined && !dispatch("dragover", under, x, y) };
446
+ }
447
+ }
448
+ function end(x, y, cancelled) {
449
+ if (press !== undefined) {
450
+ clearTimeout(press.timer);
451
+ press = undefined;
452
+ }
453
+ if (drag !== undefined) {
454
+ const { source, ghost, over, accepted } = drag;
455
+ if (over && accepted && !cancelled) {
456
+ dispatch("drop", over, x, y);
457
+ }
458
+ else if (over) {
459
+ dispatch("dragleave", over, x, y);
460
+ }
461
+ dispatch("dragend", source, x, y);
462
+ ghost.remove();
463
+ drag = undefined;
464
+ }
465
+ }
466
+ function onTouchStart(event) {
467
+ const touch = event.touches[0];
468
+ const source = event.touches.length === 1 && event.target instanceof Element
469
+ ? event.target.closest("[draggable='true']")
470
+ : null;
471
+ if (touch && source) {
472
+ press = { source, x: touch.clientX, y: touch.clientY, timer: setTimeout(start, Hold) };
473
+ }
474
+ }
475
+ function onTouchMove(event) {
476
+ const touch = event.touches[0];
477
+ if (touch !== undefined && drag !== undefined) {
478
+ event.preventDefault(); // the finger drags rather than scrolls
479
+ move(touch.clientX, touch.clientY);
480
+ }
481
+ else if (touch !== undefined && press !== undefined && Math.hypot(touch.clientX - press.x, touch.clientY - press.y) > Slop) {
482
+ end(touch.clientX, touch.clientY, true);
483
+ }
484
+ }
485
+ function onTouchEnd(event) {
486
+ const touch = event.changedTouches[0];
487
+ end(touch?.clientX ?? 0, touch?.clientY ?? 0, event.type === "touchcancel");
488
+ }
489
+ document.addEventListener("touchstart", onTouchStart, { passive: true });
490
+ document.addEventListener("touchmove", onTouchMove, { passive: false });
491
+ document.addEventListener("touchend", onTouchEnd);
492
+ document.addEventListener("touchcancel", onTouchEnd);
493
+ return () => {
494
+ end(0, 0, true);
495
+ document.removeEventListener("touchstart", onTouchStart);
496
+ document.removeEventListener("touchmove", onTouchMove);
497
+ document.removeEventListener("touchend", onTouchEnd);
498
+ document.removeEventListener("touchcancel", onTouchEnd);
499
+ };
500
+ }
501
+ /**
502
+ * Scrolls the container under a drag as the pointer nears its edge.
503
+ *
504
+ * @returns A function removing the listener
505
+ */
506
+ function scroll() {
507
+ function onDragOver({ target, clientX, clientY }) {
508
+ const container = target instanceof Element ? scrollable(target) : undefined;
509
+ const box = container?.getBoundingClientRect();
510
+ if (container && box) {
511
+ const dx = clientX < box.left + Margin ? -Step : clientX > box.right - Margin ? Step : 0;
512
+ const dy = clientY < box.top + Margin ? -Step : clientY > box.bottom - Margin ? Step : 0;
513
+ if (dx !== 0 || dy !== 0) {
514
+ container.scrollBy(dx, dy);
515
+ }
516
+ }
517
+ }
518
+ document.addEventListener("dragover", onDragOver);
519
+ return () => document.removeEventListener("dragover", onDragOver);
520
+ }
521
+ /**
522
+ * Retrieves the nearest container scrolling an element, if any.
523
+ */
524
+ function scrollable(element) {
525
+ const { overflowX, overflowY } = getComputedStyle(element);
526
+ const scrolls = /auto|scroll/.test(overflowX + overflowY)
527
+ && (element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth);
528
+ return scrolls ? element : element.parentElement ? scrollable(element.parentElement) : undefined;
529
+ }
530
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
531
+ /**
532
+ * Binds an entry to the service for the lifetime of a component.
533
+ *
534
+ * The entry always carries the props of the last render, so DOM listeners reading it never act on stale values. The
535
+ * component renders again whenever the service changes, so the state it reads off the service is never a render behind.
536
+ *
537
+ * @typeParam T The kind of entry bound, a source or a target
538
+ *
539
+ * @param service The service the entry is bound to; nothing is bound outside a {@link Transfer} context
540
+ * @param props The props of the current render, copied into the entry
541
+ * @param add Selects the service method adding the entry and returning the function that removes it again
542
+ *
543
+ * @returns The entry bound to the service, the same object across renders
544
+ */
545
+ function useTransferEntry(service, props, add) {
546
+ const [entry] = useState(() => ({ ...props }));
547
+ const [, setVersion] = useState(0);
548
+ useLayoutEffect(() => { Object.assign(entry, props); });
549
+ useEffect(() => service && add(service)(entry), [service]);
550
+ useEffect(() => service?.subscribe(() => setVersion(version => version + 1)), [service]);
551
+ return entry;
552
+ }
553
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
554
+ /**
555
+ * Binds the drag listeners of a source to its element.
556
+ *
557
+ * @returns A function unbinding them
558
+ */
559
+ function bind(service, entry, root, grip, setDragging) {
560
+ const surface = grip === root;
561
+ function onPointerDown(event) {
562
+ grip.draggable = !(surface && isReserved(event));
563
+ }
564
+ function onDragStart(event) {
565
+ const { dataTransfer } = event;
566
+ if (dataTransfer !== null && event.target === grip) {
567
+ const box = root.getBoundingClientRect();
568
+ dataTransfer.setData(entry.type, entry.id);
569
+ Object.entries(entry.payload ?? {}).forEach(([type, value]) => dataTransfer.setData(type, value));
570
+ dataTransfer.effectAllowed = "copyMove";
571
+ dataTransfer.setDragImage(root, event.clientX - box.left, event.clientY - box.top);
572
+ service.begin(entry);
573
+ setDragging(true);
574
+ }
575
+ }
576
+ function onDragEnd() {
577
+ service.end();
578
+ setDragging(false);
579
+ }
580
+ grip.draggable = true;
581
+ grip.addEventListener("pointerdown", onPointerDown);
582
+ grip.addEventListener("dragstart", onDragStart);
583
+ grip.addEventListener("dragend", onDragEnd);
584
+ return () => {
585
+ grip.removeAttribute("draggable");
586
+ grip.removeEventListener("pointerdown", onPointerDown);
587
+ grip.removeEventListener("dragstart", onDragStart);
588
+ grip.removeEventListener("dragend", onDragEnd);
589
+ };
590
+ }
591
+ /**
592
+ * Binds the drop listeners of a target to its element.
593
+ *
594
+ * @returns A function unbinding them
595
+ */
596
+ function listen(service, entry, root, setTarget, setSide) {
597
+ function locate({ clientY }) {
598
+ const { top, height } = root.getBoundingClientRect();
599
+ return !entry.sides ? undefined : clientY < top + height / 2 ? "before" : "after";
600
+ }
601
+ function leave() {
602
+ setTarget(false);
603
+ setSide(undefined);
604
+ }
605
+ function taken(event) {
606
+ return event.dataTransfer !== null && accepts(entry.accept, [...event.dataTransfer.types]);
607
+ }
608
+ function onDragOver(event) {
609
+ if (taken(event)) {
610
+ event.preventDefault(); // takes the drop
611
+ event.stopPropagation(); // leaves no enclosing target taking it as well
612
+ event.dataTransfer.dropEffect = service.dragged() ? "move" : "copy";
613
+ setTarget(true);
614
+ setSide(locate(event));
615
+ }
616
+ }
617
+ function onDragLeave(event) {
618
+ if (!(event.relatedTarget instanceof Node && root.contains(event.relatedTarget))) {
619
+ leave();
620
+ }
621
+ }
622
+ function onDrop(event) {
623
+ if (taken(event)) {
624
+ event.preventDefault();
625
+ event.stopPropagation();
626
+ leave();
627
+ const { dataTransfer, clientX, clientY } = event;
628
+ const source = service.dragged();
629
+ const internal = source !== undefined && dataTransfer.getData(source.type) === source.id;
630
+ const box = internal ? document.getElementById(source.element)?.getBoundingClientRect() : undefined;
631
+ /*
632
+ * Outside content is read here, since a DataTransfer cannot be read once the drop event is over; an item
633
+ * of the page glides from the box it stood in under the pointer as it was dropped.
634
+ */
635
+ const load = internal
636
+ ? { source, from: box && new DOMRect(clientX - box.width / 2, clientY - box.height / 2, box.width, box.height) }
637
+ : {
638
+ files: [...dataTransfer.files],
639
+ strings: Object.fromEntries([...dataTransfer.types]
640
+ .map(type => type.toLowerCase())
641
+ .filter(type => type !== "files" && accepts(entry.accept, [type]))
642
+ .map(type => [type, dataTransfer.getData(type)]))
643
+ };
644
+ void service.drop({ target: entry, side: locate(event) }, load);
645
+ }
646
+ }
647
+ function onDragEnd() {
648
+ leave();
649
+ }
650
+ root.addEventListener("dragenter", onDragOver);
651
+ root.addEventListener("dragover", onDragOver);
652
+ root.addEventListener("dragleave", onDragLeave);
653
+ root.addEventListener("drop", onDrop);
654
+ document.addEventListener("dragend", onDragEnd);
655
+ return () => {
656
+ root.removeEventListener("dragenter", onDragOver);
657
+ root.removeEventListener("dragover", onDragOver);
658
+ root.removeEventListener("dragleave", onDragLeave);
659
+ root.removeEventListener("drop", onDrop);
660
+ document.removeEventListener("dragend", onDragEnd);
661
+ };
662
+ }
663
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
664
+ /**
665
+ * Checks whether a target takes any of the types a transfer carries.
666
+ *
667
+ * Types are compared regardless of case, since browsers lowercase the types they expose during a drag.
668
+ *
669
+ * @param accept The MIME types the target takes
670
+ * @param types The MIME types the transfer carries
671
+ *
672
+ * @returns `true` if `accept` and `types` share at least one type
673
+ */
674
+ function accepts(accept, types) {
675
+ const taken = new Set(accept.map(type => type.toLowerCase()));
676
+ return types.some(type => taken.has(type.toLowerCase()));
677
+ }
678
+ /**
679
+ * Settles the answer of a target to a drop.
680
+ *
681
+ * A rejected promise ends the wait as a fulfilled one does, taking the drop, and is passed on unhandled, as if it had
682
+ * never been returned, so a target reporting failures catches them in the promise it returns.
683
+ *
684
+ * @param outcome The answer of the target
685
+ *
686
+ * @returns A promise resolving to `false` if the target refused the drop, and to `true` otherwise
687
+ */
688
+ function settle(outcome) {
689
+ return Promise.resolve(outcome).then(value => value !== false, error => {
690
+ void Promise.reject(error); // passed on unhandled, as if the target had never returned it
691
+ return true;
692
+ });
693
+ }
694
+ /**
695
+ * Words the announcement closing a transfer.
696
+ *
697
+ * @param source The name of the item moved
698
+ * @param target The name of the target it was moved to
699
+ * @param taken Whether the target took the item
700
+ * @param side The side of the target the item landed on, for a target taking sides; the target itself if omitted
701
+ *
702
+ * @returns The English sentence telling a reader how the transfer ended
703
+ */
704
+ function announcement(source, target, taken, side) {
705
+ const place = `${side ?? "to"} ${target}`;
706
+ return taken ? `${source} moved ${place}.` : `Moving ${source} ${place} was refused.`;
707
+ }
708
+ /**
709
+ * Names the content of an outside drop for announcements.
710
+ *
711
+ * @param files The files dropped
712
+ *
713
+ * @returns The name of the file dropped, the count of the files dropped, or `Content` where no file was dropped
714
+ */
715
+ function describe(files) {
716
+ return files.length > 1 ? `${files.length} files` : files[0]?.name ?? "Content";
717
+ }
718
+ /**
719
+ * Converts a CSS time to milliseconds.
720
+ *
721
+ * Takes both units CSS states times in: a registered `<time>` property reads back in seconds whatever unit it took.
722
+ *
723
+ * @param time The CSS time, such as `200ms` or `0.2s`
724
+ *
725
+ * @returns The duration of `time` in milliseconds, or `0` if `time` is no CSS time
726
+ */
727
+ function milliseconds(time) {
728
+ const match = /^\s*(-?[\d.]+)(ms|s)\s*$/i.exec(time);
729
+ const value = match ? parseFloat(match[1] ?? "") : NaN;
730
+ return Number.isFinite(value) ? match?.[2]?.toLowerCase() === "s" ? value * 1000 : value : 0;
731
+ }
732
+ //# sourceMappingURL=transfer.js.map