@barqjs/aria 0.0.0-stage → 0.2.0-next.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
@@ -0,0 +1,1152 @@
1
+ /**
2
+ * A window splitter: panels in a row or a column, and the handles between them.
3
+ *
4
+ * The decisions, since the mechanism is arithmetic:
5
+ *
6
+ * - **Sizes are percentages of the group.** A layout in pixels has to be
7
+ * re-measured whenever the container changes and drifts as it is rounded; a
8
+ * layout in percentages survives a resize untouched. A limit may still be
9
+ * WRITTEN in `px`, `rem`, `em`, `vw` or `vh`, and is turned into a share of
10
+ * the group whenever the group is measured. Unmeasured, such a limit says
11
+ * nothing yet rather than something wrong.
12
+ * - **A handle moves more than its two neighbours.** When the panel beside it
13
+ * reaches its limit, the move carries on into the panel after that one, which
14
+ * is what dragging a divider across a full row should do.
15
+ * - **A drag is measured from where it began.** Each move is the whole distance
16
+ * since the press, applied to the layout as it was then. Adding up small
17
+ * steps instead loses whatever a clamped step threw away, so the handle
18
+ * wanders off the pointer.
19
+ * - **Collapsing is a snap, not a size.** A collapsible panel is at its
20
+ * collapsed size or at least its minimum and never between: a drag jumps at
21
+ * the halfway point, and one key press at the minimum jumps the whole way.
22
+ * - **A move is in screen terms.** Positive is toward the right or the bottom,
23
+ * so a right-to-left row turns it round here and no caller has to.
24
+ * - **The order is the document's.** Panels and handles register as they are
25
+ * built, which is the order a server render and the first paint use; once
26
+ * the elements exist they are re-read in document order, so a panel that
27
+ * appears later lands between the right handles.
28
+ */
29
+
30
+ import { type Accessor, createSignal, createEffect, untrack } from "@barqjs/core";
31
+ import { isServer } from "@barqjs/web";
32
+ import { tryCleanup } from "@barqjs/primitives/utils";
33
+ import { ownerWindow } from "./dom.ts";
34
+ import { type ReadingDirection, useDirection } from "./i18n.ts";
35
+ import type { ElementRef } from "./interactions/press.ts";
36
+ import type { Orientation } from "./selection.ts";
37
+ import { access, type DOMProps, filterDOMProps, type MaybeAccessor, mergeProps } from "./utils.ts";
38
+
39
+ /** A percentage as a number, or a length as `"30%"`, `"240px"`, `"15rem"`, `"20vw"`. */
40
+ export type SplitterSize = number | string;
41
+
42
+ export type SizeUnit = "%" | "px" | "rem" | "em" | "vw" | "vh";
43
+
44
+ export interface ParsedSize {
45
+ value: number;
46
+ unit: SizeUnit;
47
+ }
48
+
49
+ /** What a length is measured against. */
50
+ export interface SizeContext {
51
+ /** The group's own extent along its axis. */
52
+ groupPixels: number;
53
+ rootFontSize?: number;
54
+ fontSize?: number;
55
+ viewportWidth?: number;
56
+ viewportHeight?: number;
57
+ }
58
+
59
+ /** One panel's limits, all as percentages of the group. */
60
+ export interface PanelConstraints {
61
+ minSize: number;
62
+ maxSize: number;
63
+ collapsedSize: number;
64
+ collapsible: boolean;
65
+ defaultSize?: number;
66
+ }
67
+
68
+ export interface PanelSize {
69
+ asPercentage: number;
70
+ inPixels: number;
71
+ }
72
+
73
+ export type ResizeTrigger = "keyboard" | "pointer" | "imperative";
74
+
75
+ const SIZE = /^(-?\d*\.?\d+)(%|px|rem|em|vw|vh)?$/;
76
+ const EPSILON = 1e-6;
77
+
78
+ const same = (a: number, b: number): boolean => Math.abs(a - b) < EPSILON;
79
+ const tidy = (value: number): number => Number.parseFloat(value.toFixed(10));
80
+ const sameLayout = (a: readonly number[], b: readonly number[]): boolean =>
81
+ a.length === b.length && a.every((each, index) => same(each, b[index] ?? Number.NaN));
82
+
83
+ export function parseSize(value: SplitterSize | undefined): ParsedSize | undefined {
84
+ if (value === undefined) return undefined;
85
+ if (typeof value === "number") return Number.isFinite(value) ? { value, unit: "%" } : undefined;
86
+ const match = SIZE.exec(value.trim());
87
+ if (match === null) return undefined;
88
+ return { value: Number.parseFloat(match[1] ?? "0"), unit: (match[2] as SizeUnit) ?? "%" };
89
+ }
90
+
91
+ export function toPercentage(
92
+ value: SplitterSize | undefined,
93
+ context: SizeContext,
94
+ ): number | undefined {
95
+ const parsed = parseSize(value);
96
+ if (parsed === undefined) return undefined;
97
+ if (parsed.unit === "%") return parsed.value;
98
+ if (context.groupPixels <= 0) return undefined;
99
+
100
+ let pixels: number;
101
+ if (parsed.unit === "px") pixels = parsed.value;
102
+ else if (parsed.unit === "rem") pixels = parsed.value * (context.rootFontSize ?? 16);
103
+ else if (parsed.unit === "em") {
104
+ pixels = parsed.value * (context.fontSize ?? context.rootFontSize ?? 16);
105
+ } else if (parsed.unit === "vw") pixels = (parsed.value / 100) * (context.viewportWidth ?? 0);
106
+ else pixels = (parsed.value / 100) * (context.viewportHeight ?? 0);
107
+
108
+ return tidy((pixels / context.groupPixels) * 100);
109
+ }
110
+
111
+ export function clampPanelSize(constraints: PanelConstraints, size: number): number {
112
+ let next = size;
113
+ if (next < constraints.minSize && !same(next, constraints.minSize)) {
114
+ if (constraints.collapsible) {
115
+ const halfway = (constraints.collapsedSize + constraints.minSize) / 2;
116
+ next = next < halfway ? constraints.collapsedSize : constraints.minSize;
117
+ } else {
118
+ next = constraints.minSize;
119
+ }
120
+ }
121
+ return tidy(Math.min(constraints.maxSize, next));
122
+ }
123
+
124
+ /** The sizes panels asked for, with the ones that asked for none sharing the rest. */
125
+ export function defaultLayout(constraints: readonly PanelConstraints[]): number[] {
126
+ const named = constraints.reduce((sum, each) => sum + (each.defaultSize ?? 0), 0);
127
+ const unnamed = constraints.filter((each) => each.defaultSize === undefined).length;
128
+ const share = unnamed === 0 ? 0 : Math.max(0, 100 - named) / unnamed;
129
+ return constraints.map((each) => each.defaultSize ?? share);
130
+ }
131
+
132
+ /** A layout that adds up to a hundred with every panel inside its limits. */
133
+ export function validateLayout(
134
+ layout: readonly number[],
135
+ constraints: readonly PanelConstraints[],
136
+ ): number[] {
137
+ const next = [...layout];
138
+ if (next.length === 0) return next;
139
+
140
+ const total = next.reduce((sum, each) => sum + each, 0);
141
+ if (total <= 0) next.fill(100 / next.length);
142
+ else if (!same(total, 100)) {
143
+ for (let index = 0; index < next.length; index++)
144
+ next[index] = (100 / total) * (next[index] ?? 0);
145
+ }
146
+
147
+ let remaining = 0;
148
+ for (let index = 0; index < next.length; index++) {
149
+ const limits = constraints[index];
150
+ const unsafe = next[index] ?? 0;
151
+ if (limits === undefined) continue;
152
+ const safe = clampPanelSize(limits, unsafe);
153
+ if (!same(unsafe, safe)) {
154
+ remaining += unsafe - safe;
155
+ next[index] = safe;
156
+ }
157
+ }
158
+
159
+ if (!same(remaining, 0)) {
160
+ for (let index = 0; index < next.length; index++) {
161
+ const limits = constraints[index];
162
+ const previous = next[index] ?? 0;
163
+ if (limits === undefined) continue;
164
+ const safe = clampPanelSize(limits, previous + remaining);
165
+ if (!same(previous, safe)) {
166
+ remaining -= safe - previous;
167
+ next[index] = safe;
168
+ if (same(remaining, 0)) break;
169
+ }
170
+ }
171
+ }
172
+
173
+ return next.map(tidy);
174
+ }
175
+
176
+ export interface AdjustLayoutOptions {
177
+ /** Positive grows the panel before the handle. */
178
+ delta: number;
179
+ /** The layout the delta is measured from. */
180
+ initialLayout: readonly number[];
181
+ /** The layout on screen, returned as it is when nothing can move. */
182
+ prevLayout: readonly number[];
183
+ constraints: readonly PanelConstraints[];
184
+ /** The panels on either side of the handle. */
185
+ pivot: readonly [number, number];
186
+ trigger: ResizeTrigger;
187
+ }
188
+
189
+ /**
190
+ * Move a handle by `delta`, as far as the limits on both sides allow.
191
+ *
192
+ * Returns `prevLayout` itself, the same array, when the move changes nothing,
193
+ * so a caller can tell by identity.
194
+ */
195
+ export function adjustLayoutByDelta(options: AdjustLayoutOptions): number[] {
196
+ const { initialLayout, prevLayout, constraints, pivot, trigger } = options;
197
+ const [first, second] = pivot;
198
+ const previous = prevLayout as number[];
199
+ let { delta } = options;
200
+
201
+ if (same(delta, 0)) {
202
+ return sameLayout(initialLayout, prevLayout) ? previous : [...initialLayout];
203
+ }
204
+
205
+ const limitsAt = (index: number): PanelConstraints =>
206
+ constraints[index] ?? { minSize: 0, maxSize: 100, collapsedSize: 0, collapsible: false };
207
+ const next = [...initialLayout];
208
+ let applied = 0;
209
+
210
+ if (trigger === "keyboard") {
211
+ // A step is smaller than the gap between collapsed and minimum, and a
212
+ // panel may not rest inside that gap, so the step becomes the whole gap.
213
+ const opening = delta < 0 ? second : first;
214
+ const openingLimits = limitsAt(opening);
215
+ if (openingLimits.collapsible && same(next[opening] ?? 0, openingLimits.collapsedSize)) {
216
+ const gap = openingLimits.minSize - openingLimits.collapsedSize;
217
+ if (gap > Math.abs(delta)) delta = delta < 0 ? -gap : gap;
218
+ }
219
+
220
+ const closing = delta < 0 ? first : second;
221
+ const closingLimits = limitsAt(closing);
222
+ if (closingLimits.collapsible && same(next[closing] ?? 0, closingLimits.minSize)) {
223
+ const gap = closingLimits.minSize - closingLimits.collapsedSize;
224
+ if (gap > Math.abs(delta)) delta = delta < 0 ? -gap : gap;
225
+ }
226
+ }
227
+
228
+ {
229
+ // No further than the growing side can take.
230
+ const step = delta < 0 ? 1 : -1;
231
+ let index = delta < 0 ? second : first;
232
+ let available = 0;
233
+ while (index >= 0 && index < next.length) {
234
+ available += clampPanelSize(limitsAt(index), 100) - (initialLayout[index] ?? 0);
235
+ index += step;
236
+ }
237
+ const least = Math.min(Math.abs(delta), Math.abs(available));
238
+ delta = delta < 0 ? -least : least;
239
+ }
240
+
241
+ {
242
+ // Take it from the shrinking side, nearest the handle first.
243
+ const step = delta < 0 ? -1 : 1;
244
+ let index = delta < 0 ? first : second;
245
+ while (index >= 0 && index < next.length) {
246
+ const wanted = Math.abs(delta) - Math.abs(applied);
247
+ const before = initialLayout[index] ?? 0;
248
+ const safe = clampPanelSize(limitsAt(index), before - wanted);
249
+ if (!same(before, safe)) {
250
+ applied += before - safe;
251
+ next[index] = safe;
252
+ if (applied > Math.abs(delta) || same(applied, Math.abs(delta))) break;
253
+ }
254
+ index += step;
255
+ }
256
+ }
257
+
258
+ if (sameLayout(prevLayout, next)) return previous;
259
+
260
+ {
261
+ const growing = delta < 0 ? second : first;
262
+ const unsafe = (initialLayout[growing] ?? 0) + applied;
263
+ const safe = clampPanelSize(limitsAt(growing), unsafe);
264
+ next[growing] = safe;
265
+
266
+ // The growing panel snapped: out of collapse to more than was given, or
267
+ // back into it. The shrinking side makes up the difference.
268
+ if (!same(safe, unsafe)) {
269
+ let remaining = unsafe - safe;
270
+ const step = delta < 0 ? -1 : 1;
271
+ let index = delta < 0 ? first : second;
272
+ while (index >= 0 && index < next.length) {
273
+ const before = next[index] ?? 0;
274
+ const settled = clampPanelSize(limitsAt(index), before + remaining);
275
+ if (!same(before, settled)) {
276
+ remaining -= settled - before;
277
+ next[index] = settled;
278
+ }
279
+ if (same(remaining, 0)) break;
280
+ index += step;
281
+ }
282
+ }
283
+ }
284
+
285
+ const total = next.reduce((sum, each) => sum + each, 0);
286
+ if (!same(total, 100)) return previous;
287
+ if (sameLayout(prevLayout, next)) return previous;
288
+ return next.map(tidy);
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // State
293
+ // ---------------------------------------------------------------------------
294
+
295
+ export interface SplitterStorage {
296
+ getItem(name: string): string | null;
297
+ setItem(name: string, value: string): void;
298
+ }
299
+
300
+ export interface SplitterStateOptions {
301
+ /** The group's element, which is what a pixel is a share of. */
302
+ ref: ElementRef;
303
+ /** @default "horizontal" */
304
+ orientation?: MaybeAccessor<Orientation | undefined>;
305
+ /** Overrides the direction in scope. */
306
+ direction?: MaybeAccessor<ReadingDirection | undefined>;
307
+ /** No handle moves; the imperative calls still do. */
308
+ isDisabled?: MaybeAccessor<boolean | undefined>;
309
+ /** How far an arrow key moves a handle, as a percentage. @default 10 */
310
+ keyboardResizeBy?: MaybeAccessor<number | undefined>;
311
+ /** Remember the layout under this name and start from it next time. */
312
+ autoSaveId?: MaybeAccessor<string | undefined>;
313
+ /** @default localStorage */
314
+ storage?: MaybeAccessor<SplitterStorage | undefined>;
315
+ /** Sizes by panel id, used when every panel present is named in it. */
316
+ defaultLayout?: MaybeAccessor<Readonly<Record<string, number>> | undefined>;
317
+ /** Every change a person or a call made, as it happens. */
318
+ onLayoutChange?: (layout: Record<string, number>, sizes: number[]) => void;
319
+ /** The same, once: after a key press or a call, and when a drag ends. */
320
+ onLayoutChanged?: (layout: Record<string, number>, sizes: number[]) => void;
321
+ }
322
+
323
+ export interface SplitterPanelOptions {
324
+ id: string;
325
+ /**
326
+ * Whether the id was made up rather than given. A made-up id differs from
327
+ * one page load to the next, so a saved layout names such a panel by its
328
+ * position instead.
329
+ */
330
+ isGeneratedId?: boolean;
331
+ ref: ElementRef;
332
+ defaultSize?: MaybeAccessor<SplitterSize | undefined>;
333
+ /** @default 0 */
334
+ minSize?: MaybeAccessor<SplitterSize | undefined>;
335
+ /** @default 100 */
336
+ maxSize?: MaybeAccessor<SplitterSize | undefined>;
337
+ collapsible?: MaybeAccessor<boolean | undefined>;
338
+ /** @default 0 */
339
+ collapsedSize?: MaybeAccessor<SplitterSize | undefined>;
340
+ onResize?: (size: PanelSize, id: string, previous: PanelSize | undefined) => void;
341
+ onCollapse?: () => void;
342
+ onExpand?: () => void;
343
+ }
344
+
345
+ export interface SplitterState {
346
+ orientation: Accessor<Orientation>;
347
+ direction: Accessor<ReadingDirection>;
348
+ isDisabled: Accessor<boolean>;
349
+ /** How far one arrow key moves a handle, as a percentage. */
350
+ keyboardStep: Accessor<number>;
351
+ /** In layout order. */
352
+ panelIds: Accessor<readonly string[]>;
353
+ /** Every panel's percentage, in layout order. */
354
+ layout: Accessor<number[]>;
355
+ sizeOf(id: string): number;
356
+ constraintsOf(id: string): PanelConstraints;
357
+ isCollapsed(id: string): boolean;
358
+ getSize(id: string): PanelSize;
359
+ collapse(id: string): void;
360
+ /** Back to the size it was collapsed from, and at least `minSize`. */
361
+ expand(id: string, minSize?: SplitterSize): void;
362
+ resize(id: string, size: SplitterSize): void;
363
+ getLayout(): Record<string, number>;
364
+ setLayout(layout: Readonly<Record<string, number>> | readonly number[]): void;
365
+ registerPanel(options: SplitterPanelOptions): () => void;
366
+ registerHandle(id: string, element: Accessor<Element | null>): () => void;
367
+ /** The panels before and after a handle. */
368
+ panelsAround(handleId: string): readonly [string, string] | null;
369
+ /** One step from a handle, in screen terms: positive is right or down. */
370
+ resizeBy(handleId: string, delta: number, trigger: ResizeTrigger): void;
371
+ /** Collapse the panel a handle controls, or bring it back. */
372
+ toggleCollapse(handleId: string): void;
373
+ startDrag(handleId: string): void;
374
+ /** The whole distance since {@link startDrag}, as a percentage, in screen terms. */
375
+ dragBy(handleId: string, delta: number): void;
376
+ endDrag(handleId: string): void;
377
+ draggingHandle: Accessor<string | null>;
378
+ /** The handle elements in layout order, for moving focus among them. */
379
+ handleElements(): HTMLElement[];
380
+ /** What a length is measured against, right now. */
381
+ sizeContext(): SizeContext;
382
+ }
383
+
384
+ interface PanelEntry {
385
+ kind: "panel";
386
+ id: string;
387
+ options: SplitterPanelOptions;
388
+ }
389
+
390
+ interface HandleEntry {
391
+ kind: "handle";
392
+ id: string;
393
+ element: Accessor<Element | null>;
394
+ }
395
+
396
+ type Entry = PanelEntry | HandleEntry;
397
+
398
+ interface Saved {
399
+ layout: number[];
400
+ expandTo: Record<string, number>;
401
+ }
402
+
403
+ const STORAGE_PREFIX = "barq.splitter:";
404
+
405
+ /**
406
+ * A value kept beside the signal that announces it.
407
+ *
408
+ * A write to a signal is staged until the next flush, and this state is read
409
+ * straight after it is written: a panel registers and the layout is worked out
410
+ * in the same breath, a drag starts and moves in one event. The signal carries
411
+ * the dependency and the variable carries the answer.
412
+ */
413
+ function kept<T>(initial: T): [Accessor<T>, (next: T) => void] {
414
+ let value = initial;
415
+ // `ownedWrite`: panels and handles register from their own component
416
+ // bodies, and the layout is worked out as each one arrives.
417
+ const [version, bump] = createSignal(0, { equals: false, ownedWrite: true });
418
+ return [
419
+ () => {
420
+ version();
421
+ return value;
422
+ },
423
+ (next) => {
424
+ if (Object.is(next, value)) return;
425
+ value = next;
426
+ bump(0);
427
+ },
428
+ ];
429
+ }
430
+
431
+ function inDocumentOrder(a: Element, b: Element): number {
432
+ const position = a.compareDocumentPosition(b);
433
+ if ((position & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) return -1;
434
+ if ((position & Node.DOCUMENT_POSITION_PRECEDING) !== 0) return 1;
435
+ return 0;
436
+ }
437
+
438
+ export function splitterState(options: SplitterStateOptions): SplitterState {
439
+ const scoped = useDirection();
440
+ const orientation = (): Orientation => access(options.orientation) ?? "horizontal";
441
+ const direction = (): ReadingDirection => access(options.direction) ?? scoped();
442
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
443
+
444
+ const entries = new Map<string, Entry>();
445
+ const [order, setOrder] = kept<readonly string[]>([]);
446
+ const [sizes, setSizes] = kept<Readonly<Record<string, number>>>({});
447
+ const [groupPixels, setGroupPixels] = kept(0);
448
+ const [dragging, setDragging] = kept<string | null>(null);
449
+
450
+ /** The size each collapsed panel came from, which is where it goes back to. */
451
+ const expandTo = new Map<string, number>();
452
+ let dragStart: number[] | null = null;
453
+ let dragMoved = false;
454
+
455
+ const keyOf = (entry: Entry): string => `${entry.kind}:${entry.id}`;
456
+ const elementOf = (entry: Entry): Element | null =>
457
+ entry.kind === "panel" ? (access(entry.options.ref) ?? null) : entry.element();
458
+
459
+ const ordered = (): Entry[] => {
460
+ const out: Entry[] = [];
461
+ for (const key of order()) {
462
+ const entry = entries.get(key);
463
+ if (entry !== undefined) out.push(entry);
464
+ }
465
+ return out;
466
+ };
467
+
468
+ const panels = (): PanelEntry[] =>
469
+ ordered().filter((each): each is PanelEntry => each.kind === "panel");
470
+ const panelIds = (): readonly string[] => panels().map((each) => each.id);
471
+
472
+ const extentOf = (element: Element, along: Orientation): number => {
473
+ const box = element.getBoundingClientRect();
474
+ return along === "horizontal" ? box.width : box.height;
475
+ };
476
+ const measure = (): number => {
477
+ const element = access(options.ref);
478
+ if (element === null || element === undefined) return 0;
479
+ return extentOf(element, orientation());
480
+ };
481
+
482
+ const sizeContext = (): SizeContext => {
483
+ const element = access(options.ref) ?? null;
484
+ const context: SizeContext = { groupPixels: groupPixels() || measure() };
485
+ if (isServer || element === null) return context;
486
+ const view = ownerWindow(element);
487
+ const fontOf = (target: Element): number | undefined => {
488
+ const parsed = Number.parseFloat(view.getComputedStyle(target).fontSize);
489
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
490
+ };
491
+ return {
492
+ ...context,
493
+ rootFontSize: fontOf(element.ownerDocument.documentElement),
494
+ fontSize: fontOf(element),
495
+ viewportWidth: view.innerWidth,
496
+ viewportHeight: view.innerHeight,
497
+ };
498
+ };
499
+
500
+ const usesLengths = (): boolean =>
501
+ panels().some((each) =>
502
+ [
503
+ each.options.defaultSize,
504
+ each.options.minSize,
505
+ each.options.maxSize,
506
+ each.options.collapsedSize,
507
+ ]
508
+ .map((value) => parseSize(access(value)))
509
+ .some((parsed) => parsed !== undefined && parsed.unit !== "%"),
510
+ );
511
+
512
+ const resolve = (panel: SplitterPanelOptions, context: SizeContext): PanelConstraints => {
513
+ const maxSize = Math.min(100, toPercentage(access(panel.maxSize), context) ?? 100);
514
+ const minSize = Math.min(
515
+ maxSize,
516
+ Math.max(0, toPercentage(access(panel.minSize), context) ?? 0),
517
+ );
518
+ const collapsedSize = Math.min(
519
+ minSize,
520
+ Math.max(0, toPercentage(access(panel.collapsedSize), context) ?? 0),
521
+ );
522
+ return {
523
+ minSize,
524
+ maxSize,
525
+ collapsedSize,
526
+ collapsible: access(panel.collapsible) === true,
527
+ defaultSize: toPercentage(access(panel.defaultSize), context),
528
+ };
529
+ };
530
+
531
+ const constraintsNow = (): PanelConstraints[] => {
532
+ const context = usesLengths() ? sizeContext() : { groupPixels: 0 };
533
+ return panels().map((each) => resolve(each.options, context));
534
+ };
535
+
536
+ const layout = (): number[] => {
537
+ const held = sizes();
538
+ return panelIds().map((id) => held[id] ?? 0);
539
+ };
540
+
541
+ const record = (ids: readonly string[], values: readonly number[]): Record<string, number> =>
542
+ Object.fromEntries(ids.map((id, index) => [id, values[index] ?? 0]));
543
+
544
+ // -------------------------------------------------------------------------
545
+ // Persistence
546
+ // -------------------------------------------------------------------------
547
+
548
+ const storage = (): SplitterStorage | null => {
549
+ const given = access(options.storage);
550
+ if (given !== undefined) return given;
551
+ try {
552
+ return typeof localStorage === "undefined" ? null : localStorage;
553
+ } catch {
554
+ return null;
555
+ }
556
+ };
557
+
558
+ const savedName = (panel: PanelEntry, index: number): string =>
559
+ panel.options.isGeneratedId === true ? `#${String(index)}` : panel.id;
560
+
561
+ /** Which panels a saved layout is for: a different set is a different layout. */
562
+ const panelKey = (list: readonly PanelEntry[]): string => list.map(savedName).join(",");
563
+
564
+ const readSaved = (): Record<string, Saved> => {
565
+ const name = access(options.autoSaveId);
566
+ const store = storage();
567
+ if (name === undefined || store === null) return {};
568
+ try {
569
+ const parsed: unknown = JSON.parse(store.getItem(STORAGE_PREFIX + name) ?? "{}");
570
+ return typeof parsed === "object" && parsed !== null ? (parsed as Record<string, Saved>) : {};
571
+ } catch {
572
+ return {};
573
+ }
574
+ };
575
+
576
+ const loadSaved = (list: readonly PanelEntry[]): number[] | null => {
577
+ if (access(options.autoSaveId) === undefined) return null;
578
+ const saved = readSaved()[panelKey(list)];
579
+ if (saved === undefined || !Array.isArray(saved.layout)) return null;
580
+ if (saved.layout.length !== list.length) return null;
581
+ if (!saved.layout.every((each) => typeof each === "number" && Number.isFinite(each)))
582
+ return null;
583
+ if (typeof saved.expandTo === "object" && saved.expandTo !== null) {
584
+ list.forEach((each, index) => {
585
+ const size = saved.expandTo[savedName(each, index)];
586
+ if (typeof size === "number") expandTo.set(each.id, size);
587
+ });
588
+ }
589
+ return saved.layout;
590
+ };
591
+
592
+ const save = (): void => {
593
+ const name = access(options.autoSaveId);
594
+ const store = storage();
595
+ if (name === undefined || store === null) return;
596
+ const list = untrack(panels);
597
+ const all = readSaved();
598
+ all[panelKey(list)] = {
599
+ layout: untrack(layout),
600
+ expandTo: Object.fromEntries(
601
+ list.flatMap((each, index) => {
602
+ const size = expandTo.get(each.id);
603
+ return size === undefined ? [] : [[savedName(each, index), size]];
604
+ }),
605
+ ),
606
+ };
607
+ try {
608
+ store.setItem(STORAGE_PREFIX + name, JSON.stringify(all));
609
+ } catch {
610
+ // A full or forbidden store loses the layout, not the page.
611
+ }
612
+ };
613
+
614
+ // -------------------------------------------------------------------------
615
+ // Layout
616
+ // -------------------------------------------------------------------------
617
+
618
+ /** Work the layout out again, keeping it when the same panels are present. */
619
+ const settle = (): void => {
620
+ const list = untrack(panels);
621
+ const ids = list.map((each) => each.id);
622
+ const limits = untrack(constraintsNow);
623
+ const held = untrack(sizes);
624
+
625
+ let unsafe: number[] | null = null;
626
+ const known = Object.keys(held);
627
+ if (known.length === ids.length && ids.every((id) => held[id] !== undefined)) {
628
+ unsafe = ids.map((id) => held[id] ?? 0);
629
+ }
630
+ if (unsafe === null) unsafe = loadSaved(list);
631
+ if (unsafe === null) {
632
+ const declared = access(options.defaultLayout);
633
+ if (
634
+ declared !== undefined &&
635
+ ids.length > 0 &&
636
+ ids.every((id) => declared[id] !== undefined)
637
+ ) {
638
+ unsafe = ids.map((id) => declared[id] ?? 0);
639
+ }
640
+ }
641
+ unsafe ??= defaultLayout(limits);
642
+
643
+ setSizes(record(ids, validateLayout(unsafe, limits)));
644
+ };
645
+
646
+ const pixelsOf = (percentage: number): number =>
647
+ (untrack(sizeContext).groupPixels * percentage) / 100;
648
+ const sized = (percentage: number): PanelSize => ({
649
+ asPercentage: percentage,
650
+ inPixels: pixelsOf(percentage),
651
+ });
652
+
653
+ /** Put a layout a person or a call asked for on screen, and tell everyone. */
654
+ const commit = (next: readonly number[], settled: boolean): boolean => {
655
+ const list = untrack(panels);
656
+ const ids = list.map((each) => each.id);
657
+ const before = untrack(layout);
658
+ if (next === before || sameLayout(before, next)) return false;
659
+ const limits = untrack(constraintsNow);
660
+
661
+ setSizes(record(ids, next));
662
+
663
+ list.forEach((each, index) => {
664
+ const was = before[index] ?? 0;
665
+ const now = next[index] ?? 0;
666
+ if (same(was, now)) return;
667
+ const bounds = limits[index];
668
+ each.options.onResize?.(sized(now), each.id, sized(was));
669
+ if (bounds === undefined || !bounds.collapsible) return;
670
+ const wasCollapsed = same(was, bounds.collapsedSize);
671
+ const isCollapsed = same(now, bounds.collapsedSize);
672
+ if (isCollapsed && !wasCollapsed) {
673
+ // Where a drag, a key or a call took it from is where it goes back to.
674
+ expandTo.set(each.id, was);
675
+ each.options.onCollapse?.();
676
+ } else if (!isCollapsed && wasCollapsed) {
677
+ each.options.onExpand?.();
678
+ }
679
+ });
680
+
681
+ const named = record(ids, next);
682
+ options.onLayoutChange?.(named, [...next]);
683
+ if (settled) {
684
+ options.onLayoutChanged?.(named, [...next]);
685
+ save();
686
+ }
687
+ return true;
688
+ };
689
+
690
+ const indexOf = (id: string): number => untrack(panelIds).indexOf(id);
691
+
692
+ /** The handle a panel is resized through: the one after it, or before the last. */
693
+ const pivotOf = (index: number, count: number): readonly [number, number] =>
694
+ index === count - 1 ? [index - 1, index] : [index, index + 1];
695
+
696
+ const moveTo = (id: string, target: number): void => {
697
+ const index = indexOf(id);
698
+ const before = untrack(layout);
699
+ if (index < 0 || before.length < 2) return;
700
+ const size = before[index] ?? 0;
701
+ const isLast = index === before.length - 1;
702
+ const next = adjustLayoutByDelta({
703
+ delta: isLast ? size - target : target - size,
704
+ initialLayout: before,
705
+ prevLayout: before,
706
+ constraints: untrack(constraintsNow),
707
+ pivot: pivotOf(index, before.length),
708
+ trigger: "imperative",
709
+ });
710
+ commit(next, true);
711
+ };
712
+
713
+ const constraintsOf = (id: string): PanelConstraints => {
714
+ const entry = entries.get(`panel:${id}`);
715
+ if (entry === undefined || entry.kind !== "panel") {
716
+ return { minSize: 0, maxSize: 100, collapsedSize: 0, collapsible: false };
717
+ }
718
+ return resolve(entry.options, usesLengths() ? sizeContext() : { groupPixels: 0 });
719
+ };
720
+
721
+ const sizeOf = (id: string): number => sizes()[id] ?? 0;
722
+ const isCollapsed = (id: string): boolean => {
723
+ const limits = constraintsOf(id);
724
+ return limits.collapsible && same(sizeOf(id), limits.collapsedSize);
725
+ };
726
+
727
+ const panelsAround = (handleId: string): readonly [string, string] | null => {
728
+ const list = ordered();
729
+ const at = list.findIndex((each) => each.kind === "handle" && each.id === handleId);
730
+ if (at < 0) return null;
731
+ let before: string | null = null;
732
+ let after: string | null = null;
733
+ for (let index = at - 1; index >= 0 && before === null; index--) {
734
+ const entry = list[index];
735
+ if (entry?.kind === "panel") before = entry.id;
736
+ }
737
+ for (let index = at + 1; index < list.length && after === null; index++) {
738
+ const entry = list[index];
739
+ if (entry?.kind === "panel") after = entry.id;
740
+ }
741
+ return before === null || after === null ? null : [before, after];
742
+ };
743
+
744
+ const pivotAround = (handleId: string): readonly [number, number] | null => {
745
+ const around = untrack(() => panelsAround(handleId));
746
+ if (around === null) return null;
747
+ const ids = untrack(panelIds);
748
+ return [ids.indexOf(around[0]), ids.indexOf(around[1])];
749
+ };
750
+
751
+ /** Screen terms to layout terms: a right-to-left row runs the other way. */
752
+ const logical = (delta: number): number =>
753
+ untrack(orientation) === "horizontal" && untrack(direction) === "rtl" ? -delta : delta;
754
+
755
+ const add = (entry: Entry): (() => void) => {
756
+ const key = keyOf(entry);
757
+ entries.set(key, entry);
758
+ const before = untrack(order);
759
+ if (!before.includes(key)) setOrder([...before, key]);
760
+ if (entry.kind === "panel") settle();
761
+ return () => {
762
+ if (entries.get(key) !== entry) return;
763
+ entries.delete(key);
764
+ setOrder(untrack(order).filter((each) => each !== key));
765
+ if (entry.kind === "panel") {
766
+ expandTo.delete(entry.id);
767
+ settle();
768
+ }
769
+ };
770
+ };
771
+
772
+ const collapse = (id: string): void => {
773
+ const limits = untrack(() => constraintsOf(id));
774
+ if (!limits.collapsible || untrack(() => isCollapsed(id))) return;
775
+ moveTo(id, limits.collapsedSize);
776
+ };
777
+
778
+ const expand = (id: string, minSize?: SplitterSize): void => {
779
+ const limits = untrack(() => constraintsOf(id));
780
+ if (!limits.collapsible || !untrack(() => isCollapsed(id))) return;
781
+ const least = Math.max(
782
+ limits.minSize,
783
+ toPercentage(minSize, untrack(sizeContext)) ?? limits.minSize,
784
+ );
785
+ const remembered = expandTo.get(id);
786
+ moveTo(id, remembered !== undefined && remembered >= least ? remembered : least);
787
+ };
788
+
789
+ if (!isServer) {
790
+ createEffect(
791
+ () => {
792
+ const keys = order();
793
+ const elements = keys.map((key) => {
794
+ const entry = entries.get(key);
795
+ return entry === undefined ? null : elementOf(entry);
796
+ });
797
+ return { keys, elements };
798
+ },
799
+ ({ keys, elements }) => {
800
+ const placed: { key: string; element: Element }[] = [];
801
+ for (const [index, key] of keys.entries()) {
802
+ const element = elements[index] ?? null;
803
+ // Not all built yet, or not in one tree yet: the registration order
804
+ // stands until they are, and each ref landing runs this again.
805
+ if (element === null || !element.isConnected) return;
806
+ placed.push({ key, element });
807
+ }
808
+ const sorted = placed
809
+ .toSorted((a, b) => inDocumentOrder(a.element, b.element))
810
+ .map((each) => each.key);
811
+ if (sorted.some((key, index) => key !== keys[index])) setOrder(sorted);
812
+ },
813
+ );
814
+
815
+ createEffect(
816
+ // Orientation read so a turn from row to column measures the other axis.
817
+ () => [access(options.ref), orientation()] as const,
818
+ ([element, along]) => {
819
+ if (element === null || element === undefined) return undefined;
820
+ const update = (): void => {
821
+ const next = extentOf(element, along);
822
+ if (next === untrack(groupPixels)) return;
823
+ setGroupPixels(next);
824
+ // Only a limit written as a length changes its share when the group does.
825
+ if (untrack(usesLengths)) settle();
826
+ };
827
+ update();
828
+ if (typeof ResizeObserver === "undefined") return undefined;
829
+ const observer = new ResizeObserver(update);
830
+ observer.observe(element);
831
+ return () => observer.disconnect();
832
+ },
833
+ );
834
+ }
835
+
836
+ return {
837
+ orientation,
838
+ direction,
839
+ isDisabled,
840
+ keyboardStep: () => access(options.keyboardResizeBy) ?? 10,
841
+ panelIds,
842
+ layout,
843
+ sizeOf,
844
+ constraintsOf,
845
+ isCollapsed,
846
+ getSize: (id) => sized(untrack(() => sizeOf(id))),
847
+ collapse,
848
+ expand,
849
+ resize(id, size) {
850
+ const target = toPercentage(size, untrack(sizeContext));
851
+ if (target !== undefined) moveTo(id, target);
852
+ },
853
+ getLayout: () => record(untrack(panelIds), untrack(layout)),
854
+ setLayout(next) {
855
+ const ids = untrack(panelIds);
856
+ const values = Array.isArray(next)
857
+ ? (next as readonly number[])
858
+ : ids.map((id) => (next as Readonly<Record<string, number>>)[id] ?? 0);
859
+ if (values.length !== ids.length) return;
860
+ commit(validateLayout(values, untrack(constraintsNow)), true);
861
+ },
862
+ registerPanel: (panel) => add({ kind: "panel", id: panel.id, options: panel }),
863
+ registerHandle: (id, element) => add({ kind: "handle", id, element }),
864
+ panelsAround,
865
+ resizeBy(handleId, delta, trigger) {
866
+ if (untrack(isDisabled)) return;
867
+ const pivot = pivotAround(handleId);
868
+ if (pivot === null) return;
869
+ const before = untrack(layout);
870
+ commit(
871
+ adjustLayoutByDelta({
872
+ delta: logical(delta),
873
+ initialLayout: before,
874
+ prevLayout: before,
875
+ constraints: untrack(constraintsNow),
876
+ pivot,
877
+ trigger,
878
+ }),
879
+ true,
880
+ );
881
+ },
882
+ toggleCollapse(handleId) {
883
+ if (untrack(isDisabled)) return;
884
+ const around = untrack(() => panelsAround(handleId));
885
+ if (around === null) return;
886
+ // The panel before the handle is the one it controls; one after it that
887
+ // collapses is the next best thing a key can do.
888
+ const id = around.find((each) => untrack(() => constraintsOf(each)).collapsible);
889
+ if (id === undefined) return;
890
+ if (untrack(() => isCollapsed(id))) expand(id);
891
+ else collapse(id);
892
+ },
893
+ startDrag(handleId) {
894
+ if (untrack(isDisabled) || pivotAround(handleId) === null) return;
895
+ dragStart = untrack(layout);
896
+ dragMoved = false;
897
+ setDragging(handleId);
898
+ },
899
+ dragBy(handleId, delta) {
900
+ if (dragStart === null || untrack(dragging) !== handleId) return;
901
+ const pivot = pivotAround(handleId);
902
+ if (pivot === null) return;
903
+ const moved = commit(
904
+ adjustLayoutByDelta({
905
+ delta: logical(delta),
906
+ initialLayout: dragStart,
907
+ prevLayout: untrack(layout),
908
+ constraints: untrack(constraintsNow),
909
+ pivot,
910
+ trigger: "pointer",
911
+ }),
912
+ false,
913
+ );
914
+ dragMoved ||= moved;
915
+ },
916
+ endDrag(handleId) {
917
+ if (untrack(dragging) !== handleId) return;
918
+ const start = dragStart;
919
+ dragStart = null;
920
+ setDragging(null);
921
+ const now = untrack(layout);
922
+ if (!dragMoved || start === null || sameLayout(start, now)) return;
923
+ options.onLayoutChanged?.(record(untrack(panelIds), now), [...now]);
924
+ save();
925
+ },
926
+ draggingHandle: dragging,
927
+ handleElements() {
928
+ const out: HTMLElement[] = [];
929
+ for (const entry of untrack(ordered)) {
930
+ if (entry.kind !== "handle") continue;
931
+ const element = entry.element();
932
+ if (element instanceof HTMLElement) out.push(element);
933
+ }
934
+ return out;
935
+ },
936
+ sizeContext,
937
+ };
938
+ }
939
+
940
+ // ---------------------------------------------------------------------------
941
+ // Panel
942
+ // ---------------------------------------------------------------------------
943
+
944
+ /** What a caller holding a panel can do to it. */
945
+ export interface SplitterPanelHandle {
946
+ collapse(): void;
947
+ expand(minSize?: SplitterSize): void;
948
+ getId(): string;
949
+ getSize(): PanelSize;
950
+ isCollapsed(): boolean;
951
+ isExpanded(): boolean;
952
+ resize(size: SplitterSize): void;
953
+ }
954
+
955
+ export interface SplitterPanelResult {
956
+ panelProps: DOMProps;
957
+ /** A percentage of the group. */
958
+ size: Accessor<number>;
959
+ isCollapsed: Accessor<boolean>;
960
+ handle: SplitterPanelHandle;
961
+ }
962
+
963
+ /**
964
+ * One panel: registered with the group for as long as its owner lives.
965
+ *
966
+ * ```tsx
967
+ * const domRef = ref<HTMLDivElement>();
968
+ * const { panelProps, size } = splitterPanel({ id: "nav", ref: domRef, minSize: 15 }, state);
969
+ * <div {...panelProps} ref={domRef.set} style={{ flex: `0 0 ${size()}%` }} />
970
+ * ```
971
+ */
972
+ export function splitterPanel(
973
+ options: SplitterPanelOptions,
974
+ state: SplitterState,
975
+ ): SplitterPanelResult {
976
+ const { id } = options;
977
+ // While the component is built rather than in an effect: a server render
978
+ // runs no effects, and its markup has to carry the sizes too.
979
+ tryCleanup(state.registerPanel(options));
980
+
981
+ const size = (): number => state.sizeOf(id);
982
+ const isCollapsed = (): boolean => state.isCollapsed(id);
983
+
984
+ return {
985
+ size,
986
+ isCollapsed,
987
+ panelProps: {
988
+ id,
989
+ "data-panel": "",
990
+ "data-panel-id": id,
991
+ "data-panel-size": () => String(Number.parseFloat(size().toFixed(1))),
992
+ "data-panel-collapsible": () => (access(options.collapsible) === true ? "true" : undefined),
993
+ "data-collapsed": () => (isCollapsed() ? "" : undefined),
994
+ },
995
+ handle: {
996
+ collapse: () => state.collapse(id),
997
+ expand: (minSize) => state.expand(id, minSize),
998
+ getId: () => id,
999
+ getSize: () => state.getSize(id),
1000
+ isCollapsed: () => untrack(isCollapsed),
1001
+ isExpanded: () => !untrack(isCollapsed),
1002
+ resize: (next) => state.resize(id, next),
1003
+ },
1004
+ };
1005
+ }
1006
+
1007
+ // ---------------------------------------------------------------------------
1008
+ // Handle
1009
+ // ---------------------------------------------------------------------------
1010
+
1011
+ export interface SplitterHandleOptions {
1012
+ id: string;
1013
+ ref: ElementRef;
1014
+ isDisabled?: MaybeAccessor<boolean | undefined>;
1015
+ onDragging?: (isDragging: boolean) => void;
1016
+ "aria-label"?: MaybeAccessor<string | undefined>;
1017
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
1018
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
1019
+ }
1020
+
1021
+ export interface SplitterHandleResult {
1022
+ separatorProps: DOMProps;
1023
+ isDragging: Accessor<boolean>;
1024
+ isHovered: Accessor<boolean>;
1025
+ isDisabled: Accessor<boolean>;
1026
+ }
1027
+
1028
+ /**
1029
+ * The divider between two panels, as the window splitter pattern describes it.
1030
+ *
1031
+ * A focusable `separator` whose value is the size of the panel before it. The
1032
+ * arrows along the group's axis move it a step, Home and End send it to that
1033
+ * panel's limits, Enter collapses the panel and brings it back, and F6 goes to
1034
+ * the next handle in the group. The arrows of the other axis are left to the
1035
+ * page.
1036
+ */
1037
+ export function splitterHandle(
1038
+ options: SplitterHandleOptions,
1039
+ state: SplitterState,
1040
+ ): SplitterHandleResult {
1041
+ const { id } = options;
1042
+ tryCleanup(state.registerHandle(id, () => access(options.ref) ?? null));
1043
+
1044
+ const [isHovered, setHovered] = createSignal(false);
1045
+ const isDisabled = (): boolean => state.isDisabled() || access(options.isDisabled) === true;
1046
+ const isDragging = (): boolean => state.draggingHandle() === id;
1047
+ const primary = (): string | undefined => state.panelsAround(id)?.[0];
1048
+
1049
+ const percentOf = (pixels: number): number => {
1050
+ const whole = untrack(() => state.sizeContext().groupPixels);
1051
+ return whole <= 0 ? 0 : (pixels / whole) * 100;
1052
+ };
1053
+
1054
+ const onKeyDown = (event: KeyboardEvent): void => {
1055
+ if (event.defaultPrevented || untrack(isDisabled)) return;
1056
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
1057
+ const horizontal = untrack(state.orientation) === "horizontal";
1058
+ const step = untrack(state.keyboardStep);
1059
+
1060
+ let delta: number | null = null;
1061
+ if (event.key === (horizontal ? "ArrowLeft" : "ArrowUp")) delta = -step;
1062
+ else if (event.key === (horizontal ? "ArrowRight" : "ArrowDown")) delta = step;
1063
+
1064
+ if (delta !== null) {
1065
+ event.preventDefault();
1066
+ state.resizeBy(id, delta, "keyboard");
1067
+ } else if (event.key === "Home" || event.key === "End") {
1068
+ event.preventDefault();
1069
+ // To the limit of the panel before the handle, whichever side of the
1070
+ // screen that is: the logical end, not the visual one.
1071
+ const flipped = horizontal && untrack(state.direction) === "rtl";
1072
+ state.resizeBy(id, (event.key === "Home") === flipped ? 100 : -100, "keyboard");
1073
+ } else if (event.key === "Enter") {
1074
+ event.preventDefault();
1075
+ state.toggleCollapse(id);
1076
+ } else if (event.key === "F6") {
1077
+ event.preventDefault();
1078
+ const handles = state.handleElements();
1079
+ const at = handles.indexOf(event.currentTarget as HTMLElement);
1080
+ if (at < 0 || handles.length < 2) return;
1081
+ const to = (at + (event.shiftKey ? handles.length - 1 : 1)) % handles.length;
1082
+ handles[to]?.focus();
1083
+ }
1084
+ };
1085
+
1086
+ const onPointerDown = (event: PointerEvent): void => {
1087
+ if (untrack(isDisabled) || (event.pointerType === "mouse" && event.button !== 0)) return;
1088
+ const element = event.currentTarget as HTMLElement;
1089
+ const horizontal = untrack(state.orientation) === "horizontal";
1090
+ const origin = horizontal ? event.clientX : event.clientY;
1091
+
1092
+ state.startDrag(id);
1093
+ if (untrack(state.draggingHandle) !== id) return;
1094
+ // The page must not start a text selection or a scroll under the drag.
1095
+ event.preventDefault();
1096
+ element.focus({ preventScroll: true });
1097
+ try {
1098
+ element.setPointerCapture(event.pointerId);
1099
+ } catch {
1100
+ // A pointer that is already gone has nothing to capture.
1101
+ }
1102
+ options.onDragging?.(true);
1103
+
1104
+ const onMove = (next: PointerEvent): void => {
1105
+ const now = horizontal ? next.clientX : next.clientY;
1106
+ state.dragBy(id, percentOf(now - origin));
1107
+ };
1108
+ const onEnd = (): void => {
1109
+ element.removeEventListener("pointermove", onMove);
1110
+ element.removeEventListener("pointerup", onEnd);
1111
+ element.removeEventListener("pointercancel", onEnd);
1112
+ element.removeEventListener("lostpointercapture", onEnd);
1113
+ state.endDrag(id);
1114
+ options.onDragging?.(false);
1115
+ };
1116
+ element.addEventListener("pointermove", onMove);
1117
+ element.addEventListener("pointerup", onEnd);
1118
+ element.addEventListener("pointercancel", onEnd);
1119
+ element.addEventListener("lostpointercapture", onEnd);
1120
+ };
1121
+
1122
+ const value = (pick: (limits: PanelConstraints, size: number) => number): number | undefined => {
1123
+ const panel = primary();
1124
+ if (panel === undefined) return undefined;
1125
+ return Math.round(pick(state.constraintsOf(panel), state.sizeOf(panel)));
1126
+ };
1127
+
1128
+ return {
1129
+ isDragging,
1130
+ isHovered,
1131
+ isDisabled,
1132
+ separatorProps: mergeProps(filterDOMProps(options, { labelable: true }), {
1133
+ role: "separator",
1134
+ tabIndex: () => (isDisabled() ? undefined : 0),
1135
+ // Perpendicular to the group: a row of panels is divided by vertical lines.
1136
+ "aria-orientation": () => (state.orientation() === "horizontal" ? "vertical" : "horizontal"),
1137
+ "aria-controls": primary,
1138
+ "aria-valuenow": () => value((_, size) => size),
1139
+ "aria-valuemin": () =>
1140
+ value((limits) => (limits.collapsible ? limits.collapsedSize : limits.minSize)),
1141
+ "aria-valuemax": () => value((limits) => limits.maxSize),
1142
+ "aria-disabled": () => isDisabled() || undefined,
1143
+ "data-separator": () =>
1144
+ isDisabled() ? "disabled" : isDragging() ? "active" : isHovered() ? "hover" : "inactive",
1145
+ "data-disabled": () => (isDisabled() ? "" : undefined),
1146
+ onKeyDown,
1147
+ onPointerDown,
1148
+ onPointerEnter: () => setHovered(true),
1149
+ onPointerLeave: () => setHovered(false),
1150
+ }),
1151
+ };
1152
+ }