@jcsoftdev/ui 0.7.1 → 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 (48) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +3 -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 +44 -0
  32. package/dist/i18n/strings.js +22 -0
  33. package/package.json +2 -2
  34. package/src/atoms/elapsed-time/elapsed-time.tsx +101 -0
  35. package/src/atoms/elapsed-time/index.ts +6 -0
  36. package/src/atoms/elapsed-time/model.ts +54 -0
  37. package/src/atoms/elapsed-time/ticker.ts +39 -0
  38. package/src/atoms/index.ts +2 -0
  39. package/src/atoms/table-glyph/index.ts +14 -0
  40. package/src/atoms/table-glyph/layout.ts +187 -0
  41. package/src/atoms/table-glyph/table-glyph.tsx +161 -0
  42. package/src/containers/floor-plan/edit-model.ts +115 -0
  43. package/src/containers/floor-plan/floor-plan.tsx +393 -0
  44. package/src/containers/floor-plan/index.ts +20 -0
  45. package/src/containers/floor-plan/model.ts +81 -0
  46. package/src/containers/floor-plan/use-floor-plan-edit.ts +135 -0
  47. package/src/containers/index.ts +1 -0
  48. package/src/i18n/strings.ts +44 -0
@@ -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";
@@ -22,6 +22,28 @@ export interface UiStrings {
22
22
  more: string;
23
23
  /** Accessible total on the bottom bar "More" button; `{count}` is replaced. */
24
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;
25
47
  remove: string;
26
48
  noResults: string;
27
49
  clear: string;
@@ -160,6 +182,17 @@ export declare const uiStrings: {
160
182
  readonly copied: "Copied";
161
183
  readonly more: "More";
162
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.";
163
196
  readonly remove: "Remove";
164
197
  readonly noResults: "No results";
165
198
  readonly clear: "Clear";
@@ -250,6 +283,17 @@ export declare const uiStrings: {
250
283
  readonly copied: "Copiado";
251
284
  readonly more: "Más";
252
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.";
253
297
  readonly remove: "Quitar";
254
298
  readonly noResults: "Sin resultados";
255
299
  readonly clear: "Limpiar";
@@ -22,6 +22,17 @@ const uiStrings = {
22
22
  copied: "Copied",
23
23
  more: "More",
24
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.",
25
36
  remove: "Remove",
26
37
  noResults: "No results",
27
38
  clear: "Clear",
@@ -112,6 +123,17 @@ const uiStrings = {
112
123
  copied: "Copiado",
113
124
  more: "M\xE1s",
114
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.",
115
137
  remove: "Quitar",
116
138
  noResults: "Sin resultados",
117
139
  clear: "Limpiar",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcsoftdev/ui",
3
- "version": "0.7.1",
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.1"
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";
@@ -0,0 +1,187 @@
1
+ export type TableShape = "round" | "square" | "rect" | "bar";
2
+
3
+ export interface Chair {
4
+ cx: number;
5
+ cy: number;
6
+ rotate: number;
7
+ width: number;
8
+ height: number;
9
+ circle: boolean;
10
+ }
11
+
12
+ export interface GlyphLayout {
13
+ width: number;
14
+ height: number;
15
+ body: { x: number; y: number; width: number; height: number; round: boolean };
16
+ chairs: Chair[];
17
+ }
18
+
19
+ export const UNIT = 100;
20
+ export const CHAIR_DEPTH = 18;
21
+ export const CHAIR_WIDTH = 26;
22
+ export const CHAIR_GAP = 6;
23
+ const INSET = CHAIR_DEPTH + CHAIR_GAP;
24
+
25
+ type Side = "top" | "bottom" | "left" | "right";
26
+
27
+ function spread(count: number, length: number): number[] {
28
+ return Array.from({ length: count }, (_, i) => ((i + 0.5) / count) * length);
29
+ }
30
+
31
+ function chairWidthFor(count: number, length: number): number {
32
+ if (count === 0) return CHAIR_WIDTH;
33
+ return Math.max(6, Math.min(CHAIR_WIDTH, length / count - CHAIR_GAP));
34
+ }
35
+
36
+ function sideChair(side: Side, along: number, w: number, h: number, size: number): Chair {
37
+ const horizontal = side === "top" || side === "bottom";
38
+ const half = CHAIR_DEPTH / 2;
39
+ const cx = horizontal ? along : side === "left" ? half : w - half;
40
+ const cy = horizontal ? (side === "top" ? half : h - half) : along;
41
+ return {
42
+ cx,
43
+ cy,
44
+ rotate: horizontal ? 0 : 90,
45
+ width: size,
46
+ height: CHAIR_DEPTH,
47
+ circle: false,
48
+ };
49
+ }
50
+
51
+ /** Chairs per side of a square table: one per side up to four seats, then spread evenly with the remainder going top, bottom, left, right. */
52
+ export function squareSideCounts(seats: number): Record<Side, number> {
53
+ const order: Side[] = ["top", "bottom", "left", "right"];
54
+ const counts: Record<Side, number> = { top: 0, bottom: 0, left: 0, right: 0 };
55
+ const base = Math.floor(seats / 4);
56
+ const extra = seats % 4;
57
+ order.forEach((side, i) => {
58
+ counts[side] = base + (i < extra ? 1 : 0);
59
+ });
60
+ return counts;
61
+ }
62
+
63
+ /** Chairs of a rect table: one at each end, the rest split between the two long sides (top gets the odd one). */
64
+ export function rectSideCounts(seats: number): Record<Side, number> {
65
+ const ends = Math.min(seats, 2);
66
+ const rest = seats - ends;
67
+ return {
68
+ left: ends >= 1 ? 1 : 0,
69
+ right: ends >= 2 ? 1 : 0,
70
+ top: Math.ceil(rest / 2),
71
+ bottom: Math.floor(rest / 2),
72
+ };
73
+ }
74
+
75
+ function sidedChairs(counts: Record<Side, number>, w: number, h: number): Chair[] {
76
+ const out: Chair[] = [];
77
+ for (const side of ["top", "bottom", "left", "right"] as const) {
78
+ const horizontal = side === "top" || side === "bottom";
79
+ const length = horizontal ? w - 2 * INSET : h - 2 * INSET;
80
+ const offset = INSET;
81
+ const size = chairWidthFor(counts[side], length);
82
+ for (const along of spread(counts[side], length)) {
83
+ out.push(sideChair(side, offset + along, w, h, size));
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+
89
+ function roundLayout(seats: number, w: number, h: number): GlyphLayout {
90
+ const cx = w / 2;
91
+ const cy = h / 2;
92
+ const radius = Math.max(8, Math.min(w, h) / 2 - INSET);
93
+ const orbit = radius + CHAIR_GAP + CHAIR_DEPTH / 2;
94
+ const size = chairWidthFor(seats, 2 * Math.PI * orbit);
95
+ const chairs = Array.from({ length: seats }, (_, i) => {
96
+ const angle = -Math.PI / 2 + (i * 2 * Math.PI) / seats;
97
+ return {
98
+ cx: cx + orbit * Math.cos(angle),
99
+ cy: cy + orbit * Math.sin(angle),
100
+ rotate: (angle * 180) / Math.PI + 90,
101
+ width: size,
102
+ height: CHAIR_DEPTH,
103
+ circle: false,
104
+ };
105
+ });
106
+ return {
107
+ width: w,
108
+ height: h,
109
+ body: { x: cx - radius, y: cy - radius, width: 2 * radius, height: 2 * radius, round: true },
110
+ chairs,
111
+ };
112
+ }
113
+
114
+ function barLayout(seats: number, w: number, h: number): GlyphLayout {
115
+ const counterHeight = Math.max(14, h * 0.4);
116
+ const stool = Math.min(
117
+ CHAIR_WIDTH * 0.8,
118
+ h - counterHeight - CHAIR_GAP,
119
+ w / Math.max(seats, 1) - 4,
120
+ );
121
+ const diameter = Math.max(6, stool);
122
+ const chairs = spread(seats, w - 2 * CHAIR_GAP).map((x) => ({
123
+ cx: CHAIR_GAP + x,
124
+ cy: counterHeight + CHAIR_GAP + diameter / 2,
125
+ rotate: 0,
126
+ width: diameter,
127
+ height: diameter,
128
+ circle: true,
129
+ }));
130
+ return {
131
+ width: w,
132
+ height: h,
133
+ body: { x: 0, y: 0, width: w, height: counterHeight, round: false },
134
+ chairs,
135
+ };
136
+ }
137
+
138
+ function transpose(layout: GlyphLayout): GlyphLayout {
139
+ return {
140
+ width: layout.height,
141
+ height: layout.width,
142
+ body: {
143
+ x: layout.body.y,
144
+ y: layout.body.x,
145
+ width: layout.body.height,
146
+ height: layout.body.width,
147
+ round: layout.body.round,
148
+ },
149
+ chairs: layout.chairs.map((c) => ({
150
+ ...c,
151
+ cx: c.cy,
152
+ cy: c.cx,
153
+ rotate: c.circle ? 0 : c.rotate === 0 ? 90 : 0,
154
+ })),
155
+ };
156
+ }
157
+
158
+ function framed(counts: Record<Side, number>, w: number, h: number): GlyphLayout {
159
+ return {
160
+ width: w,
161
+ height: h,
162
+ body: { x: INSET, y: INSET, width: w - 2 * INSET, height: h - 2 * INSET, round: false },
163
+ chairs: sidedChairs(counts, w, h),
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Geometry of a table glyph in a `width` x `height` box (100 units per grid cell). Round tables
169
+ * space chairs radially; square ones put a chair per side up to four, then spread; rect tables
170
+ * seat one at each end and split the rest along the long sides; bars line stools up in a row.
171
+ * Rect and bar follow the longer axis of the box.
172
+ */
173
+ export function glyphLayout(
174
+ shape: TableShape,
175
+ seats: number,
176
+ width: number,
177
+ height: number,
178
+ ): GlyphLayout {
179
+ const count = Math.max(0, Math.floor(seats));
180
+ if (shape === "round") return roundLayout(count, width, height);
181
+ if (shape === "square") return framed(squareSideCounts(count), width, height);
182
+ const vertical = height > width;
183
+ const w = vertical ? height : width;
184
+ const h = vertical ? width : height;
185
+ const layout = shape === "rect" ? framed(rectSideCounts(count), w, h) : barLayout(count, w, h);
186
+ return vertical ? transpose(layout) : layout;
187
+ }