@uniflowed/ui 0.0.0-alpha.4 → 0.0.0-alpha.40

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 (52) hide show
  1. package/accordion.js +360 -0
  2. package/alert-dialog.js +282 -0
  3. package/alert.js +142 -0
  4. package/avatar.js +276 -0
  5. package/breadcrumb.js +138 -0
  6. package/calendar.js +547 -0
  7. package/carousel.js +410 -0
  8. package/checkbox.js +216 -31
  9. package/collapsible.js +169 -0
  10. package/combobox.js +209 -40
  11. package/context-menu.js +206 -0
  12. package/date-picker.js +346 -0
  13. package/dialog.js +229 -197
  14. package/drawer.js +490 -0
  15. package/field.js +257 -42
  16. package/hover-card.js +330 -0
  17. package/index.js +1548 -24
  18. package/input-otp.js +218 -0
  19. package/interactions.js +2323 -0
  20. package/internal/anchor.js +565 -0
  21. package/internal/date-grid.js +260 -0
  22. package/internal/disclosure.js +298 -0
  23. package/internal/focus.js +64 -0
  24. package/internal/form-value.js +83 -0
  25. package/internal/hover-intent.js +259 -0
  26. package/internal/menu-tree.js +228 -0
  27. package/internal/merge-props.js +206 -7
  28. package/internal/range.js +147 -0
  29. package/internal/roving-focus.js +205 -11
  30. package/menu.js +521 -336
  31. package/menubar.js +288 -0
  32. package/navigation-menu.js +251 -0
  33. package/package.json +8 -12
  34. package/pagination.js +209 -0
  35. package/popover.js +344 -0
  36. package/progress.js +91 -0
  37. package/radio-group.js +302 -0
  38. package/resizable.js +447 -0
  39. package/scroll-area.js +283 -0
  40. package/select.js +888 -0
  41. package/separator.js +97 -0
  42. package/sheet.js +189 -0
  43. package/sidebar.js +313 -0
  44. package/skeleton.js +159 -0
  45. package/slider.js +405 -0
  46. package/switch.js +43 -34
  47. package/table.js +520 -0
  48. package/tabs.js +99 -96
  49. package/toast.js +592 -0
  50. package/toggle-group.js +282 -0
  51. package/toggle.js +105 -0
  52. package/tooltip.js +400 -0
@@ -0,0 +1,565 @@
1
+ // @flow
2
+ //
3
+ // Where an overlay goes, given where its trigger is.
4
+ //
5
+ // A popover, a tooltip and a hover card are the same three sentences: a box
6
+ // appears next to another box, it stays on the screen when there is no room
7
+ // where it was asked to go, and it says where it ended up so a stylesheet can
8
+ // point an arrow at the trigger. Written into each component, those three
9
+ // sentences are three copies that agree until one of them is fixed.
10
+ //
11
+ // # Flip *and* shift, because a flip alone is not enough
12
+ //
13
+ // There are two answers to "it does not fit", and a positioning layer needs
14
+ // both:
15
+ //
16
+ // * **Flip** — the main axis. A menu whose trigger is near the bottom of the
17
+ // viewport opens upwards instead of off the page, and reports
18
+ // `data-side="top"` so the arrow moves with it.
19
+ // * **Shift** — the cross axis. A menu wider than its trigger, aligned to a
20
+ // trigger near the right edge, has nowhere to flip *to*: both alignments
21
+ // overflow when the overlay is wider than the room on either side of the
22
+ // anchor. Sliding it back along the trigger is the only answer that keeps
23
+ // it on screen, and it is what Floating UI calls `shift`.
24
+ //
25
+ // Flipping the *alignment* — `start` becomes `end` when the aligned edge would
26
+ // leave the viewport — is the thing that looks like a shift and is not. It
27
+ // moves the overlay by its own width, which is a jump the reader sees, and it
28
+ // still overflows in exactly the case above. So the alignment never flips here:
29
+ // the side flips, the cross axis slides, and `data-align` keeps saying what the
30
+ // caller asked for.
31
+ //
32
+ // # One tier, measured, and why there is no declarative second one
33
+ //
34
+ // The platform grew this capability: CSS anchor positioning places an element
35
+ // against an `anchor-name` in the compositor, with `position-try-fallbacks` for
36
+ // the collision case and no JavaScript on the scroll path. It is the better
37
+ // mechanism and it is deliberately not used here, because it cannot express
38
+ // half of what this module promises:
39
+ //
40
+ // * `position-area` places a box in one of a grid of regions around the
41
+ // anchor. There is no spelling that says "and then move it back inside the
42
+ // viewport": the property chooses a region, it does not clamp a coordinate.
43
+ // * `position-try-fallbacks`, with the built-in `flip-block` / `flip-inline`
44
+ // or a hand-written `@position-try` block, tries another *placement* when
45
+ // the first overflows. Every one of those is a flip. None is a slide.
46
+ // * `position-area: span-all` with `justify-self: anchor-center` centres the
47
+ // overlay on the anchor and then needs a `margin-inline` to pull it back
48
+ // inside — and that margin is a number only a measurement produces, so the
49
+ // declarative path would be a measured path wearing a stylesheet.
50
+ //
51
+ // A tier that flips and a tier that flips *and* slides put the same overlay in
52
+ // two different places, and which one a reader gets depends on their browser.
53
+ // Shipping one tier that both engines run is worth more than shipping the
54
+ // faster one to some of them, so this module measures. It is the reason
55
+ // `packages/ui` has no `CSS.supports` in it: there is nothing to branch on.
56
+ //
57
+ // The measuring is kept cheap rather than clever. A placement is computed on
58
+ // open, on a scroll anywhere in the page, on a viewport resize and on a resize
59
+ // of either box — and each of those is one `getBoundingClientRect` per box
60
+ // followed by the arithmetic below, which reads nothing else.
61
+ //
62
+ // # Why the arithmetic is a function and not a hook
63
+ //
64
+ // `placeOverlay` takes three rectangles and returns a placement. It touches no
65
+ // element, no window and no React, so the whole of the collision behaviour —
66
+ // every flip, every slide, right-to-left alignment, the overlay that is wider
67
+ // than the viewport — is testable by calling it with numbers. That matters more
68
+ // here than in most modules: the DOM these components are tested in computes no
69
+ // layout at all, so a test that went through the hook could only assert *that*
70
+ // a position was applied, never that it was the right one.
71
+ //
72
+ // # Why an overlay is `position: fixed`
73
+ //
74
+ // Because the coordinates are the viewport's. It also gets most of what a
75
+ // portal is usually reached for: a fixed box is not clipped by an ancestor's
76
+ // `overflow: hidden`, so a menu in a table row or a scroll container is not cut
77
+ // in half — without moving the element away from its trigger in the
78
+ // accessibility tree, which is the trade `dialog.js`'s header refuses to make.
79
+ // The exception is an ancestor with `transform`, `filter` or `will-change`,
80
+ // which becomes the containing block for a fixed descendant; that is the CSS
81
+ // the top layer would answer, and answering it is ubugeeei-prod/uf#256's
82
+ // remaining half rather than this module's.
83
+ //
84
+ // # Why this is `internal/` and not a subpath
85
+ //
86
+ // The same reason `roving-focus.js` gives. This is not a positioning library,
87
+ // it is the relationship the overlay parts build: a `data-side` that agrees
88
+ // with the coordinates, one set of custom-property names for a stylesheet to
89
+ // read, and one definition of what `start` means in a right-to-left page.
90
+ // Exported, a consumer could build a part that positions itself differently and
91
+ // still calls itself an overlay.
92
+
93
+ import { useEffect, useState } from "@uniflowed/react";
94
+ import { useStableCallback } from "@uniflowed/hooks/lifecycle";
95
+
96
+ import type { Direction } from "./roving-focus.js";
97
+ import { directionOf } from "./roving-focus.js";
98
+
99
+ /**
100
+ * Which side of its trigger an overlay opens onto.
101
+ *
102
+ * Physical rather than logical, which is the opposite of `Align` below and is
103
+ * deliberate: `side` answers "above or below", and the two horizontal ones are
104
+ * named after the screen because a design that puts a popover to the right of
105
+ * a toolbar means the right of the toolbar in any writing direction. What the
106
+ * writing direction changes is the *alignment*, which is where the reading
107
+ * order actually lives.
108
+ */
109
+ export type Side = "top" | "right" | "bottom" | "left";
110
+
111
+ /**
112
+ * A side a caller may ask for, which is the four above plus the two that mean
113
+ * "the way the reader reads".
114
+ *
115
+ * The WAI-ARIA menu pattern puts a submenu on the inline end - to the right of a
116
+ * left-to-right menu and to the left of a right-to-left one - and `menu.js`
117
+ * already spells the *keys* that way, so a physical-only `side` would have left
118
+ * one half of that pattern mirrored and the other half not. `Placement` and
119
+ * `placeOverlay` stay physical: a logical side is resolved once, against the
120
+ * trigger's own direction, before any arithmetic sees it.
121
+ */
122
+ export type LogicalSide = Side | "inline-start" | "inline-end";
123
+
124
+ /**
125
+ * Where the overlay sits along the trigger's other axis.
126
+ *
127
+ * Logical: `start` is the left edge in a left-to-right page and the right edge
128
+ * in a right-to-left one, so a menu aligned to the start of its trigger opens
129
+ * the way the reader reads in both.
130
+ */
131
+ export type Align = "start" | "center" | "end";
132
+
133
+ /** A box, in viewport coordinates: what `getBoundingClientRect` reports. */
134
+ export type Rect = {|
135
+ readonly x: number,
136
+ readonly y: number,
137
+ readonly width: number,
138
+ readonly height: number,
139
+ |};
140
+
141
+ /** Everything `placeOverlay` needs, and nothing it could read for itself. */
142
+ export type Anchoring = {|
143
+ /** The trigger. */
144
+ readonly anchor: Rect,
145
+ /** The overlay. Only its size is used; where it is now does not matter. */
146
+ readonly overlay: Rect,
147
+ /** What it has to stay inside, which is the viewport for a fixed element. */
148
+ readonly viewport: Rect,
149
+ readonly side: Side,
150
+ readonly align: Align,
151
+ /** The gap between the trigger and the overlay, in pixels. */
152
+ readonly sideOffset: number,
153
+ /** A nudge along the cross axis, in the direction the page reads. */
154
+ readonly alignOffset: number,
155
+ /** Whether to flip and slide at all. `false` places it exactly as asked. */
156
+ readonly avoidCollisions: boolean,
157
+ /** How close to the viewport edge the overlay may come. */
158
+ readonly collisionPadding: number,
159
+ readonly direction: Direction,
160
+ |};
161
+
162
+ /** Where the overlay goes, and what the placement had to do to get there. */
163
+ export type Placement = {|
164
+ readonly x: number,
165
+ readonly y: number,
166
+ /** The side it ended up on, which is the requested one unless it flipped. */
167
+ readonly side: Side,
168
+ /** The requested alignment. It never changes; see the module header. */
169
+ readonly align: Align,
170
+ /** How far it slid along the cross axis, so an arrow can be moved back. */
171
+ readonly shift: number,
172
+ /** The room between the trigger and the viewport edge, and across it. */
173
+ readonly availableWidth: number,
174
+ readonly availableHeight: number,
175
+ |};
176
+
177
+ /** What `useAnchor` reports back for `data-side` and `data-align`. */
178
+ export type Anchored = {|
179
+ readonly side: Side,
180
+ readonly align: Align,
181
+ |};
182
+
183
+ /** What `useAnchor` is told, on top of the geometry `placeOverlay` needs. */
184
+ export type AnchorRequest = {|
185
+ readonly anchorRef: { current: HTMLElement | null },
186
+ /**
187
+ * A box to place against instead of the anchor element's own.
188
+ *
189
+ * A context menu opens *at a point* rather than against an element: the
190
+ * pointer coordinates the reader right-clicked at, which is a zero-sized
191
+ * rectangle no element in the document has. The element is still needed —
192
+ * it is what the writing direction is read from, what a `ResizeObserver`
193
+ * watches, and what focus returns to — so this replaces the *measurement*
194
+ * and nothing else.
195
+ *
196
+ * `null` (and absent) means "measure the element", which is every other
197
+ * overlay in this package.
198
+ *
199
+ * It has to be stable between renders for the same position, because it is
200
+ * one of the things the placement effect re-runs for; a fresh object each
201
+ * render would re-measure on every render of the page around it.
202
+ */
203
+ readonly anchorRect?: Rect | null,
204
+ readonly overlayRef: { current: HTMLElement | null },
205
+ /** Nothing is measured while it is closed: there is nothing to measure. */
206
+ readonly open: boolean,
207
+ /** Resolved against the trigger's writing direction; see `LogicalSide`. */
208
+ readonly side: LogicalSide,
209
+ readonly align: Align,
210
+ readonly sideOffset: number,
211
+ readonly alignOffset: number,
212
+ readonly avoidCollisions: boolean,
213
+ readonly collisionPadding: number,
214
+ |};
215
+
216
+ /** The side a flip goes to. */
217
+ const OPPOSITE: { readonly [Side]: Side } = {
218
+ top: "bottom",
219
+ bottom: "top",
220
+ left: "right",
221
+ right: "left",
222
+ };
223
+
224
+ /**
225
+ * The side on the screen that `side` names for a reader reading `direction`.
226
+ *
227
+ * The four physical ones pass through unchanged, because a design that puts a
228
+ * popover to the right of a toolbar means the right of the toolbar in Arabic
229
+ * too; `Side`'s own documentation says why that is the useful default and why
230
+ * alignment is the axis that mirrors.
231
+ */
232
+ export function physicalSide(side: LogicalSide, direction: Direction): Side {
233
+ // Written out rather than left to a wildcard, so that a sixth side added to
234
+ // `LogicalSide` one day is a checker error here instead of a value that falls
235
+ // through unresolved.
236
+ return match (side) {
237
+ "inline-start" => direction === "rtl" ? "right" : "left",
238
+ "inline-end" => direction === "rtl" ? "left" : "right",
239
+ "top" => "top",
240
+ "right" => "right",
241
+ "bottom" => "bottom",
242
+ "left" => "left",
243
+ };
244
+ }
245
+
246
+ /** Whether a side stacks the overlay above the trigger or beside it. */
247
+ function isVertical(side: Side): boolean {
248
+ return side === "top" || side === "bottom";
249
+ }
250
+
251
+ /**
252
+ * The space between each edge of the anchor and the edge of the viewport,
253
+ * already minus the padding the overlay must not come inside.
254
+ *
255
+ * Negative for an anchor that is itself off the screen, which is a real state
256
+ * — a trigger scrolled halfway out of a container — and is why nothing below
257
+ * assumes these are positive.
258
+ */
259
+ function roomAround(
260
+ anchor: Rect,
261
+ viewport: Rect,
262
+ collisionPadding: number,
263
+ ): { readonly [Side]: number } {
264
+ return {
265
+ top: anchor.y - (viewport.y + collisionPadding),
266
+ bottom: viewport.y + viewport.height - collisionPadding - (anchor.y + anchor.height),
267
+ left: anchor.x - (viewport.x + collisionPadding),
268
+ right: viewport.x + viewport.width - collisionPadding - (anchor.x + anchor.width),
269
+ };
270
+ }
271
+
272
+ /**
273
+ * The side the overlay actually fits on.
274
+ *
275
+ * The requested side wins whenever it fits, because a component that moved an
276
+ * overlay it did not have to move is one a designer cannot lay out against.
277
+ * When it does not fit and the opposite side does, it flips. When *neither*
278
+ * fits — a tall overlay next to a trigger in the middle of a short viewport —
279
+ * it takes the side with more room, so the reader sees as much of it as the
280
+ * page allows and `availableHeight` tells the stylesheet how much that was.
281
+ */
282
+ function sideThatFits(anchoring: Anchoring, room: { readonly [Side]: number }): Side {
283
+ const { overlay, side, sideOffset } = anchoring;
284
+ const needed = (isVertical(side) ? overlay.height : overlay.width) + sideOffset;
285
+ const opposite = OPPOSITE[side];
286
+ if (room[side] >= needed) {
287
+ return side;
288
+ }
289
+ if (room[opposite] >= needed) {
290
+ return opposite;
291
+ }
292
+ return room[opposite] > room[side] ? opposite : side;
293
+ }
294
+
295
+ /**
296
+ * Where the overlay's leading edge goes along the cross axis, before sliding.
297
+ *
298
+ * `start` is the anchor's leading edge, `end` puts the overlay's trailing edge
299
+ * on the anchor's, and `center` splits the difference. Which edge is "leading"
300
+ * is the writing direction's business, and only on a horizontal cross axis: a
301
+ * page that reads right to left still reads top to bottom, so an overlay beside
302
+ * its trigger aligns to the top for `start` either way.
303
+ */
304
+ function alignedAt(
305
+ align: Align,
306
+ mirrored: boolean,
307
+ anchorStart: number,
308
+ anchorSize: number,
309
+ overlaySize: number,
310
+ ): number {
311
+ const resolved = mirrored ? mirror(align) : align;
312
+ return match (resolved) {
313
+ "start" => anchorStart,
314
+ "center" => anchorStart + anchorSize / 2 - overlaySize / 2,
315
+ "end" => anchorStart + anchorSize - overlaySize,
316
+ };
317
+ }
318
+
319
+ /** `start` and `end` swapped, for a right-to-left page. */
320
+ function mirror(align: Align): Align {
321
+ return match (align) {
322
+ "start" => "end",
323
+ "center" => "center",
324
+ "end" => "start",
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Place `overlay` against `anchor` inside `viewport`.
330
+ *
331
+ * Pure arithmetic over three rectangles: no element, no window, no React. See
332
+ * the module header for why that is the point rather than a convenience.
333
+ */
334
+ export function placeOverlay(anchoring: Anchoring): Placement {
335
+ const {
336
+ align,
337
+ alignOffset,
338
+ anchor,
339
+ avoidCollisions,
340
+ collisionPadding,
341
+ direction,
342
+ overlay,
343
+ sideOffset,
344
+ viewport,
345
+ } = anchoring;
346
+
347
+ const room = roomAround(anchor, viewport, collisionPadding);
348
+ const side = avoidCollisions ? sideThatFits(anchoring, room) : anchoring.side;
349
+ const vertical = isVertical(side);
350
+
351
+ // The main axis: hard against the trigger's edge, plus the gap. The overlay
352
+ // is never pushed along this axis, because pushing it would slide it over
353
+ // the trigger it is meant to be pointing at.
354
+ const main = match (side) {
355
+ "top" => anchor.y - overlay.height - sideOffset,
356
+ "bottom" => anchor.y + anchor.height + sideOffset,
357
+ "left" => anchor.x - overlay.width - sideOffset,
358
+ "right" => anchor.x + anchor.width + sideOffset,
359
+ };
360
+
361
+ // The cross axis: aligned, nudged, then slid back inside if it has to be.
362
+ const anchorStart = vertical ? anchor.x : anchor.y;
363
+ const anchorSize = vertical ? anchor.width : anchor.height;
364
+ const overlaySize = vertical ? overlay.width : overlay.height;
365
+ const viewportStart = vertical ? viewport.x : viewport.y;
366
+ const viewportSize = vertical ? viewport.width : viewport.height;
367
+ // A positive `alignOffset` moves the overlay the way the page reads, so the
368
+ // same number nudges a menu in the same visual direction as its own text.
369
+ const reading = vertical && direction === "rtl" ? -1 : 1;
370
+ const wanted =
371
+ alignedAt(align, vertical && direction === "rtl", anchorStart, anchorSize, overlaySize) +
372
+ alignOffset * reading;
373
+
374
+ const lowest = viewportStart + collisionPadding;
375
+ const highest = viewportStart + viewportSize - collisionPadding - overlaySize;
376
+ // `Math.max` last, so an overlay *wider* than the viewport — where `highest`
377
+ // is below `lowest` and no position satisfies both — is pinned to the leading
378
+ // edge rather than pushed off the far one. `availableWidth` is what a
379
+ // stylesheet reads to stop it being that wide in the first place.
380
+ const cross = avoidCollisions ? Math.max(lowest, Math.min(wanted, highest)) : wanted;
381
+
382
+ const alongSide = Math.max(0, room[side] - sideOffset);
383
+ const acrossSide = Math.max(0, viewportSize - collisionPadding * 2);
384
+
385
+ return {
386
+ align,
387
+ availableHeight: vertical ? alongSide : acrossSide,
388
+ availableWidth: vertical ? acrossSide : alongSide,
389
+ shift: cross - wanted,
390
+ side,
391
+ x: vertical ? cross : main,
392
+ y: vertical ? main : cross,
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Write a placement onto the overlay.
398
+ *
399
+ * Imperatively, and only these seven properties. They change on every scroll
400
+ * frame while an overlay is open, and putting them in state would re-render the
401
+ * overlay and everything in it sixty times a second to move a box — which is
402
+ * exactly the cost `index.js`'s header says this package does not pay. React
403
+ * owns nothing written here: it never sets `left`, `top` or a custom property
404
+ * on these elements, and a caller who passes a `style` of their own keeps every
405
+ * property in it except the ones this component's position is made of.
406
+ *
407
+ * The two measurements are the ones a caller cannot compute for themselves. A
408
+ * `Select` popup that must match its trigger's width needs the trigger
409
+ * measured; a menu near the bottom of the page needs to know how much room is
410
+ * left before it can decide to scroll rather than overflow.
411
+ */
412
+ function write(overlay: HTMLElement, anchor: Rect, placement: Placement): void {
413
+ const style = overlay.style;
414
+ style.position = "fixed";
415
+ style.left = `${placement.x}px`;
416
+ style.top = `${placement.y}px`;
417
+ style.setProperty("--uf-anchor-trigger-width", `${anchor.width}px`);
418
+ style.setProperty("--uf-anchor-trigger-height", `${anchor.height}px`);
419
+ style.setProperty("--uf-anchor-available-width", `${placement.availableWidth}px`);
420
+ style.setProperty("--uf-anchor-available-height", `${placement.availableHeight}px`);
421
+ // How far the slide moved it, so an arrow drawn by a stylesheet can be moved
422
+ // back the other way and keep pointing at the trigger.
423
+ style.setProperty("--uf-anchor-shift", `${placement.shift}px`);
424
+ }
425
+
426
+ /** The rectangle of an element, as the arithmetic above wants it. */
427
+ function rectOf(element: HTMLElement): Rect {
428
+ const box = element.getBoundingClientRect();
429
+ return { height: box.height, width: box.width, x: box.left, y: box.top };
430
+ }
431
+
432
+ /**
433
+ * Keep an overlay against its trigger for as long as it is open.
434
+ *
435
+ * Returns the side and alignment it settled on, which the part renders as
436
+ * `data-side` and `data-align`. Those are state — they change rarely, a
437
+ * stylesheet has to see them, and a flip is exactly the moment an arrow has to
438
+ * move — while the coordinates are written straight to the element; `write`
439
+ * says why.
440
+ */
441
+ export hook useAnchor(request: AnchorRequest): Anchored {
442
+ const {
443
+ align,
444
+ alignOffset,
445
+ anchorRect,
446
+ anchorRef,
447
+ avoidCollisions,
448
+ collisionPadding,
449
+ open,
450
+ overlayRef,
451
+ side,
452
+ sideOffset,
453
+ } = request;
454
+ // Absent and `null` are one answer here — "measure the element" — so the two
455
+ // spellings become one value before anything depends on it.
456
+ const virtual = anchorRect ?? null;
457
+ // The left-to-right reading of a logical side, which is what `Anchored`
458
+ // reports until something has been measured. In a right-to-left page a
459
+ // submenu's `inline-end` is the *left*, and the first `reflow` says so - one
460
+ // commit later, exactly as a flip does, and for the same reason: the direction
461
+ // is a fact about the document, and a render may not read one.
462
+ const [settled, setSettled] = useState<Anchored>({ align, side: physicalSide(side, "ltr") });
463
+
464
+ const reflow = useStableCallback(() => {
465
+ const anchor = anchorRef.current;
466
+ const overlay = overlayRef.current;
467
+ const view = overlay?.ownerDocument?.defaultView;
468
+ if (anchor == null || overlay == null || view == null) {
469
+ return;
470
+ }
471
+ const box = virtual ?? rectOf(anchor);
472
+ const placement = placeOverlay({
473
+ align,
474
+ alignOffset,
475
+ anchor: box,
476
+ avoidCollisions,
477
+ collisionPadding,
478
+ direction: directionOf(anchor),
479
+ overlay: rectOf(overlay),
480
+ side: physicalSide(side, directionOf(anchor)),
481
+ sideOffset,
482
+ // The viewport of a fixed element, which is the whole of it: a fixed box
483
+ // is positioned against the viewport rather than against whatever is
484
+ // scrolled around it.
485
+ viewport: { height: view.innerHeight, width: view.innerWidth, x: 0, y: 0 },
486
+ });
487
+ write(overlay, box, placement);
488
+ setSettled((current) =>
489
+ current.side === placement.side && current.align === placement.align
490
+ ? // The same object, so a scroll that changes nothing renders nothing.
491
+ current
492
+ : { align: placement.align, side: placement.side },
493
+ );
494
+ });
495
+
496
+ useEffect(() => {
497
+ const anchor = anchorRef.current;
498
+ const overlay = overlayRef.current;
499
+ const view = overlay?.ownerDocument?.defaultView;
500
+ if (!open || anchor == null || overlay == null || view == null) {
501
+ // Forget the measurement when the overlay closes. It is only read while
502
+ // `open`, but a body that stays mounted across a close — `PopoverBody`
503
+ // does — reopens in a commit where `open` is already `true`, and would
504
+ // report the *previous* opening's side until `reflow` corrects it from
505
+ // an effect, which runs after paint. That is one frame of an arrow
506
+ // drawn from `data-side` pointing the wrong way, after a reopen that
507
+ // follows a flip.
508
+ if (!open) {
509
+ const asked = physicalSide(side, anchor == null ? "ltr" : directionOf(anchor));
510
+ setSettled((current) =>
511
+ current.side === asked && current.align === align ? current : { align, side: asked },
512
+ );
513
+ }
514
+ return;
515
+ }
516
+ reflow();
517
+
518
+ const document = overlay.ownerDocument;
519
+ const moved = () => reflow();
520
+ // Capture, because a scroll event does not bubble: a trigger inside a
521
+ // scrolling panel would otherwise move under an overlay that never heard
522
+ // about it. Passive, because this never prevents the scroll it is watching.
523
+ document.addEventListener("scroll", moved, { capture: true, passive: true });
524
+ view.addEventListener("resize", moved);
525
+ // A trigger that grows — a button whose label changed, a field that gained
526
+ // a second line — moves the overlay without any scroll or resize event
527
+ // being fired at all.
528
+ //
529
+ // Read off the window rather than through a local: a capitalised name
530
+ // holding a constructor is read as a React component by `uf lint`, and it
531
+ // is right to — the rule cannot tell this one from a component, and the
532
+ // window's own property is the thing being asked about anyway.
533
+ const host: $FlowFixMe = view;
534
+ const sizes = typeof host.ResizeObserver === "function" ? new host.ResizeObserver(moved) : null;
535
+ sizes?.observe(anchor);
536
+ sizes?.observe(overlay);
537
+
538
+ return () => {
539
+ document.removeEventListener("scroll", moved, true);
540
+ view.removeEventListener("resize", moved);
541
+ sizes?.disconnect();
542
+ };
543
+ // The measurements are read through `reflow`, which is stable and always
544
+ // has the latest of them; they are named here so that changing one — a
545
+ // caller flipping `side` on a breakpoint — measures again.
546
+ }, [
547
+ align,
548
+ alignOffset,
549
+ anchorRect,
550
+ anchorRef,
551
+ avoidCollisions,
552
+ collisionPadding,
553
+ open,
554
+ overlayRef,
555
+ reflow,
556
+ side,
557
+ sideOffset,
558
+ ]);
559
+
560
+ // What was asked for until there is something measured to report, so the
561
+ // first commit — and the server's markup, which measures nothing at all —
562
+ // says the requested side rather than the last one some other opening
563
+ // happened to settle on.
564
+ return open ? settled : { align, side: physicalSide(side, "ltr") };
565
+ }