@versini/ui-togglegroup 9.2.6 → 9.2.7

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- @versini/ui-togglegroup v9.2.6
2
+ @versini/ui-togglegroup v9.2.7
3
3
  © 2026 gizmette.com
4
4
  */
5
5
 
@@ -7,44 +7,22 @@ import { jsx, jsxs } from "react/jsx-runtime";
7
7
  import { useUncontrolled } from "@versini/ui-hooks/use-uncontrolled";
8
8
  import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
9
9
  import clsx from "clsx";
10
-
11
-
12
-
13
10
  const TOGGLEGROUP_CLASSNAME = "av-togglegroup";
14
11
  const TOGGLEGROUP_ITEM_WRAPPER_CLASSNAME = "av-togglegroup-item-wrapper";
15
12
  const TOGGLEGROUP_ITEM_CLASSNAME = "av-togglegroup-item";
16
-
17
-
18
-
19
-
20
-
21
-
22
- /* v8 ignore start - default context values are fallbacks, never used directly */ const ToggleGroupContext = createContext({
13
+ const ToggleGroupContext = createContext({
23
14
  size: "medium",
24
15
  flat: false,
25
16
  value: "",
26
17
  toggleValue: ()=>{},
27
18
  disabled: false,
28
- tabbableValue: undefined,
19
+ tabbableValue: void 0,
29
20
  onItemFocus: ()=>{},
30
21
  registerItem: ()=>{},
31
22
  unregisterItem: ()=>{}
32
- }); /* v8 ignore stop */
33
-
34
-
35
-
36
- /**
37
- * `useLayoutEffect` in the browser, `useEffect` on the server — avoids React's
38
- * "useLayoutEffect does nothing on the server" warning during SSR while keeping
39
- * the synchronous, pre-paint timing in the browser.
40
- */ /* v8 ignore start - useEffect fallback only runs during SSR (window undefined) */ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect; /* v8 ignore stop */
41
-
42
-
43
-
44
- /**
45
- * The group is laid out horizontally but does not constrain navigation to one
46
- * axis, so both arrow pairs traverse it. PageUp/PageDown mirror Home/End.
47
- */ const MAP_KEY_TO_FOCUS_INTENT = {
23
+ });
24
+ const useIsomorphicLayoutEffect = "u" > typeof window ? useLayoutEffect : useEffect;
25
+ const MAP_KEY_TO_FOCUS_INTENT = {
48
26
  ArrowLeft: "prev",
49
27
  ArrowUp: "prev",
50
28
  ArrowRight: "next",
@@ -60,172 +38,77 @@ const getTargetIndex = (intent, currentIndex, count)=>{
60
38
  return 0;
61
39
  case "last":
62
40
  return count - 1;
63
- /**
64
- * Navigation wraps. With no item focused yet, stepping backward enters at the
65
- * end and stepping forward enters at the start.
66
- */ case "prev":
41
+ case "prev":
67
42
  return currentIndex < 0 ? count - 1 : (currentIndex - 1 + count) % count;
68
43
  default:
69
44
  return currentIndex < 0 ? 0 : (currentIndex + 1) % count;
70
45
  }
71
46
  };
72
- /**
73
- * Returns an onKeyDown handler for the group implementing roving focus: arrow
74
- * keys on either axis with wrap and disabled-skip, plus
75
- * Home/End/PageUp/PageDown. Focus moves only — activation stays with the native
76
- * button (Enter/Space fire a click), so arrowing across the group never changes
77
- * the selection.
78
- */ const useToggleGroupKeyboard = ({ getItems })=>{
79
- return useCallback((event)=>{
80
- /**
81
- * Shift+Tab leaves the group; every other modifier combination is left to
82
- * the browser so shortcuts are not swallowed.
83
- */ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) {
84
- return;
85
- }
47
+ const useToggleGroupKeyboard = ({ getItems })=>useCallback((event)=>{
48
+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
86
49
  const intent = MAP_KEY_TO_FOCUS_INTENT[event.key];
87
- if (intent === undefined) {
88
- return;
89
- }
90
- // Disabled buttons are not focusable, so they are never candidates.
50
+ if (void 0 === intent) return;
91
51
  const items = getItems().filter((item)=>!item.disabled);
92
- if (items.length === 0) {
93
- return;
94
- }
52
+ if (0 === items.length) return;
95
53
  event.preventDefault();
96
54
  const currentIndex = items.findIndex((item)=>item.element === document.activeElement);
97
55
  items[getTargetIndex(intent, currentIndex, items.length)].element.focus();
98
56
  }, [
99
57
  getItems
100
58
  ]);
101
- };
102
-
103
-
104
-
105
-
106
- const getToggleGroupItemFocusClasses = ()=>{
107
- return clsx(/**
108
- * outline-hidden, not outline-none: the indicator here is a ring, which
109
- * paints through box-shadow and is dropped in forced-colors mode.
110
- * outline-hidden additionally emits a transparent outline under
111
- * forced-colors, which the OS then paints, so keyboard focus survives.
112
- */ "outline-hidden", "focus-visible:ring-2", "focus-visible:ring-inset", "focus-visible:ring-focus-dark");
113
- };
114
- const getToggleGroupItemActiveClasses = ({ flat })=>{
115
- return clsx("data-[state=on]:bg-surface-lightest data-[state=on]:text-copy-dark", "dark:data-[state=on]:bg-surface-dark dark:data-[state=on]:text-copy-light", !flat && "av-bg-split-overlay");
116
- };
117
- const getToggleGroupItemSizeClasses = ({ size })=>{
118
- return clsx({
119
- "h-full px-1 sm:px-2": size === "small",
120
- "h-full px-3": size === "medium",
121
- "h-full px-4": size === "large"
59
+ const getToggleGroupItemFocusClasses = ()=>clsx("outline-hidden", "focus-visible:ring-2", "focus-visible:ring-inset", "focus-visible:ring-focus-dark");
60
+ const getToggleGroupItemActiveClasses = ({ flat })=>clsx("data-[state=on]:bg-surface-lightest data-[state=on]:text-copy-dark", "dark:data-[state=on]:bg-surface-dark dark:data-[state=on]:text-copy-light", !flat && "av-bg-split-overlay");
61
+ const getToggleGroupItemSizeClasses = ({ size })=>clsx({
62
+ "h-full px-1 sm:px-2": "small" === size,
63
+ "h-full px-3": "medium" === size,
64
+ "h-full px-4": "large" === size
122
65
  });
123
- };
124
- const getToggleGroupSizeClasses = ({ size })=>{
125
- return clsx({
126
- "h-6": size === "small",
127
- "h-8": size === "medium",
128
- "h-12": size === "large"
66
+ const getToggleGroupSizeClasses = ({ size })=>clsx({
67
+ "h-6": "small" === size,
68
+ "h-8": "medium" === size,
69
+ "h-12": "large" === size
129
70
  });
130
- };
131
- const getToggleGroupItemWrapperClasses = ()=>{
132
- return clsx(TOGGLEGROUP_ITEM_WRAPPER_CLASSNAME, "relative", "[&>button]:rounded-none", "first:[&>button]:rounded-l-md", "last:[&>button]:rounded-r-md", "border-r border-border-medium last:border-r-0");
133
- };
134
- const getToggleGroupItemClasses = ({ size, flat })=>{
135
- return {
71
+ const getToggleGroupItemWrapperClasses = ()=>clsx(TOGGLEGROUP_ITEM_WRAPPER_CLASSNAME, "relative", "[&>button]:rounded-none", "first:[&>button]:rounded-l-md", "last:[&>button]:rounded-r-md", "border-r border-border-medium last:border-r-0");
72
+ const getToggleGroupItemClasses = ({ size, flat })=>({
136
73
  wrapperClass: getToggleGroupItemWrapperClasses(),
137
74
  itemClass: clsx(TOGGLEGROUP_ITEM_CLASSNAME, "group", "text-sm cursor-pointer", "flex items-center justify-center bg-transparent", "transition duration-200 ease", getToggleGroupItemSizeClasses({
138
75
  size
139
76
  }), getToggleGroupItemFocusClasses(), getToggleGroupItemActiveClasses({
140
77
  flat
141
78
  }))
142
- };
143
- };
144
- const getToggleGroupClasses = ({ className, size })=>{
145
- return clsx(TOGGLEGROUP_CLASSNAME, "inline-flex", "rounded-md", "border border-border-medium", "bg-surface-light text-copy-dark/70", getToggleGroupSizeClasses({
79
+ });
80
+ const getToggleGroupClasses = ({ className, size })=>clsx(TOGGLEGROUP_CLASSNAME, "inline-flex", "rounded-md", "border border-border-medium", "bg-surface-light text-copy-dark/70", getToggleGroupSizeClasses({
146
81
  size
147
82
  }), className);
148
- };
149
-
150
-
151
-
152
-
153
-
154
-
155
-
156
-
157
- /**
158
- * ToggleGroup root. Owns the pressed value (controlled or uncontrolled), the
159
- * item registry, and the shared context.
160
- *
161
- * Invariants:
162
- * 1. Unique values — item `value`s must be unique within a group; duplicates
163
- * are unsupported and dev-warn (no runtime de-dup).
164
- * 2. Exactly one tabbable item — `tabIndex=0` goes to the last focused item if
165
- * it is still registered and enabled, else the pressed item, else the first
166
- * enabled item, else the first; all others get `tabIndex=-1`. The group is
167
- * therefore a single tab stop.
168
- * 3. Deselectable — pressing the already-pressed item clears the selection and
169
- * reports an empty string, rather than being a no-op as in a radio group.
170
- * 4. Focus without activation — arrow keys move focus only; activation is left
171
- * to the native button, so Enter/Space toggle the focused item.
172
- * 5. Group disable — the group's `disabled` prop disables every item; disabled
173
- * buttons are not focusable and are skipped by keyboard navigation.
174
- * 6. DOM-order traversal — item order is resolved on read
175
- * (compareDocumentPosition) so keyboard navigation matches visual order even
176
- * after a keyed reorder, which does not remount the items.
177
- * 7. Focus recovery — if the item holding focus unmounts or becomes disabled,
178
- * focus moves to the item that inherits the tab stop rather than falling to
179
- * <body>.
180
- *
181
- */ const ToggleGroup = ({ children, value, onValueChange, disabled = false, size = "medium", defaultValue, className, flat = false })=>{
83
+ const ToggleGroup = ({ children, value, onValueChange, disabled = false, size = "medium", defaultValue, className, flat = false })=>{
182
84
  const [pressedValue, setPressedValue] = useUncontrolled({
183
85
  value,
184
86
  defaultValue,
185
- /**
186
- * Empty string, not undefined, is the "nothing pressed" state — it is what
187
- * deselecting reports, so the uncontrolled seed has to match.
188
- */ finalValue: "",
87
+ finalValue: "",
189
88
  onChange: onValueChange
190
89
  });
191
90
  const itemsRef = useRef([]);
192
91
  const focusWithinRef = useRef(false);
193
- const [tabStopValue, setTabStopValue] = useState(undefined);
194
- /**
195
- * Bumped whenever an item registers or unregisters; it is a dependency of the
196
- * context memo so consumers re-render and recompute the roving tabIndex from
197
- * the (mutable) registry.
198
- */ const [registrationVersion, setRegistrationVersion] = useState(0);
92
+ const [tabStopValue, setTabStopValue] = useState(void 0);
93
+ const [registrationVersion, setRegistrationVersion] = useState(0);
199
94
  const bumpVersion = useCallback(()=>setRegistrationVersion((version)=>version + 1), []);
200
- /**
201
- * Stable toggle setter (useUncontrolled returns a fresh setter each render in
202
- * uncontrolled mode; refs keep `toggleValue`'s identity stable so the context
203
- * memo is not invalidated on every render).
204
- */ const setPressedRef = useRef(setPressedValue);
95
+ const setPressedRef = useRef(setPressedValue);
205
96
  setPressedRef.current = setPressedValue;
206
97
  const pressedRef = useRef(pressedValue);
207
98
  pressedRef.current = pressedValue;
208
99
  const toggleValue = useCallback((next)=>{
209
- // Invariant 3: pressing the pressed item clears the selection.
210
100
  setPressedRef.current(pressedRef.current === next ? "" : next);
211
- /**
212
- * Claim the tab stop here rather than relying on focus alone: Safari and
213
- * Firefox on macOS do not focus a button on click, and a controlled parent
214
- * can change the value with no focus event at all.
215
- */ setTabStopValue(next);
101
+ setTabStopValue(next);
216
102
  }, []);
217
103
  const getItems = useCallback(()=>itemsRef.current, []);
218
104
  const registerItem = useCallback((registration)=>{
219
105
  const existingIndex = itemsRef.current.findIndex((item)=>item.element === registration.element);
220
- /* v8 ignore start - re-registration of the same element on re-render */ if (existingIndex >= 0) {
106
+ if (existingIndex >= 0) {
221
107
  itemsRef.current[existingIndex] = registration;
222
108
  bumpVersion();
223
109
  return;
224
110
  }
225
- /* v8 ignore stop */ if (itemsRef.current.some((item)=>item.value === registration.value)) {
226
- console.warn(`[ui-togglegroup] Duplicate ToggleGroupItem value "${registration.value}". Item values must be unique within a ToggleGroup.`);
227
- }
228
- // Order is applied in getItems, so registration order does not matter.
111
+ if (itemsRef.current.some((item)=>item.value === registration.value)) console.warn(`[ui-togglegroup] Duplicate ToggleGroupItem value "${registration.value}". Item values must be unique within a ToggleGroup.`);
229
112
  itemsRef.current.push(registration);
230
113
  bumpVersion();
231
114
  }, [
@@ -247,21 +130,9 @@ const getToggleGroupClasses = ({ className, size })=>{
247
130
  focusWithinRef.current = true;
248
131
  }, []);
249
132
  const handleRootBlur = useCallback((event)=>{
250
- /**
251
- * Keep the flag when focus is lost to <body> (e.g. the focused item unmounts)
252
- * so recovery can restore it; only clear when focus genuinely moves to an
253
- * element outside this group.
254
- */ if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget)) {
255
- focusWithinRef.current = false;
256
- }
133
+ if (event.relatedTarget && !event.currentTarget.contains(event.relatedTarget)) focusWithinRef.current = false;
257
134
  }, []);
258
- /**
259
- * Invariant 6. Keep the registry in DOM order after every commit. React can
260
- * reorder keyed items without remounting them, so the registration effect
261
- * never re-runs and any order captured at registration time goes stale. This
262
- * has to happen post-commit: during render the DOM still reflects the previous
263
- * order, so comparing document positions there reads the old layout.
264
- */ useIsomorphicLayoutEffect(()=>{
135
+ useIsomorphicLayoutEffect(()=>{
265
136
  const current = itemsRef.current;
266
137
  const sorted = current.slice().sort((a, b)=>a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
267
138
  if (sorted.some((item, index)=>item !== current[index])) {
@@ -269,50 +140,23 @@ const getToggleGroupClasses = ({ className, size })=>{
269
140
  bumpVersion();
270
141
  }
271
142
  });
272
- /**
273
- * Invariant 2. The last focused item keeps the tab stop so returning to the
274
- * group lands where the user left it; before any focus, the pressed item does.
275
- * The fallback therefore means first in visual order, matching traversal.
276
- */ const items = itemsRef.current;
277
- const isTabbable = (candidate)=>candidate !== undefined && items.some((item)=>item.value === candidate && !item.disabled && !disabled);
143
+ const items = itemsRef.current;
144
+ const isTabbable = (candidate)=>void 0 !== candidate && items.some((item)=>item.value === candidate && !item.disabled && !disabled);
278
145
  let tabbableValue;
279
- if (isTabbable(tabStopValue)) {
280
- tabbableValue = tabStopValue;
281
- } else if (isTabbable(pressedValue)) {
282
- tabbableValue = pressedValue;
283
- } else {
284
- tabbableValue = (items.find((item)=>!item.disabled) ?? items[0])?.value;
285
- }
286
- /**
287
- * Invariant 7. When the item holding focus unmounts or becomes disabled the
288
- * browser drops focus to <body>; move it to whichever item now owns the tab
289
- * stop so a keyboard user is not ejected to the top of the document. Gated on
290
- * the previous tab stop having actually gone away, so clicking on inert page
291
- * background never pulls focus back into the group.
292
- */ useIsomorphicLayoutEffect(()=>{
293
- if (tabStopValue === undefined || !focusWithinRef.current) {
294
- return;
295
- }
146
+ tabbableValue = isTabbable(tabStopValue) ? tabStopValue : isTabbable(pressedValue) ? pressedValue : (items.find((item)=>!item.disabled) ?? items[0])?.value;
147
+ useIsomorphicLayoutEffect(()=>{
148
+ if (void 0 === tabStopValue || !focusWithinRef.current) return;
296
149
  const stillUsable = itemsRef.current.some((item)=>item.value === tabStopValue && !item.disabled);
297
- if (stillUsable) {
298
- return;
299
- }
300
- /**
301
- * Recover from the two ways focus ends up stranded: the browser drops it to
302
- * <body> when the focused element is removed, and it can be left sitting on
303
- * an element that has just been disabled.
304
- */ const active = document.activeElement;
150
+ if (stillUsable) return;
151
+ const active = document.activeElement;
305
152
  const stranded = active === document.body || itemsRef.current.some((item)=>item.element === active && item.disabled);
306
- if (!stranded) {
307
- return;
308
- }
153
+ if (!stranded) return;
309
154
  const recovered = itemsRef.current.find((item)=>item.value === tabbableValue && !item.disabled);
310
155
  if (recovered) {
311
156
  recovered.element.focus();
312
157
  setTabStopValue(recovered.value);
313
158
  }
314
159
  });
315
- // biome-ignore lint/correctness/useExhaustiveDependencies: registrationVersion is an intentional tripwire. The memo reads the mutable item registry (a ref the linter cannot see), so it MUST recompute on every (un)registration; removing this dep reintroduces a stale roving tabIndex.
316
160
  const contextValue = useMemo(()=>({
317
161
  size,
318
162
  flat,
@@ -330,17 +174,14 @@ const getToggleGroupClasses = ({ className, size })=>{
330
174
  toggleValue,
331
175
  disabled,
332
176
  tabbableValue,
333
- /**
334
- * registrationVersion drives recompute of the roving tabIndex from the
335
- * registry when an item (un)registers.
336
- */ registrationVersion,
177
+ registrationVersion,
337
178
  onItemFocus,
338
179
  registerItem,
339
180
  unregisterItem
340
181
  ]);
341
- return /*#__PURE__*/ jsx(ToggleGroupContext.Provider, {
182
+ return jsx(ToggleGroupContext.Provider, {
342
183
  value: contextValue,
343
- children: /*#__PURE__*/ jsx("div", {
184
+ children: jsx("div", {
344
185
  role: "radiogroup",
345
186
  className: getToggleGroupClasses({
346
187
  className,
@@ -354,30 +195,14 @@ const getToggleGroupClasses = ({ className, size })=>{
354
195
  });
355
196
  };
356
197
  ToggleGroup.displayName = "ToggleGroup";
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
198
  const ToggleGroupItem = ({ value, disabled = false, children, className, onClick, onFocus, onPointerDown, ...rest })=>{
368
199
  const { size, flat, value: pressedValue, toggleValue, disabled: groupDisabled, tabbableValue, onItemFocus, registerItem, unregisterItem } = useContext(ToggleGroupContext);
369
200
  const buttonRef = useRef(null);
370
- // Invariant 5: the group's `disabled` disables every item.
371
201
  const isDisabled = groupDisabled || disabled;
372
- /**
373
- * Register in a layout effect (before paint) so the first render already sees
374
- * a populated registry and the roving tabIndex settles without a flicker.
375
- */ useIsomorphicLayoutEffect(()=>{
202
+ useIsomorphicLayoutEffect(()=>{
376
203
  const element = buttonRef.current;
377
- /* v8 ignore start - ref is always set after mount */ if (!element) {
378
- return;
379
- }
380
- /* v8 ignore stop */ registerItem({
204
+ if (!element) return;
205
+ registerItem({
381
206
  element,
382
207
  value,
383
208
  disabled: isDisabled
@@ -397,16 +222,16 @@ const ToggleGroupItem = ({ value, disabled = false, children, className, onClick
397
222
  });
398
223
  const pressed = pressedValue === value;
399
224
  const label = children ?? value;
400
- return /*#__PURE__*/ jsx("div", {
225
+ return jsx("div", {
401
226
  className: wrapperClass,
402
- children: /*#__PURE__*/ jsx("button", {
227
+ children: jsx("button", {
403
228
  ...rest,
404
229
  ref: buttonRef,
405
230
  type: "button",
406
231
  role: "radio",
407
232
  "aria-checked": pressed,
408
233
  "data-state": pressed ? "on" : "off",
409
- "data-disabled": isDisabled ? "" : undefined,
234
+ "data-disabled": isDisabled ? "" : void 0,
410
235
  disabled: isDisabled,
411
236
  tabIndex: tabbableValue === value ? 0 : -1,
412
237
  className: clsx(itemClass, className),
@@ -418,23 +243,19 @@ const ToggleGroupItem = ({ value, disabled = false, children, className, onClick
418
243
  onFocus?.(event);
419
244
  onItemFocus(value);
420
245
  },
421
- /**
422
- * Pointer interaction claims the tab stop even when the browser does not
423
- * focus the button (Safari, Firefox on macOS) or when a consumer handler
424
- * vetoes the click.
425
- */ onPointerDown: (event)=>{
246
+ onPointerDown: (event)=>{
426
247
  onPointerDown?.(event);
427
248
  onItemFocus(value);
428
249
  },
429
- children: /*#__PURE__*/ jsxs("span", {
250
+ children: jsxs("span", {
430
251
  className: "grid",
431
252
  children: [
432
- /*#__PURE__*/ jsx("span", {
253
+ jsx("span", {
433
254
  "aria-hidden": "true",
434
255
  className: "invisible font-semibold [grid-area:1/1]",
435
256
  children: label
436
257
  }),
437
- /*#__PURE__*/ jsx("span", {
258
+ jsx("span", {
438
259
  className: "[grid-area:1/1] group-data-[state=on]:font-semibold",
439
260
  children: label
440
261
  })
@@ -444,9 +265,4 @@ const ToggleGroupItem = ({ value, disabled = false, children, className, onClick
444
265
  });
445
266
  };
446
267
  ToggleGroupItem.displayName = "ToggleGroupItem";
447
-
448
-
449
-
450
-
451
-
452
268
  export { TOGGLEGROUP_CLASSNAME, TOGGLEGROUP_ITEM_CLASSNAME, TOGGLEGROUP_ITEM_WRAPPER_CLASSNAME, ToggleGroup, ToggleGroupItem };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@versini/ui-togglegroup",
3
- "version": "9.2.6",
3
+ "version": "9.2.7",
4
4
  "license": "MIT",
5
5
  "author": "Arno Versini",
6
6
  "publishConfig": {
@@ -19,7 +19,7 @@
19
19
  "README.md"
20
20
  ],
21
21
  "devDependencies": {
22
- "@versini/ui-styles": "9.7.8"
22
+ "@versini/ui-styles": "9.7.9"
23
23
  },
24
24
  "dependencies": {
25
25
  "@versini/ui-hooks": "6.2.3",