@jcsoftdev/ui 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +12 -2
  3. package/dist/atoms/avatar/avatar.d.ts +6 -1
  4. package/dist/atoms/avatar/avatar.js +3 -2
  5. package/dist/containers/kanban/kanban.js +2 -0
  6. package/dist/containers/list-detail/list-detail.js +2 -0
  7. package/dist/containers/responsive-list/responsive-list.d.ts +1 -1
  8. package/dist/containers/responsive-list/responsive-list.js +127 -116
  9. package/dist/forms/number-stepper/index.d.ts +1 -1
  10. package/dist/forms/number-stepper/number-stepper.d.ts +7 -0
  11. package/dist/forms/number-stepper/number-stepper.js +37 -6
  12. package/dist/i18n/strings.d.ts +12 -0
  13. package/dist/i18n/strings.js +6 -0
  14. package/dist/overlays/dialog/dialog.d.ts +1 -0
  15. package/dist/overlays/dialog/dialog.js +1 -1
  16. package/dist/overlays/toaster/toast-store.d.ts +2 -0
  17. package/dist/overlays/toaster/toast-store.js +6 -1
  18. package/dist/overlays/toaster/toaster.js +13 -0
  19. package/dist/shell/bottom-nav/bottom-nav.d.ts +5 -1
  20. package/dist/shell/bottom-nav/bottom-nav.js +52 -9
  21. package/dist/states/skeleton/skeleton.d.ts +16 -1
  22. package/dist/states/skeleton/skeleton.js +12 -4
  23. package/dist/utils/focus-chain.d.ts +11 -0
  24. package/dist/utils/focus-chain.js +39 -0
  25. package/dist/utils/focus-rescue.d.ts +13 -0
  26. package/dist/utils/focus-rescue.js +48 -0
  27. package/package.json +2 -2
  28. package/src/atoms/avatar/avatar.tsx +8 -2
  29. package/src/containers/kanban/kanban.tsx +2 -0
  30. package/src/containers/list-detail/list-detail.tsx +2 -0
  31. package/src/containers/responsive-list/responsive-list.tsx +8 -2
  32. package/src/forms/number-stepper/index.ts +1 -0
  33. package/src/forms/number-stepper/number-stepper.tsx +51 -6
  34. package/src/i18n/strings.ts +12 -0
  35. package/src/overlays/dialog/dialog.tsx +2 -1
  36. package/src/overlays/toaster/toast-store.ts +8 -0
  37. package/src/overlays/toaster/toaster.tsx +14 -0
  38. package/src/shell/bottom-nav/bottom-nav.tsx +78 -8
  39. package/src/states/skeleton/skeleton.tsx +32 -4
  40. package/src/utils/focus-chain.ts +53 -0
  41. package/src/utils/focus-rescue.ts +68 -0
@@ -20,6 +20,8 @@ export interface UiStrings {
20
20
  copy: string;
21
21
  copied: string;
22
22
  more: string;
23
+ /** Accessible total on the bottom bar "More" button; `{count}` is replaced. */
24
+ morePending: string;
23
25
  remove: string;
24
26
  noResults: string;
25
27
  clear: string;
@@ -42,6 +44,10 @@ export interface UiStrings {
42
44
  steps: string;
43
45
  /** Default accessible name of an `Aside`. */
44
46
  aside: string;
47
+ /** Verb of the `NumberStepper` plus button; the field label follows it. */
48
+ increase: string;
49
+ /** Verb of the `NumberStepper` minus button; the field label follows it. */
50
+ decrease: string;
45
51
  /** Back action of a single-pane `ListDetail`. */
46
52
  backToList: string;
47
53
  /** Screen-reader state of a `DueChip` past its date. */
@@ -155,6 +161,7 @@ export const uiStrings = {
155
161
  copy: "Copy",
156
162
  copied: "Copied",
157
163
  more: "More",
164
+ morePending: "{count} pending",
158
165
  remove: "Remove",
159
166
  noResults: "No results",
160
167
  clear: "Clear",
@@ -174,6 +181,8 @@ export const uiStrings = {
174
181
  stepOf: "Step {current} of {total}: {label}",
175
182
  steps: "Steps",
176
183
  aside: "Related information",
184
+ increase: "Increase",
185
+ decrease: "Decrease",
177
186
  backToList: "Back to list",
178
187
  overdue: "Overdue",
179
188
  dueSoon: "Due soon",
@@ -242,6 +251,7 @@ export const uiStrings = {
242
251
  copy: "Copiar",
243
252
  copied: "Copiado",
244
253
  more: "Más",
254
+ morePending: "{count} pendientes",
245
255
  remove: "Quitar",
246
256
  noResults: "Sin resultados",
247
257
  clear: "Limpiar",
@@ -261,6 +271,8 @@ export const uiStrings = {
261
271
  stepOf: "Paso {current} de {total}: {label}",
262
272
  steps: "Pasos",
263
273
  aside: "Información relacionada",
274
+ increase: "Aumentar",
275
+ decrease: "Disminuir",
264
276
  backToList: "Volver a la lista",
265
277
  overdue: "Vencido",
266
278
  dueSoon: "Vence pronto",
@@ -129,10 +129,11 @@ export function DialogContent({
129
129
  );
130
130
  }
131
131
 
132
+ /** Title above description at every width; pass `flex-row items-center` in `className` for a side-by-side layout. */
132
133
  export function DialogHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
133
134
  return (
134
135
  <div
135
- className={cn("flex items-center gap-2.5 border-b-divider py-3.5 pr-10 pl-4.5", className)}
136
+ className={cn("flex flex-col gap-1 border-b-divider py-3.5 pr-10 pl-4.5", className)}
136
137
  {...props}
137
138
  />
138
139
  );
@@ -1,4 +1,5 @@
1
1
  import type { ReactNode } from "react";
2
+ import { focusChain } from "../../utils/focus-chain.js";
2
3
 
3
4
  /** `error` is the danger toast (kept under its original name); `info` and `warning` are neutral-status additions. */
4
5
  export type ToastTone = "default" | "success" | "error" | "info" | "warning";
@@ -26,6 +27,8 @@ export interface ToastRecord extends Omit<ToastOptions, "id"> {
26
27
  state: "open" | "closed";
27
28
  /** Bumped on every update so timers restart. */
28
29
  revision: number;
30
+ /** Where focus was, nearest first, when the toast was published; focus returns there once the toast leaves. */
31
+ origin: readonly HTMLElement[];
29
32
  }
30
33
 
31
34
  const EMPTY: readonly ToastRecord[] = [];
@@ -53,6 +56,10 @@ export function getServerSnapshot(): readonly ToastRecord[] {
53
56
  return EMPTY;
54
57
  }
55
58
 
59
+ function currentFocusChain(): readonly HTMLElement[] {
60
+ return typeof document === "undefined" ? [] : focusChain(document.activeElement);
61
+ }
62
+
56
63
  /** Adds a toast, or updates and reopens the one sharing `options.id`. Returns its id. */
57
64
  export function publish(
58
65
  message: ReactNode,
@@ -68,6 +75,7 @@ export function publish(
68
75
  tone,
69
76
  state: "open",
70
77
  revision: (existing?.revision ?? 0) + 1,
78
+ origin: existing?.origin ?? currentFocusChain(),
71
79
  };
72
80
  commit(existing ? toasts.map((t) => (t.id === id ? record : t)) : [...toasts, record]);
73
81
  return id;
@@ -5,6 +5,7 @@ import {
5
5
  type KeyboardEvent,
6
6
  type PointerEvent,
7
7
  useEffect,
8
+ useLayoutEffect,
8
9
  useRef,
9
10
  useState,
10
11
  useSyncExternalStore,
@@ -14,6 +15,7 @@ import { useUiStrings } from "../../i18n/ui-strings-provider.js";
14
15
  import { Portal } from "../../primitives/portal.js";
15
16
  import type { ClassNames } from "../../utils/class-names.js";
16
17
  import { cn } from "../../utils/cn.js";
18
+ import { restoreFocusFromChain } from "../../utils/focus-chain.js";
17
19
  import { usePrefersReducedMotion } from "../../utils/reduced-motion.js";
18
20
  import {
19
21
  dismiss,
@@ -254,11 +256,22 @@ function ToastItem({ record, duration, reducedMotion, classNames }: ToastItemPro
254
256
  const [entered, setEntered] = useState(false);
255
257
  const [dragX, setDragX] = useState(0);
256
258
  const drag = useRef<{ x: number; pointerId: number } | null>(null);
259
+ const rootRef = useRef<HTMLDivElement>(null);
257
260
  const hidden = useDocumentHidden();
258
261
  const effectiveDuration = record.duration ?? duration;
259
262
 
260
263
  useDismissTimer(record, effectiveDuration, hovered || focused || hidden);
261
264
 
265
+ const originRef = useRef(record.origin);
266
+ originRef.current = record.origin;
267
+ useLayoutEffect(
268
+ () => () => {
269
+ const current = document.activeElement;
270
+ if (current && rootRef.current?.contains(current)) restoreFocusFromChain(originRef.current);
271
+ },
272
+ [],
273
+ );
274
+
262
275
  useEffect(() => {
263
276
  const frame = requestAnimationFrame(() => setEntered(true));
264
277
  return () => cancelAnimationFrame(frame);
@@ -305,6 +318,7 @@ function ToastItem({ record, duration, reducedMotion, classNames }: ToastItemPro
305
318
  return (
306
319
  // biome-ignore lint/a11y/noStaticElementInteractions: role is status/alert; handlers only pause the timer, swipe and Escape.
307
320
  <div
321
+ ref={rootRef}
308
322
  role={isError ? "alert" : "status"}
309
323
  aria-live={isError ? "assertive" : "polite"}
310
324
  aria-atomic="true"
@@ -36,6 +36,10 @@ export interface BottomNavProps {
36
36
  maxSlots?: number;
37
37
  /** Text of the "More" button and the drawer title. Defaults to the localized "More". */
38
38
  moreLabel?: string;
39
+ /** Accessible text of the total on "More"; defaults to the localized "{count} pending". */
40
+ moreBadgeLabel?: (count: number) => string;
41
+ /** `count` (default) shows numeric badges as a count chip on the phone bar; `dot` keeps the small dot. */
42
+ badgeStyle?: "count" | "dot";
39
43
  /** Pinned at the bottom of the "More" drawer, e.g. the account or a sign-out button. */
40
44
  moreFooter?: ReactNode;
41
45
  /** Link renderer; defaults to a plain anchor. */
@@ -45,6 +49,45 @@ export interface BottomNavProps {
45
49
  classNames?: ClassNames<BottomNavPart>;
46
50
  }
47
51
 
52
+ const BADGE_CAP = 99;
53
+
54
+ function numericBadge(badge: ReactNode): number | undefined {
55
+ if (typeof badge === "number") return Number.isFinite(badge) ? badge : undefined;
56
+ if (typeof badge === "string" && /^\s*\d+\s*$/.test(badge)) return Number(badge);
57
+ return undefined;
58
+ }
59
+
60
+ function formatCount(count: number): string {
61
+ return count > BADGE_CAP ? `${BADGE_CAP}+` : String(count);
62
+ }
63
+
64
+ const dotClasses = "absolute -top-0.5 -right-1 size-2 rounded-pill";
65
+
66
+ const chipClasses =
67
+ "absolute -top-1.5 -right-2.5 inline-flex h-4 min-w-4 items-center justify-center rounded-pill px-1 font-bold text-count text-surface leading-none";
68
+
69
+ function BadgeMark({
70
+ count,
71
+ danger,
72
+ asDot,
73
+ className,
74
+ }: {
75
+ count: number | undefined;
76
+ danger: boolean;
77
+ asDot: boolean;
78
+ className?: string;
79
+ }) {
80
+ const tone = danger ? "bg-danger" : "bg-warning";
81
+ if (count === undefined || asDot) {
82
+ return <span aria-hidden="true" className={cn(dotClasses, tone, className)} />;
83
+ }
84
+ return (
85
+ <span aria-hidden="true" className={cn(chipClasses, tone, className)}>
86
+ {formatCount(count)}
87
+ </span>
88
+ );
89
+ }
90
+
48
91
  const defaultRenderLink: BottomNavRenderLink = ({ children, ...props }) => (
49
92
  <a {...props}>{children}</a>
50
93
  );
@@ -63,6 +106,8 @@ export function BottomNav({
63
106
  ariaLabel,
64
107
  maxSlots = BOTTOM_NAV_MAX_SLOTS,
65
108
  moreLabel,
109
+ moreBadgeLabel,
110
+ badgeStyle = "count",
66
111
  moreFooter,
67
112
  renderLink = defaultRenderLink,
68
113
  className,
@@ -73,6 +118,20 @@ export function BottomNav({
73
118
  const { visible, overflow } = splitBottomNavItems(items, maxSlots);
74
119
  const more = moreLabel ?? strings.more;
75
120
  const moreActive = overflow.some((item) => item.active);
121
+ const badged = overflow.filter((item) => item.badge !== undefined);
122
+ const overflowCounts = badged.map((item) => numericBadge(item.badge));
123
+ const overflowTotal = overflowCounts.reduce<number | undefined>(
124
+ (sum, count) => (count === undefined ? sum : (sum ?? 0) + count),
125
+ undefined,
126
+ );
127
+ const overflowDanger = badged.some((item) => item.badgeTone === "danger");
128
+ const overflowBadgeText =
129
+ overflowTotal === undefined
130
+ ? undefined
131
+ : (
132
+ moreBadgeLabel ??
133
+ ((count: number) => strings.morePending.replace("{count}", String(count)))
134
+ )(overflowTotal);
76
135
 
77
136
  return (
78
137
  <>
@@ -102,13 +161,11 @@ export function BottomNav({
102
161
  {item.icon}
103
162
  {item.badge !== undefined ? (
104
163
  <>
105
- <span
106
- aria-hidden="true"
107
- className={cn(
108
- "absolute -top-0.5 -right-1 size-2 rounded-pill",
109
- item.badgeTone === "danger" ? "bg-danger" : "bg-warning",
110
- classNames?.badge,
111
- )}
164
+ <BadgeMark
165
+ count={numericBadge(item.badge)}
166
+ danger={item.badgeTone === "danger"}
167
+ asDot={badgeStyle === "dot"}
168
+ className={classNames?.badge}
112
169
  />
113
170
  <span className="sr-only">{item.badgeLabel ?? item.badge}</span>
114
171
  </>
@@ -130,8 +187,21 @@ export function BottomNav({
130
187
  onClick={() => setMoreOpen(true)}
131
188
  className={cn(slotClasses, classNames?.moreButton)}
132
189
  >
133
- <Menu aria-hidden="true" />
190
+ <span className="relative">
191
+ <Menu aria-hidden="true" />
192
+ {badged.length > 0 ? (
193
+ <BadgeMark
194
+ count={overflowTotal}
195
+ danger={overflowDanger}
196
+ asDot={badgeStyle === "dot"}
197
+ className={classNames?.badge}
198
+ />
199
+ ) : null}
200
+ </span>
134
201
  <span>{more}</span>
202
+ {badged.length > 0 && overflowBadgeText ? (
203
+ <span className="sr-only">{overflowBadgeText}</span>
204
+ ) : null}
135
205
  </button>
136
206
  </li>
137
207
  ) : null}
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import type { ReactNode } from "react";
3
+ import { createContext, type ReactNode, useContext } from "react";
4
4
  import { useUiStrings } from "../../i18n/index.js";
5
5
  import { cn } from "../../utils/cn.js";
6
6
 
@@ -8,6 +8,25 @@ export type SkeletonVariant = "lines" | "table" | "card" | "list" | "kpis" | "ke
8
8
 
9
9
  const PLACEHOLDER_IDS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"] as const;
10
10
 
11
+ const SkeletonGroupContext = createContext(false);
12
+
13
+ export interface SkeletonGroupProps {
14
+ /** Text announced once for the whole region. Defaults to the localized "Loading". */
15
+ label?: string;
16
+ className?: string;
17
+ children: ReactNode;
18
+ }
19
+
20
+ /** One status announcement for every `Skeleton` inside; they render silent. */
21
+ export function SkeletonGroup({ label, className, children }: SkeletonGroupProps) {
22
+ const strings = useUiStrings();
23
+ return (
24
+ <div role="status" aria-busy="true" aria-label={label ?? strings.loading} className={className}>
25
+ <SkeletonGroupContext.Provider value={true}>{children}</SkeletonGroupContext.Provider>
26
+ </div>
27
+ );
28
+ }
29
+
11
30
  export interface SkeletonProps {
12
31
  variant?: SkeletonVariant;
13
32
  /** Number of lines for the `lines` variant. */
@@ -18,6 +37,12 @@ export interface SkeletonProps {
18
37
  count?: number;
19
38
  /** Text announced to screen readers while loading. */
20
39
  label?: string;
40
+ /**
41
+ * Whether this skeleton is its own status region. Defaults to `true`, except inside a
42
+ * `SkeletonGroup`, which announces once. Set `false` on repeated skeletons so a screen reader
43
+ * does not say "Loading" for each; wrap them in a `SkeletonGroup` or a status of your own.
44
+ */
45
+ announce?: boolean;
21
46
  /**
22
47
  * Classes on the root. The `bar` variant is one block sized by them (`h-8 w-32`), 12px tall and
23
48
  * full width otherwise.
@@ -42,14 +67,17 @@ export function Skeleton({
42
67
  rows = 4,
43
68
  count = 4,
44
69
  label,
70
+ announce,
45
71
  className,
46
72
  }: SkeletonProps) {
47
73
  const strings = useUiStrings();
74
+ const grouped = useContext(SkeletonGroupContext);
75
+ const silent = !(announce ?? !grouped);
48
76
  return (
49
77
  <div
50
- role="status"
51
- aria-busy="true"
52
- aria-label={label ?? strings.loading}
78
+ {...(silent
79
+ ? { "aria-hidden": true }
80
+ : { role: "status", "aria-busy": true, "aria-label": label ?? strings.loading })}
53
81
  className={cn(
54
82
  "animate-pulse",
55
83
  variant === "bar" && "block h-3 w-full rounded-xs bg-surface-2",
@@ -0,0 +1,53 @@
1
+ const FOCUSABLE =
2
+ 'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
3
+
4
+ const CONTAINER_TAGS = new Set(["UL", "OL", "TBODY", "TABLE", "MAIN", "SECTION", "ARTICLE"]);
5
+
6
+ export function isVisible(element: Element): boolean {
7
+ return element.getClientRects().length > 0;
8
+ }
9
+
10
+ export function focusLosing(): boolean {
11
+ const active = document.activeElement;
12
+ return active === null || active === document.body || active === document.documentElement;
13
+ }
14
+
15
+ /** Focuses the element, or a control inside it; returns whether focus moved there. */
16
+ export function focusWithin(element: HTMLElement): boolean {
17
+ const target = element.hasAttribute("tabindex")
18
+ ? element
19
+ : (element.querySelector<HTMLElement>(FOCUSABLE) ?? element);
20
+ if (!target.hasAttribute("tabindex") && !target.matches(FOCUSABLE)) {
21
+ target.setAttribute("tabindex", "-1");
22
+ }
23
+ target.focus({ preventScroll: false });
24
+ return document.activeElement === target;
25
+ }
26
+
27
+ /** The element and its ancestors up to the body, nearest first. */
28
+ export function focusChain(element: Element | null): HTMLElement[] {
29
+ const chain: HTMLElement[] = [];
30
+ for (let node = element; node && node !== document.body; node = node.parentElement) {
31
+ if (node instanceof HTMLElement) chain.push(node);
32
+ }
33
+ return chain;
34
+ }
35
+
36
+ /**
37
+ * Focuses the first element of a chain captured with `focusChain` that still lives in the
38
+ * document: the element itself, otherwise the nearest surviving interactive or list-like ancestor.
39
+ */
40
+ export function restoreFocusFromChain(chain: readonly HTMLElement[]): boolean {
41
+ for (const [index, element] of chain.entries()) {
42
+ if (!element.isConnected || !isVisible(element)) continue;
43
+ const usable =
44
+ index === 0 ||
45
+ element.hasAttribute("tabindex") ||
46
+ element.matches(FOCUSABLE) ||
47
+ CONTAINER_TAGS.has(element.tagName) ||
48
+ element.getAttribute("role") === "listbox" ||
49
+ element.getAttribute("role") === "list";
50
+ if (usable && focusWithin(element)) return true;
51
+ }
52
+ return false;
53
+ }
@@ -0,0 +1,68 @@
1
+ import { type RefObject, useEffect } from "react";
2
+ import { focusLosing, focusWithin, isVisible } from "./focus-chain.js";
3
+
4
+ export interface FocusRescueOptions {
5
+ /** Selector of the items inside the root. */
6
+ item: string;
7
+ /** Selector of the nearest ancestor that groups sibling items; the next item is looked up inside it. */
8
+ group: string;
9
+ }
10
+
11
+ /**
12
+ * When the focused item leaves the DOM (approved, started, moved away) the browser drops focus on
13
+ * the body. This hands it to the item that took its place, the last one when it was the tail, or
14
+ * the group when nothing is left. Focus that moved on purpose is never touched.
15
+ */
16
+ export function useFocusRescue(
17
+ rootRef: RefObject<HTMLElement | null>,
18
+ { item, group }: FocusRescueOptions,
19
+ ) {
20
+ useEffect(() => {
21
+ const root = rootRef.current;
22
+ if (!root) return;
23
+ let tracked: { element: HTMLElement; group: HTMLElement; index: number } | null = null;
24
+
25
+ const itemsOf = (scope: HTMLElement) =>
26
+ Array.from(scope.querySelectorAll<HTMLElement>(item)).filter(
27
+ (candidate) => candidate.closest(group) === scope && isVisible(candidate),
28
+ );
29
+
30
+ const track = (element: HTMLElement | null) => {
31
+ const found = element?.closest<HTMLElement>(item);
32
+ const scope = found?.closest<HTMLElement>(group);
33
+ if (!found || !scope) return;
34
+ tracked = { element: found, group: scope, index: itemsOf(scope).indexOf(found) };
35
+ };
36
+
37
+ const onFocusIn = (event: FocusEvent) =>
38
+ track(event.target instanceof HTMLElement ? event.target : null);
39
+
40
+ const rescue = () => {
41
+ if (!tracked) return;
42
+ if (tracked.element.isConnected) {
43
+ track(tracked.element);
44
+ return;
45
+ }
46
+ const lost = tracked;
47
+ if (!focusLosing()) {
48
+ tracked = null;
49
+ return;
50
+ }
51
+ tracked = null;
52
+ const scope = lost.group.isConnected ? lost.group : null;
53
+ if (!scope) return;
54
+ const siblings = itemsOf(scope);
55
+ const next = siblings[Math.min(Math.max(lost.index, 0), siblings.length - 1)];
56
+ if (next) focusWithin(next);
57
+ else focusWithin(scope);
58
+ };
59
+
60
+ root.addEventListener("focusin", onFocusIn);
61
+ const observer = new MutationObserver(rescue);
62
+ observer.observe(root, { childList: true, subtree: true });
63
+ return () => {
64
+ root.removeEventListener("focusin", onFocusIn);
65
+ observer.disconnect();
66
+ };
67
+ }, [rootRef, item, group]);
68
+ }