@jcsoftdev/ui 0.7.0 → 0.8.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 (51) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +9 -0
  3. package/dist/atoms/elapsed-time/elapsed-time.d.ts +29 -0
  4. package/dist/atoms/elapsed-time/elapsed-time.js +65 -0
  5. package/dist/atoms/elapsed-time/index.d.ts +2 -0
  6. package/dist/atoms/elapsed-time/index.js +9 -0
  7. package/dist/atoms/elapsed-time/model.d.ts +17 -0
  8. package/dist/atoms/elapsed-time/model.js +37 -0
  9. package/dist/atoms/elapsed-time/ticker.d.ts +5 -0
  10. package/dist/atoms/elapsed-time/ticker.js +37 -0
  11. package/dist/atoms/index.d.ts +2 -0
  12. package/dist/atoms/index.js +2 -0
  13. package/dist/atoms/table-glyph/index.d.ts +2 -0
  14. package/dist/atoms/table-glyph/index.js +14 -0
  15. package/dist/atoms/table-glyph/layout.d.ts +38 -0
  16. package/dist/atoms/table-glyph/layout.js +152 -0
  17. package/dist/atoms/table-glyph/table-glyph.d.ts +32 -0
  18. package/dist/atoms/table-glyph/table-glyph.js +131 -0
  19. package/dist/containers/floor-plan/edit-model.d.ts +33 -0
  20. package/dist/containers/floor-plan/edit-model.js +82 -0
  21. package/dist/containers/floor-plan/floor-plan.d.ts +83 -0
  22. package/dist/containers/floor-plan/floor-plan.js +278 -0
  23. package/dist/containers/floor-plan/index.d.ts +3 -0
  24. package/dist/containers/floor-plan/index.js +21 -0
  25. package/dist/containers/floor-plan/model.d.ts +36 -0
  26. package/dist/containers/floor-plan/model.js +52 -0
  27. package/dist/containers/floor-plan/use-floor-plan-edit.d.ts +26 -0
  28. package/dist/containers/floor-plan/use-floor-plan-edit.js +97 -0
  29. package/dist/containers/index.d.ts +1 -0
  30. package/dist/containers/index.js +1 -0
  31. package/dist/i18n/strings.d.ts +48 -0
  32. package/dist/i18n/strings.js +24 -0
  33. package/dist/shell/bottom-nav/bottom-nav.d.ts +5 -1
  34. package/dist/shell/bottom-nav/bottom-nav.js +52 -9
  35. package/package.json +2 -2
  36. package/src/atoms/elapsed-time/elapsed-time.tsx +101 -0
  37. package/src/atoms/elapsed-time/index.ts +6 -0
  38. package/src/atoms/elapsed-time/model.ts +54 -0
  39. package/src/atoms/elapsed-time/ticker.ts +39 -0
  40. package/src/atoms/index.ts +2 -0
  41. package/src/atoms/table-glyph/index.ts +14 -0
  42. package/src/atoms/table-glyph/layout.ts +187 -0
  43. package/src/atoms/table-glyph/table-glyph.tsx +161 -0
  44. package/src/containers/floor-plan/edit-model.ts +115 -0
  45. package/src/containers/floor-plan/floor-plan.tsx +393 -0
  46. package/src/containers/floor-plan/index.ts +20 -0
  47. package/src/containers/floor-plan/model.ts +81 -0
  48. package/src/containers/floor-plan/use-floor-plan-edit.ts +135 -0
  49. package/src/containers/index.ts +1 -0
  50. package/src/i18n/strings.ts +48 -0
  51. package/src/shell/bottom-nav/bottom-nav.tsx +78 -8
@@ -0,0 +1,52 @@
1
+ const DEFAULT_PX_PER_UNIT = 32;
2
+ const CHAIR_BAND = 0.24;
3
+ const MIN_INSIDE_WIDTH = 44;
4
+ const MIN_INSIDE_HEIGHT = 30;
5
+ function labelPlacement(item, pxPerUnit = DEFAULT_PX_PER_UNIT) {
6
+ if (item.shape === "bar") return "below";
7
+ const usable = (units) => units * pxPerUnit * (1 - 2 * CHAIR_BAND);
8
+ const round = item.shape === "round" ? Math.SQRT1_2 : 1;
9
+ const fits = usable(item.width) * round >= MIN_INSIDE_WIDTH && usable(item.height) * round >= MIN_INSIDE_HEIGHT;
10
+ return fits ? "inside" : "below";
11
+ }
12
+ function percentBox(box, width, height) {
13
+ return {
14
+ left: `${box.x / width * 100}%`,
15
+ top: `${box.y / height * 100}%`,
16
+ width: `${box.width / width * 100}%`,
17
+ height: `${box.height / height * 100}%`
18
+ };
19
+ }
20
+ const GROUP_PADDING = 0.2;
21
+ function groupOutlines(items) {
22
+ const groups = /* @__PURE__ */ new Map();
23
+ for (const item of items) {
24
+ if (item.groupId === void 0) continue;
25
+ const list = groups.get(item.groupId) ?? [];
26
+ list.push(item);
27
+ groups.set(item.groupId, list);
28
+ }
29
+ const outlines = [];
30
+ for (const [groupId, members] of groups) {
31
+ if (members.length < 2) continue;
32
+ const left = Math.min(...members.map((m) => m.x));
33
+ const top = Math.min(...members.map((m) => m.y));
34
+ const right = Math.max(...members.map((m) => m.x + m.width));
35
+ const bottom = Math.max(...members.map((m) => m.y + m.height));
36
+ outlines.push({
37
+ groupId,
38
+ x: left - GROUP_PADDING,
39
+ y: top - GROUP_PADDING,
40
+ width: right - left + 2 * GROUP_PADDING,
41
+ height: bottom - top + 2 * GROUP_PADDING
42
+ });
43
+ }
44
+ return outlines;
45
+ }
46
+ export {
47
+ DEFAULT_PX_PER_UNIT,
48
+ GROUP_PADDING,
49
+ groupOutlines,
50
+ labelPlacement,
51
+ percentBox
52
+ };
@@ -0,0 +1,26 @@
1
+ import { type PointerEvent, type RefObject } from "react";
2
+ import { type EditBounds, type ResizeHandle } from "./edit-model.js";
3
+ import type { FloorPlanBox } from "./model.js";
4
+ type DragMode = "move" | ResizeHandle;
5
+ interface Options<I extends FloorPlanBox, L extends FloorPlanBox> {
6
+ enabled: boolean;
7
+ items: readonly I[];
8
+ landmarks: readonly L[];
9
+ bounds: EditBounds;
10
+ canvasRef: RefObject<HTMLElement | null>;
11
+ onChange?: ((items: I[], landmarks: L[]) => void) | undefined;
12
+ onSelect?: ((id: string) => void) | undefined;
13
+ }
14
+ /** Drag, resize, rotate and keyboard edits of floor plan boxes; commits only on release, never mid-drag. */
15
+ export declare function useFloorPlanEdit<I extends FloorPlanBox, L extends FloorPlanBox>({ enabled, items, landmarks, bounds, canvasRef, onChange, onSelect, }: Options<I, L>): {
16
+ view: <T extends FloorPlanBox>(entry: T) => T;
17
+ dragProps: (entry: FloorPlanBox, mode: DragMode) => {
18
+ onPointerDown: (event: PointerEvent<HTMLElement>) => void;
19
+ onPointerMove: (event: PointerEvent<HTMLElement>) => void;
20
+ onPointerUp: (event: PointerEvent<HTMLElement>) => void;
21
+ onPointerCancel: () => void;
22
+ };
23
+ onKeyDown: (entry: FloorPlanBox) => (event: React.KeyboardEvent<HTMLElement>) => void;
24
+ rotate: (entry: FloorPlanBox) => void;
25
+ };
26
+ export {};
@@ -0,0 +1,97 @@
1
+ import { useRef, useState } from "react";
2
+ import {
3
+ editKey,
4
+ moveBox,
5
+ resizeBox,
6
+ sameBox
7
+ } from "./edit-model.js";
8
+ const DRAG_THRESHOLD_PX = 3;
9
+ function capturePointer(element, pointerId) {
10
+ try {
11
+ element.setPointerCapture(pointerId);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+ const pick = ({ x, y, width, height }) => ({ x, y, width, height });
18
+ function useFloorPlanEdit({
19
+ enabled,
20
+ items,
21
+ landmarks,
22
+ bounds,
23
+ canvasRef,
24
+ onChange,
25
+ onSelect
26
+ }) {
27
+ const [draft, setDraft] = useState(null);
28
+ const drag = useRef(null);
29
+ const view = (entry) => draft?.id === entry.id ? { ...entry, ...draft.box } : entry;
30
+ const commit = (id, box) => {
31
+ const current = [...items, ...landmarks].find((entry) => entry.id === id);
32
+ if (!current || sameBox(pick(current), box)) return;
33
+ const apply = (list) => list.map((entry) => entry.id === id ? { ...entry, ...box } : entry);
34
+ onChange?.(apply(items), apply(landmarks));
35
+ };
36
+ const dragProps = (entry, mode) => ({
37
+ onPointerDown: (event) => {
38
+ if (!enabled || event.button !== 0) return;
39
+ const canvas = canvasRef.current;
40
+ if (!canvas) return;
41
+ event.stopPropagation();
42
+ capturePointer(event.currentTarget, event.pointerId);
43
+ drag.current = {
44
+ id: entry.id,
45
+ mode,
46
+ startX: event.clientX,
47
+ startY: event.clientY,
48
+ origin: pick(entry),
49
+ unit: canvas.getBoundingClientRect().width / bounds.width,
50
+ moved: false
51
+ };
52
+ onSelect?.(entry.id);
53
+ },
54
+ onPointerMove: (event) => {
55
+ const current = drag.current;
56
+ if (!current || current.id !== entry.id) return;
57
+ const px = Math.hypot(event.clientX - current.startX, event.clientY - current.startY);
58
+ if (!current.moved && px < DRAG_THRESHOLD_PX) return;
59
+ current.moved = true;
60
+ const dx = (event.clientX - current.startX) / current.unit;
61
+ const dy = (event.clientY - current.startY) / current.unit;
62
+ const box = current.mode === "move" ? moveBox(current.origin, dx, dy, bounds) : resizeBox(current.origin, current.mode, dx, dy, bounds);
63
+ setDraft(
64
+ (previous) => previous && sameBox(previous.box, box) ? previous : { id: entry.id, box }
65
+ );
66
+ },
67
+ onPointerUp: (event) => {
68
+ const current = drag.current;
69
+ if (!current || current.id !== entry.id) return;
70
+ drag.current = null;
71
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
72
+ event.currentTarget.releasePointerCapture(event.pointerId);
73
+ }
74
+ if (current.moved && draft) commit(entry.id, draft.box);
75
+ setDraft(null);
76
+ },
77
+ onPointerCancel: () => {
78
+ drag.current = null;
79
+ setDraft(null);
80
+ }
81
+ });
82
+ const onKeyDown = (entry) => (event) => {
83
+ if (!enabled) return;
84
+ const result = editKey(pick(entry), event, bounds);
85
+ if (!result) return;
86
+ event.preventDefault();
87
+ commit(entry.id, result.box);
88
+ };
89
+ const rotate = (entry) => {
90
+ const result = editKey(pick(entry), { key: "r", altKey: false, shiftKey: false }, bounds);
91
+ if (result) commit(entry.id, result.box);
92
+ };
93
+ return { view, dragProps, onKeyDown, rotate };
94
+ }
95
+ export {
96
+ useFloorPlanEdit
97
+ };
@@ -17,6 +17,7 @@ export * from "./facts/index.js";
17
17
  export * from "./feed/index.js";
18
18
  export * from "./file-tree/index.js";
19
19
  export * from "./filter-bar/index.js";
20
+ export * from "./floor-plan/index.js";
20
21
  export * from "./generic-row/index.js";
21
22
  export * from "./grid/index.js";
22
23
  export * from "./hbars/index.js";
@@ -17,6 +17,7 @@ export * from "./facts/index.js";
17
17
  export * from "./feed/index.js";
18
18
  export * from "./file-tree/index.js";
19
19
  export * from "./filter-bar/index.js";
20
+ export * from "./floor-plan/index.js";
20
21
  export * from "./generic-row/index.js";
21
22
  export * from "./grid/index.js";
22
23
  export * from "./hbars/index.js";
@@ -20,6 +20,30 @@ 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;
25
+ /** Accessible text of an `ElapsedTime` at exactly one minute; `{count}` is replaced. */
26
+ elapsedMinutesOne: string;
27
+ /** Accessible text of an `ElapsedTime`; `{count}` is replaced. */
28
+ elapsedMinutes: string;
29
+ /** Visible text of an `ElapsedTime` with `format="minutes"`; `{count}` is replaced. */
30
+ minutesShort: string;
31
+ /** Accessible text of a countdown `ElapsedTime`; `{time}` is the remaining time. */
32
+ countdownLeft: string;
33
+ /** Accessible text of a countdown `ElapsedTime` past its target; `{time}` is the overrun. */
34
+ countdownOver: string;
35
+ /** Seat count of a floor plan table; `{count}` is replaced. */
36
+ seats: string;
37
+ /** Seat count of a one-seat floor plan table; `{count}` is replaced. */
38
+ seatsOne: string;
39
+ /** Screen-reader state of a floor plan item ringed as late. */
40
+ late: string;
41
+ /** Default accessible name of a `FloorPlan`. */
42
+ floorPlan: string;
43
+ /** Accessible name of the rotate button of an editable `FloorPlan` item. */
44
+ rotate: string;
45
+ /** Keyboard help of an editable `FloorPlan`. */
46
+ floorPlanEditHint: string;
23
47
  remove: string;
24
48
  noResults: string;
25
49
  clear: string;
@@ -157,6 +181,18 @@ export declare const uiStrings: {
157
181
  readonly copy: "Copy";
158
182
  readonly copied: "Copied";
159
183
  readonly more: "More";
184
+ readonly morePending: "{count} pending";
185
+ readonly elapsedMinutesOne: "{count} minute";
186
+ readonly elapsedMinutes: "{count} minutes";
187
+ readonly minutesShort: "{count} min";
188
+ readonly countdownLeft: "{time} left";
189
+ readonly countdownOver: "{time} over";
190
+ readonly seats: "{count} seats";
191
+ readonly seatsOne: "{count} seat";
192
+ readonly late: "Late";
193
+ readonly floorPlan: "Floor plan";
194
+ readonly rotate: "Rotate 90°";
195
+ readonly floorPlanEditHint: "Alt with arrows moves, Alt and Shift with arrows resizes, R rotates.";
160
196
  readonly remove: "Remove";
161
197
  readonly noResults: "No results";
162
198
  readonly clear: "Clear";
@@ -246,6 +282,18 @@ export declare const uiStrings: {
246
282
  readonly copy: "Copiar";
247
283
  readonly copied: "Copiado";
248
284
  readonly more: "Más";
285
+ readonly morePending: "{count} pendientes";
286
+ readonly elapsedMinutesOne: "{count} minuto";
287
+ readonly elapsedMinutes: "{count} minutos";
288
+ readonly minutesShort: "{count} min";
289
+ readonly countdownLeft: "faltan {time}";
290
+ readonly countdownOver: "{time} de retraso";
291
+ readonly seats: "{count} asientos";
292
+ readonly seatsOne: "{count} asiento";
293
+ readonly late: "Con retraso";
294
+ readonly floorPlan: "Plano de sala";
295
+ readonly rotate: "Girar 90°";
296
+ readonly floorPlanEditHint: "Alt con flechas mueve, Alt y Mayús con flechas cambia el tamaño, R gira.";
249
297
  readonly remove: "Quitar";
250
298
  readonly noResults: "Sin resultados";
251
299
  readonly clear: "Limpiar";
@@ -21,6 +21,18 @@ const uiStrings = {
21
21
  copy: "Copy",
22
22
  copied: "Copied",
23
23
  more: "More",
24
+ morePending: "{count} pending",
25
+ elapsedMinutesOne: "{count} minute",
26
+ elapsedMinutes: "{count} minutes",
27
+ minutesShort: "{count} min",
28
+ countdownLeft: "{time} left",
29
+ countdownOver: "{time} over",
30
+ seats: "{count} seats",
31
+ seatsOne: "{count} seat",
32
+ late: "Late",
33
+ floorPlan: "Floor plan",
34
+ rotate: "Rotate 90\xB0",
35
+ floorPlanEditHint: "Alt with arrows moves, Alt and Shift with arrows resizes, R rotates.",
24
36
  remove: "Remove",
25
37
  noResults: "No results",
26
38
  clear: "Clear",
@@ -110,6 +122,18 @@ const uiStrings = {
110
122
  copy: "Copiar",
111
123
  copied: "Copiado",
112
124
  more: "M\xE1s",
125
+ morePending: "{count} pendientes",
126
+ elapsedMinutesOne: "{count} minuto",
127
+ elapsedMinutes: "{count} minutos",
128
+ minutesShort: "{count} min",
129
+ countdownLeft: "faltan {time}",
130
+ countdownOver: "{time} de retraso",
131
+ seats: "{count} asientos",
132
+ seatsOne: "{count} asiento",
133
+ late: "Con retraso",
134
+ floorPlan: "Plano de sala",
135
+ rotate: "Girar 90\xB0",
136
+ floorPlanEditHint: "Alt con flechas mueve, Alt y May\xFAs con flechas cambia el tama\xF1o, R gira.",
113
137
  remove: "Quitar",
114
138
  noResults: "Sin resultados",
115
139
  clear: "Limpiar",
@@ -17,6 +17,10 @@ export interface BottomNavProps {
17
17
  maxSlots?: number;
18
18
  /** Text of the "More" button and the drawer title. Defaults to the localized "More". */
19
19
  moreLabel?: string;
20
+ /** Accessible text of the total on "More"; defaults to the localized "{count} pending". */
21
+ moreBadgeLabel?: (count: number) => string;
22
+ /** `count` (default) shows numeric badges as a count chip on the phone bar; `dot` keeps the small dot. */
23
+ badgeStyle?: "count" | "dot";
20
24
  /** Pinned at the bottom of the "More" drawer, e.g. the account or a sign-out button. */
21
25
  moreFooter?: ReactNode;
22
26
  /** Link renderer; defaults to a plain anchor. */
@@ -31,4 +35,4 @@ export interface BottomNavProps {
31
35
  * inside `AppShell`: it sticks to the bottom of the viewport and hides itself once the shell is
32
36
  * 900 px or wider, where the sidebar takes over. Without an `AppShell` it is always visible.
33
37
  */
34
- export declare function BottomNav({ items, ariaLabel, maxSlots, moreLabel, moreFooter, renderLink, className, classNames, }: BottomNavProps): import("react").JSX.Element;
38
+ export declare function BottomNav({ items, ariaLabel, maxSlots, moreLabel, moreBadgeLabel, badgeStyle, moreFooter, renderLink, className, classNames, }: BottomNavProps): import("react").JSX.Element;
@@ -6,6 +6,29 @@ import { Menu } from "../../icons/index.js";
6
6
  import { Drawer, DrawerContent, DrawerTitle } from "../../overlays/drawer/index.js";
7
7
  import { cn } from "../../utils/cn.js";
8
8
  import { BOTTOM_NAV_MAX_SLOTS, splitBottomNavItems } from "./split.js";
9
+ const BADGE_CAP = 99;
10
+ function numericBadge(badge) {
11
+ if (typeof badge === "number") return Number.isFinite(badge) ? badge : void 0;
12
+ if (typeof badge === "string" && /^\s*\d+\s*$/.test(badge)) return Number(badge);
13
+ return void 0;
14
+ }
15
+ function formatCount(count) {
16
+ return count > BADGE_CAP ? `${BADGE_CAP}+` : String(count);
17
+ }
18
+ const dotClasses = "absolute -top-0.5 -right-1 size-2 rounded-pill";
19
+ const chipClasses = "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";
20
+ function BadgeMark({
21
+ count,
22
+ danger,
23
+ asDot,
24
+ className
25
+ }) {
26
+ const tone = danger ? "bg-danger" : "bg-warning";
27
+ if (count === void 0 || asDot) {
28
+ return /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: cn(dotClasses, tone, className) });
29
+ }
30
+ return /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: cn(chipClasses, tone, className), children: formatCount(count) });
31
+ }
9
32
  const defaultRenderLink = ({ children, ...props }) => /* @__PURE__ */ jsx("a", { ...props, children });
10
33
  const slotClasses = "relative flex min-h-14 w-full flex-col items-center justify-center gap-0.5 px-1 text-ink-2 text-meta focus-visible:focus-ring aria-[current=page]:font-bold aria-[current=page]:text-accent-ink data-[active=true]:font-bold data-[active=true]:text-accent-ink [&_svg]:size-5 [&_svg]:shrink-0";
11
34
  function BottomNav({
@@ -13,6 +36,8 @@ function BottomNav({
13
36
  ariaLabel,
14
37
  maxSlots = BOTTOM_NAV_MAX_SLOTS,
15
38
  moreLabel,
39
+ moreBadgeLabel,
40
+ badgeStyle = "count",
16
41
  moreFooter,
17
42
  renderLink = defaultRenderLink,
18
43
  className,
@@ -23,6 +48,14 @@ function BottomNav({
23
48
  const { visible, overflow } = splitBottomNavItems(items, maxSlots);
24
49
  const more = moreLabel ?? strings.more;
25
50
  const moreActive = overflow.some((item) => item.active);
51
+ const badged = overflow.filter((item) => item.badge !== void 0);
52
+ const overflowCounts = badged.map((item) => numericBadge(item.badge));
53
+ const overflowTotal = overflowCounts.reduce(
54
+ (sum, count) => count === void 0 ? sum : (sum ?? 0) + count,
55
+ void 0
56
+ );
57
+ const overflowDanger = badged.some((item) => item.badgeTone === "danger");
58
+ const overflowBadgeText = overflowTotal === void 0 ? void 0 : (moreBadgeLabel ?? ((count) => strings.morePending.replace("{count}", String(count))))(overflowTotal);
26
59
  return /* @__PURE__ */ jsxs(Fragment, { children: [
27
60
  /* @__PURE__ */ jsx(
28
61
  "nav",
@@ -50,14 +83,12 @@ function BottomNav({
50
83
  item.icon,
51
84
  item.badge !== void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
52
85
  /* @__PURE__ */ jsx(
53
- "span",
86
+ BadgeMark,
54
87
  {
55
- "aria-hidden": "true",
56
- className: cn(
57
- "absolute -top-0.5 -right-1 size-2 rounded-pill",
58
- item.badgeTone === "danger" ? "bg-danger" : "bg-warning",
59
- classNames?.badge
60
- )
88
+ count: numericBadge(item.badge),
89
+ danger: item.badgeTone === "danger",
90
+ asDot: badgeStyle === "dot",
91
+ className: classNames?.badge
61
92
  }
62
93
  ),
63
94
  /* @__PURE__ */ jsx("span", { className: "sr-only", children: item.badgeLabel ?? item.badge })
@@ -76,8 +107,20 @@ function BottomNav({
76
107
  onClick: () => setMoreOpen(true),
77
108
  className: cn(slotClasses, classNames?.moreButton),
78
109
  children: [
79
- /* @__PURE__ */ jsx(Menu, { "aria-hidden": "true" }),
80
- /* @__PURE__ */ jsx("span", { children: more })
110
+ /* @__PURE__ */ jsxs("span", { className: "relative", children: [
111
+ /* @__PURE__ */ jsx(Menu, { "aria-hidden": "true" }),
112
+ badged.length > 0 ? /* @__PURE__ */ jsx(
113
+ BadgeMark,
114
+ {
115
+ count: overflowTotal,
116
+ danger: overflowDanger,
117
+ asDot: badgeStyle === "dot",
118
+ className: classNames?.badge
119
+ }
120
+ ) : null
121
+ ] }),
122
+ /* @__PURE__ */ jsx("span", { children: more }),
123
+ badged.length > 0 && overflowBadgeText ? /* @__PURE__ */ jsx("span", { className: "sr-only", children: overflowBadgeText }) : null
81
124
  ]
82
125
  }
83
126
  ) }) : null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcsoftdev/ui",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Token-driven React component library: React 19, Tailwind v4.",
5
5
  "author": "jcsoftdev",
6
6
  "license": "MIT",
@@ -102,7 +102,7 @@
102
102
  "typescript": "^5.5.4",
103
103
  "vite": "7.3.6",
104
104
  "vitest": "4.1.11",
105
- "@jcsoftdev/ui-tokens": "^0.7.0"
105
+ "@jcsoftdev/ui-tokens": "^0.8.0"
106
106
  },
107
107
  "publishConfig": {
108
108
  "access": "public"
@@ -0,0 +1,101 @@
1
+ "use client";
2
+
3
+ import { type ComponentPropsWithoutRef, useSyncExternalStore } from "react";
4
+ import { useUiStrings } from "../../i18n/index.js";
5
+ import type { ClassNames } from "../../utils/class-names.js";
6
+ import { cn } from "../../utils/cn.js";
7
+ import { usePrefersReducedMotion } from "../../utils/reduced-motion.js";
8
+ import { type ElapsedTone, formatClock, isoDuration, readElapsed, toneFor } from "./model.js";
9
+ import { getTickerSnapshot, subscribeTicker } from "./ticker.js";
10
+
11
+ export type ElapsedTimePart = "root" | "text";
12
+
13
+ export interface ElapsedTimeProps extends Omit<ComponentPropsWithoutRef<"time">, "children"> {
14
+ /** Moment the timer counts from. */
15
+ since: Date | string;
16
+ /** Server clock minus the client clock in ms, so a skewed device still shows the server's elapsed time. */
17
+ serverOffsetMs?: number;
18
+ /**
19
+ * `mm:ss` (default) shows a ticking clock; `minutes` shows whole minutes. With reduced motion
20
+ * requested, `mm:ss` is shown as whole minutes so the digits stop ticking.
21
+ */
22
+ format?: "mm:ss" | "minutes";
23
+ /** Minutes from which the text turns warning (counting up), or down to which it does (countdown). */
24
+ warnAt?: number;
25
+ /** Minutes from which the text turns danger (counting up), or down to which it does (countdown). A countdown past its target is always danger. */
26
+ dangerAt?: number;
27
+ /** Turns the timer into a countdown to this moment; `since` is then only the fallback reference. */
28
+ countdownTo?: Date | string;
29
+ /** Per-part classes merged with `cn`; consumer classes win. `className` still targets the root and is merged last. */
30
+ classNames?: ClassNames<ElapsedTimePart>;
31
+ }
32
+
33
+ const toneClasses: Record<ElapsedTone, string> = {
34
+ neutral: "text-ink-2",
35
+ warning: "font-bold text-warning",
36
+ danger: "font-bold text-danger",
37
+ };
38
+
39
+ function fill(template: string, key: string, value: string): string {
40
+ return template.replace(`{${key}}`, value);
41
+ }
42
+
43
+ /**
44
+ * A live timer in tabular numerals. Every instance shares one ticker (a single timer, aligned to
45
+ * the second, running only while something is mounted). It renders `<time>` with an ISO duration
46
+ * in `dateTime`, exposes plain text such as "12 minutes" to assistive tech and is never an
47
+ * `aria-live` region, so it does not interrupt anyone.
48
+ */
49
+ export function ElapsedTime({
50
+ since,
51
+ serverOffsetMs,
52
+ format = "mm:ss",
53
+ warnAt,
54
+ dangerAt,
55
+ countdownTo,
56
+ className,
57
+ classNames,
58
+ ...props
59
+ }: ElapsedTimeProps) {
60
+ const strings = useUiStrings();
61
+ const reducedMotion = usePrefersReducedMotion();
62
+ const now = useSyncExternalStore(subscribeTicker, getTickerSnapshot, getTickerSnapshot);
63
+ const countdown = countdownTo !== undefined;
64
+ const reading = readElapsed({ since, now, serverOffsetMs, countdownTo });
65
+ const tone = toneFor(reading, countdown, warnAt, dangerAt);
66
+ const minutes = Math.floor(reading.seconds / 60);
67
+ const asClock = format === "mm:ss" && !reducedMotion;
68
+ const visible = asClock
69
+ ? formatClock(reading.seconds)
70
+ : fill(strings.minutesShort, "count", String(minutes));
71
+ const spoken = fill(
72
+ minutes === 1 ? strings.elapsedMinutesOne : strings.elapsedMinutes,
73
+ "count",
74
+ String(minutes),
75
+ );
76
+ const announced = countdown
77
+ ? fill(reading.over ? strings.countdownOver : strings.countdownLeft, "time", spoken)
78
+ : spoken;
79
+
80
+ return (
81
+ <time
82
+ dateTime={isoDuration(reading.seconds)}
83
+ data-tone={tone === "neutral" ? undefined : tone}
84
+ data-countdown={countdown ? "" : undefined}
85
+ className={cn(
86
+ "inline-block text-data tabular-nums transition-colors motion-reduce:transition-none",
87
+ toneClasses[tone],
88
+ classNames?.root,
89
+ className,
90
+ )}
91
+ {...props}
92
+ >
93
+ <span aria-hidden="true" suppressHydrationWarning className={classNames?.text}>
94
+ {visible}
95
+ </span>
96
+ <span className="sr-only" suppressHydrationWarning>
97
+ {announced}
98
+ </span>
99
+ </time>
100
+ );
101
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ ElapsedTime,
3
+ type ElapsedTimePart,
4
+ type ElapsedTimeProps,
5
+ } from "./elapsed-time.js";
6
+ export { type ElapsedReading, type ElapsedTone, readElapsed, toneFor } from "./model.js";
@@ -0,0 +1,54 @@
1
+ export type ElapsedTone = "neutral" | "warning" | "danger";
2
+
3
+ export interface ElapsedReading {
4
+ /** Whole seconds away from the reference: elapsed since it, or remaining until the target. */
5
+ seconds: number;
6
+ /** True once a countdown passed its target. */
7
+ over: boolean;
8
+ }
9
+
10
+ export function toMs(value: Date | string | number): number {
11
+ return value instanceof Date ? value.getTime() : new Date(value).getTime();
12
+ }
13
+
14
+ export function readElapsed(options: {
15
+ since: Date | string;
16
+ now: number;
17
+ serverOffsetMs?: number | undefined;
18
+ countdownTo?: Date | string | undefined;
19
+ }): ElapsedReading {
20
+ const { since, now, serverOffsetMs = 0, countdownTo } = options;
21
+ const clock = now + serverOffsetMs;
22
+ if (countdownTo !== undefined) {
23
+ const diff = Math.floor((toMs(countdownTo) - clock) / 1000);
24
+ return { seconds: Math.abs(diff), over: diff < 0 };
25
+ }
26
+ return { seconds: Math.max(0, Math.floor((clock - toMs(since)) / 1000)), over: false };
27
+ }
28
+
29
+ export function toneFor(
30
+ reading: ElapsedReading,
31
+ countdown: boolean,
32
+ warnAt?: number,
33
+ dangerAt?: number,
34
+ ): ElapsedTone {
35
+ const minutes = reading.seconds / 60;
36
+ if (countdown) {
37
+ if (reading.over || (dangerAt !== undefined && minutes <= dangerAt)) return "danger";
38
+ if (warnAt !== undefined && minutes <= warnAt) return "warning";
39
+ return "neutral";
40
+ }
41
+ if (dangerAt !== undefined && minutes >= dangerAt) return "danger";
42
+ if (warnAt !== undefined && minutes >= warnAt) return "warning";
43
+ return "neutral";
44
+ }
45
+
46
+ const pad = (n: number) => String(n).padStart(2, "0");
47
+
48
+ export function formatClock(seconds: number): string {
49
+ return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}`;
50
+ }
51
+
52
+ export function isoDuration(seconds: number): string {
53
+ return `PT${Math.floor(seconds / 60)}M${seconds % 60}S`;
54
+ }
@@ -0,0 +1,39 @@
1
+ const listeners = new Set<() => void>();
2
+ let timer: ReturnType<typeof setTimeout> | undefined;
3
+
4
+ function stamp(): number {
5
+ return Math.floor(Date.now() / 1000) * 1000;
6
+ }
7
+
8
+ function schedule() {
9
+ timer = setTimeout(
10
+ () => {
11
+ for (const listener of [...listeners]) listener();
12
+ if (listeners.size > 0) schedule();
13
+ else timer = undefined;
14
+ },
15
+ 1000 - (Date.now() % 1000) + 5,
16
+ );
17
+ }
18
+
19
+ /** Subscribes to the one-second ticker every `ElapsedTime` shares; the timer runs only while someone listens. */
20
+ export function subscribeTicker(listener: () => void): () => void {
21
+ listeners.add(listener);
22
+ if (timer === undefined) schedule();
23
+ return () => {
24
+ listeners.delete(listener);
25
+ if (listeners.size === 0 && timer !== undefined) {
26
+ clearTimeout(timer);
27
+ timer = undefined;
28
+ }
29
+ };
30
+ }
31
+
32
+ /** Wall clock floored to the second, stable between ticks so it is a valid external-store snapshot. */
33
+ export function getTickerSnapshot(): number {
34
+ return stamp();
35
+ }
36
+
37
+ export function tickerListenerCount(): number {
38
+ return listeners.size;
39
+ }
@@ -6,6 +6,7 @@ export * from "./checkbox/index.js";
6
6
  export * from "./chip/index.js";
7
7
  export * from "./divider/index.js";
8
8
  export * from "./due-chip/index.js";
9
+ export * from "./elapsed-time/index.js";
9
10
  export * from "./icon/index.js";
10
11
  export * from "./icon-button/index.js";
11
12
  export * from "./kbd/index.js";
@@ -19,4 +20,5 @@ export * from "./spinner/index.js";
19
20
  export * from "./status-dot/index.js";
20
21
  export * from "./status-pill/index.js";
21
22
  export * from "./switch/index.js";
23
+ export * from "./table-glyph/index.js";
22
24
  export * from "./trend-chip/index.js";
@@ -0,0 +1,14 @@
1
+ export {
2
+ type Chair,
3
+ glyphLayout,
4
+ rectSideCounts,
5
+ squareSideCounts,
6
+ type TableShape,
7
+ } from "./layout.js";
8
+ export {
9
+ TableGlyph,
10
+ type TableGlyphPart,
11
+ type TableGlyphPattern,
12
+ type TableGlyphProps,
13
+ type TableGlyphSize,
14
+ } from "./table-glyph.js";