@oaiz/app-kit 0.0.0-stage → 0.1.4128

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/THIRD_PARTY_NOTICES.md +76 -0
  4. package/package.json +139 -4
  5. package/registry.json +1847 -0
  6. package/src/components/activity-timeline.tsx +227 -0
  7. package/src/components/app-shell.tsx +622 -0
  8. package/src/components/bar-list.tsx +47 -0
  9. package/src/components/board.tsx +700 -0
  10. package/src/components/calendar-view.tsx +1388 -0
  11. package/src/components/card-grid.tsx +462 -0
  12. package/src/components/charts.tsx +701 -0
  13. package/src/components/chat-markdown.tsx +230 -0
  14. package/src/components/chat-panel.tsx +760 -0
  15. package/src/components/code-editor.tsx +276 -0
  16. package/src/components/collection-controls.tsx +226 -0
  17. package/src/components/command-palette.tsx +403 -0
  18. package/src/components/confirm-action.tsx +123 -0
  19. package/src/components/data-table.tsx +821 -0
  20. package/src/components/date-input.tsx +429 -0
  21. package/src/components/empty-state.tsx +31 -0
  22. package/src/components/error-state.tsx +37 -0
  23. package/src/components/file-upload.tsx +595 -0
  24. package/src/components/filter-bar.tsx +415 -0
  25. package/src/components/grouped-picker.tsx +250 -0
  26. package/src/components/line-items.tsx +601 -0
  27. package/src/components/list-view.tsx +491 -0
  28. package/src/components/metrics.tsx +53 -0
  29. package/src/components/page-header.tsx +33 -0
  30. package/src/components/property-picker.tsx +546 -0
  31. package/src/components/record-detail.tsx +416 -0
  32. package/src/components/record-form.tsx +295 -0
  33. package/src/components/record-name.tsx +85 -0
  34. package/src/components/save-bar.tsx +142 -0
  35. package/src/components/sign-in.tsx +179 -0
  36. package/src/components/split-view.tsx +128 -0
  37. package/src/components/status-dot.tsx +56 -0
  38. package/src/components/stepper.tsx +153 -0
  39. package/src/components/text-diff-model.ts +111 -0
  40. package/src/components/text-diff.tsx +98 -0
  41. package/src/components/time-zone-picker.tsx +69 -0
  42. package/src/components/ui/accordion.tsx +138 -0
  43. package/src/components/ui/alert-dialog.tsx +67 -0
  44. package/src/components/ui/alert.tsx +65 -0
  45. package/src/components/ui/avatar-group.tsx +119 -0
  46. package/src/components/ui/avatar.tsx +55 -0
  47. package/src/components/ui/badge.tsx +59 -0
  48. package/src/components/ui/bottom-navigation.tsx +102 -0
  49. package/src/components/ui/breadcrumb.tsx +117 -0
  50. package/src/components/ui/button.tsx +71 -0
  51. package/src/components/ui/card.tsx +95 -0
  52. package/src/components/ui/checkbox.tsx +31 -0
  53. package/src/components/ui/collapsible.tsx +27 -0
  54. package/src/components/ui/context-menu.tsx +270 -0
  55. package/src/components/ui/count-up.tsx +136 -0
  56. package/src/components/ui/detail-disclosure-section.tsx +109 -0
  57. package/src/components/ui/dialog.tsx +157 -0
  58. package/src/components/ui/dropdown-menu.tsx +273 -0
  59. package/src/components/ui/form-field.tsx +155 -0
  60. package/src/components/ui/heading.tsx +126 -0
  61. package/src/components/ui/hover-card.tsx +45 -0
  62. package/src/components/ui/input.tsx +50 -0
  63. package/src/components/ui/label.tsx +30 -0
  64. package/src/components/ui/orb-spinner.tsx +238 -0
  65. package/src/components/ui/popover.tsx +59 -0
  66. package/src/components/ui/progress-ring.tsx +125 -0
  67. package/src/components/ui/progress.tsx +38 -0
  68. package/src/components/ui/radio-group.tsx +124 -0
  69. package/src/components/ui/resizable.tsx +48 -0
  70. package/src/components/ui/scroll-fade.tsx +98 -0
  71. package/src/components/ui/segmented-control.tsx +70 -0
  72. package/src/components/ui/select.tsx +230 -0
  73. package/src/components/ui/separator.tsx +29 -0
  74. package/src/components/ui/sheet.tsx +170 -0
  75. package/src/components/ui/shimmer-text.tsx +87 -0
  76. package/src/components/ui/shortcut.tsx +39 -0
  77. package/src/components/ui/skeleton.tsx +15 -0
  78. package/src/components/ui/slider.tsx +48 -0
  79. package/src/components/ui/switch.tsx +44 -0
  80. package/src/components/ui/table.tsx +119 -0
  81. package/src/components/ui/tabs.tsx +80 -0
  82. package/src/components/ui/text.tsx +93 -0
  83. package/src/components/ui/textarea.tsx +51 -0
  84. package/src/components/ui/toast.tsx +141 -0
  85. package/src/components/ui/toaster.tsx +40 -0
  86. package/src/components/ui/tooltip.tsx +38 -0
  87. package/src/components/ui/top-banner.tsx +108 -0
  88. package/src/components/ui/tree-view.tsx +215 -0
  89. package/src/components/ui/use-toast.tsx +184 -0
  90. package/src/components/ui/voice-orb.tsx +252 -0
  91. package/src/hooks/oaiz-chat.tsx +530 -0
  92. package/src/hooks/oaiz-data.tsx +617 -0
  93. package/src/hooks/oaiz-session.tsx +63 -0
  94. package/src/hooks/use-arrivals.ts +19 -0
  95. package/src/hooks/use-breakpoint.ts +100 -0
  96. package/src/hooks/use-media-query.ts +36 -0
  97. package/src/hooks/use-theme.ts +67 -0
  98. package/src/hooks/use-url-state.ts +77 -0
  99. package/src/lib/breakpoints.ts +81 -0
  100. package/src/lib/csp-nonce.ts +15 -0
  101. package/src/lib/format.ts +291 -0
  102. package/src/lib/speech-level.ts +118 -0
  103. package/src/lib/utils.ts +109 -0
  104. package/src/styles/oaiz/app.css +21 -0
  105. package/src/styles/oaiz/scrollbars.css +20 -0
  106. package/src/styles/oaiz/tokens.css +952 -0
  107. package/src/styles/oaiz/voice-orb.css +39 -0
@@ -0,0 +1,100 @@
1
+ import * as React from 'react';
2
+ import {
3
+ BREAKPOINT_ORDER,
4
+ MEDIA_QUERIES,
5
+ MEDIA_QUERIES_BELOW,
6
+ type Breakpoint,
7
+ type BreakpointTier,
8
+ } from '../lib/breakpoints';
9
+ import { subscribeToQuery, useMediaQuery } from './use-media-query';
10
+
11
+ const noop = (): void => undefined;
12
+
13
+ /**
14
+ * One subscription for every named tier boundary, so a hook re-reads on any
15
+ * crossing. The browser evaluates the same rem media queries as Tailwind.
16
+ */
17
+ function subscribeToTiers(onStoreChange: () => void): () => void {
18
+ if (typeof window === 'undefined') return noop;
19
+
20
+ const unsubscribe = BREAKPOINT_ORDER.filter(
21
+ (tier): tier is Breakpoint => tier !== 'base',
22
+ ).map((tier) => subscribeToQuery(MEDIA_QUERIES[tier])(onStoreChange));
23
+
24
+ return () => {
25
+ unsubscribe.forEach((cleanup) => cleanup());
26
+ };
27
+ }
28
+
29
+ /**
30
+ * The widest tier whose min-width the viewport satisfies, or `'base'` below the
31
+ * narrowest one.
32
+ *
33
+ * A tier name means exactly what the matching CSS variant means — `'half'` is
34
+ * true from 56.25rem up, just as `half:` applies from 56.25rem up — so a
35
+ * component that branches in TS and a stylesheet that branches in CSS never
36
+ * disagree.
37
+ * `'base'` is the unprefixed state.
38
+ *
39
+ * base < 40rem
40
+ * mobile >= 40rem
41
+ * half >= 56.25rem
42
+ * normal >= 75rem
43
+ * ultrawide >= 96rem
44
+ *
45
+ * Prefer a CSS variant when the difference is purely visual; it costs no
46
+ * render. Reach for this when the *markup* differs between tiers, or when a
47
+ * value has to cross into JS.
48
+ */
49
+ export function useBreakpoint(): BreakpointTier {
50
+ return React.useSyncExternalStore(
51
+ subscribeToTiers,
52
+ computeTier,
53
+ getServerTier,
54
+ );
55
+ }
56
+
57
+ function computeTier(): BreakpointTier {
58
+ if (typeof window === 'undefined') return getServerTier();
59
+
60
+ let active: BreakpointTier = 'base';
61
+ for (const tier of BREAKPOINT_ORDER) {
62
+ if (tier !== 'base' && window.matchMedia(MEDIA_QUERIES[tier]).matches) {
63
+ active = tier;
64
+ }
65
+ }
66
+ return active;
67
+ }
68
+
69
+ const getServerTier = (): BreakpointTier => 'normal';
70
+ /**
71
+ * True from `tier`'s min-width up — the TS twin of the `tier:` CSS variant.
72
+ * `useBreakpointAtLeast('half')` is true exactly when `half:` applies.
73
+ */
74
+ export function useBreakpointAtLeast(tier: Breakpoint): boolean {
75
+ return useMediaQuery(MEDIA_QUERIES[tier]);
76
+ }
77
+
78
+ /**
79
+ * True below `tier`'s min-width — the TS twin of the `max-tier:` CSS variant.
80
+ * `useBreakpointBelow('half')` is true exactly when `max-half:` applies.
81
+ */
82
+ export function useBreakpointBelow(tier: Breakpoint): boolean {
83
+ return useMediaQuery(MEDIA_QUERIES_BELOW[tier]);
84
+ }
85
+
86
+ /**
87
+ * True on a phone-width viewport: narrower than the 40rem mobile tier,
88
+ * i.e. the `base` tier. Equivalent to `useBreakpointBelow('mobile')`, kept as a
89
+ * named hook because "is this the phone layout?" is the question most call
90
+ * sites are actually asking.
91
+ *
92
+ * Pass a tier or a pixel number to test against a different cutoff.
93
+ */
94
+ export function useIsMobile(breakpoint?: number | Breakpoint): boolean {
95
+ const query =
96
+ typeof breakpoint === 'number'
97
+ ? `not all and (min-width: ${breakpoint}px)`
98
+ : MEDIA_QUERIES_BELOW[breakpoint ?? 'mobile'];
99
+ return useMediaQuery(query);
100
+ }
@@ -0,0 +1,36 @@
1
+ import * as React from 'react';
2
+
3
+ const noop = () => undefined;
4
+ const getServerSnapshot = () => false;
5
+
6
+ /** Shared subscribe/getSnapshot pair, so every responsive hook reads the same way. */
7
+ export function subscribeToQuery(query: string) {
8
+ return (onStoreChange: () => void) => {
9
+ if (typeof window === 'undefined') return noop;
10
+ const list = window.matchMedia(query);
11
+ list.addEventListener('change', onStoreChange);
12
+ return () => list.removeEventListener('change', onStoreChange);
13
+ };
14
+ }
15
+
16
+ /**
17
+ * SSR-safe hook that subscribes to a CSS media query string.
18
+ *
19
+ * Reach for this only when the thing you are asking about is *not* a width
20
+ * tier — orientation, `prefers-reduced-motion`, a one-off width. For tiers use
21
+ * `useBreakpoint`, `useBreakpointAtLeast` or `useBreakpointBelow`, which stay
22
+ * in step with the `mobile:` / `half:` / `normal:` / `ultrawide:` CSS variants.
23
+ *
24
+ * Uses `React.useSyncExternalStore`, so it is flicker-free and concurrent-safe.
25
+ * The server snapshot is always `false`.
26
+ */
27
+ export function useMediaQuery(query: string): boolean {
28
+ const subscribe = React.useMemo(() => subscribeToQuery(query), [query]);
29
+
30
+ const getSnapshot = React.useCallback(() => {
31
+ if (typeof window === 'undefined') return false;
32
+ return window.matchMedia(query).matches;
33
+ }, [query]);
34
+
35
+ return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
36
+ }
@@ -0,0 +1,67 @@
1
+ import { useCallback, useEffect, useSyncExternalStore } from 'react';
2
+
3
+ /** The member's choice: a fixed theme, or whatever their system uses. */
4
+ export type ThemeChoice = 'light' | 'dark' | 'system';
5
+
6
+ const STORAGE_KEY = 'oaiz.theme';
7
+ const DARK_QUERY = '(prefers-color-scheme: dark)';
8
+ const listeners = new Set<() => void>();
9
+ // The choice for this page, for a browser that refuses storage.
10
+ let pageChoice: ThemeChoice = 'system';
11
+
12
+ function readChoice(): ThemeChoice {
13
+ try {
14
+ const stored = localStorage.getItem(STORAGE_KEY);
15
+ return stored === 'light' || stored === 'dark' ? stored : 'system';
16
+ } catch {
17
+ return pageChoice;
18
+ }
19
+ }
20
+
21
+ function systemIsDark(): boolean {
22
+ return typeof window !== 'undefined' && (window.matchMedia?.(DARK_QUERY).matches ?? false);
23
+ }
24
+
25
+ /** Puts the `dark` class on `<html>`, where the theme's tokens read it, for the stored choice. */
26
+ export function applyStoredTheme(): void {
27
+ if (typeof document === 'undefined') return;
28
+ const choice = readChoice();
29
+ const dark = choice === 'dark' || (choice === 'system' && systemIsDark());
30
+ document.documentElement.classList.toggle('dark', dark);
31
+ }
32
+
33
+ function subscribe(onChange: () => void) {
34
+ listeners.add(onChange);
35
+ return () => listeners.delete(onChange);
36
+ }
37
+
38
+ /**
39
+ * The member's theme on this app: light, dark or the system's, remembered in this browser. Call
40
+ * `applyStoredTheme()` once in `main.tsx` before rendering, so the first paint has the right
41
+ * colours; this hook then follows the system while the choice is `system`.
42
+ */
43
+ export function useTheme() {
44
+ const choice = useSyncExternalStore(subscribe, readChoice, () => 'system' as ThemeChoice);
45
+
46
+ useEffect(() => {
47
+ applyStoredTheme();
48
+ if (choice !== 'system') return;
49
+ const query = window.matchMedia?.(DARK_QUERY);
50
+ query?.addEventListener('change', applyStoredTheme);
51
+ return () => query?.removeEventListener('change', applyStoredTheme);
52
+ }, [choice]);
53
+
54
+ const setChoice = useCallback((next: ThemeChoice) => {
55
+ pageChoice = next;
56
+ try {
57
+ if (next === 'system') localStorage.removeItem(STORAGE_KEY);
58
+ else localStorage.setItem(STORAGE_KEY, next);
59
+ } catch {
60
+ // readChoice answers pageChoice while storage is refused.
61
+ }
62
+ applyStoredTheme();
63
+ for (const listener of listeners) listener();
64
+ }, []);
65
+
66
+ return { choice, setChoice };
67
+ }
@@ -0,0 +1,77 @@
1
+ import { useCallback, useSyncExternalStore } from 'react';
2
+ import { flushSync } from 'react-dom';
3
+
4
+ const CHANGED = 'oaiz:url-state';
5
+
6
+ /** The address a push writes once its view transition starts. */
7
+ let pending: URL | null = null;
8
+
9
+ function subscribe(listener: () => void) {
10
+ window.addEventListener('popstate', listener);
11
+ window.addEventListener(CHANGED, listener);
12
+ return () => {
13
+ window.removeEventListener('popstate', listener);
14
+ window.removeEventListener(CHANGED, listener);
15
+ };
16
+ }
17
+
18
+ export type UrlStateOptions = {
19
+ /**
20
+ * `push`: Back returns to the previous value, for a screen or an open record. `replace`: Back
21
+ * skips it, for search, filters, sort and page.
22
+ */
23
+ history?: 'push' | 'replace';
24
+ };
25
+
26
+ /**
27
+ * One value in the page address, read and set like `useState`, so that a reload and Back keep it
28
+ * and a link shares it. The address leaves out a value equal to `initial`.
29
+ */
30
+ export function useUrlState(
31
+ key: string,
32
+ initial = '',
33
+ options: UrlStateOptions = {},
34
+ ): [string, (next: string) => void] {
35
+ const history = options.history ?? 'replace';
36
+ const value = useSyncExternalStore(
37
+ subscribe,
38
+ () => new URLSearchParams(window.location.search).get(key) ?? initial,
39
+ );
40
+ const set = useCallback(
41
+ (next: string) => {
42
+ // Values set while a push waits for its transition join that push, so one click that sets
43
+ // two values makes one history entry holding both.
44
+ const url = new URL((pending ?? window.location).href);
45
+ if (next === initial) url.searchParams.delete(key);
46
+ else url.searchParams.set(key, next);
47
+ if (pending) {
48
+ pending = url;
49
+ return;
50
+ }
51
+ if (url.href === window.location.href) return;
52
+ if (history === 'replace') {
53
+ window.history.replaceState(window.history.state, '', url);
54
+ window.dispatchEvent(new Event(CHANGED));
55
+ return;
56
+ }
57
+ pending = url;
58
+ // A new screen or record cross-fades in, where the browser can and the member allows motion.
59
+ const go = () =>
60
+ flushSync(() => {
61
+ const target = pending;
62
+ pending = null;
63
+ if (!target || target.href === window.location.href) return;
64
+ window.history.pushState(window.history.state, '', target);
65
+ window.dispatchEvent(new Event(CHANGED));
66
+ });
67
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
68
+ if (reduce || typeof document.startViewTransition !== 'function') go();
69
+ else {
70
+ // A superseding transition can skip the animation after its navigation callback runs.
71
+ void document.startViewTransition(go).ready.catch(() => undefined);
72
+ }
73
+ },
74
+ [key, initial, history],
75
+ );
76
+ return [value, set];
77
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Breakpoints and responsive design tokens for OAIZ UI.
3
+ *
4
+ * Every tier is a **min-width**, so the name means the same thing everywhere it
5
+ * appears — in a stylesheet, in a media query string, and in TS:
6
+ *
7
+ * `half:px-6` applies from 56.25rem up
8
+ * `MEDIA_QUERIES.half` matches from 56.25rem up
9
+ * `useBreakpointAtLeast('half')` true from 56.25rem up
10
+ * `useBreakpoint() === 'half'` true from 56.25rem until `normal`
11
+ *
12
+ * Below the narrowest tier is `'base'`, mirroring an unprefixed CSS utility.
13
+ *
14
+ * - base: < 40rem — phone; single column, drawer/sheet navigation
15
+ * - mobile: >= 40rem — large phone and up
16
+ * - half: >= 56.25rem — 2-up split screen / tiled desktop window
17
+ * - normal: >= 75rem — standard full laptop & desktop screen
18
+ * - ultrawide: >= 96rem — large displays, max container width
19
+ */
20
+
21
+ export const BREAKPOINTS = {
22
+ mobile: '40rem',
23
+ half: '56.25rem',
24
+ normal: '75rem',
25
+ ultrawide: '96rem',
26
+ } as const;
27
+
28
+ /** A tier with a min-width of its own. */
29
+ export type Breakpoint = keyof typeof BREAKPOINTS;
30
+
31
+ /** Every tier a viewport can be in, including the unprefixed `base` state. */
32
+ export type BreakpointTier = 'base' | Breakpoint;
33
+
34
+ /** Narrowest to widest. The single source of tier ordering. */
35
+ export const BREAKPOINT_ORDER = [
36
+ 'base',
37
+ 'mobile',
38
+ 'half',
39
+ 'normal',
40
+ 'ultrawide',
41
+ ] as const satisfies readonly BreakpointTier[];
42
+
43
+ /** `tier:` in CSS — matches from the tier's min-width up. */
44
+ export const MEDIA_QUERIES = {
45
+ mobile: `(min-width: ${BREAKPOINTS.mobile})`,
46
+ half: `(min-width: ${BREAKPOINTS.half})`,
47
+ normal: `(min-width: ${BREAKPOINTS.normal})`,
48
+ ultrawide: `(min-width: ${BREAKPOINTS.ultrawide})`,
49
+ } as const;
50
+
51
+ /** The logical complement of the matching min-width query. */
52
+ export const MEDIA_QUERIES_BELOW = {
53
+ mobile: `not all and ${MEDIA_QUERIES.mobile}`,
54
+ half: `not all and ${MEDIA_QUERIES.half}`,
55
+ normal: `not all and ${MEDIA_QUERIES.normal}`,
56
+ ultrawide: `not all and ${MEDIA_QUERIES.ultrawide}`,
57
+ } as const;
58
+
59
+ export const TOUCH_TARGETS = {
60
+ min: '2.75rem', // 44px (WCAG 2.5.5 / Apple HIG)
61
+ compact: '2.25rem', // 36px dense touch target
62
+ comfortable: '3rem', // 48px comfortable touch target (Android Material)
63
+ } as const;
64
+
65
+ export const SAFE_AREAS = {
66
+ top: 'env(safe-area-inset-top, 0px)',
67
+ right: 'env(safe-area-inset-right, 0px)',
68
+ bottom: 'env(safe-area-inset-bottom, 0px)',
69
+ left: 'env(safe-area-inset-left, 0px)',
70
+ } as const;
71
+
72
+ export const SPACING_GUTTERS = {
73
+ mobile: '1rem', // 16px
74
+ tablet: '1.5rem', // 24px
75
+ desktop: '2rem', // 32px
76
+ } as const;
77
+
78
+ export const LAYOUT_HEIGHTS = {
79
+ mobileHeader: '3.5rem', // 56px
80
+ mobileNav: '4rem', // 64px
81
+ } as const;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The CSP nonce the document publishes in `<meta property="csp-nonce">`, for
3
+ * style elements created after page load. Browsers hide the parsed attribute
4
+ * and keep the value on the `nonce` property; DOMs without that property keep
5
+ * only the attribute. Returns `undefined` when the document has no such meta.
6
+ */
7
+ export function cspNonce(): string | undefined {
8
+ const meta = document.querySelector<HTMLMetaElement>(
9
+ 'meta[property="csp-nonce"]',
10
+ );
11
+ if (meta?.nonce) return meta.nonce;
12
+ const attribute = meta?.getAttribute('nonce');
13
+ if (attribute) return attribute;
14
+ return undefined;
15
+ }
@@ -0,0 +1,291 @@
1
+ /**
2
+ * How an app shows numbers, money, dates and times: one place, so every screen
3
+ * writes "€1.2k", "3 days ago" and "12 Mar 2027" the same way. Each formatter
4
+ * takes an optional locale and otherwise uses the browser's.
5
+ */
6
+
7
+ type Locale = string | undefined;
8
+
9
+ const cache = new Map<
10
+ string,
11
+ Intl.NumberFormat | Intl.DateTimeFormat | Intl.RelativeTimeFormat
12
+ >();
13
+
14
+ function cached<
15
+ T extends Intl.NumberFormat | Intl.DateTimeFormat | Intl.RelativeTimeFormat,
16
+ >(key: string, make: () => T): T {
17
+ let format = cache.get(key) as T | undefined;
18
+ if (!format) {
19
+ format = make();
20
+ cache.set(key, format);
21
+ }
22
+ return format;
23
+ }
24
+
25
+ /** A plain number with grouping: 1,234.5. */
26
+ export function formatNumber(
27
+ value: number,
28
+ options: { locale?: Locale; maximumFractionDigits?: number } = {},
29
+ ): string {
30
+ const digits = options.maximumFractionDigits ?? 2;
31
+ return cached(
32
+ `n|${options.locale}|${digits}`,
33
+ () =>
34
+ new Intl.NumberFormat(options.locale, { maximumFractionDigits: digits }),
35
+ ).format(value);
36
+ }
37
+
38
+ /** A short number for a figure that need not be exact: 1.2k, 3.4M. */
39
+ export function formatCompact(
40
+ value: number,
41
+ options: { locale?: Locale } = {},
42
+ ): string {
43
+ return cached(
44
+ `c|${options.locale}`,
45
+ () =>
46
+ new Intl.NumberFormat(options.locale, {
47
+ notation: 'compact',
48
+ maximumFractionDigits: 1,
49
+ }),
50
+ ).format(value);
51
+ }
52
+
53
+ /**
54
+ * An amount of money in `currency` (ISO 4217, such as "EUR"); `compact` writes €1.2k and `whole`
55
+ * writes €6,000 for amounts that are never in cents, such as deal values.
56
+ */
57
+ export function formatCurrency(
58
+ value: number,
59
+ currency: string,
60
+ options: { locale?: Locale; compact?: boolean; whole?: boolean } = {},
61
+ ): string {
62
+ const compact = options.compact ?? false;
63
+ const whole = options.whole ?? false;
64
+ return cached(
65
+ `m|${options.locale}|${currency}|${compact}|${whole}`,
66
+ () =>
67
+ new Intl.NumberFormat(options.locale, {
68
+ style: 'currency',
69
+ currency,
70
+ ...(compact ? { notation: 'compact', maximumFractionDigits: 1 } : {}),
71
+ ...(whole && !compact
72
+ ? { minimumFractionDigits: 0, maximumFractionDigits: 0 }
73
+ : {}),
74
+ }),
75
+ ).format(value);
76
+ }
77
+
78
+ /** A share, where 1 is 100%: 0.256 becomes 25.6%. */
79
+ export function formatPercent(
80
+ value: number,
81
+ options: { locale?: Locale; maximumFractionDigits?: number } = {},
82
+ ): string {
83
+ const digits = options.maximumFractionDigits ?? 1;
84
+ return cached(
85
+ `p|${options.locale}|${digits}`,
86
+ () =>
87
+ new Intl.NumberFormat(options.locale, {
88
+ style: 'percent',
89
+ maximumFractionDigits: digits,
90
+ }),
91
+ ).format(value);
92
+ }
93
+
94
+ /**
95
+ * A day of the member's own calendar as `YYYY-MM-DD`: the value of a date input and of a `date`
96
+ * column. It reads the local date, never `toISOString()`, which gives the UTC day.
97
+ */
98
+ export function localDay(date: Date = new Date()): string {
99
+ const month = String(date.getMonth() + 1).padStart(2, '0');
100
+ const day = String(date.getDate()).padStart(2, '0');
101
+ return `${date.getFullYear()}-${month}-${day}`;
102
+ }
103
+
104
+ /** The local midnight a `YYYY-MM-DD` day starts at, or null for anything else. */
105
+ export function parseLocalDay(day: string): Date | null {
106
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
107
+ if (!match) return null;
108
+ const date = new Date(
109
+ Number(match[1]),
110
+ Number(match[2]) - 1,
111
+ Number(match[3]),
112
+ );
113
+ return localDay(date) === day ? date : null;
114
+ }
115
+
116
+ function toDate(value: Date | string | number): Date | null {
117
+ if (value instanceof Date)
118
+ return Number.isNaN(value.getTime()) ? null : value;
119
+ if (typeof value === 'string') {
120
+ const day = parseLocalDay(value);
121
+ if (day) return day;
122
+ }
123
+ const date = new Date(value);
124
+ return Number.isNaN(date.getTime()) ? null : date;
125
+ }
126
+
127
+ /**
128
+ * A date: 12 Mar 2027, or 12 Mar with `year: false` for dates in a list that all fall close to now.
129
+ * A `YYYY-MM-DD` string is read as that day, wherever the member is.
130
+ */
131
+ export function formatDate(
132
+ value: Date | string | number,
133
+ options: { locale?: Locale; year?: boolean } = {},
134
+ ): string {
135
+ const date = toDate(value);
136
+ if (!date) return '';
137
+ const year = options.year ?? true;
138
+ return cached(
139
+ `d|${options.locale}|${year}`,
140
+ () =>
141
+ new Intl.DateTimeFormat(options.locale, {
142
+ day: 'numeric',
143
+ month: 'short',
144
+ ...(year ? { year: 'numeric' } : {}),
145
+ }),
146
+ ).format(date);
147
+ }
148
+
149
+ /** A date and time: 12 Mar 2027, 14:05. */
150
+ export function formatDateTime(
151
+ value: Date | string | number,
152
+ options: { locale?: Locale } = {},
153
+ ): string {
154
+ const date = toDate(value);
155
+ if (!date) return '';
156
+ return cached(
157
+ `dt|${options.locale}`,
158
+ () =>
159
+ new Intl.DateTimeFormat(options.locale, {
160
+ day: 'numeric',
161
+ month: 'short',
162
+ year: 'numeric',
163
+ hour: 'numeric',
164
+ minute: '2-digit',
165
+ }),
166
+ ).format(date);
167
+ }
168
+
169
+ /** A time of day on the member's clock: 14:05, or 2:05 PM where the locale writes it so. */
170
+ export function formatTime(
171
+ value: Date | string | number,
172
+ options: { locale?: Locale; timeZone?: string } = {},
173
+ ): string {
174
+ const date = toDate(value);
175
+ if (!date) return '';
176
+ return cached(
177
+ `t|${options.locale}|${options.timeZone}`,
178
+ () =>
179
+ new Intl.DateTimeFormat(options.locale, {
180
+ hour: 'numeric',
181
+ minute: '2-digit',
182
+ timeZone: options.timeZone,
183
+ }),
184
+ ).format(date);
185
+ }
186
+
187
+ /** The name of a day of the week: Mon, or Monday with `style: 'long'`, or M with `'narrow'`. */
188
+ export function formatWeekday(
189
+ value: Date | string | number,
190
+ options: { locale?: Locale; style?: 'long' | 'short' | 'narrow' } = {},
191
+ ): string {
192
+ const date = toDate(value);
193
+ if (!date) return '';
194
+ const style = options.style ?? 'short';
195
+ return cached(
196
+ `w|${options.locale}|${style}`,
197
+ () => new Intl.DateTimeFormat(options.locale, { weekday: style }),
198
+ ).format(date);
199
+ }
200
+
201
+ /** A month and its year: November 2026; `style: 'short'` writes Nov, for a chart axis of months. */
202
+ export function formatMonth(
203
+ value: Date | string | number,
204
+ options: { locale?: Locale; style?: 'long' | 'short' } = {},
205
+ ): string {
206
+ const date = toDate(value);
207
+ if (!date) return '';
208
+ const style = options.style ?? 'long';
209
+ return cached(
210
+ `mo|${options.locale}|${style}`,
211
+ () =>
212
+ new Intl.DateTimeFormat(
213
+ options.locale,
214
+ style === 'short'
215
+ ? { month: 'short' }
216
+ : { month: 'long', year: 'numeric' },
217
+ ),
218
+ ).format(date);
219
+ }
220
+
221
+ /** A day with its weekday, for a heading over that day's items: Monday 9 November. */
222
+ export function formatDay(
223
+ value: Date | string | number,
224
+ options: { locale?: Locale } = {},
225
+ ): string {
226
+ const date = toDate(value);
227
+ if (!date) return '';
228
+ return cached(
229
+ `dy|${options.locale}`,
230
+ () =>
231
+ new Intl.DateTimeFormat(options.locale, {
232
+ weekday: 'long',
233
+ day: 'numeric',
234
+ month: 'long',
235
+ }),
236
+ ).format(date);
237
+ }
238
+
239
+ /** A span of days written once where the ends share a month or year: 9 – 15 Nov 2026. */
240
+ export function formatDayRange(
241
+ from: Date | string | number,
242
+ to: Date | string | number,
243
+ options: { locale?: Locale } = {},
244
+ ): string {
245
+ const start = toDate(from);
246
+ const end = toDate(to);
247
+ if (!start || !end) return '';
248
+ return (
249
+ cached(
250
+ `d|${options.locale}|true`,
251
+ () =>
252
+ new Intl.DateTimeFormat(options.locale, {
253
+ day: 'numeric',
254
+ month: 'short',
255
+ year: 'numeric',
256
+ }),
257
+ ) as Intl.DateTimeFormat
258
+ ).formatRange(start, end);
259
+ }
260
+
261
+ const RELATIVE_STEPS: [Intl.RelativeTimeFormatUnit, number][] = [
262
+ ['second', 60],
263
+ ['minute', 60],
264
+ ['hour', 24],
265
+ ['day', 7],
266
+ ['week', 4.34524],
267
+ ['month', 12],
268
+ ['year', Number.POSITIVE_INFINITY],
269
+ ];
270
+
271
+ /** How long ago or from now: "3 days ago", "in 2 hours", "now". */
272
+ export function formatRelative(
273
+ value: Date | string | number,
274
+ options: { locale?: Locale; now?: Date } = {},
275
+ ): string {
276
+ const date = toDate(value);
277
+ if (!date) return '';
278
+ const format = cached(
279
+ `r|${options.locale}`,
280
+ () => new Intl.RelativeTimeFormat(options.locale, { numeric: 'auto' }),
281
+ );
282
+ let amount = (date.getTime() - (options.now ?? new Date()).getTime()) / 1000;
283
+ if (Math.abs(amount) < 45) return format.format(0, 'second');
284
+ for (const [unit, size] of RELATIVE_STEPS) {
285
+ // Compare the rounded amount, so 11.99 months reads as a year, not "12 months ago".
286
+ if (Math.abs(Math.round(amount)) < size)
287
+ return format.format(Math.round(amount), unit);
288
+ amount /= size;
289
+ }
290
+ return format.format(Math.round(amount), 'year');
291
+ }