@uniflowed/ui 0.0.0-alpha.10

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.
package/popover.js ADDED
@@ -0,0 +1,326 @@
1
+ // @flow
2
+ //
3
+ // A popover: a dialog that is not modal, which is the whole of the difference.
4
+ //
5
+ // `dialog.js` is modal and only modal, on purpose — every line of it is a
6
+ // promise that the rest of the page is unavailable. A popover makes the
7
+ // opposite promise, and it has to make it in every one of the same places:
8
+ //
9
+ // * No `aria-modal`, because the page behind is still there.
10
+ // * Nothing is made `inert` and nothing is `aria-hidden`, because a reader
11
+ // may still reach it.
12
+ // * The page is not scroll-locked, because a wheel over a popover scrolling
13
+ // the page behind is what a reader expects from something that did not
14
+ // take the page over.
15
+ // * **`Tab` leaves.** This is the load-bearing one. A trap is what makes a
16
+ // modal dialog safe and what makes a popover a hole a reader falls into:
17
+ // they tabbed in, they tab out, and a component that wraps them back to
18
+ // the first control has taken the page away without ever saying so.
19
+ //
20
+ // So a popover is not a `Dialog` with a flag. A flag would mean every one of
21
+ // the behaviours above reading it, and the failure of the one that forgot would
22
+ // be a dialog that is not modal while announcing that it is — silent, and
23
+ // wrong in the direction that traps people.
24
+ //
25
+ // What it *does* share with a dialog is the part a reader notices when it is
26
+ // missing: focus moves into it when it opens, `Escape` closes it, and focus
27
+ // goes back to the trigger — unless the reader dismissed it by pressing or
28
+ // tabbing somewhere else, in which case it stays where they put it.
29
+ //
30
+ // # Where it goes
31
+ //
32
+ // `internal/anchor.js`, the same as every other overlay here: `side`, `align`,
33
+ // `sideOffset` and `alignOffset` place it against the trigger, it flips and
34
+ // slides to stay on the screen, and it reports where it ended up as `data-side`
35
+ // and `data-align` so a stylesheet can point an arrow without measuring
36
+ // anything itself.
37
+ //
38
+ // # Its name
39
+ //
40
+ // `role="dialog"` needs an accessible name, and a popover has no `Title` part
41
+ // to take one from — shadcn's does not either, and adding one would make the
42
+ // common case (a form, a colour picker, a date picker) carry a heading nobody
43
+ // asked for. So the body is named after the button that opened it, which is
44
+ // true and is what a reader would say the popover is, and a caller who passes
45
+ // `aria-label` or `aria-labelledby` of their own keeps it.
46
+
47
+ "use client";
48
+
49
+ import * as React from "@uniflowed/react";
50
+ import {
51
+ createContext,
52
+ useContext,
53
+ useEffect,
54
+ useId,
55
+ useMemo,
56
+ useRef,
57
+ useState,
58
+ } from "@uniflowed/react";
59
+ import { useStableCallback } from "@uniflowed/hooks/lifecycle";
60
+
61
+ import type { Align, Side } from "./internal/anchor.js";
62
+ import type { Rest } from "./internal/merge-props.js";
63
+ import { composeHandlers, composeRefs, withoutComposed } from "./internal/merge-props.js";
64
+ import { focusable } from "./internal/focus.js";
65
+ import { useAnchor } from "./internal/anchor.js";
66
+ import { useControlled } from "./internal/controlled-state.js";
67
+ import { usePresence } from "./internal/disclosure.js";
68
+
69
+ export type { Align, Side } from "./internal/anchor.js";
70
+
71
+ type PopoverState = {|
72
+ readonly base: string,
73
+ readonly open: boolean,
74
+ readonly setOpen: (open: boolean) => void,
75
+ /** What opened it, where it is anchored, and where focus goes back to. */
76
+ readonly triggerRef: { current: HTMLElement | null },
77
+ /**
78
+ * Whether a trigger is rendered, so the body only names one that exists.
79
+ *
80
+ * A popover opened by `defaultOpen` in a page with no trigger is a real
81
+ * arrangement — a first-run hint pointing at something — and an
82
+ * `aria-labelledby` naming the id that trigger *would* have had makes a
83
+ * screen reader announce nothing at all.
84
+ */
85
+ readonly triggered: boolean,
86
+ readonly registerTrigger: (present: boolean) => void,
87
+ |};
88
+
89
+ const PopoverContext: React.Context<PopoverState | null> = createContext(null);
90
+
91
+ /**
92
+ * The popover a part belongs to.
93
+ *
94
+ * Raising rather than returning null, for the reason `useDialog` gives: a
95
+ * `Popover.Body` outside a root would render a `role="dialog"` that nothing
96
+ * opens, closes or names, and it would look correct.
97
+ */
98
+ hook usePopover(part: string): PopoverState {
99
+ const state = useContext(PopoverContext);
100
+ if (state == null) {
101
+ throw new Error(`${part} must be rendered inside a Popover.Root`);
102
+ }
103
+ return state;
104
+ }
105
+
106
+ /**
107
+ * The popover, open or closed. Uncontrolled unless `open` is given.
108
+ *
109
+ * Renders no element of its own: the trigger and the body are siblings in
110
+ * whatever layout the caller wrote, and a wrapper would put a `<div>` between
111
+ * them for the caller to style around.
112
+ */
113
+ export component PopoverRoot(
114
+ children: React.Node,
115
+ defaultOpen?: boolean = false,
116
+ open?: boolean,
117
+ onOpenChange?: (open: boolean) => void,
118
+ ) {
119
+ const base = useId();
120
+ const [isOpen, setOpen] = useControlled(open, defaultOpen, onOpenChange);
121
+ const triggerRef = useRef<HTMLElement | null>(null);
122
+ const [triggered, setTriggered] = useState(false);
123
+
124
+ const state = useMemo(
125
+ () => ({
126
+ base,
127
+ open: isOpen,
128
+ registerTrigger: setTriggered,
129
+ setOpen,
130
+ triggerRef,
131
+ triggered,
132
+ }),
133
+ [base, isOpen, setOpen, triggered],
134
+ );
135
+
136
+ return <PopoverContext.Provider value={state}>{children}</PopoverContext.Provider>;
137
+ }
138
+
139
+ /**
140
+ * The button that opens the popover, and what it is anchored to.
141
+ *
142
+ * A toggle rather than an opener: pressing the button of an open popover closes
143
+ * it, which is what every disclosure does and what a reader who pressed it by
144
+ * accident expects. The outside-press handler in `Popover.Body` knows the
145
+ * trigger is not "outside" for exactly this reason — closing there and letting
146
+ * this click reopen made the press a no-op that flickered.
147
+ */
148
+ export component PopoverTrigger(children: React.Node, ...rest: Rest) {
149
+ const popover = usePopover("Popover.Trigger");
150
+ const passed = withoutComposed(rest, ["onClick", "ref"]);
151
+ usePresence(popover.registerTrigger);
152
+
153
+ return (
154
+ <button
155
+ {...passed}
156
+ // Only while it is open: an `aria-controls` naming an element that is not
157
+ // in the document tells a reader there is somewhere to go and then has
158
+ // nowhere to send them.
159
+ aria-controls={popover.open ? `${popover.base}-body` : undefined}
160
+ aria-expanded={popover.open ? "true" : "false"}
161
+ aria-haspopup="dialog"
162
+ id={`${popover.base}-trigger`}
163
+ onClick={composeHandlers(rest.onClick, () => popover.setOpen(!popover.open))}
164
+ ref={composeRefs(rest.ref, (element) => {
165
+ popover.triggerRef.current = element;
166
+ })}
167
+ type="button"
168
+ >
169
+ {children}
170
+ </button>
171
+ );
172
+ }
173
+
174
+ /**
175
+ * The popover itself: positioned, focused, dismissible, and not a trap.
176
+ *
177
+ * The three ways out are the three a reader tries. `Escape` closes it and gives
178
+ * focus back to the trigger, because the reader is still where they were. A
179
+ * press outside closes it and leaves focus alone, because they have already
180
+ * moved on. `Tab` past the last control inside closes it for the same reason
181
+ * and leaves focus where the browser put it — which is the behaviour that
182
+ * separates this from a dialog, and the one a copy of `dialog.js` with the
183
+ * `aria-modal` deleted would get wrong.
184
+ */
185
+ export component PopoverBody(
186
+ children: React.Node,
187
+ align?: Align = "center",
188
+ alignOffset?: number = 0,
189
+ avoidCollisions?: boolean = true,
190
+ collisionPadding?: number = 0,
191
+ side?: Side = "bottom",
192
+ sideOffset?: number = 0,
193
+ ...rest: Rest
194
+ ) {
195
+ const popover = usePopover("Popover.Body");
196
+ const bodyRef = useRef<HTMLElement | null>(null);
197
+ // Stable, so the effect below depends on `open` and on nothing else. Keyed on
198
+ // `setOpen` it re-ran whenever the caller passed a fresh `onOpenChange`
199
+ // closure — which is every render — and re-running it took focus back from
200
+ // wherever the reader had moved it inside the popover.
201
+ const close = useStableCallback(() => popover.setOpen(false));
202
+ // Set when the reader left rather than closed: a press outside, or a Tab that
203
+ // carried them out. Focus is theirs from then on, and dragging it back to the
204
+ // trigger would undo the thing they just did.
205
+ const left = useRef(false);
206
+ const triggerRef = popover.triggerRef;
207
+
208
+ const anchored = useAnchor({
209
+ align,
210
+ alignOffset,
211
+ anchorRef: triggerRef,
212
+ avoidCollisions,
213
+ collisionPadding,
214
+ open: popover.open,
215
+ overlayRef: bodyRef,
216
+ side,
217
+ sideOffset,
218
+ });
219
+
220
+ useEffect(() => {
221
+ const body = bodyRef.current;
222
+ if (!popover.open || body == null) {
223
+ return;
224
+ }
225
+ const document = body.ownerDocument;
226
+ const trigger = triggerRef.current;
227
+ // Whatever had focus, which is the trigger for a popover that was opened
228
+ // and the previously focused element for one that opened itself.
229
+ const opener = trigger ?? (document.activeElement as $FlowFixMe);
230
+
231
+ const outside = (target: EventTarget | null): boolean => {
232
+ const node: $FlowFixMe = target;
233
+ // The trigger is outside the body and is not "outside" for this purpose.
234
+ return node != null && !body.contains(node) && !(trigger?.contains(node) ?? false);
235
+ };
236
+
237
+ const onOutsidePress = (event: Event) => {
238
+ if (!outside(event.target)) {
239
+ return;
240
+ }
241
+ left.current = true;
242
+ close();
243
+ };
244
+ // Capture, so a press is seen even where something below it stops the
245
+ // event — a menu inside the popover, for instance.
246
+ document.addEventListener("pointerdown", onOutsidePress, true);
247
+
248
+ // Tab out is a dismissal, not an escape hatch that leaves a popover open
249
+ // behind the reader: a non-modal overlay whose reader has gone is one they
250
+ // can no longer press Escape at, because Escape is handled where focus is.
251
+ const onFocusMoved = (event: Event) => {
252
+ if (!outside(event.target)) {
253
+ return;
254
+ }
255
+ left.current = true;
256
+ close();
257
+ };
258
+ document.addEventListener("focusin", onFocusMoved, true);
259
+
260
+ // The first thing worth acting on, and the popover itself when it holds
261
+ // nothing focusable, so focus is inside it either way and Escape reaches
262
+ // the handler below.
263
+ (focusable(body)[0] ?? body).focus();
264
+
265
+ return () => {
266
+ document.removeEventListener("pointerdown", onOutsidePress, true);
267
+ document.removeEventListener("focusin", onFocusMoved, true);
268
+ if (left.current) {
269
+ left.current = false;
270
+ return;
271
+ }
272
+ // Only when focus would otherwise be lost to `<body>`, the same
273
+ // condition `menu.js` restores under: a popover closed by a control
274
+ // inside it that moved focus somewhere deliberate must not have that
275
+ // undone.
276
+ const active = document.activeElement;
277
+ if (active == null || active === document.body || body.contains(active)) {
278
+ opener?.focus?.();
279
+ }
280
+ };
281
+ }, [popover.open, triggerRef, close]);
282
+
283
+ if (!popover.open) {
284
+ return null;
285
+ }
286
+
287
+ const passed = withoutComposed(rest, ["onKeyDown", "ref"]);
288
+ // Named by its trigger unless the caller said otherwise. Setting it anyway
289
+ // would override an `aria-label` they passed — `aria-labelledby` wins — and
290
+ // leave the popover announced as its button rather than as itself.
291
+ const named = rest["aria-label"] != null || rest["aria-labelledby"] != null;
292
+
293
+ return (
294
+ <div
295
+ // `passed` first, then this component's semantics; see
296
+ // `internal/merge-props.js` for the three bugs that rule is made of.
297
+ {...passed}
298
+ aria-labelledby={named || !popover.triggered ? undefined : `${popover.base}-trigger`}
299
+ data-align={anchored.align}
300
+ data-side={anchored.side}
301
+ data-state="open"
302
+ id={`${popover.base}-body`}
303
+ onKeyDown={composeHandlers(rest.onKeyDown, (event) => {
304
+ if (event.key !== "Escape") {
305
+ return;
306
+ }
307
+ event.preventDefault();
308
+ // This popover, not the dialog around it. Two overlays nest in the
309
+ // DOM, so without this one Escape closed both.
310
+ event.stopPropagation();
311
+ close();
312
+ })}
313
+ ref={composeRefs(rest.ref, (element) => {
314
+ bodyRef.current = element;
315
+ })}
316
+ // No `aria-modal`. The page behind a popover is still available, and
317
+ // saying otherwise is the one lie a screen reader cannot see through.
318
+ role="dialog"
319
+ // So the popover can hold focus itself when it contains nothing
320
+ // focusable, and so Escape has somewhere to be heard.
321
+ tabIndex={-1}
322
+ >
323
+ {children}
324
+ </div>
325
+ );
326
+ }
package/progress.js ADDED
@@ -0,0 +1,86 @@
1
+ // @flow
2
+ //
3
+ // A progress bar, whose one line is the line everybody gets wrong.
4
+ //
5
+ // This is the smallest component in the package and the one most often written
6
+ // inline, which is exactly why it is worth owning: `<div className="bar" />`
7
+ // with a width in a style attribute is invisible to a screen reader, and the
8
+ // version that adds a role usually adds the rest of it wrong.
9
+ //
10
+ // # The indeterminate state
11
+ //
12
+ // A progress bar that does not know how far along it is **omits
13
+ // `aria-valuenow` entirely**. It does not set it to `0`.
14
+ //
15
+ // The two are opposite statements. `aria-valuenow="0"` says "nothing has
16
+ // happened yet", and a reader who asks again in ten seconds and hears zero
17
+ // again concludes the operation is stuck. Omitting it says "in progress,
18
+ // amount unknown", which is what a spinner means and what is actually true.
19
+ // The whole component is a conditional, and this is the condition.
20
+ //
21
+ // # `aria-valuetext`, for when the percentage is not the answer
22
+ //
23
+ // "3 of 10 files" is what a reader wants to hear; "30" is a number they then
24
+ // have to do arithmetic on. `aria-valuetext` replaces the announced value
25
+ // without touching `aria-valuenow`, so the assistive technology still has the
26
+ // number to draw a gauge with and the reader still hears the sentence.
27
+ //
28
+ // It is a prop rather than something a caller adds afterwards because
29
+ // `aria-valuenow` and `aria-valuetext` have to agree, and a caller spreading
30
+ // one of them onto a component that owns the other gets a control that says
31
+ // two different things.
32
+ //
33
+ // # No `"use client"`
34
+ //
35
+ // It holds no state, listens to nothing and manages no focus, so it renders on
36
+ // a server. That is the reason this is a component and not a hook: everything
37
+ // it knows, it was told.
38
+
39
+ import * as React from "@uniflowed/react";
40
+
41
+ import type { Rest } from "./internal/merge-props.js";
42
+ import { clamp } from "./internal/range.js";
43
+
44
+ /**
45
+ * How far along something is, or that it is under way at all.
46
+ *
47
+ * `value` is `null` for a bar that does not know — the default, because a bar
48
+ * that has not been told anything genuinely does not know, and the safe answer
49
+ * has to be the honest one rather than "nothing has happened".
50
+ *
51
+ * A name is the caller's: `aria-label="Uploading"` or an `aria-labelledby`
52
+ * pointing at a heading. A progress bar with no name is announced as
53
+ * "progressbar" and a reader is left to guess what is progressing, which is
54
+ * why every example in the documentation carries one.
55
+ *
56
+ * Nothing here is drawn and nothing is measured for the caller — unlike
57
+ * `Slider`, whose value may be its own, a progress bar's value arrived as a
58
+ * prop, so the caller already has everything they need to size a bar with and
59
+ * a helpful custom property would only be their own arithmetic handed back.
60
+ */
61
+ export component Progress(
62
+ value?: number | null = null,
63
+ min?: number = 0,
64
+ max?: number = 100,
65
+ valueText?: string,
66
+ children?: React.Node,
67
+ ...rest: Rest
68
+ ) {
69
+ const known = value == null ? null : clamp(value, min, max);
70
+
71
+ return (
72
+ <div
73
+ {...rest}
74
+ aria-valuemax={max}
75
+ aria-valuemin={min}
76
+ // Omitted, not zeroed. `aria-valuenow="0"` tells a reader that nothing
77
+ // has happened; leaving it out tells them the amount is unknown, which
78
+ // is the true one and the one a spinner means.
79
+ aria-valuenow={known ?? undefined}
80
+ aria-valuetext={valueText}
81
+ role="progressbar"
82
+ >
83
+ {children}
84
+ </div>
85
+ );
86
+ }