@underpin/ui 0.0.0-stage → 2.0.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 (258) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -2
  3. package/components/autocomplete.d.ts +25 -0
  4. package/components/autocomplete.js +71 -0
  5. package/components/autocomplete.js.map +1 -0
  6. package/components/avatar.d.ts +5 -0
  7. package/components/avatar.js +26 -0
  8. package/components/avatar.js.map +1 -0
  9. package/components/badge.d.ts +36 -0
  10. package/components/badge.js +140 -0
  11. package/components/badge.js.map +1 -0
  12. package/components/bar-list.d.ts +133 -0
  13. package/components/bar-list.js +204 -0
  14. package/components/bar-list.js.map +1 -0
  15. package/components/breakdown-card.d.ts +30 -0
  16. package/components/breakdown-card.js +43 -0
  17. package/components/breakdown-card.js.map +1 -0
  18. package/components/button-group.d.ts +17 -0
  19. package/components/button-group.js +27 -0
  20. package/components/button-group.js.map +1 -0
  21. package/components/button.d.ts +39 -0
  22. package/components/button.js +128 -0
  23. package/components/button.js.map +1 -0
  24. package/components/calendar.d.ts +27 -0
  25. package/components/calendar.js +95 -0
  26. package/components/calendar.js.map +1 -0
  27. package/components/callout.d.ts +26 -0
  28. package/components/callout.js +71 -0
  29. package/components/callout.js.map +1 -0
  30. package/components/card.d.ts +55 -0
  31. package/components/card.js +96 -0
  32. package/components/card.js.map +1 -0
  33. package/components/chart.d.ts +32 -0
  34. package/components/chart.js +43 -0
  35. package/components/chart.js.map +1 -0
  36. package/components/checkbox.d.ts +15 -0
  37. package/components/checkbox.js +42 -0
  38. package/components/checkbox.js.map +1 -0
  39. package/components/code-block.d.ts +21 -0
  40. package/components/code-block.js +35 -0
  41. package/components/code-block.js.map +1 -0
  42. package/components/collapse.d.ts +14 -0
  43. package/components/collapse.js +25 -0
  44. package/components/collapse.js.map +1 -0
  45. package/components/combobox.d.ts +71 -0
  46. package/components/combobox.js +155 -0
  47. package/components/combobox.js.map +1 -0
  48. package/components/copy-button.d.ts +29 -0
  49. package/components/copy-button.js +100 -0
  50. package/components/copy-button.js.map +1 -0
  51. package/components/copy-input.d.ts +15 -0
  52. package/components/copy-input.js +51 -0
  53. package/components/copy-input.js.map +1 -0
  54. package/components/date-picker-trigger.d.ts +12 -0
  55. package/components/date-picker-trigger.js +30 -0
  56. package/components/date-picker-trigger.js.map +1 -0
  57. package/components/date-picker.d.ts +36 -0
  58. package/components/date-picker.js +70 -0
  59. package/components/date-picker.js.map +1 -0
  60. package/components/detail-row.d.ts +51 -0
  61. package/components/detail-row.js +77 -0
  62. package/components/detail-row.js.map +1 -0
  63. package/components/dialog.d.ts +121 -0
  64. package/components/dialog.js +327 -0
  65. package/components/dialog.js.map +1 -0
  66. package/components/disabled-reason.d.ts +31 -0
  67. package/components/disabled-reason.js +67 -0
  68. package/components/disabled-reason.js.map +1 -0
  69. package/components/empty-state.d.ts +41 -0
  70. package/components/empty-state.js +84 -0
  71. package/components/empty-state.js.map +1 -0
  72. package/components/entity-avatar.d.ts +54 -0
  73. package/components/entity-avatar.js +68 -0
  74. package/components/entity-avatar.js.map +1 -0
  75. package/components/form-section.d.ts +22 -0
  76. package/components/form-section.js +38 -0
  77. package/components/form-section.js.map +1 -0
  78. package/components/form.d.ts +199 -0
  79. package/components/form.js +456 -0
  80. package/components/form.js.map +1 -0
  81. package/components/formatted-number.d.ts +21 -0
  82. package/components/formatted-number.js +13 -0
  83. package/components/formatted-number.js.map +1 -0
  84. package/components/heading.d.ts +23 -0
  85. package/components/heading.js +44 -0
  86. package/components/heading.js.map +1 -0
  87. package/components/icon-swap.d.ts +15 -0
  88. package/components/icon-swap.js +29 -0
  89. package/components/icon-swap.js.map +1 -0
  90. package/components/inline-action.d.ts +21 -0
  91. package/components/inline-action.js +36 -0
  92. package/components/inline-action.js.map +1 -0
  93. package/components/input.d.ts +51 -0
  94. package/components/input.js +52 -0
  95. package/components/input.js.map +1 -0
  96. package/components/kbd.d.ts +17 -0
  97. package/components/kbd.js +34 -0
  98. package/components/kbd.js.map +1 -0
  99. package/components/label.d.ts +10 -0
  100. package/components/label.js +20 -0
  101. package/components/label.js.map +1 -0
  102. package/components/menu.d.ts +77 -0
  103. package/components/menu.js +189 -0
  104. package/components/menu.js.map +1 -0
  105. package/components/nav-button.d.ts +34 -0
  106. package/components/nav-button.js +71 -0
  107. package/components/nav-button.js.map +1 -0
  108. package/components/nav.d.ts +39 -0
  109. package/components/nav.js +68 -0
  110. package/components/nav.js.map +1 -0
  111. package/components/number-input.d.ts +16 -0
  112. package/components/number-input.js +25 -0
  113. package/components/number-input.js.map +1 -0
  114. package/components/page.d.ts +14 -0
  115. package/components/page.js +23 -0
  116. package/components/page.js.map +1 -0
  117. package/components/pagination.d.ts +15 -0
  118. package/components/pagination.js +63 -0
  119. package/components/pagination.js.map +1 -0
  120. package/components/ping.d.ts +38 -0
  121. package/components/ping.js +50 -0
  122. package/components/ping.js.map +1 -0
  123. package/components/popover.d.ts +5 -0
  124. package/components/popover.js +25 -0
  125. package/components/popover.js.map +1 -0
  126. package/components/radio-group.d.ts +35 -0
  127. package/components/radio-group.js +81 -0
  128. package/components/radio-group.js.map +1 -0
  129. package/components/relative-time.d.ts +25 -0
  130. package/components/relative-time.js +51 -0
  131. package/components/relative-time.js.map +1 -0
  132. package/components/saved-mark.d.ts +15 -0
  133. package/components/saved-mark.js +45 -0
  134. package/components/saved-mark.js.map +1 -0
  135. package/components/search-input.d.ts +13 -0
  136. package/components/search-input.js +44 -0
  137. package/components/search-input.js.map +1 -0
  138. package/components/section-header.d.ts +83 -0
  139. package/components/section-header.js +170 -0
  140. package/components/section-header.js.map +1 -0
  141. package/components/segmented-control.d.ts +24 -0
  142. package/components/segmented-control.js +70 -0
  143. package/components/segmented-control.js.map +1 -0
  144. package/components/select.d.ts +28 -0
  145. package/components/select.js +129 -0
  146. package/components/select.js.map +1 -0
  147. package/components/shortcut-keys.d.ts +14 -0
  148. package/components/shortcut-keys.js +32 -0
  149. package/components/shortcut-keys.js.map +1 -0
  150. package/components/shortcuts-dialog.d.ts +10 -0
  151. package/components/shortcuts-dialog.js +92 -0
  152. package/components/shortcuts-dialog.js.map +1 -0
  153. package/components/skeleton.d.ts +8 -0
  154. package/components/skeleton.js +23 -0
  155. package/components/skeleton.js.map +1 -0
  156. package/components/sparkline.d.ts +25 -0
  157. package/components/sparkline.js +70 -0
  158. package/components/sparkline.js.map +1 -0
  159. package/components/stack.d.ts +21 -0
  160. package/components/stack.js +45 -0
  161. package/components/stack.js.map +1 -0
  162. package/components/stat-strip.d.ts +43 -0
  163. package/components/stat-strip.js +151 -0
  164. package/components/stat-strip.js.map +1 -0
  165. package/components/steps.d.ts +19 -0
  166. package/components/steps.js +25 -0
  167. package/components/steps.js.map +1 -0
  168. package/components/switch.d.ts +16 -0
  169. package/components/switch.js +29 -0
  170. package/components/switch.js.map +1 -0
  171. package/components/tabs.d.ts +18 -0
  172. package/components/tabs.js +65 -0
  173. package/components/tabs.js.map +1 -0
  174. package/components/text-link.d.ts +16 -0
  175. package/components/text-link.js +32 -0
  176. package/components/text-link.js.map +1 -0
  177. package/components/textarea.d.ts +10 -0
  178. package/components/textarea.js +23 -0
  179. package/components/textarea.js.map +1 -0
  180. package/components/theme.d.ts +28 -0
  181. package/components/theme.js +158 -0
  182. package/components/theme.js.map +1 -0
  183. package/components/time-series-chart.d.ts +122 -0
  184. package/components/time-series-chart.js +722 -0
  185. package/components/time-series-chart.js.map +1 -0
  186. package/components/toaster.d.ts +3 -0
  187. package/components/toaster.js +44 -0
  188. package/components/toaster.js.map +1 -0
  189. package/components/tooltip.d.ts +64 -0
  190. package/components/tooltip.js +126 -0
  191. package/components/tooltip.js.map +1 -0
  192. package/components/view-picker.d.ts +20 -0
  193. package/components/view-picker.js +24 -0
  194. package/components/view-picker.js.map +1 -0
  195. package/fonts/inter-OFL.txt +93 -0
  196. package/fonts/inter-cyrillic-ext.woff2 +0 -0
  197. package/fonts/inter-cyrillic.woff2 +0 -0
  198. package/fonts/inter-greek-ext.woff2 +0 -0
  199. package/fonts/inter-greek.woff2 +0 -0
  200. package/fonts/inter-latin-ext.woff2 +0 -0
  201. package/fonts/inter-latin.woff2 +0 -0
  202. package/fonts/inter-vietnamese.woff2 +0 -0
  203. package/fonts.css +83 -0
  204. package/lib/animation.d.ts +14 -0
  205. package/lib/animation.js +20 -0
  206. package/lib/animation.js.map +1 -0
  207. package/lib/aria.d.ts +5 -0
  208. package/lib/aria.js +12 -0
  209. package/lib/aria.js.map +1 -0
  210. package/lib/chart-curve.d.ts +13 -0
  211. package/lib/chart-curve.js +79 -0
  212. package/lib/chart-curve.js.map +1 -0
  213. package/lib/classes.d.ts +134 -0
  214. package/lib/classes.js +152 -0
  215. package/lib/classes.js.map +1 -0
  216. package/lib/color.d.ts +25 -0
  217. package/lib/color.js +149 -0
  218. package/lib/color.js.map +1 -0
  219. package/lib/day.d.ts +9 -0
  220. package/lib/day.js +20 -0
  221. package/lib/day.js.map +1 -0
  222. package/lib/design-tokens.d.ts +56 -0
  223. package/lib/design-tokens.js +196 -0
  224. package/lib/design-tokens.js.map +1 -0
  225. package/lib/icon.d.ts +17 -0
  226. package/lib/icon.js +34 -0
  227. package/lib/icon.js.map +1 -0
  228. package/lib/icons.d.ts +23 -0
  229. package/lib/icons.js +28 -0
  230. package/lib/icons.js.map +1 -0
  231. package/lib/interactive.d.ts +21 -0
  232. package/lib/interactive.js +31 -0
  233. package/lib/interactive.js.map +1 -0
  234. package/lib/media.d.ts +58 -0
  235. package/lib/media.js +116 -0
  236. package/lib/media.js.map +1 -0
  237. package/lib/segmented.d.ts +57 -0
  238. package/lib/segmented.js +83 -0
  239. package/lib/segmented.js.map +1 -0
  240. package/lib/shortcuts.d.ts +94 -0
  241. package/lib/shortcuts.js +271 -0
  242. package/lib/shortcuts.js.map +1 -0
  243. package/lib/slot.d.ts +9 -0
  244. package/lib/slot.js +18 -0
  245. package/lib/slot.js.map +1 -0
  246. package/lib/time-series.d.ts +100 -0
  247. package/lib/time-series.js +144 -0
  248. package/lib/time-series.js.map +1 -0
  249. package/lib/tone.d.ts +6 -0
  250. package/lib/tone.js +0 -0
  251. package/lib/variants.d.ts +12 -0
  252. package/lib/variants.js +14 -0
  253. package/lib/variants.js.map +1 -0
  254. package/package.json +116 -4
  255. package/styles.css +619 -0
  256. package/tokens.d.ts +104 -0
  257. package/tokens.js +108 -0
  258. package/tokens.js.map +1 -0
@@ -0,0 +1,271 @@
1
+ "use client";
2
+ import { useEffect, useRef, useSyncExternalStore } from "react";
3
+ import { useHotkeys } from "react-hotkeys-hook";
4
+ // src/lib/shortcuts.ts
5
+ const EMPTY = [];
6
+ const listeners = /* @__PURE__ */ new Set();
7
+ let registrations = [];
8
+ let snapshot = EMPTY;
9
+ /** Rebuilt once per change, so `useSyncExternalStore` sees a referentially stable snapshot. */
10
+ function publish() {
11
+ const groups = /* @__PURE__ */ new Map();
12
+ const seen = /* @__PURE__ */ new Set();
13
+ for (const { group, keys, label } of registrations) {
14
+ const id = `${group}\t${keys}\t${label}`;
15
+ if (seen.has(id)) continue;
16
+ seen.add(id);
17
+ const existing = groups.get(group) ?? {
18
+ group,
19
+ shortcuts: []
20
+ };
21
+ existing.shortcuts.push({
22
+ keys,
23
+ label
24
+ });
25
+ groups.set(group, existing);
26
+ }
27
+ snapshot = groups.size ? [...groups.values()] : EMPTY;
28
+ for (const listener of listeners) listener();
29
+ }
30
+ /** Add rows to the registry and get back the call that removes them. `useShortcuts` is the way in. */
31
+ function registerShortcuts(entries) {
32
+ registrations = [...registrations, ...entries];
33
+ publish();
34
+ return () => {
35
+ registrations = registrations.filter((entry) => !entries.includes(entry));
36
+ publish();
37
+ };
38
+ }
39
+ function subscribe(onChange) {
40
+ listeners.add(onChange);
41
+ return () => void listeners.delete(onChange);
42
+ }
43
+ /** The current list outside React, for tests. */
44
+ function getShortcutList() {
45
+ return snapshot;
46
+ }
47
+ /** The shortcuts mounted right now, grouped, for the reference dialog. Empty on the server. */
48
+ function useShortcutList() {
49
+ return useSyncExternalStore(subscribe, () => snapshot, () => EMPTY);
50
+ }
51
+ /**
52
+ * `useKey`: match the character the key produced, not its physical position, so `d` is the key
53
+ * labelled D on an AZERTY keyboard too. Form tags are filtered per shortcut below, and
54
+ * `preventDefault` is ours: the library would run it before knowing whether anything matched.
55
+ *
56
+ * `capture`: an open Base UI popup (a menu, a select) calls `stopPropagation` on every printable
57
+ * key to feed its own typeahead, so a listener on the document would never see the keys a
58
+ * dropdown covers. Capturing runs the page's shortcuts first, and a match stops the key there.
59
+ */
60
+ const HOTKEY_OPTIONS = {
61
+ useKey: true,
62
+ enableOnFormTags: true,
63
+ enableOnContentEditable: true,
64
+ eventListenerOptions: { capture: true }
65
+ };
66
+ /**
67
+ * Widgets that take every key typed inside them: an open modal, and the popups that read a
68
+ * printable key as typeahead.
69
+ */
70
+ const KEY_OWNER_SELECTOR = "[role=\"dialog\"],[role=\"menu\"],[role=\"menubar\"],[role=\"listbox\"]";
71
+ /** Composite widgets that move their own focus with the keys below and leave the rest alone. */
72
+ const NAVIGATOR_SELECTOR = "[role=\"tablist\"],[role=\"grid\"],[role=\"radiogroup\"]";
73
+ const NAVIGATION_KEYS = [
74
+ "ArrowLeft",
75
+ "ArrowRight",
76
+ "ArrowUp",
77
+ "ArrowDown",
78
+ "Home",
79
+ "End"
80
+ ];
81
+ /** A menu's rows of every kind: an item, a radio and a checkbox. */
82
+ const MENU_ROW_SELECTOR = "[role=\"menuitem\"],[role=\"menuitemradio\"],[role=\"menuitemcheckbox\"]";
83
+ const FORM_TAGS = [
84
+ "INPUT",
85
+ "TEXTAREA",
86
+ "SELECT"
87
+ ];
88
+ function isFormTarget(target) {
89
+ return !!target && (FORM_TAGS.includes(target.tagName) || target.isContentEditable);
90
+ }
91
+ /**
92
+ * A key string as the library reports the hotkey it matched, lower-cased and trimmed, so two can
93
+ * be compared like for like. A shortcut badge names its key this way in `data-shortcut`.
94
+ */
95
+ function toHotkey(keys) {
96
+ return keys.trim().toLowerCase();
97
+ }
98
+ /** The badge an open menu prints for `key`, found by the `data-shortcut` the badge carries. */
99
+ function findMenuBadge(menu, key) {
100
+ const hotkey = toHotkey(key);
101
+ return [...menu.querySelectorAll("[data-shortcut]")].find((badge) => badge.dataset.shortcut === hotkey);
102
+ }
103
+ /**
104
+ * Whether `key` is one an open menu prints outside its rows, a hint beside a control in the menu
105
+ * such as the date range's "Show by B": it stays the page's shortcut, so pressing it does what
106
+ * the hint says. A row's own badge belongs to the menu, which picks that row instead.
107
+ */
108
+ function isMenuHint(owner, target, key) {
109
+ if (!owner.matches("[role=\"menu\"]") || isFormTarget(target)) return false;
110
+ const badge = findMenuBadge(owner, key);
111
+ return !!badge && !badge.closest(MENU_ROW_SELECTOR);
112
+ }
113
+ /**
114
+ * Whether a key typed over `target` belongs to the widget around it rather than to the page's
115
+ * shortcuts. Anything typed inside an open modal belongs to that modal, the shortcuts the modal
116
+ * registered itself included; that is the ceiling on one flat registry, and per-modal scopes
117
+ * (react-hotkeys-hook's HotkeysProvider) are what lifts it. A menu or a listbox reads letters as
118
+ * typeahead, so it keeps every key too, except the keys a menu prints: a row's badge picks that
119
+ * row (`findShortcutRow`), and a hint outside the rows stays the page's. Tabs, a grid and a
120
+ * radio group only step with the arrow keys, Home and End: stepping through a card's tabs must
121
+ * not also step the date range, but a letter typed after clicking a tab still reaches the page.
122
+ */
123
+ function isWidgetKey(target, key) {
124
+ if (!target) return false;
125
+ const owner = target.closest(KEY_OWNER_SELECTOR);
126
+ if (owner) return !isMenuHint(owner, target, key);
127
+ return NAVIGATION_KEYS.includes(key) && !!target.closest(NAVIGATOR_SELECTOR);
128
+ }
129
+ /** A text field with nothing typed in it yet, so a key pressed there is not part of a query. */
130
+ function isEmptyField(target) {
131
+ return (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) && target.value === "";
132
+ }
133
+ /**
134
+ * The row of an open menu whose badge shows the key pressed, for the menu to pick as a click
135
+ * would. The letters printed beside the rows answer ahead of the menu's typeahead, which would
136
+ * jump to the first row starting with that letter instead. Only a single character counts, with
137
+ * no Ctrl, Cmd or Alt held (Shift may be, for a `?`). In a field in the menu, such as its search,
138
+ * a key counts only while the field is empty: the search takes focus as the menu opens, and the
139
+ * keys printed on its rows still work then, while a query once begun keeps every key it types.
140
+ */
141
+ function findShortcutRow(menu, event) {
142
+ const { key, ctrlKey, metaKey, altKey, target } = event;
143
+ if (ctrlKey || metaKey || altKey || key.length !== 1 || key === " ") return;
144
+ if (target instanceof Element && isFormTarget(target) && !isEmptyField(target)) return;
145
+ return findMenuBadge(menu, key)?.closest(MENU_ROW_SELECTOR) ?? void 0;
146
+ }
147
+ /**
148
+ * Register any number of shortcuts for as long as the component is mounted. One `useHotkeys` call
149
+ * carries them all, since the list may change length between renders, and the callback routes
150
+ * back to the right handler by the hotkey string the library matched.
151
+ */
152
+ function useShortcuts(shortcuts) {
153
+ const active = shortcuts.filter((shortcut) => shortcut.enabled !== false);
154
+ const activeRef = useRef(active);
155
+ useEffect(() => {
156
+ activeRef.current = active;
157
+ });
158
+ const hotkeys = [...new Set(active.map((shortcut) => toHotkey(shortcut.keys)))].join(",");
159
+ useHotkeys(hotkeys, (event, hotkeysEvent) => {
160
+ if (event.repeat) return;
161
+ const target = event.target instanceof Element ? event.target : null;
162
+ if (isWidgetKey(target, event.key)) return;
163
+ const typing = isFormTarget(target);
164
+ const matched = activeRef.current.filter((shortcut) => toHotkey(shortcut.keys) === hotkeysEvent.hotkey && (shortcut.enableOnFormTags === true || !typing));
165
+ if (matched.length === 0) return;
166
+ event.preventDefault();
167
+ event.stopPropagation();
168
+ for (const shortcut of matched) shortcut.handler(event);
169
+ }, HOTKEY_OPTIONS);
170
+ const signature = active.map((shortcut) => `${shortcut.group}\t${shortcut.keys}\t${shortcut.label}`).join("\n");
171
+ useEffect(() => {
172
+ return registerShortcuts(activeRef.current.map(({ group, keys, label }) => ({
173
+ group,
174
+ keys,
175
+ label
176
+ })));
177
+ }, [signature]);
178
+ }
179
+ /** A single shortcut, for the common case. */
180
+ function useShortcut(shortcut) {
181
+ useShortcuts([shortcut]);
182
+ }
183
+ /** In Apple order (control, option, shift, command): [mac glyph, label elsewhere]. */
184
+ const MODIFIERS = {
185
+ ctrl: ["⌃", "Ctrl"],
186
+ alt: ["⌥", "Alt"],
187
+ shift: ["⇧", "⇧"],
188
+ mod: ["⌘", "Ctrl"]
189
+ };
190
+ /** Each modifier as a screen reader should say it: [on a mac, elsewhere]. */
191
+ const SPOKEN_MODIFIERS = {
192
+ ctrl: ["Control", "Control"],
193
+ alt: ["Option", "Alt"],
194
+ shift: ["Shift", "Shift"],
195
+ mod: ["Command", "Control"]
196
+ };
197
+ const KEY_LABELS = {
198
+ left: "←",
199
+ right: "→",
200
+ up: "↑",
201
+ down: "↓",
202
+ esc: "Esc",
203
+ escape: "Esc",
204
+ enter: "↵",
205
+ space: "Space"
206
+ };
207
+ /** The keys whose badge is a glyph a screen reader would name by its Unicode name. */
208
+ const SPOKEN_KEYS = {
209
+ left: "Left arrow",
210
+ right: "Right arrow",
211
+ up: "Up arrow",
212
+ down: "Down arrow",
213
+ esc: "Escape",
214
+ escape: "Escape",
215
+ enter: "Enter"
216
+ };
217
+ /**
218
+ * Deliberately the same rule react-hotkeys-hook applies internally to decide whether `mod`
219
+ * means Meta or Control. It does not export it, and it only ever runs on a keystroke, so it
220
+ * cannot be reused, but it is the authority on what `mod` actually matches. Detecting the
221
+ * platform some other way (navigator.platform, userAgentData) risks a badge that says ⌘ while
222
+ * the matcher is waiting for Ctrl, and the label would be lying about the shortcut.
223
+ */
224
+ function isMacUserAgent(userAgent) {
225
+ return /mac/i.test(userAgent) && !/iphone|ipad|ipod/i.test(userAgent);
226
+ }
227
+ /** Read at call time, not at import: on the server there is no navigator at all. */
228
+ function readIsMac() {
229
+ return typeof navigator !== "undefined" && isMacUserAgent(navigator.userAgent);
230
+ }
231
+ function noSubscribe() {
232
+ return () => {};
233
+ }
234
+ /**
235
+ * Whether to spell shortcuts the Apple way. A hook rather than a module constant because this
236
+ * package renders under SSR: read at import time, the server produced "Ctrl" and the client
237
+ * hydrated "⌘", which is a hydration mismatch on every shortcut badge. Returning false as the
238
+ * server snapshot makes the first client render agree, then React re-renders with the truth.
239
+ */
240
+ function useIsMac() {
241
+ return useSyncExternalStore(noSubscribe, readIsMac, () => false);
242
+ }
243
+ /** A key string split into its modifiers, in Apple order, and its key. */
244
+ function parseKeys(keys) {
245
+ const parts = toHotkey(keys).split("+").map((part) => part.trim());
246
+ const key = parts.find((part) => !(part in MODIFIERS)) ?? "";
247
+ const written = parts.filter((part) => part in MODIFIERS);
248
+ return {
249
+ modifiers: written.length === 1 && written[0] === "shift" && /^[^a-z0-9]$/.test(key) ? [] : Object.keys(MODIFIERS).filter((modifier) => written.includes(modifier)),
250
+ key
251
+ };
252
+ }
253
+ function formatKeyName(key) {
254
+ return `${key.charAt(0).toUpperCase()}${key.slice(1)}`;
255
+ }
256
+ /** A key string as badge parts: the modifiers in Apple order, then the key. Platform injectable for tests. */
257
+ function formatKeys(keys, mac = readIsMac()) {
258
+ const { modifiers, key } = parseKeys(keys);
259
+ return [...modifiers.map((modifier) => MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier), KEY_LABELS[key] ?? formatKeyName(key)];
260
+ }
261
+ /**
262
+ * A key string as a screen reader should say it ("Command K"): the badge's glyphs would be read
263
+ * by their Unicode names, "place of interest sign" for ⌘. Platform injectable for tests.
264
+ */
265
+ function formatSpokenKeys(keys, mac = readIsMac()) {
266
+ const { modifiers, key } = parseKeys(keys);
267
+ return [...modifiers.map((modifier) => SPOKEN_MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier), SPOKEN_KEYS[key] ?? formatKeyName(key)].join(" ");
268
+ }
269
+ export { findShortcutRow, formatKeys, formatSpokenKeys, getShortcutList, isMacUserAgent, isWidgetKey, registerShortcuts, toHotkey, useIsMac, useShortcut, useShortcutList, useShortcuts };
270
+
271
+ //# sourceMappingURL=shortcuts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shortcuts.js","names":[],"sources":["../../src/lib/shortcuts.ts"],"sourcesContent":["\"use client\"\n\nimport { useEffect, useRef, useSyncExternalStore } from \"react\"\nimport { useHotkeys } from \"react-hotkeys-hook\"\n\nexport interface Shortcut {\n /**\n * react-hotkeys-hook key string: `d`, `mod+k`, `shift+?`, `left`. Matched on the character the\n * key produces, so a letter is the key labelled with it on any layout.\n */\n keys: string\n\n /** Human label shown in the reference dialog, e.g. \"Today\". */\n label: string\n\n /** Section in the reference dialog, e.g. \"Date range\". Sections appear in registration order. */\n group: string\n\n handler: (event: KeyboardEvent) => void\n\n /** Default true. A disabled shortcut neither fires nor shows up in the reference dialog. */\n enabled?: boolean\n\n /** Fire while typing in inputs, textareas, selects and contenteditable. Default false. */\n enableOnFormTags?: boolean\n}\n\nexport interface ShortcutGroup {\n group: string\n shortcuts: { keys: string; label: string }[]\n}\n\n/** What `findShortcutRow` reads off a key press: a DOM event or React's. */\nexport interface MenuKeyEvent {\n key: string\n ctrlKey: boolean\n metaKey: boolean\n altKey: boolean\n target: EventTarget | null\n}\n\n// The registry the reference dialog is built from: every mounted shortcut's metadata, in\n// registration order, behind a `useSyncExternalStore` snapshot.\n\ntype Registration = Pick<Shortcut, \"group\" | \"keys\" | \"label\">\n\nconst EMPTY: ShortcutGroup[] = []\nconst listeners = new Set<() => void>()\n\nlet registrations: Registration[] = []\nlet snapshot = EMPTY\n\n/** Rebuilt once per change, so `useSyncExternalStore` sees a referentially stable snapshot. */\nfunction publish() {\n const groups = new Map<string, ShortcutGroup>()\n const seen = new Set<string>()\n\n for (const { group, keys, label } of registrations) {\n const id = `${group}\\t${keys}\\t${label}`\n if (seen.has(id)) continue\n seen.add(id)\n\n const existing = groups.get(group) ?? { group, shortcuts: [] }\n existing.shortcuts.push({ keys, label })\n groups.set(group, existing)\n }\n\n snapshot = groups.size ? [...groups.values()] : EMPTY\n for (const listener of listeners) listener()\n}\n\n/** Add rows to the registry and get back the call that removes them. `useShortcuts` is the way in. */\nexport function registerShortcuts(entries: Registration[]) {\n registrations = [...registrations, ...entries]\n publish()\n\n return () => {\n registrations = registrations.filter(entry => !entries.includes(entry))\n publish()\n }\n}\n\nfunction subscribe(onChange: () => void) {\n listeners.add(onChange)\n return () => void listeners.delete(onChange)\n}\n\n/** The current list outside React, for tests. */\nexport function getShortcutList() {\n return snapshot\n}\n\n/** The shortcuts mounted right now, grouped, for the reference dialog. Empty on the server. */\nexport function useShortcutList(): ShortcutGroup[] {\n return useSyncExternalStore(\n subscribe,\n () => snapshot,\n () => EMPTY,\n )\n}\n\n// Matching a keystroke to a handler.\n\n/**\n * `useKey`: match the character the key produced, not its physical position, so `d` is the key\n * labelled D on an AZERTY keyboard too. Form tags are filtered per shortcut below, and\n * `preventDefault` is ours: the library would run it before knowing whether anything matched.\n *\n * `capture`: an open Base UI popup (a menu, a select) calls `stopPropagation` on every printable\n * key to feed its own typeahead, so a listener on the document would never see the keys a\n * dropdown covers. Capturing runs the page's shortcuts first, and a match stops the key there.\n */\nconst HOTKEY_OPTIONS = {\n useKey: true,\n enableOnFormTags: true,\n enableOnContentEditable: true,\n eventListenerOptions: { capture: true },\n}\n\n/**\n * Widgets that take every key typed inside them: an open modal, and the popups that read a\n * printable key as typeahead.\n */\nconst KEY_OWNER_SELECTOR = '[role=\"dialog\"],[role=\"menu\"],[role=\"menubar\"],[role=\"listbox\"]'\n\n/** Composite widgets that move their own focus with the keys below and leave the rest alone. */\nconst NAVIGATOR_SELECTOR = '[role=\"tablist\"],[role=\"grid\"],[role=\"radiogroup\"]'\nconst NAVIGATION_KEYS = [\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\", \"Home\", \"End\"]\n\n/** A menu's rows of every kind: an item, a radio and a checkbox. */\nconst MENU_ROW_SELECTOR = '[role=\"menuitem\"],[role=\"menuitemradio\"],[role=\"menuitemcheckbox\"]'\n\nconst FORM_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"]\n\nfunction isFormTarget(target: Element | null) {\n return (\n !!target && (FORM_TAGS.includes(target.tagName) || (target as HTMLElement).isContentEditable)\n )\n}\n\n/**\n * A key string as the library reports the hotkey it matched, lower-cased and trimmed, so two can\n * be compared like for like. A shortcut badge names its key this way in `data-shortcut`.\n */\nexport function toHotkey(keys: string) {\n return keys.trim().toLowerCase()\n}\n\n/** The badge an open menu prints for `key`, found by the `data-shortcut` the badge carries. */\nfunction findMenuBadge(menu: Element, key: string) {\n const hotkey = toHotkey(key)\n return [...menu.querySelectorAll<HTMLElement>(\"[data-shortcut]\")].find(\n badge => badge.dataset.shortcut === hotkey,\n )\n}\n\n/**\n * Whether `key` is one an open menu prints outside its rows, a hint beside a control in the menu\n * such as the date range's \"Show by B\": it stays the page's shortcut, so pressing it does what\n * the hint says. A row's own badge belongs to the menu, which picks that row instead.\n */\nfunction isMenuHint(owner: Element, target: Element, key: string) {\n if (!owner.matches('[role=\"menu\"]') || isFormTarget(target)) return false\n const badge = findMenuBadge(owner, key)\n return !!badge && !badge.closest(MENU_ROW_SELECTOR)\n}\n\n/**\n * Whether a key typed over `target` belongs to the widget around it rather than to the page's\n * shortcuts. Anything typed inside an open modal belongs to that modal, the shortcuts the modal\n * registered itself included; that is the ceiling on one flat registry, and per-modal scopes\n * (react-hotkeys-hook's HotkeysProvider) are what lifts it. A menu or a listbox reads letters as\n * typeahead, so it keeps every key too, except the keys a menu prints: a row's badge picks that\n * row (`findShortcutRow`), and a hint outside the rows stays the page's. Tabs, a grid and a\n * radio group only step with the arrow keys, Home and End: stepping through a card's tabs must\n * not also step the date range, but a letter typed after clicking a tab still reaches the page.\n */\nexport function isWidgetKey(target: Element | null, key: string) {\n if (!target) return false\n const owner = target.closest(KEY_OWNER_SELECTOR)\n if (owner) return !isMenuHint(owner, target, key)\n return NAVIGATION_KEYS.includes(key) && !!target.closest(NAVIGATOR_SELECTOR)\n}\n\n/** A text field with nothing typed in it yet, so a key pressed there is not part of a query. */\nfunction isEmptyField(target: Element) {\n return (\n (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) &&\n target.value === \"\"\n )\n}\n\n/**\n * The row of an open menu whose badge shows the key pressed, for the menu to pick as a click\n * would. The letters printed beside the rows answer ahead of the menu's typeahead, which would\n * jump to the first row starting with that letter instead. Only a single character counts, with\n * no Ctrl, Cmd or Alt held (Shift may be, for a `?`). In a field in the menu, such as its search,\n * a key counts only while the field is empty: the search takes focus as the menu opens, and the\n * keys printed on its rows still work then, while a query once begun keeps every key it types.\n */\nexport function findShortcutRow(menu: Element, event: MenuKeyEvent) {\n const { key, ctrlKey, metaKey, altKey, target } = event\n if (ctrlKey || metaKey || altKey || key.length !== 1 || key === \" \") return\n if (target instanceof Element && isFormTarget(target) && !isEmptyField(target)) return\n return findMenuBadge(menu, key)?.closest<HTMLElement>(MENU_ROW_SELECTOR) ?? undefined\n}\n\n/**\n * Register any number of shortcuts for as long as the component is mounted. One `useHotkeys` call\n * carries them all, since the list may change length between renders, and the callback routes\n * back to the right handler by the hotkey string the library matched.\n */\nexport function useShortcuts(shortcuts: Shortcut[]) {\n const active = shortcuts.filter(shortcut => shortcut.enabled !== false)\n\n // The latest handlers, read by the dispatch callback without re-registering anything.\n const activeRef = useRef(active)\n useEffect(() => {\n activeRef.current = active\n })\n\n const hotkeys = [...new Set(active.map(shortcut => toHotkey(shortcut.keys)))].join(\",\")\n\n useHotkeys(\n hotkeys,\n (event, hotkeysEvent) => {\n if (event.repeat) return\n\n const target = event.target instanceof Element ? event.target : null\n\n if (isWidgetKey(target, event.key)) return\n\n const typing = isFormTarget(target)\n const matched = activeRef.current.filter(\n shortcut =>\n toHotkey(shortcut.keys) === hotkeysEvent.hotkey &&\n (shortcut.enableOnFormTags === true || !typing),\n )\n\n if (matched.length === 0) return\n\n // The key belongs to the shortcut, not to whatever it was typed over: an open dropdown\n // should not also run its typeahead on it.\n event.preventDefault()\n event.stopPropagation()\n for (const shortcut of matched) shortcut.handler(event)\n },\n HOTKEY_OPTIONS,\n )\n\n // Only the metadata reaches the dialog, so re-register when that changes, not on every\n // render.\n const signature = active\n .map(shortcut => `${shortcut.group}\\t${shortcut.keys}\\t${shortcut.label}`)\n .join(\"\\n\")\n\n useEffect(() => {\n return registerShortcuts(\n activeRef.current.map(({ group, keys, label }) => ({ group, keys, label })),\n )\n }, [signature])\n}\n\n/** A single shortcut, for the common case. */\nexport function useShortcut(shortcut: Shortcut) {\n useShortcuts([shortcut])\n}\n\n// Spelling a key string out as badge parts.\n\n/** In Apple order (control, option, shift, command): [mac glyph, label elsewhere]. */\nconst MODIFIERS: Record<string, [string, string]> = {\n ctrl: [\"⌃\", \"Ctrl\"],\n alt: [\"⌥\", \"Alt\"],\n shift: [\"⇧\", \"⇧\"],\n mod: [\"⌘\", \"Ctrl\"],\n}\n\n/** Each modifier as a screen reader should say it: [on a mac, elsewhere]. */\nconst SPOKEN_MODIFIERS: Record<string, [string, string]> = {\n ctrl: [\"Control\", \"Control\"],\n alt: [\"Option\", \"Alt\"],\n shift: [\"Shift\", \"Shift\"],\n mod: [\"Command\", \"Control\"],\n}\n\nconst KEY_LABELS: Record<string, string> = {\n left: \"←\",\n right: \"→\",\n up: \"↑\",\n down: \"↓\",\n esc: \"Esc\",\n escape: \"Esc\",\n enter: \"↵\",\n space: \"Space\",\n}\n\n/** The keys whose badge is a glyph a screen reader would name by its Unicode name. */\nconst SPOKEN_KEYS: Record<string, string> = {\n left: \"Left arrow\",\n right: \"Right arrow\",\n up: \"Up arrow\",\n down: \"Down arrow\",\n esc: \"Escape\",\n escape: \"Escape\",\n enter: \"Enter\",\n}\n\n/**\n * Deliberately the same rule react-hotkeys-hook applies internally to decide whether `mod`\n * means Meta or Control. It does not export it, and it only ever runs on a keystroke, so it\n * cannot be reused, but it is the authority on what `mod` actually matches. Detecting the\n * platform some other way (navigator.platform, userAgentData) risks a badge that says ⌘ while\n * the matcher is waiting for Ctrl, and the label would be lying about the shortcut.\n */\nexport function isMacUserAgent(userAgent: string): boolean {\n return /mac/i.test(userAgent) && !/iphone|ipad|ipod/i.test(userAgent)\n}\n\n/** Read at call time, not at import: on the server there is no navigator at all. */\nfunction readIsMac() {\n return typeof navigator !== \"undefined\" && isMacUserAgent(navigator.userAgent)\n}\n\n// The platform never changes within a document, so the store never notifies.\nfunction noSubscribe() {\n return () => {}\n}\n\n/**\n * Whether to spell shortcuts the Apple way. A hook rather than a module constant because this\n * package renders under SSR: read at import time, the server produced \"Ctrl\" and the client\n * hydrated \"⌘\", which is a hydration mismatch on every shortcut badge. Returning false as the\n * server snapshot makes the first client render agree, then React re-renders with the truth.\n */\nexport function useIsMac() {\n return useSyncExternalStore(noSubscribe, readIsMac, () => false)\n}\n\ninterface ParsedKeys {\n /** In Apple order. */\n modifiers: string[]\n key: string\n}\n\n/** A key string split into its modifiers, in Apple order, and its key. */\nfunction parseKeys(keys: string): ParsedKeys {\n const parts = toHotkey(keys)\n .split(\"+\")\n .map(part => part.trim())\n const key = parts.find(part => !(part in MODIFIERS)) ?? \"\"\n const written = parts.filter(part => part in MODIFIERS)\n\n // `shift+?` is typed as one key; the shift is only there so the library can match it.\n const shiftedSymbol = written.length === 1 && written[0] === \"shift\" && /^[^a-z0-9]$/.test(key)\n const modifiers = shiftedSymbol\n ? []\n : Object.keys(MODIFIERS).filter(modifier => written.includes(modifier))\n\n return { modifiers, key }\n}\n\nfunction formatKeyName(key: string) {\n return `${key.charAt(0).toUpperCase()}${key.slice(1)}`\n}\n\n/** A key string as badge parts: the modifiers in Apple order, then the key. Platform injectable for tests. */\nexport function formatKeys(keys: string, mac = readIsMac()): string[] {\n const { modifiers, key } = parseKeys(keys)\n\n return [\n ...modifiers.map(modifier => MODIFIERS[modifier]?.[mac ? 0 : 1] ?? modifier),\n KEY_LABELS[key] ?? formatKeyName(key),\n ]\n}\n\n/**\n * A key string as a screen reader should say it (\"Command K\"): the badge's glyphs would be read\n * by their Unicode names, \"place of interest sign\" for ⌘. Platform injectable for tests.\n */\nexport function formatSpokenKeys(keys: string, mac = readIsMac()) {\n const { modifiers, key } = parseKeys(keys)\n\n return [\n ...modifiers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,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,MAAM,CAAC;AACrD;;AAGA,SAAgB,WAAW,MAAc,MAAM,UAAU,GAAa;CACpE,MAAM,EAAE,WAAW,QAAQ,UAAU,IAAI;CAEzC,OAAO,CACL,GAAG,UAAU,KAAI,aAAY,UAAU,SAAS,GAAG,MAAM,IAAI,MAAM,QAAQ,GAC3E,WAAW,QAAQ,cAAc,GAAG,CACtC;AACF;;;;;AAMA,SAAgB,iBAAiB,MAAc,MAAM,UAAU,GAAG;CAChE,MAAM,EAAE,WAAW,QAAQ,UAAU,IAAI;CAEzC,OAAO,CACL,GAAG,UAAU,KAAI,aAAY,iBAAiB,SAAS,GAAG,MAAM,IAAI,MAAM,QAAQ,GAClF,YAAY,QAAQ,cAAc,GAAG,CACvC,CAAC,CAAC,KAAK,GAAG;AACZ"}
package/lib/slot.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { ReactNode } from "react";
2
+ /**
3
+ * Merges props onto a React element without adding a wrapper DOM node.
4
+ * Uses Base UI's `mergeProps` for type-safe className concatenation,
5
+ * event handler composition, and style merging.
6
+ *
7
+ * Returns the element as-is if it's not a valid React element (null, undefined, text).
8
+ */
9
+ export declare function slot(element: ReactNode, props: Record<string, unknown>): ReactNode;
package/lib/slot.js ADDED
@@ -0,0 +1,18 @@
1
+ import { mergeProps } from "@base-ui/react";
2
+ import { cloneElement, isValidElement } from "react";
3
+ // src/lib/slot.ts
4
+ /**
5
+ * Merges props onto a React element without adding a wrapper DOM node.
6
+ * Uses Base UI's `mergeProps` for type-safe className concatenation,
7
+ * event handler composition, and style merging.
8
+ *
9
+ * Returns the element as-is if it's not a valid React element (null, undefined, text).
10
+ */
11
+ function slot(element, props) {
12
+ if (!isValidElement(element)) return element;
13
+ const target = element;
14
+ return cloneElement(target, mergeProps(props, target.props));
15
+ }
16
+ export { slot };
17
+
18
+ //# sourceMappingURL=slot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slot.js","names":[],"sources":["../../src/lib/slot.ts"],"sourcesContent":["import { mergeProps } from \"@base-ui/react\"\nimport { cloneElement, isValidElement, type ReactElement, type ReactNode } from \"react\"\n\n/**\n * Merges props onto a React element without adding a wrapper DOM node.\n * Uses Base UI's `mergeProps` for type-safe className concatenation,\n * event handler composition, and style merging.\n *\n * Returns the element as-is if it's not a valid React element (null, undefined, text).\n */\nexport function slot(element: ReactNode, props: Record<string, unknown>): ReactNode {\n if (!isValidElement(element)) {\n return element\n }\n\n const target = element as ReactElement<Record<string, unknown>>\n\n return cloneElement(target, mergeProps(props, target.props))\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,KAAK,SAAoB,OAA2C;CAClF,IAAI,CAAC,eAAe,OAAO,GACzB,OAAO;CAGT,MAAM,SAAS;CAEf,OAAO,aAAa,QAAQ,WAAW,OAAO,OAAO,KAAK,CAAC;AAC7D"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The arithmetic behind `TimeSeriesChart`: its point and note shapes, round grid lines, evenly
3
+ * spaced date ticks, and notes folded onto the buckets that hold them. Pure, so it is tested
4
+ * without rendering a chart.
5
+ */
6
+ export interface TimeSeriesSeries {
7
+ /** Reads `point.values[key]`. */
8
+ key: string;
9
+ label: string;
10
+ /** One of the `--color-chart-*` tokens; defaults to `SERIES_COLORS` by index. */
11
+ color?: string;
12
+ }
13
+ /** The hues of a multi-series chart's lines, in series order; a fourth line wraps to the first. */
14
+ export declare const SERIES_COLORS: string[];
15
+ export interface TimeSeriesPoint {
16
+ date: Date;
17
+ value: number;
18
+ /**
19
+ * The same bucket in a compared period, drawn as a dashed, unfilled line.
20
+ */
21
+ previous?: number;
22
+ /**
23
+ * An optional second series drawn as bars behind the line, on its own left-hand axis
24
+ * (a different unit, e.g. revenue against a traffic line). Shown when any point is above zero.
25
+ */
26
+ bar?: number;
27
+ /**
28
+ * A segment stacked on `bar`, drawn as a dashed outline: the part the bar lost (a refund
29
+ * over net revenue). Drawn, and listed in the tooltip, once any point is above zero.
30
+ */
31
+ outline?: number;
32
+ /** Multi-series mode: one figure per `TimeSeriesSeries.key`. */
33
+ values?: Record<string, number>;
34
+ /**
35
+ * The bucket covers only part of its period, so its figures read low: the last buckets while
36
+ * they are still running, or the first when a rolling range starts mid-bucket. The line
37
+ * reaches them dashed and their bars are dashed outlines, so a partial bucket never reads as
38
+ * a drop.
39
+ */
40
+ partial?: boolean;
41
+ /**
42
+ * Figures of the bucket that the chart does not draw, already formatted, listed in its
43
+ * tooltip under a hairline.
44
+ */
45
+ details?: {
46
+ label: string;
47
+ value: string;
48
+ }[];
49
+ }
50
+ export interface TimeSeriesNote {
51
+ date: Date;
52
+ text: string;
53
+ /** Who wrote it; the tooltip's small line over the text ("Piotr · Sep 10"). */
54
+ author?: string;
55
+ }
56
+ /**
57
+ * The wash under a line, as `TimeSeriesChart` and `Sparkline` draw it: a quarter of the series'
58
+ * hue at the line, fading to nothing at the baseline. Offsets run from the top of the plot.
59
+ */
60
+ export declare const AREA_FADE: readonly [{
61
+ readonly offset: 0.05;
62
+ readonly opacity: 0.25;
63
+ }, {
64
+ readonly offset: 0.95;
65
+ readonly opacity: 0.01;
66
+ }];
67
+ /** How many buckets at the end of the series are still running. */
68
+ export declare function countRunning(data: Pick<TimeSeriesPoint, "partial">[]): number;
69
+ /** How many partial buckets open the series, leaving out the running ones at its end. */
70
+ export declare function countPartialStart(data: Pick<TimeSeriesPoint, "partial">[]): number;
71
+ /** The sum of one series over the range, for the legend; a point without the key counts as zero. */
72
+ export declare function seriesTotal(data: TimeSeriesPoint[], key: string): number;
73
+ /**
74
+ * Grid lines from 0 up past `max`, all on round numbers. A plain step (1, 2, 5) wins unless the
75
+ * data would fill less than three quarters of the scale it makes, and steps whose ticks render
76
+ * the same label are ruled out: a currency axis over a few cents otherwise reads "$0.01,
77
+ * $0.01". An empty series is a plain 0–4.
78
+ */
79
+ export declare function niceTicks(max: number, { integer, format }?: {
80
+ integer?: boolean;
81
+ format?: (value: number) => string;
82
+ }): number[];
83
+ /** Grid lines over a fixed scale (a rate pinned to `[0, 100]`), in equal intervals. */
84
+ export declare function domainTicks([low, high]: [number, number]): number[];
85
+ /**
86
+ * Tick instants on a time axis: every nth bucket from the first, with the smallest whole n
87
+ * that fits `count` labels. Ticks land on real buckets and the gaps are equal, so the labels
88
+ * step by a constant amount ("2 AM, 4 AM, 6 AM") instead of drifting between 1 and 2. The
89
+ * tail bucket is dropped when it doesn't fall on the step rather than crowding the last gap.
90
+ */
91
+ export declare function pickTicks(times: number[], count: number): number[];
92
+ /**
93
+ * Notes grouped onto the bucket that holds them: a note belongs to the last bucket starting at
94
+ * or before it, so a week bucket folds in its seven days and an hourly chart shows a midnight
95
+ * note on its 00:00 bucket. Anything past the trailing bucket's `end` is outside the range and
96
+ * dropped, as is anything before the first bucket. Without an `end` the trailing bucket is taken
97
+ * to be as wide as the one before it (wrong for months, hence the parameter); a lone bucket
98
+ * then has no width to infer from, so only a note on its exact instant lands.
99
+ */
100
+ export declare function bucketNotes(times: number[], notes: TimeSeriesNote[], endOfLast?: number): Map<number, TimeSeriesNote[]>;
@@ -0,0 +1,144 @@
1
+ // src/lib/time-series.ts
2
+ /** The hues of a multi-series chart's lines, in series order; a fourth line wraps to the first. */
3
+ const SERIES_COLORS = [
4
+ "var(--color-chart-1)",
5
+ "var(--color-chart-2)",
6
+ "var(--color-chart-3)"
7
+ ];
8
+ /**
9
+ * The wash under a line, as `TimeSeriesChart` and `Sparkline` draw it: a quarter of the series'
10
+ * hue at the line, fading to nothing at the baseline. Offsets run from the top of the plot.
11
+ */
12
+ const AREA_FADE = [{
13
+ offset: .05,
14
+ opacity: .25
15
+ }, {
16
+ offset: .95,
17
+ opacity: .01
18
+ }];
19
+ /** How many buckets at the end of the series are still running. */
20
+ function countRunning(data) {
21
+ let count = 0;
22
+ while (count < data.length && data[data.length - 1 - count]?.partial) count += 1;
23
+ return count;
24
+ }
25
+ /** How many partial buckets open the series, leaving out the running ones at its end. */
26
+ function countPartialStart(data) {
27
+ const limit = data.length - countRunning(data);
28
+ let count = 0;
29
+ while (count < limit && data[count]?.partial) count += 1;
30
+ return count;
31
+ }
32
+ /** The sum of one series over the range, for the legend; a point without the key counts as zero. */
33
+ function seriesTotal(data, key) {
34
+ return data.reduce((sum, point) => sum + (point.values?.[key] ?? 0), 0);
35
+ }
36
+ /** Plainest tick steps, tried first: one of these times a power of ten. */
37
+ const PLAIN_STEPS = [
38
+ 1,
39
+ 2,
40
+ 5,
41
+ 10
42
+ ];
43
+ /** Finer steps, for the ranges no plain step fits without leaving the plot half empty. */
44
+ const FINE_STEPS = [
45
+ 1,
46
+ 1.2,
47
+ 1.5,
48
+ 2,
49
+ 2.5,
50
+ 3,
51
+ 4,
52
+ 5,
53
+ 6,
54
+ 8,
55
+ 10
56
+ ];
57
+ /** The smallest step on `ladder` that fits `raw`; a whole-number series never gets a fractional one. */
58
+ function roundStep(raw, ladder, integer) {
59
+ const power = 10 ** Math.floor(Math.log10(raw));
60
+ return ladder.map((unit) => unit * power).find((unit) => unit >= raw && (!integer || Number.isInteger(unit))) ?? raw;
61
+ }
62
+ /**
63
+ * Intervals between horizontal grid lines. Fixed rather than scaled to the data, so the
64
+ * bar axis, drawn on the same lines over its own unit, keeps one scale as the metric on the
65
+ * value axis changes; otherwise the same revenue bars resize on every switch of the stat strip.
66
+ * Four intervals also divide a `[0, 100]` rate into round quarters.
67
+ */
68
+ const GRID_INTERVALS = 4;
69
+ /** The grid lines at `step` apart, from zero. */
70
+ function ticksOf(step) {
71
+ return Array.from({ length: 5 }, (_, index) => Number((step * index).toPrecision(12)));
72
+ }
73
+ /**
74
+ * Grid lines from 0 up past `max`, all on round numbers. A plain step (1, 2, 5) wins unless the
75
+ * data would fill less than three quarters of the scale it makes, and steps whose ticks render
76
+ * the same label are ruled out: a currency axis over a few cents otherwise reads "$0.01,
77
+ * $0.01". An empty series is a plain 0–4.
78
+ */
79
+ function niceTicks(max, { integer = false, format } = {}) {
80
+ if (!(max > 0)) return ticksOf(1);
81
+ function scaleOn(ladder) {
82
+ const step = roundStep(max / GRID_INTERVALS, ladder, integer);
83
+ return {
84
+ top: step * GRID_INTERVALS,
85
+ ticks: ticksOf(step)
86
+ };
87
+ }
88
+ const plain = scaleOn(PLAIN_STEPS);
89
+ const readable = [plain, scaleOn(FINE_STEPS)].filter((scale) => !format || new Set(scale.ticks.map(format)).size === scale.ticks.length);
90
+ const fallback = readable[0] ?? plain;
91
+ return readable.find((scale) => max >= scale.top * .75)?.ticks ?? fallback.ticks;
92
+ }
93
+ /** Grid lines over a fixed scale (a rate pinned to `[0, 100]`), in equal intervals. */
94
+ function domainTicks([low, high]) {
95
+ return ticksOf((high - low) / GRID_INTERVALS).map((value) => low + value);
96
+ }
97
+ /**
98
+ * Tick instants on a time axis: every nth bucket from the first, with the smallest whole n
99
+ * that fits `count` labels. Ticks land on real buckets and the gaps are equal, so the labels
100
+ * step by a constant amount ("2 AM, 4 AM, 6 AM") instead of drifting between 1 and 2. The
101
+ * tail bucket is dropped when it doesn't fall on the step rather than crowding the last gap.
102
+ */
103
+ function pickTicks(times, count) {
104
+ const total = times.length;
105
+ if (total <= count) return times;
106
+ const step = Math.ceil((total - 1) / (count - 1));
107
+ return times.filter((_, index) => index % step === 0);
108
+ }
109
+ /**
110
+ * Notes grouped onto the bucket that holds them: a note belongs to the last bucket starting at
111
+ * or before it, so a week bucket folds in its seven days and an hourly chart shows a midnight
112
+ * note on its 00:00 bucket. Anything past the trailing bucket's `end` is outside the range and
113
+ * dropped, as is anything before the first bucket. Without an `end` the trailing bucket is taken
114
+ * to be as wide as the one before it (wrong for months, hence the parameter); a lone bucket
115
+ * then has no width to infer from, so only a note on its exact instant lands.
116
+ */
117
+ function bucketNotes(times, notes, endOfLast) {
118
+ const bucketed = /* @__PURE__ */ new Map();
119
+ const count = times.length;
120
+ const first = times[0];
121
+ const last = times[count - 1];
122
+ if (first === void 0 || last === void 0) return bucketed;
123
+ const before = times[count - 2];
124
+ const end = endOfLast ?? (before === void 0 ? last : last + (last - before));
125
+ for (const note of notes) {
126
+ const time = note.date.getTime();
127
+ if (time < first || (end === last ? time !== last : time >= end)) continue;
128
+ let low = 0;
129
+ let high = count - 1;
130
+ while (low < high) {
131
+ const middle = Math.ceil((low + high) / 2);
132
+ if ((times[middle] ?? Number.POSITIVE_INFINITY) <= time) low = middle;
133
+ else high = middle - 1;
134
+ }
135
+ const start = times[low] ?? first;
136
+ const existing = bucketed.get(start);
137
+ if (existing) existing.push(note);
138
+ else bucketed.set(start, [note]);
139
+ }
140
+ return bucketed;
141
+ }
142
+ export { AREA_FADE, SERIES_COLORS, bucketNotes, countPartialStart, countRunning, domainTicks, niceTicks, pickTicks, seriesTotal };
143
+
144
+ //# sourceMappingURL=time-series.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time-series.js","names":[],"sources":["../../src/lib/time-series.ts"],"sourcesContent":["/**\n * The arithmetic behind `TimeSeriesChart`: its point and note shapes, round grid lines, evenly\n * spaced date ticks, and notes folded onto the buckets that hold them. Pure, so it is tested\n * without rendering a chart.\n */\n\nexport interface TimeSeriesSeries {\n /** Reads `point.values[key]`. */\n key: string\n label: string\n /** One of the `--color-chart-*` tokens; defaults to `SERIES_COLORS` by index. */\n color?: string\n}\n\n/** The hues of a multi-series chart's lines, in series order; a fourth line wraps to the first. */\nexport const SERIES_COLORS = [\n \"var(--color-chart-1)\",\n \"var(--color-chart-2)\",\n \"var(--color-chart-3)\",\n]\n\nexport interface TimeSeriesPoint {\n date: Date\n value: number\n /**\n * The same bucket in a compared period, drawn as a dashed, unfilled line.\n */\n previous?: number\n /**\n * An optional second series drawn as bars behind the line, on its own left-hand axis\n * (a different unit, e.g. revenue against a traffic line). Shown when any point is above zero.\n */\n bar?: number\n /**\n * A segment stacked on `bar`, drawn as a dashed outline: the part the bar lost (a refund\n * over net revenue). Drawn, and listed in the tooltip, once any point is above zero.\n */\n outline?: number\n /** Multi-series mode: one figure per `TimeSeriesSeries.key`. */\n values?: Record<string, number>\n /**\n * The bucket covers only part of its period, so its figures read low: the last buckets while\n * they are still running, or the first when a rolling range starts mid-bucket. The line\n * reaches them dashed and their bars are dashed outlines, so a partial bucket never reads as\n * a drop.\n */\n partial?: boolean\n /**\n * Figures of the bucket that the chart does not draw, already formatted, listed in its\n * tooltip under a hairline.\n */\n details?: { label: string; value: string }[]\n}\n\nexport interface TimeSeriesNote {\n date: Date\n text: string\n /** Who wrote it; the tooltip's small line over the text (\"Piotr · Sep 10\"). */\n author?: string\n}\n\n/**\n * The wash under a line, as `TimeSeriesChart` and `Sparkline` draw it: a quarter of the series'\n * hue at the line, fading to nothing at the baseline. Offsets run from the top of the plot.\n */\nexport const AREA_FADE = [\n { offset: 0.05, opacity: 0.25 },\n { offset: 0.95, opacity: 0.01 },\n] as const\n\n/** How many buckets at the end of the series are still running. */\nexport function countRunning(data: Pick<TimeSeriesPoint, \"partial\">[]): number {\n let count = 0\n while (count < data.length && data[data.length - 1 - count]?.partial) count += 1\n return count\n}\n\n/** How many partial buckets open the series, leaving out the running ones at its end. */\nexport function countPartialStart(data: Pick<TimeSeriesPoint, \"partial\">[]): number {\n const limit = data.length - countRunning(data)\n let count = 0\n while (count < limit && data[count]?.partial) count += 1\n return count\n}\n\n/** The sum of one series over the range, for the legend; a point without the key counts as zero. */\nexport function seriesTotal(data: TimeSeriesPoint[], key: string): number {\n return data.reduce((sum, point) => sum + (point.values?.[key] ?? 0), 0)\n}\n\n/** Plainest tick steps, tried first: one of these times a power of ten. */\nconst PLAIN_STEPS = [1, 2, 5, 10]\n\n/** Finer steps, for the ranges no plain step fits without leaving the plot half empty. */\nconst FINE_STEPS = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]\n\n/** The smallest step on `ladder` that fits `raw`; a whole-number series never gets a fractional one. */\nfunction roundStep(raw: number, ladder: number[], integer: boolean): number {\n const power = 10 ** Math.floor(Math.log10(raw))\n return (\n ladder\n .map(unit => unit * power)\n .find(unit => unit >= raw && (!integer || Number.isInteger(unit))) ?? raw\n )\n}\n\n/**\n * Intervals between horizontal grid lines. Fixed rather than scaled to the data, so the\n * bar axis, drawn on the same lines over its own unit, keeps one scale as the metric on the\n * value axis changes; otherwise the same revenue bars resize on every switch of the stat strip.\n * Four intervals also divide a `[0, 100]` rate into round quarters.\n */\nconst GRID_INTERVALS = 4\n\n/** The grid lines at `step` apart, from zero. */\nfunction ticksOf(step: number): number[] {\n // toPrecision kills the float dust a 0.1 step leaves behind (0.30000000000000004).\n return Array.from({ length: GRID_INTERVALS + 1 }, (_, index) =>\n Number((step * index).toPrecision(12)),\n )\n}\n\n/**\n * Grid lines from 0 up past `max`, all on round numbers. A plain step (1, 2, 5) wins unless the\n * data would fill less than three quarters of the scale it makes, and steps whose ticks render\n * the same label are ruled out: a currency axis over a few cents otherwise reads \"$0.01,\n * $0.01\". An empty series is a plain 0–4.\n */\nexport function niceTicks(\n max: number,\n { integer = false, format }: { integer?: boolean; format?: (value: number) => string } = {},\n): number[] {\n if (!(max > 0)) return ticksOf(1)\n\n function scaleOn(ladder: number[]) {\n const step = roundStep(max / GRID_INTERVALS, ladder, integer)\n return { top: step * GRID_INTERVALS, ticks: ticksOf(step) }\n }\n const plain = scaleOn(PLAIN_STEPS)\n const readable = [plain, scaleOn(FINE_STEPS)].filter(\n scale => !format || new Set(scale.ticks.map(format)).size === scale.ticks.length,\n )\n // Where neither step can tell its labels apart (a sub-cent money axis, a sub-second\n // duration), the plain one stands: it repeats itself least.\n const fallback = readable[0] ?? plain\n\n return readable.find(scale => max >= scale.top * 0.75)?.ticks ?? fallback.ticks\n}\n\n/** Grid lines over a fixed scale (a rate pinned to `[0, 100]`), in equal intervals. */\nexport function domainTicks([low, high]: [number, number]): number[] {\n return ticksOf((high - low) / GRID_INTERVALS).map(value => low + value)\n}\n\n/**\n * Tick instants on a time axis: every nth bucket from the first, with the smallest whole n\n * that fits `count` labels. Ticks land on real buckets and the gaps are equal, so the labels\n * step by a constant amount (\"2 AM, 4 AM, 6 AM\") instead of drifting between 1 and 2. The\n * tail bucket is dropped when it doesn't fall on the step rather than crowding the last gap.\n */\nexport function pickTicks(times: number[], count: number): number[] {\n const total = times.length\n if (total <= count) return times\n const step = Math.ceil((total - 1) / (count - 1))\n return times.filter((_, index) => index % step === 0)\n}\n\n/**\n * Notes grouped onto the bucket that holds them: a note belongs to the last bucket starting at\n * or before it, so a week bucket folds in its seven days and an hourly chart shows a midnight\n * note on its 00:00 bucket. Anything past the trailing bucket's `end` is outside the range and\n * dropped, as is anything before the first bucket. Without an `end` the trailing bucket is taken\n * to be as wide as the one before it (wrong for months, hence the parameter); a lone bucket\n * then has no width to infer from, so only a note on its exact instant lands.\n */\nexport function bucketNotes(\n times: number[],\n notes: TimeSeriesNote[],\n endOfLast?: number,\n): Map<number, TimeSeriesNote[]> {\n const bucketed = new Map<number, TimeSeriesNote[]>()\n const count = times.length\n const first = times[0]\n const last = times[count - 1]\n if (first === undefined || last === undefined) return bucketed\n\n const before = times[count - 2]\n const end = endOfLast ?? (before === undefined ? last : last + (last - before))\n\n for (const note of notes) {\n const time = note.date.getTime()\n if (time < first || (end === last ? time !== last : time >= end)) continue\n\n // The last bucket starting at or before the note; `times` is ascending.\n let low = 0\n let high = count - 1\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if ((times[middle] ?? Number.POSITIVE_INFINITY) <= time) low = middle\n else high = middle - 1\n }\n\n const start = times[low] ?? first\n const existing = bucketed.get(start)\n if (existing) existing.push(note)\n else bucketed.set(start, [note])\n }\n\n return bucketed\n}\n"],"mappings":";;AAeA,MAAa,gBAAgB;CAC3B;CACA;CACA;AACF;;;;;AA8CA,MAAa,YAAY,CACvB;CAAE,QAAQ;CAAM,SAAS;AAAK,GAC9B;CAAE,QAAQ;CAAM,SAAS;AAAK,CAChC;;AAGA,SAAgB,aAAa,MAAkD;CAC7E,IAAI,QAAQ;CACZ,OAAO,QAAQ,KAAK,UAAU,KAAK,KAAK,SAAS,IAAI,MAAM,EAAE,SAAS,SAAS;CAC/E,OAAO;AAC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AI,UAAU,SAAS,KAAK,IAAI;OAC3B,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CACjC;CAEA,OAAO;AACT"}
package/lib/tone.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The semantic status vocabulary shared by tone-aware primitives (Ping, Badge, Callout) and
3
+ * by consumers that colour a state: callers pick a meaning, never a palette, so two views of
4
+ * the same state can't drift apart.
5
+ */
6
+ export type Tone = "success" | "warning" | "danger" | "neutral";
package/lib/tone.js ADDED
File without changes
@@ -0,0 +1,12 @@
1
+ import { CnFunction } from "cn";
2
+ import { VariantProps } from "tailwind-variants";
3
+ export declare const MERGE_CONFIG: {
4
+ extend: {
5
+ theme: {
6
+ text: string[];
7
+ };
8
+ };
9
+ };
10
+ export declare const cn: CnFunction;
11
+ export declare const variants: import("tailwind-variants").TV<import("tailwind-variants").TVCustomConfig>;
12
+ export type { VariantProps };
@@ -0,0 +1,14 @@
1
+ import { createCn } from "cn/config";
2
+ import { createTV } from "tailwind-variants/config";
3
+ // src/lib/variants.ts
4
+ const MERGE_CONFIG = { extend: { theme: { text: [
5
+ "2xs",
6
+ "control",
7
+ "copy",
8
+ "figure"
9
+ ] } } };
10
+ const cn = createCn(MERGE_CONFIG);
11
+ const variants = createTV({ twMergeConfig: MERGE_CONFIG });
12
+ export { MERGE_CONFIG, cn, variants };
13
+
14
+ //# sourceMappingURL=variants.js.map