@contui/ui 0.0.0-stage → 0.1.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 (427) hide show
  1. package/LICENSE +30 -0
  2. package/README.md +150 -2
  3. package/cli/contui.mjs +250 -0
  4. package/dist/charts/area-chart.d.ts +8 -0
  5. package/dist/charts/area-chart.js +9 -0
  6. package/dist/charts/bar-chart.d.ts +9 -0
  7. package/dist/charts/bar-chart.js +10 -0
  8. package/dist/charts/bubble-chart.d.ts +60 -0
  9. package/dist/charts/bubble-chart.js +392 -0
  10. package/dist/charts/bullet-chart.d.ts +53 -0
  11. package/dist/charts/bullet-chart.js +123 -0
  12. package/dist/charts/candlestick-chart.d.ts +77 -0
  13. package/dist/charts/candlestick-chart.js +558 -0
  14. package/dist/charts/cartesian.d.ts +121 -0
  15. package/dist/charts/cartesian.js +625 -0
  16. package/dist/charts/chart-card.d.ts +80 -0
  17. package/dist/charts/chart-card.js +114 -0
  18. package/dist/charts/donut-chart.d.ts +40 -0
  19. package/dist/charts/donut-chart.js +88 -0
  20. package/dist/charts/funnel-chart.d.ts +16 -0
  21. package/dist/charts/funnel-chart.js +164 -0
  22. package/dist/charts/horizontal-bar-chart.d.ts +67 -0
  23. package/dist/charts/horizontal-bar-chart.js +481 -0
  24. package/dist/charts/index.d.ts +21 -0
  25. package/dist/charts/index.js +32 -0
  26. package/dist/charts/legend.d.ts +23 -0
  27. package/dist/charts/legend.js +22 -0
  28. package/dist/charts/lib/candlestick-window.d.ts +15 -0
  29. package/dist/charts/lib/candlestick-window.js +23 -0
  30. package/dist/charts/lib/color.d.ts +39 -0
  31. package/dist/charts/lib/color.js +83 -0
  32. package/dist/charts/lib/format.d.ts +11 -0
  33. package/dist/charts/lib/format.js +33 -0
  34. package/dist/charts/lib/frame.d.ts +6 -0
  35. package/dist/charts/lib/frame.js +6 -0
  36. package/dist/charts/lib/layout.d.ts +11 -0
  37. package/dist/charts/lib/layout.js +71 -0
  38. package/dist/charts/lib/path.d.ts +35 -0
  39. package/dist/charts/lib/path.js +203 -0
  40. package/dist/charts/lib/scale.d.ts +41 -0
  41. package/dist/charts/lib/scale.js +80 -0
  42. package/dist/charts/lib/use-active.d.ts +18 -0
  43. package/dist/charts/lib/use-active.js +71 -0
  44. package/dist/charts/lib/use-size.d.ts +9 -0
  45. package/dist/charts/lib/use-size.js +40 -0
  46. package/dist/charts/line-chart.d.ts +7 -0
  47. package/dist/charts/line-chart.js +8 -0
  48. package/dist/charts/radar-chart.d.ts +27 -0
  49. package/dist/charts/radar-chart.js +165 -0
  50. package/dist/charts/rose-chart.d.ts +35 -0
  51. package/dist/charts/rose-chart.js +242 -0
  52. package/dist/charts/sparkline.d.ts +35 -0
  53. package/dist/charts/sparkline.js +110 -0
  54. package/dist/charts/tooltip.d.ts +35 -0
  55. package/dist/charts/tooltip.js +22 -0
  56. package/dist/charts/treemap.d.ts +28 -0
  57. package/dist/charts/treemap.js +103 -0
  58. package/dist/charts/uptime-strip.d.ts +40 -0
  59. package/dist/charts/uptime-strip.js +178 -0
  60. package/dist/components/accordion.d.ts +31 -0
  61. package/dist/components/accordion.js +34 -0
  62. package/dist/components/activity-item.d.ts +12 -0
  63. package/dist/components/activity-item.js +6 -0
  64. package/dist/components/alert.d.ts +21 -0
  65. package/dist/components/alert.js +58 -0
  66. package/dist/components/assistant-answer.d.ts +52 -0
  67. package/dist/components/assistant-answer.js +40 -0
  68. package/dist/components/assistant-prompt.d.ts +63 -0
  69. package/dist/components/assistant-prompt.js +122 -0
  70. package/dist/components/avatar.d.ts +28 -0
  71. package/dist/components/avatar.js +75 -0
  72. package/dist/components/badge.d.ts +16 -0
  73. package/dist/components/badge.js +33 -0
  74. package/dist/components/bar-list.d.ts +65 -0
  75. package/dist/components/bar-list.js +119 -0
  76. package/dist/components/block-slider.d.ts +43 -0
  77. package/dist/components/block-slider.js +63 -0
  78. package/dist/components/branch-graph.d.ts +87 -0
  79. package/dist/components/branch-graph.js +231 -0
  80. package/dist/components/breadcrumb.d.ts +41 -0
  81. package/dist/components/breadcrumb.js +53 -0
  82. package/dist/components/button.d.ts +23 -0
  83. package/dist/components/button.js +108 -0
  84. package/dist/components/calendar.d.ts +5 -0
  85. package/dist/components/calendar.js +90 -0
  86. package/dist/components/card.d.ts +65 -0
  87. package/dist/components/card.js +104 -0
  88. package/dist/components/chat-attachment.d.ts +47 -0
  89. package/dist/components/chat-attachment.js +63 -0
  90. package/dist/components/chat-event.d.ts +7 -0
  91. package/dist/components/chat-event.js +7 -0
  92. package/dist/components/chat-message.d.ts +59 -0
  93. package/dist/components/chat-message.js +91 -0
  94. package/dist/components/chat-reference.d.ts +20 -0
  95. package/dist/components/chat-reference.js +41 -0
  96. package/dist/components/chat-shared.d.ts +21 -0
  97. package/dist/components/chat-shared.js +23 -0
  98. package/dist/components/chat-suggestions.d.ts +59 -0
  99. package/dist/components/chat-suggestions.js +88 -0
  100. package/dist/components/chat-thread.d.ts +39 -0
  101. package/dist/components/chat-thread.js +172 -0
  102. package/dist/components/chat-typing.d.ts +35 -0
  103. package/dist/components/chat-typing.js +66 -0
  104. package/dist/components/checkbox.d.ts +18 -0
  105. package/dist/components/checkbox.js +33 -0
  106. package/dist/components/checklist.d.ts +26 -0
  107. package/dist/components/checklist.js +18 -0
  108. package/dist/components/chip.d.ts +29 -0
  109. package/dist/components/chip.js +61 -0
  110. package/dist/components/code-input.d.ts +40 -0
  111. package/dist/components/code-input.js +285 -0
  112. package/dist/components/color-picker.d.ts +38 -0
  113. package/dist/components/color-picker.js +855 -0
  114. package/dist/components/combobox.d.ts +75 -0
  115. package/dist/components/combobox.js +112 -0
  116. package/dist/components/command-menu.d.ts +58 -0
  117. package/dist/components/command-menu.js +166 -0
  118. package/dist/components/copy-button.d.ts +16 -0
  119. package/dist/components/copy-button.js +31 -0
  120. package/dist/components/data-grid.d.ts +50 -0
  121. package/dist/components/data-grid.js +599 -0
  122. package/dist/components/date-picker.d.ts +109 -0
  123. package/dist/components/date-picker.js +268 -0
  124. package/dist/components/description-list.d.ts +12 -0
  125. package/dist/components/description-list.js +10 -0
  126. package/dist/components/dialog.d.ts +57 -0
  127. package/dist/components/dialog.js +140 -0
  128. package/dist/components/dock.d.ts +45 -0
  129. package/dist/components/dock.js +79 -0
  130. package/dist/components/drop-zone.d.ts +46 -0
  131. package/dist/components/drop-zone.js +101 -0
  132. package/dist/components/dropdown-menu.d.ts +50 -0
  133. package/dist/components/dropdown-menu.js +78 -0
  134. package/dist/components/editable-cell.d.ts +34 -0
  135. package/dist/components/editable-cell.js +89 -0
  136. package/dist/components/empty-state.d.ts +17 -0
  137. package/dist/components/empty-state.js +9 -0
  138. package/dist/components/field.d.ts +43 -0
  139. package/dist/components/field.js +75 -0
  140. package/dist/components/filter-condition.d.ts +188 -0
  141. package/dist/components/filter-condition.js +113 -0
  142. package/dist/components/filter-menu.d.ts +57 -0
  143. package/dist/components/filter-menu.js +46 -0
  144. package/dist/components/header-bar.d.ts +84 -0
  145. package/dist/components/header-bar.js +94 -0
  146. package/dist/components/hold-button.d.ts +15 -0
  147. package/dist/components/hold-button.js +88 -0
  148. package/dist/components/icon-tile.d.ts +12 -0
  149. package/dist/components/icon-tile.js +29 -0
  150. package/dist/components/info-tip.d.ts +13 -0
  151. package/dist/components/info-tip.js +26 -0
  152. package/dist/components/input.d.ts +17 -0
  153. package/dist/components/input.js +83 -0
  154. package/dist/components/kbd.d.ts +6 -0
  155. package/dist/components/kbd.js +7 -0
  156. package/dist/components/menu-item.d.ts +56 -0
  157. package/dist/components/menu-item.js +94 -0
  158. package/dist/components/message-composer.d.ts +75 -0
  159. package/dist/components/message-composer.js +199 -0
  160. package/dist/components/nav-rail.d.ts +31 -0
  161. package/dist/components/nav-rail.js +85 -0
  162. package/dist/components/notice.d.ts +45 -0
  163. package/dist/components/notice.js +66 -0
  164. package/dist/components/optimistic-undo.d.ts +28 -0
  165. package/dist/components/optimistic-undo.js +43 -0
  166. package/dist/components/option-row.d.ts +15 -0
  167. package/dist/components/option-row.js +14 -0
  168. package/dist/components/page-content.d.ts +11 -0
  169. package/dist/components/page-content.js +31 -0
  170. package/dist/components/pagination.d.ts +34 -0
  171. package/dist/components/pagination.js +41 -0
  172. package/dist/components/popover.d.ts +27 -0
  173. package/dist/components/popover.js +25 -0
  174. package/dist/components/progress.d.ts +33 -0
  175. package/dist/components/progress.js +75 -0
  176. package/dist/components/radio-group.d.ts +7 -0
  177. package/dist/components/radio-group.js +33 -0
  178. package/dist/components/readonly-field.d.ts +33 -0
  179. package/dist/components/readonly-field.js +80 -0
  180. package/dist/components/segmented-control.d.ts +21 -0
  181. package/dist/components/segmented-control.js +108 -0
  182. package/dist/components/select.d.ts +42 -0
  183. package/dist/components/select.js +86 -0
  184. package/dist/components/separator.d.ts +10 -0
  185. package/dist/components/separator.js +7 -0
  186. package/dist/components/setting-row.d.ts +53 -0
  187. package/dist/components/setting-row.js +93 -0
  188. package/dist/components/sidebar-switcher.d.ts +47 -0
  189. package/dist/components/sidebar-switcher.js +20 -0
  190. package/dist/components/sidebar.d.ts +220 -0
  191. package/dist/components/sidebar.js +327 -0
  192. package/dist/components/skeleton.d.ts +18 -0
  193. package/dist/components/skeleton.js +23 -0
  194. package/dist/components/slider.d.ts +15 -0
  195. package/dist/components/slider.js +28 -0
  196. package/dist/components/spinner.d.ts +14 -0
  197. package/dist/components/spinner.js +19 -0
  198. package/dist/components/status-dot.d.ts +24 -0
  199. package/dist/components/status-dot.js +35 -0
  200. package/dist/components/stepper.d.ts +60 -0
  201. package/dist/components/stepper.js +197 -0
  202. package/dist/components/switch.d.ts +9 -0
  203. package/dist/components/switch.js +26 -0
  204. package/dist/components/table-cell.d.ts +38 -0
  205. package/dist/components/table-cell.js +107 -0
  206. package/dist/components/table-context.d.ts +48 -0
  207. package/dist/components/table-context.js +69 -0
  208. package/dist/components/table-head.d.ts +42 -0
  209. package/dist/components/table-head.js +188 -0
  210. package/dist/components/table-tree.d.ts +96 -0
  211. package/dist/components/table-tree.js +137 -0
  212. package/dist/components/table.d.ts +78 -0
  213. package/dist/components/table.js +119 -0
  214. package/dist/components/tabs.d.ts +27 -0
  215. package/dist/components/tabs.js +79 -0
  216. package/dist/components/textarea.d.ts +3 -0
  217. package/dist/components/textarea.js +20 -0
  218. package/dist/components/theme.d.ts +41 -0
  219. package/dist/components/theme.js +60 -0
  220. package/dist/components/thinking.d.ts +68 -0
  221. package/dist/components/thinking.js +94 -0
  222. package/dist/components/toast.d.ts +39 -0
  223. package/dist/components/toast.js +110 -0
  224. package/dist/components/toolbar.d.ts +25 -0
  225. package/dist/components/toolbar.js +92 -0
  226. package/dist/components/tooltip.d.ts +23 -0
  227. package/dist/components/tooltip.js +27 -0
  228. package/dist/components/top-nav.d.ts +129 -0
  229. package/dist/components/top-nav.js +211 -0
  230. package/dist/components/truncate.d.ts +29 -0
  231. package/dist/components/truncate.js +138 -0
  232. package/dist/deprecated.d.ts +43 -0
  233. package/dist/deprecated.js +47 -0
  234. package/dist/index.d.ts +93 -0
  235. package/dist/index.js +93 -0
  236. package/dist/lib/cn.d.ts +5 -0
  237. package/dist/lib/cn.js +14 -0
  238. package/dist/lib/color.d.ts +136 -0
  239. package/dist/lib/color.js +307 -0
  240. package/dist/lib/contrast.d.ts +53 -0
  241. package/dist/lib/contrast.js +169 -0
  242. package/dist/lib/create-theme.d.ts +240 -0
  243. package/dist/lib/create-theme.js +461 -0
  244. package/dist/lib/harmony.d.ts +102 -0
  245. package/dist/lib/harmony.js +426 -0
  246. package/dist/lib/import-theme.d.ts +22 -0
  247. package/dist/lib/import-theme.js +221 -0
  248. package/dist/lib/overflow-scroll.d.ts +25 -0
  249. package/dist/lib/overflow-scroll.js +66 -0
  250. package/dist/lib/radio-toggle-render.d.ts +3 -0
  251. package/dist/lib/radio-toggle-render.js +9 -0
  252. package/dist/lib/reorder.d.ts +38 -0
  253. package/dist/lib/reorder.js +193 -0
  254. package/dist/lib/spacing.d.ts +101 -0
  255. package/dist/lib/spacing.js +118 -0
  256. package/dist/lib/tailwind-palette.d.ts +5 -0
  257. package/dist/lib/tailwind-palette.js +351 -0
  258. package/dist/lib/truncate.d.ts +18 -0
  259. package/dist/lib/truncate.js +69 -0
  260. package/dist/lib/use-single-value.d.ts +5 -0
  261. package/dist/lib/use-single-value.js +17 -0
  262. package/dist/styles.css +7988 -0
  263. package/mcp/server.mjs +87590 -0
  264. package/package.json +58 -5
  265. package/skills/continuum-fix-padding/SKILL.md +69 -0
  266. package/skills/continuum-fix-padding/scripts/compute.ts +155 -0
  267. package/skills/continuum-fix-padding/scripts/spacing.ts +189 -0
  268. package/skills/continuum-taste/SKILL.md +186 -0
  269. package/skills/continuum-taste/assets/tokens.css +647 -0
  270. package/skills/continuum-taste/references/charts.md +375 -0
  271. package/skills/continuum-taste/references/components.md +1369 -0
  272. package/skills/continuum-taste/references/foundations.md +539 -0
  273. package/skills/continuum-taste/references/media/canvas.md +75 -0
  274. package/skills/continuum-taste/references/media/css.md +61 -0
  275. package/skills/continuum-taste/references/media/react.md +161 -0
  276. package/skills/continuum-taste/references/method.md +87 -0
  277. package/skills/continuum-taste/references/pages.md +391 -0
  278. package/skills/continuum-taste/references/patterns.md +77 -0
  279. package/skills/continuum-taste/references/screens/agent.tsx +450 -0
  280. package/skills/continuum-taste/references/screens/analytics-overview.tsx +377 -0
  281. package/skills/continuum-taste/references/screens/checkout-funnel.tsx +193 -0
  282. package/skills/continuum-taste/references/screens/customer.tsx +475 -0
  283. package/skills/continuum-taste/references/screens/customers.tsx +608 -0
  284. package/skills/continuum-taste/references/screens/index.tsx +72 -0
  285. package/skills/continuum-taste/references/screens/invoice-editor.tsx +558 -0
  286. package/skills/continuum-taste/references/screens/new-customer.tsx +205 -0
  287. package/skills/continuum-taste/references/screens/overview.tsx +196 -0
  288. package/skills/continuum-taste/references/screens/report-generator.tsx +329 -0
  289. package/skills/continuum-taste/references/screens/risk-report.tsx +577 -0
  290. package/skills/continuum-taste/references/screens/sequence-editor.tsx +455 -0
  291. package/skills/continuum-taste/references/screens/settings.tsx +288 -0
  292. package/skills/continuum-taste/references/screens/shared.tsx +204 -0
  293. package/skills/continuum-taste/references/screens/sign-in.tsx +104 -0
  294. package/skills/continuum-taste/references/screens/workspace.tsx +596 -0
  295. package/skills/continuum-taste/references/theming.md +95 -0
  296. package/src/charts/area-chart.tsx +17 -0
  297. package/src/charts/bar-chart.tsx +15 -0
  298. package/src/charts/bubble-chart.tsx +913 -0
  299. package/src/charts/bullet-chart.tsx +419 -0
  300. package/src/charts/candlestick-chart.tsx +1242 -0
  301. package/src/charts/cartesian.tsx +1437 -0
  302. package/src/charts/chart-card.tsx +394 -0
  303. package/src/charts/donut-chart.tsx +299 -0
  304. package/src/charts/funnel-chart.tsx +373 -0
  305. package/src/charts/horizontal-bar-chart.tsx +991 -0
  306. package/src/charts/index.ts +76 -0
  307. package/src/charts/legend.tsx +59 -0
  308. package/src/charts/lib/candlestick-window.ts +42 -0
  309. package/src/charts/lib/color.ts +110 -0
  310. package/src/charts/lib/format.ts +42 -0
  311. package/src/charts/lib/frame.ts +6 -0
  312. package/src/charts/lib/layout.ts +78 -0
  313. package/src/charts/lib/path.ts +225 -0
  314. package/src/charts/lib/scale.ts +91 -0
  315. package/src/charts/lib/use-active.ts +87 -0
  316. package/src/charts/lib/use-size.ts +45 -0
  317. package/src/charts/line-chart.tsx +16 -0
  318. package/src/charts/radar-chart.tsx +485 -0
  319. package/src/charts/rose-chart.tsx +553 -0
  320. package/src/charts/sparkline.tsx +293 -0
  321. package/src/charts/tooltip.tsx +105 -0
  322. package/src/charts/treemap.tsx +271 -0
  323. package/src/charts/uptime-strip.tsx +469 -0
  324. package/src/components/accordion.tsx +136 -0
  325. package/src/components/activity-item.tsx +43 -0
  326. package/src/components/alert.tsx +135 -0
  327. package/src/components/assistant-answer.tsx +185 -0
  328. package/src/components/assistant-prompt.tsx +352 -0
  329. package/src/components/avatar.tsx +157 -0
  330. package/src/components/badge.tsx +55 -0
  331. package/src/components/bar-list.tsx +350 -0
  332. package/src/components/block-slider.tsx +189 -0
  333. package/src/components/branch-graph.tsx +580 -0
  334. package/src/components/breadcrumb.tsx +173 -0
  335. package/src/components/button.tsx +157 -0
  336. package/src/components/calendar.tsx +154 -0
  337. package/src/components/card.tsx +296 -0
  338. package/src/components/chat-attachment.tsx +255 -0
  339. package/src/components/chat-event.tsx +34 -0
  340. package/src/components/chat-message.tsx +332 -0
  341. package/src/components/chat-reference.tsx +100 -0
  342. package/src/components/chat-shared.ts +41 -0
  343. package/src/components/chat-suggestions.tsx +188 -0
  344. package/src/components/chat-thread.tsx +348 -0
  345. package/src/components/chat-typing.tsx +155 -0
  346. package/src/components/checkbox.tsx +83 -0
  347. package/src/components/checklist.tsx +146 -0
  348. package/src/components/chip.tsx +152 -0
  349. package/src/components/code-input.tsx +406 -0
  350. package/src/components/color-picker.tsx +1385 -0
  351. package/src/components/combobox.tsx +420 -0
  352. package/src/components/command-menu.tsx +405 -0
  353. package/src/components/copy-button.tsx +87 -0
  354. package/src/components/data-grid.tsx +965 -0
  355. package/src/components/date-picker.tsx +652 -0
  356. package/src/components/description-list.tsx +39 -0
  357. package/src/components/dialog.tsx +367 -0
  358. package/src/components/dock.tsx +192 -0
  359. package/src/components/drop-zone.tsx +283 -0
  360. package/src/components/dropdown-menu.tsx +323 -0
  361. package/src/components/editable-cell.tsx +219 -0
  362. package/src/components/empty-state.tsx +50 -0
  363. package/src/components/field.tsx +148 -0
  364. package/src/components/filter-condition.tsx +463 -0
  365. package/src/components/filter-menu.tsx +196 -0
  366. package/src/components/header-bar.tsx +220 -0
  367. package/src/components/hold-button.tsx +146 -0
  368. package/src/components/icon-tile.tsx +43 -0
  369. package/src/components/info-tip.tsx +87 -0
  370. package/src/components/input.tsx +136 -0
  371. package/src/components/kbd.tsx +17 -0
  372. package/src/components/menu-item.tsx +216 -0
  373. package/src/components/message-composer.tsx +458 -0
  374. package/src/components/nav-rail.tsx +235 -0
  375. package/src/components/notice.tsx +133 -0
  376. package/src/components/optimistic-undo.ts +68 -0
  377. package/src/components/option-row.tsx +54 -0
  378. package/src/components/page-content.tsx +44 -0
  379. package/src/components/pagination.tsx +182 -0
  380. package/src/components/popover.tsx +113 -0
  381. package/src/components/progress.tsx +222 -0
  382. package/src/components/radio-group.tsx +80 -0
  383. package/src/components/readonly-field.tsx +251 -0
  384. package/src/components/segmented-control.tsx +205 -0
  385. package/src/components/select.tsx +259 -0
  386. package/src/components/separator.tsx +30 -0
  387. package/src/components/setting-row.tsx +277 -0
  388. package/src/components/sidebar-switcher.tsx +134 -0
  389. package/src/components/sidebar.tsx +804 -0
  390. package/src/components/skeleton.tsx +57 -0
  391. package/src/components/slider.tsx +106 -0
  392. package/src/components/spinner.tsx +43 -0
  393. package/src/components/status-dot.tsx +100 -0
  394. package/src/components/stepper.tsx +459 -0
  395. package/src/components/switch.tsx +54 -0
  396. package/src/components/table-cell.tsx +239 -0
  397. package/src/components/table-context.ts +135 -0
  398. package/src/components/table-head.tsx +393 -0
  399. package/src/components/table-tree.tsx +357 -0
  400. package/src/components/table.tsx +295 -0
  401. package/src/components/tabs.tsx +191 -0
  402. package/src/components/textarea.tsx +44 -0
  403. package/src/components/theme.tsx +120 -0
  404. package/src/components/thinking.tsx +295 -0
  405. package/src/components/toast.tsx +308 -0
  406. package/src/components/toolbar.tsx +166 -0
  407. package/src/components/tooltip.tsx +84 -0
  408. package/src/components/top-nav.tsx +660 -0
  409. package/src/components/truncate.tsx +234 -0
  410. package/src/deprecated.ts +61 -0
  411. package/src/index.ts +184 -0
  412. package/src/lib/cn.ts +22 -0
  413. package/src/lib/color.ts +469 -0
  414. package/src/lib/contrast.ts +220 -0
  415. package/src/lib/create-theme.ts +659 -0
  416. package/src/lib/harmony.ts +609 -0
  417. package/src/lib/import-theme.ts +272 -0
  418. package/src/lib/overflow-scroll.tsx +108 -0
  419. package/src/lib/radio-toggle-render.tsx +15 -0
  420. package/src/lib/reorder.ts +222 -0
  421. package/src/lib/spacing.ts +189 -0
  422. package/src/lib/tailwind-palette.ts +355 -0
  423. package/src/lib/truncate.ts +79 -0
  424. package/src/lib/use-single-value.ts +23 -0
  425. package/src/styles/continuum.css +3 -0
  426. package/src/styles/theme.css +524 -0
  427. package/src/styles/tokens.css +647 -0
@@ -0,0 +1,1385 @@
1
+ 'use client';
2
+
3
+ import {
4
+ type CSSProperties,
5
+ type KeyboardEvent,
6
+ type PointerEvent,
7
+ type RefObject,
8
+ startTransition,
9
+ useEffect,
10
+ useId,
11
+ useLayoutEffect,
12
+ useMemo,
13
+ useRef,
14
+ useState,
15
+ } from 'react';
16
+ import { cn } from '../lib/cn';
17
+ import { type Gamut, hexToOklch, type Oklch, oklchToHex } from '../lib/color';
18
+ import { wcagContrast } from '../lib/contrast';
19
+ import { BlockSlider } from './block-slider';
20
+ import { Input } from './input';
21
+ import { Popover, PopoverContent, PopoverTrigger } from './popover';
22
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './select';
23
+ import { StatusDot } from './status-dot';
24
+
25
+ /*
26
+ * A colour typed or pasted by hand, in the notation the person has it in: hex, rgb, hsl or oklch.
27
+ * The theme keeps the colour as hex, so whatever is typed is read, brought inside sRGB and written
28
+ * as hex; the field then shows that hex back in the notation picked, once the field is let go. A
29
+ * value still being typed is left alone until it reads as a whole colour, and the text stays as
30
+ * typed while it is being typed.
31
+ */
32
+
33
+ export type ColorFormat = 'hex' | 'rgb' | 'hsl' | 'oklch';
34
+
35
+ const formats: { value: ColorFormat; label: string }[] = [
36
+ { value: 'hex', label: 'Hex' },
37
+ { value: 'rgb', label: 'RGB' },
38
+ { value: 'hsl', label: 'HSL' },
39
+ { value: 'oklch', label: 'OKLCH' },
40
+ ];
41
+
42
+ type Rgb = [number, number, number];
43
+
44
+ const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
45
+
46
+ const toRgb = (hex: string): Rgb => {
47
+ const n = Number.parseInt(hex.replace('#', ''), 16);
48
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
49
+ };
50
+
51
+ const toHex = ([r, g, b]: Rgb) =>
52
+ `#${[r, g, b]
53
+ .map(v =>
54
+ Math.round(clamp(v, 0, 255))
55
+ .toString(16)
56
+ .padStart(2, '0'),
57
+ )
58
+ .join('')}`;
59
+
60
+ /** Whether two hexes are the same colour to within a step of rounding on each channel. */
61
+ const sameHex = (a: string, b: string) => {
62
+ const x = toRgb(a);
63
+ const y = toRgb(b);
64
+ return x.every((v, i) => Math.abs(v - (y[i] ?? 0)) <= 1.5);
65
+ };
66
+
67
+ const rgbToHsl = ([r, g, b]: Rgb): Rgb => {
68
+ const [rn, gn, bn] = [r / 255, g / 255, b / 255];
69
+ const max = Math.max(rn, gn, bn);
70
+ const min = Math.min(rn, gn, bn);
71
+ const l = (max + min) / 2;
72
+ const d = max - min;
73
+ if (d === 0) return [0, 0, l * 100];
74
+ const s = d / (1 - Math.abs(2 * l - 1));
75
+ const h = max === rn ? ((gn - bn) / d) % 6 : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4;
76
+ return [(h * 60 + 360) % 360, s * 100, l * 100];
77
+ };
78
+
79
+ const hslToRgb = ([h, s, l]: Rgb): Rgb => {
80
+ const sn = clamp(s, 0, 100) / 100;
81
+ const ln = clamp(l, 0, 100) / 100;
82
+ const k = (n: number) => (n + (((h % 360) + 360) % 360) / 30) % 12;
83
+ const a = sn * Math.min(ln, 1 - ln);
84
+ const f = (n: number) => ln - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
85
+ return [f(0) * 255, f(8) * 255, f(4) * 255];
86
+ };
87
+
88
+ /** A hex in a notation, as CSS writes it. */
89
+ const formatColor = (hex: string, format: ColorFormat) => {
90
+ if (format === 'hex') return hex;
91
+ const rgb = toRgb(hex);
92
+ if (format === 'rgb') return `rgb(${rgb.join(' ')})`;
93
+ if (format === 'hsl') {
94
+ const [h, s, l] = rgbToHsl(rgb);
95
+ return `hsl(${Math.round(h)} ${Math.round(s)}% ${Math.round(l)}%)`;
96
+ }
97
+ const color = hexToOklch(hex) ?? { l: 0.5, c: 0, h: 0 };
98
+ return `oklch(${(color.l * 100).toFixed(1)}% ${color.c.toFixed(3)} ${color.h.toFixed(1)})`;
99
+ };
100
+
101
+ /** The numbers in a typed value, a percent sign kept as a flag: "70.5% 0.187 47.6" in any wrapping. */
102
+ const numbers = (text: string) =>
103
+ [...text.matchAll(/(-?\d*\.?\d+)(%?)/g)].map(match => ({
104
+ value: Number(match[1]),
105
+ percent: match[2] === '%',
106
+ }));
107
+
108
+ /** A typed value as hex, in the notation it is typed in; null until it reads as a whole colour. */
109
+ const parseColor = (text: string, format: ColorFormat): string | null => {
110
+ const typed = text.trim().toLowerCase();
111
+ // A hex is a hex wherever it is pasted.
112
+ const hex = /^#?([0-9a-f]{6})$/.exec(typed);
113
+ if (hex) return `#${hex[1]}`;
114
+ const short = /^#?([0-9a-f]{3})$/.exec(typed);
115
+ if (short && format === 'hex') return `#${[...(short[1] ?? '')].map(c => c + c).join('')}`;
116
+
117
+ // A value that names its own notation is read as that, whatever the field is set to.
118
+ const named = /^(rgb|hsl|oklch)a?\(/.exec(typed)?.[1] as ColorFormat | undefined;
119
+ const kind = named ?? format;
120
+ if (kind === 'hex') return null;
121
+ // A notation opened and not closed is still being written: "rgb(120 30 2" is on its way to 200.
122
+ if (typed.includes('(') && !typed.includes(')')) return null;
123
+ // The body only, so the "3" of "p3" or a name's digits are never read as a channel.
124
+ const body = typed.replace(/^[a-z]+\(/, '').replace(/\).*$/, '');
125
+ const [a, b, c] = numbers(body);
126
+ if (!a || !b || !c) return null;
127
+
128
+ if (kind === 'rgb') {
129
+ const channel = (n: { value: number; percent: boolean }) =>
130
+ n.percent ? (n.value / 100) * 255 : n.value;
131
+ const rgb: Rgb = [channel(a), channel(b), channel(c)];
132
+ return rgb.every(v => v >= 0 && v <= 255) ? toHex(rgb) : null;
133
+ }
134
+ if (kind === 'hsl') {
135
+ if (b.value > 100 || c.value > 100 || b.value < 0 || c.value < 0) return null;
136
+ return toHex(hslToRgb([a.value, b.value, c.value]));
137
+ }
138
+ // oklch: lightness as a percentage or 0 to 1, chroma as a number or a share of 0.4.
139
+ const l = a.percent || a.value > 1 ? a.value / 100 : a.value;
140
+ const chroma = b.percent ? (b.value / 100) * 0.4 : b.value;
141
+ if (l < 0 || l > 1 || chroma < 0 || chroma > 0.5) return null;
142
+ return oklchToHex({ l, c: chroma, h: ((c.value % 360) + 360) % 360 });
143
+ };
144
+
145
+ // The notation last picked, shared by every field: the page's and the picker's start on the same one.
146
+ let lastFormat: ColorFormat = 'hex';
147
+
148
+ /** The notation last picked anywhere, for a field or a picker that opens. */
149
+ const sharedFormat = () => lastFormat;
150
+
151
+ /* ---------- The value by hand ---------- */
152
+
153
+ /** One number of a notation: what it is called, how far it runs, and how it is written out. */
154
+ type Channel = {
155
+ label: string;
156
+ min: number;
157
+ max: number;
158
+ /** What an arrow moves it by; Shift takes ten of them. */
159
+ step: number;
160
+ show: (value: number) => string;
161
+ };
162
+
163
+ const round = (value: number) => String(Math.round(value));
164
+
165
+ /**
166
+ * The notations that are three numbers, each read off a hex and written back to one. The numbers
167
+ * are read at full precision and only rounded for the box, so editing one leaves the others where
168
+ * they were rather than nudging the colour by a step of rounding each time.
169
+ */
170
+ const channelSets: Record<
171
+ Exclude<ColorFormat, 'hex'>,
172
+ { channels: Channel[]; read: (hex: string) => number[]; write: (values: number[]) => string }
173
+ > = {
174
+ rgb: {
175
+ channels: (['Red', 'Green', 'Blue'] as const).map(label => ({
176
+ label,
177
+ min: 0,
178
+ max: 255,
179
+ step: 1,
180
+ show: round,
181
+ })),
182
+ read: hex => toRgb(hex),
183
+ write: ([r = 0, g = 0, b = 0]) => toHex([r, g, b]),
184
+ },
185
+ hsl: {
186
+ channels: [
187
+ { label: 'Hue', min: 0, max: 360, step: 1, show: round },
188
+ { label: 'Saturation', min: 0, max: 100, step: 1, show: round },
189
+ { label: 'Lightness', min: 0, max: 100, step: 1, show: round },
190
+ ],
191
+ read: hex => rgbToHsl(toRgb(hex)),
192
+ write: ([h = 0, s = 0, l = 0]) => toHex(hslToRgb([h, s, l])),
193
+ },
194
+ oklch: {
195
+ channels: [
196
+ { label: 'Lightness', min: 0, max: 100, step: 1, show: n => n.toFixed(1) },
197
+ { label: 'Chroma', min: 0, max: 0.4, step: 0.005, show: n => n.toFixed(3) },
198
+ { label: 'Hue', min: 0, max: 360, step: 1, show: n => n.toFixed(1) },
199
+ ],
200
+ read: hex => {
201
+ const color = hexToOklch(hex) ?? { l: 0.5, c: 0, h: 0 };
202
+ return [color.l * 100, color.c, color.h];
203
+ },
204
+ write: ([l = 0, c = 0, h = 0]) => oklchToHex({ l: l / 100, c, h }),
205
+ },
206
+ };
207
+
208
+ /**
209
+ * One channel's box: a number, taken as it is typed and kept inside the channel's range, with the
210
+ * arrows moving it a step (Shift, ten). A whole colour pasted into it is taken as the colour, so a
211
+ * paste lands wherever in the row it is dropped. As the field itself, the text stays as typed until
212
+ * the box is let go.
213
+ */
214
+ const ChannelInput = ({
215
+ channel,
216
+ label,
217
+ value,
218
+ format,
219
+ onChange,
220
+ onWhole,
221
+ }: {
222
+ channel: Channel;
223
+ /** What the colour is, so the box is named "Primary hue". */
224
+ label: string;
225
+ value: number;
226
+ format: ColorFormat;
227
+ onChange: (value: number) => void;
228
+ onWhole: (hex: string) => void;
229
+ }) => {
230
+ const shown = channel.show(value);
231
+ const [draft, setDraft] = useState(shown);
232
+ const typing = useRef(false);
233
+
234
+ useEffect(() => {
235
+ if (!typing.current) setDraft(shown);
236
+ }, [shown]);
237
+
238
+ const typed = (text: string) =>
239
+ text.trim() !== '' && Number.isFinite(Number(text)) ? Number(text) : null;
240
+
241
+ const step = (by: number) => {
242
+ const from = typed(draft) ?? value;
243
+ // Back off the floating point the step leaves behind, so 0.185 + 0.005 is 0.19 and not 0.19000000000000003.
244
+ const next = clamp(Number((from + by).toFixed(4)), channel.min, channel.max);
245
+ typing.current = false;
246
+ setDraft(channel.show(next));
247
+ onChange(next);
248
+ };
249
+
250
+ return (
251
+ <Input
252
+ aria-label={`${label} ${channel.label.toLowerCase()}`}
253
+ className="min-w-0 flex-1 px-1.5"
254
+ inputClassName="text-center tabular-nums"
255
+ inputMode="decimal"
256
+ onBlur={() => {
257
+ typing.current = false;
258
+ setDraft(shown);
259
+ }}
260
+ onChange={event => {
261
+ const next = event.target.value;
262
+ typing.current = true;
263
+ setDraft(next);
264
+ // A colour pasted over a number is the colour; a number is this channel's.
265
+ const pasted = parseColor(next, format);
266
+ if (pasted) return onWhole(pasted);
267
+ const number = typed(next);
268
+ if (number !== null) onChange(clamp(number, channel.min, channel.max));
269
+ }}
270
+ onKeyDown={event => {
271
+ if (event.key === 'Enter') return event.currentTarget.blur();
272
+ const way = event.key === 'ArrowUp' ? 1 : event.key === 'ArrowDown' ? -1 : 0;
273
+ if (!way) return;
274
+ event.preventDefault();
275
+ step(way * channel.step * (event.shiftKey ? 10 : 1));
276
+ }}
277
+ size="sm"
278
+ spellCheck={false}
279
+ value={draft}
280
+ />
281
+ );
282
+ };
283
+
284
+ export type ColorFieldProps = {
285
+ /** The colour as hex. */
286
+ value: string;
287
+ onChange: (hex: string) => void;
288
+ label?: string;
289
+ /** The notation, when what holds the field follows it (the picker's plane); the field's own otherwise. */
290
+ format?: ColorFormat;
291
+ onFormat?: (format: ColorFormat) => void;
292
+ };
293
+
294
+ /**
295
+ * The notation and the value: a short select beside the value it sets the notation of. Hex is one
296
+ * box, since it is one word; the notations that are three numbers get a box each, as a colour is
297
+ * read and corrected a channel at a time.
298
+ */
299
+ export const ColorField = ({
300
+ value,
301
+ onChange,
302
+ label = 'Colour',
303
+ format: given,
304
+ onFormat,
305
+ }: ColorFieldProps) => {
306
+ const [own, setOwn] = useState<ColorFormat>(lastFormat);
307
+ const format = given ?? own;
308
+ const set = format === 'hex' ? null : channelSets[format];
309
+ const values = set?.read(value);
310
+ const shown = formatColor(value, format);
311
+ const [draft, setDraft] = useState(shown);
312
+ // While the field has the hand, its text is its own: the colour it just wrote comes back
313
+ // written out in full ("#abc" as "#aabbcc", "rgb(1 2 3)" with its spacing), and that must not
314
+ // be dropped under the caret mid-word. It is shown on letting go.
315
+ const typing = useRef(false);
316
+
317
+ // A colour from elsewhere (the plane, another field) replaces whatever was being typed.
318
+ useEffect(() => {
319
+ if (!typing.current) setDraft(shown);
320
+ }, [shown]);
321
+
322
+ return (
323
+ <div className="flex min-w-0 flex-1 items-center gap-2">
324
+ <Select<ColorFormat>
325
+ onValueChange={next => {
326
+ if (!next) return;
327
+ lastFormat = next;
328
+ setOwn(next);
329
+ onFormat?.(next);
330
+ }}
331
+ value={format}
332
+ >
333
+ <SelectTrigger aria-label={`${label} notation`} className="w-24 shrink-0" size="sm">
334
+ <SelectValue />
335
+ </SelectTrigger>
336
+ <SelectContent>
337
+ {formats.map(item => (
338
+ <SelectItem key={item.value} value={item.value}>
339
+ {item.label}
340
+ </SelectItem>
341
+ ))}
342
+ </SelectContent>
343
+ </Select>
344
+ {set && values ? (
345
+ <div className="flex min-w-0 flex-1 items-center gap-1">
346
+ {set.channels.map((channel, i) => (
347
+ <ChannelInput
348
+ channel={channel}
349
+ format={format}
350
+ key={`${format}-${channel.label}`}
351
+ label={label}
352
+ onChange={next => {
353
+ const edited = [...values];
354
+ edited[i] = next;
355
+ const hex = set.write(edited);
356
+ if (hex !== value) onChange(hex);
357
+ }}
358
+ onWhole={hex => {
359
+ if (hex !== value) onChange(hex);
360
+ }}
361
+ value={values[i] ?? 0}
362
+ />
363
+ ))}
364
+ </div>
365
+ ) : (
366
+ <Input
367
+ aria-label={`${label} as ${format}`}
368
+ className="min-w-0 flex-1 font-mono"
369
+ onBlur={() => {
370
+ typing.current = false;
371
+ setDraft(shown);
372
+ }}
373
+ onChange={event => {
374
+ const next = event.target.value;
375
+ typing.current = true;
376
+ setDraft(next);
377
+ const hex = parseColor(next, format);
378
+ if (hex && hex !== value) onChange(hex);
379
+ }}
380
+ onKeyDown={event => {
381
+ if (event.key === 'Enter') event.currentTarget.blur();
382
+ }}
383
+ size="sm"
384
+ spellCheck={false}
385
+ value={draft}
386
+ />
387
+ )}
388
+ </div>
389
+ );
390
+ };
391
+
392
+ /* ---------- The hue's slider ---------- */
393
+
394
+ /**
395
+ * The hue wheel at one lightness and chroma, left to right from 0° to 360°: clean enough to read as
396
+ * the wheel on either surface, since it runs as a band beside the label rather than under it.
397
+ */
398
+ const hueBand = `linear-gradient(90deg in oklab, ${Array.from(
399
+ { length: 13 },
400
+ (_, i) => `oklch(0.72 0.15 ${i * 30})`,
401
+ ).join(', ')})`;
402
+
403
+ /** A hue as the band draws it, for the knob that sits on the band at that hue. */
404
+ const hueKnob = (hue: number) => `oklch(0.72 0.15 ${hue})`;
405
+
406
+ /**
407
+ * A setting as a block slider, 48px, full width: its name inside on the left, its value on the right.
408
+ *
409
+ * A track (a gradient) shows what the value picks, a hue for instance: it runs as a 4px band along
410
+ * the foot of the box, from the label's edge to the value's, with a knob on it at the value, always
411
+ * shown. The label and the value move up to make room, and stay on the plain surface, so the band can
412
+ * be drawn at full strength and the text still reads. The knob is filled with `knob` (the band's colour
413
+ * at the value) inside a ring of the surface, the way the ramp graph draws its points.
414
+ */
415
+ const BandSlider = ({
416
+ label,
417
+ value,
418
+ display,
419
+ track,
420
+ knob,
421
+ ...range
422
+ }: {
423
+ label: string;
424
+ value: number;
425
+ display: string;
426
+ track?: string;
427
+ /** The knob's fill on a track; the surface unless given. */
428
+ knob?: string;
429
+ min: number;
430
+ max: number;
431
+ step: number;
432
+ onValueChange: (value: number) => void;
433
+ }) => {
434
+ const slider = (
435
+ <BlockSlider
436
+ className={cn(
437
+ track && [
438
+ // No grey fill and no hover grip: the band and its knob say where the value is.
439
+ '**:data-[slot=block-slider-range]:bg-transparent **:data-[slot=block-slider-thumb]:after:hidden',
440
+ // A 20px grip, so its centre at either end lands on the band's end, level with the text.
441
+ '**:data-[slot=block-slider-thumb]:w-5',
442
+ // The label and the value sit in the upper part of the box, over the band.
443
+ '**:data-[slot=block-slider-info]:pb-3.5',
444
+ ],
445
+ )}
446
+ format={() => display}
447
+ label={label}
448
+ max={range.max}
449
+ min={range.min}
450
+ onValueChange={([next = value]) => range.onValueChange(next)}
451
+ size="lg"
452
+ step={range.step}
453
+ // Inset by half the grip, so the ends of the range are the ends of the band, not the box's edges.
454
+ {...(track ? { thumbAlignment: 'edge' as const } : {})}
455
+ value={[value]}
456
+ />
457
+ );
458
+ if (!track) return slider;
459
+
460
+ const at = Math.min(1, Math.max(0, (value - range.min) / (range.max - range.min)));
461
+ // The band runs between the grip's centres at either end: the box's 1px border, its 2px padding,
462
+ // then half the 20px grip.
463
+ const inset = 'calc(1px + var(--spacing) * 3)';
464
+
465
+ return (
466
+ <div className="relative" data-slot="slider-row">
467
+ {slider}
468
+ <span
469
+ aria-hidden
470
+ className="pointer-events-none absolute bottom-3 h-1 rounded-full"
471
+ style={{ left: inset, right: inset, background: track }}
472
+ />
473
+ <span
474
+ aria-hidden
475
+ className="pointer-events-none absolute bottom-2 size-3 -translate-x-1/2 rounded-full border-2 border-neutral-50 shadow-float ring-1 ring-neutral-950/15"
476
+ style={
477
+ {
478
+ left: `calc(${inset} + (100% - 2 * ${inset}) * ${at})`,
479
+ background: knob ?? 'var(--color-neutral-50)',
480
+ } as CSSProperties
481
+ }
482
+ />
483
+ </div>
484
+ );
485
+ };
486
+
487
+ /*
488
+ * The colour picker: a plane at one hue, the hue under it, the value by hand, and how the
489
+ * colour reads as a fill on the theme's light and dark surface. The notation the value is written
490
+ * in is the model the plane is drawn in: hex and rgb pick on saturation over brightness (HSB),
491
+ * hsl on saturation over lightness, oklch on its own chroma over lightness. Where a fill misses
492
+ * 3:1 against a surface is dotted over, as a contrast checker marks it; the edge is found on the
493
+ * plane shown, so it curves on HSB and lies level on oklch, whose rows share a lightness. The
494
+ * value is a hex, so every plane is sRGB's.
495
+ */
496
+
497
+ /** The most chroma any hue reaches in P3, with a little over: the arrows' limit. */
498
+ const _C_MAX = 0.37;
499
+
500
+ type Channels = [number, number, number];
501
+
502
+ /** Oklch to linear sRGB (Björn Ottosson's OKLab), unclamped: outside 0–1 is outside sRGB. */
503
+ const toLinearSrgb = ({ l, c, h }: Oklch): Channels => {
504
+ const a = c * Math.cos((h * Math.PI) / 180);
505
+ const b = c * Math.sin((h * Math.PI) / 180);
506
+ const lc = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
507
+ const mc = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
508
+ const sc = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
509
+ return [
510
+ 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc,
511
+ -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc,
512
+ -0.0041960863 * lc - 0.7034186147 * mc + 1.707614701 * sc,
513
+ ];
514
+ };
515
+
516
+ /** Linear sRGB to linear Display P3 (both D65). */
517
+ const toP3 = ([r, g, b]: Channels): Channels => [
518
+ 0.8224621209 * r + 0.1775378791 * g,
519
+ 0.0331941989 * r + 0.9668058011 * g,
520
+ 0.0170826307 * r + 0.0723974407 * g + 0.9105199286 * b,
521
+ ];
522
+
523
+ /**
524
+ * The most chroma a lightness and hue carry inside a gamut. The engine's maxChroma allows a fixed
525
+ * margin on every channel, which near black is larger than the channels themselves and lets the
526
+ * edge swing out; drawn on a plane that shows as a hook at the bottom, so the edge here is exact.
527
+ */
528
+ const edge = (l: number, h: number, gamut: Gamut = 'srgb') => {
529
+ if (l <= 0 || l >= 1) return 0;
530
+ let low = 0;
531
+ let high = 0.45;
532
+ for (let i = 0; i < 28; i++) {
533
+ const mid = (low + high) / 2;
534
+ const linear = toLinearSrgb({ l, c: mid, h });
535
+ const channels = gamut === 'p3' ? toP3(linear) : linear;
536
+ if (channels.every(v => v >= -1e-9 && v <= 1 + 1e-9)) low = mid;
537
+ else high = mid;
538
+ }
539
+ return low;
540
+ };
541
+
542
+ /** The colour with its chroma brought inside sRGB at the same lightness and hue, as a hex holds it. */
543
+ const fit = (color: Oklch): Oklch => {
544
+ const most = edge(color.l, color.h);
545
+ // A hex read back sits on the edge to within rounding; it stays as it is, so its hex does too.
546
+ return color.c > most + 1e-5 ? { ...color, c: most } : color;
547
+ };
548
+
549
+ /** A hex as oklch; a grey keeps the hue it was given, since its own means nothing. */
550
+ const fromHex = (hex: string, hue: number | undefined): Oklch => {
551
+ const color = hexToOklch(hex) ?? { l: 0.5, c: 0, h: 0 };
552
+ return color.c < 0.01 && hue !== undefined ? { ...color, h: hue } : color;
553
+ };
554
+
555
+ /* ---------- Painting the plane ---------- */
556
+
557
+ /** Whether the canvas can be drawn in Display P3, on a screen that shows it. */
558
+ let wideCanvas: boolean | undefined;
559
+ const supportsP3 = () => {
560
+ if (wideCanvas === undefined) {
561
+ try {
562
+ const context = document
563
+ .createElement('canvas')
564
+ .getContext('2d', { colorSpace: 'display-p3' });
565
+ wideCanvas =
566
+ context?.getContextAttributes().colorSpace === 'display-p3' &&
567
+ window.matchMedia('(color-gamut: p3)').matches;
568
+ } catch {
569
+ wideCanvas = false;
570
+ }
571
+ }
572
+ return wideCanvas;
573
+ };
574
+
575
+ /** Linear channels to 8-bit through the sRGB curve (P3 shares it), looked up rather than raised. */
576
+ const LUT = 4096;
577
+ const encode = (() => {
578
+ const table = new Uint8ClampedArray(LUT + 1);
579
+ for (let i = 0; i <= LUT; i++) {
580
+ const v = i / LUT;
581
+ table[i] = Math.round((v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055) * 255);
582
+ }
583
+ return table;
584
+ })();
585
+ const toByte = (linear: number) => encode[Math.round(clamp(linear, 0, 1) * LUT)] ?? 0;
586
+
587
+ /**
588
+ * The plane at one hue, pixel by pixel: lightness up, and across each row the colour from grey to
589
+ * the most vivid that lightness is in sRGB, which is as far as a hex goes. Every row runs the
590
+ * plane's whole width, so it is colour from corner to corner, as a picker is expected to be.
591
+ */
592
+ const paintPlane = (canvas: HTMLCanvasElement, hue: number) => {
593
+ const ratio = Math.min(2, window.devicePixelRatio || 1);
594
+ const w = Math.max(1, Math.round(canvas.clientWidth * ratio));
595
+ const h = Math.max(1, Math.round(canvas.clientHeight * ratio));
596
+ if (canvas.width !== w) canvas.width = w;
597
+ if (canvas.height !== h) canvas.height = h;
598
+ const wide = supportsP3();
599
+ const space: { colorSpace: PredefinedColorSpace } = {
600
+ colorSpace: wide ? 'display-p3' : 'srgb',
601
+ };
602
+ const context = canvas.getContext('2d', space) as CanvasRenderingContext2D | null;
603
+ if (!context) return;
604
+ const image = context.createImageData(w, h, space);
605
+ const { data } = image;
606
+ const angle = (hue * Math.PI) / 180;
607
+ const ca = Math.cos(angle);
608
+ const sa = Math.sin(angle);
609
+ // OKLab's a and b for one unit of chroma at this hue, carried into the LMS step once.
610
+ const kl = 0.3963377774 * ca + 0.2158037573 * sa;
611
+ const km = -0.1055613458 * ca - 0.0638541728 * sa;
612
+ const ks = -0.0894841775 * ca - 1.291485548 * sa;
613
+
614
+ for (let y = 0; y < h; y++) {
615
+ const l = 1 - (y + 0.5) / h;
616
+ const most = edge(l, hue);
617
+ for (let x = 0; x < w; x++) {
618
+ const c = ((x + 0.5) / w) * most;
619
+ const lc = (l + kl * c) ** 3;
620
+ const mc = (l + km * c) ** 3;
621
+ const sc = (l + ks * c) ** 3;
622
+ let r = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
623
+ let g = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
624
+ let b = -0.0041960863 * lc - 0.7034186147 * mc + 1.707614701 * sc;
625
+ if (wide) {
626
+ const pr = 0.8224621209 * r + 0.1775378791 * g;
627
+ const pg = 0.0331941989 * r + 0.9668058011 * g;
628
+ const pb = 0.0170826307 * r + 0.0723974407 * g + 0.9105199286 * b;
629
+ r = pr;
630
+ g = pg;
631
+ b = pb;
632
+ }
633
+ const i = (y * w + x) * 4;
634
+ data[i] = toByte(r);
635
+ data[i + 1] = toByte(g);
636
+ data[i + 2] = toByte(b);
637
+ data[i + 3] = 255;
638
+ }
639
+ }
640
+ context.putImageData(image, 0, 0);
641
+ };
642
+
643
+ /* ---------- The planes of sRGB's own models ---------- */
644
+
645
+ /** The plane a notation is picked on: oklch's own, or one of sRGB's two (HSB for hex and rgb). */
646
+ type Model = 'oklch' | 'hsl' | 'hsb';
647
+
648
+ const modelOf = (format: ColorFormat): Model =>
649
+ format === 'oklch' ? 'oklch' : format === 'hsl' ? 'hsl' : 'hsb';
650
+
651
+ /** sRGB channels, 0 to 1, at a hue with a saturation and a lightness (HSL) or a brightness (HSB). */
652
+ const srgbAt = (model: 'hsl' | 'hsb', h: number, s: number, u: number): Channels => {
653
+ const turn = ((h % 360) + 360) % 360;
654
+ if (model === 'hsb') {
655
+ const f = (n: number) => {
656
+ const k = (n + turn / 60) % 6;
657
+ return u - u * s * Math.max(0, Math.min(k, 4 - k, 1));
658
+ };
659
+ return [f(5), f(3), f(1)];
660
+ }
661
+ const a = s * Math.min(u, 1 - u);
662
+ const f = (n: number) => {
663
+ const k = (n + turn / 30) % 12;
664
+ return u - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
665
+ };
666
+ return [f(0), f(8), f(4)];
667
+ };
668
+
669
+ /** The hue, saturation and lightness or brightness of sRGB channels; a grey has hue 0. */
670
+ const fromSrgb = (model: 'hsl' | 'hsb', [r, g, b]: Channels) => {
671
+ const max = Math.max(r, g, b);
672
+ const min = Math.min(r, g, b);
673
+ const d = max - min;
674
+ const sector =
675
+ d === 0 ? 0 : max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
676
+ const h = (sector * 60 + 360) % 360;
677
+ if (model === 'hsb') return { h, s: max === 0 ? 0 : d / max, u: max };
678
+ const u = (max + min) / 2;
679
+ return { h, s: d === 0 ? 0 : d / (1 - Math.abs(2 * u - 1)), u };
680
+ };
681
+
682
+ const channelsOf = (hex: string): Channels => {
683
+ const n = Number.parseInt(hex.replace('#', ''), 16);
684
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
685
+ };
686
+
687
+ const hexOf = (channels: Channels) =>
688
+ `#${channels
689
+ .map(v =>
690
+ Math.round(clamp(v, 0, 1) * 255)
691
+ .toString(16)
692
+ .padStart(2, '0'),
693
+ )
694
+ .join('')}`;
695
+
696
+ /** An sRGB channel out of its curve, to light. */
697
+ const decode = (v: number) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
698
+
699
+ /** An sRGB plane at one hue, pixel by pixel: saturation across, lightness or brightness up. */
700
+ const paintSrgbPlane = (canvas: HTMLCanvasElement, model: 'hsl' | 'hsb', hue: number) => {
701
+ const ratio = Math.min(2, window.devicePixelRatio || 1);
702
+ const w = Math.max(1, Math.round(canvas.clientWidth * ratio));
703
+ const h = Math.max(1, Math.round(canvas.clientHeight * ratio));
704
+ if (canvas.width !== w) canvas.width = w;
705
+ if (canvas.height !== h) canvas.height = h;
706
+ // The canvas keeps the colour space it was first given, so sRGB is carried into it.
707
+ const wide = supportsP3();
708
+ const space: { colorSpace: PredefinedColorSpace } = {
709
+ colorSpace: wide ? 'display-p3' : 'srgb',
710
+ };
711
+ const context = canvas.getContext('2d', space) as CanvasRenderingContext2D | null;
712
+ if (!context) return;
713
+ const image = context.createImageData(w, h, space);
714
+ const { data } = image;
715
+ for (let y = 0; y < h; y++) {
716
+ const u = 1 - (y + 0.5) / h;
717
+ for (let x = 0; x < w; x++) {
718
+ const [sr, sg, sb] = srgbAt(model, hue, (x + 0.5) / w, u);
719
+ const linear: Channels = [decode(sr), decode(sg), decode(sb)];
720
+ const [r, g, b] = wide ? toP3(linear) : linear;
721
+ const i = (y * w + x) * 4;
722
+ data[i] = toByte(r);
723
+ data[i + 1] = toByte(g);
724
+ data[i + 2] = toByte(b);
725
+ data[i + 3] = 255;
726
+ }
727
+ }
728
+ context.putImageData(image, 0, 0);
729
+ };
730
+
731
+ /* ---------- Contrast across a plane ---------- */
732
+
733
+ /** The contrast a fill needs against what it sits on to be seen as a shape (WCAG 1.4.11). */
734
+ const FILL = 3;
735
+
736
+ /** Relative luminance of linear sRGB channels, as WCAG weighs them. */
737
+ const luminance = ([r, g, b]: Channels) =>
738
+ 0.2126 * clamp(r, 0, 1) + 0.7152 * clamp(g, 0, 1) + 0.0722 * clamp(b, 0, 1);
739
+
740
+ /** A plane's colour in light (linear sRGB) at a place: how far across, how far up, both 0 to 1. */
741
+ type LinearAt = (across: number, up: number) => Channels;
742
+
743
+ /**
744
+ * Where a fill keeps exactly 3:1 against a surface, as a line across a plane, and the region past
745
+ * it where a fill fails: over the line against a light surface, under it against a dark one. The
746
+ * line is found on the plane's own colours, so it is level on a plane whose rows share a
747
+ * lightness (oklch) and curves on one whose rows do not (HSB, HSL).
748
+ */
749
+ const contrastPath = (linearAt: LinearAt, surface: Oklch, width: number, height: number) => {
750
+ const columns = 48;
751
+ const points: [number, number][] = [];
752
+ const ground = luminance(toLinearSrgb(surface));
753
+ // Lighter than mid grey, the surface is passed by going darker; darker, by going lighter.
754
+ const light = surface.l > 0.5;
755
+ for (let i = 0; i <= columns; i++) {
756
+ const across = i / columns;
757
+ let low = 0;
758
+ let high = 1;
759
+ for (let k = 0; k < 18; k++) {
760
+ const mid = (low + high) / 2;
761
+ const own = luminance(linearAt(across, mid));
762
+ const passes = (Math.max(own, ground) + 0.05) / (Math.min(own, ground) + 0.05) >= FILL;
763
+ // Towards the surface the contrast falls: keep the half the threshold is in.
764
+ if (passes === light) low = mid;
765
+ else high = mid;
766
+ }
767
+ points.push([across * width, (1 - (low + high) / 2) * height]);
768
+ }
769
+ const first = points[0];
770
+ const last = points.at(-1);
771
+ if (!first || !last) return { line: '', area: '' };
772
+ const line = points
773
+ .map(([x, y], i) => `${i ? 'L' : 'M'} ${x.toFixed(1)} ${y.toFixed(1)}`)
774
+ .join(' ');
775
+ // The side that fails: towards the surface, so up from a light one's line, down from a dark one's.
776
+ const side = light ? 0 : height;
777
+ return {
778
+ line,
779
+ area: `${line} L ${last[0].toFixed(1)} ${side} L ${first[0].toFixed(1)} ${side} Z`,
780
+ };
781
+ };
782
+
783
+ /** The two surfaces a fill is read against: the theme's own, light and dark. */
784
+ type Surfaces = { light: Oklch; dark: Oklch };
785
+
786
+ /** Which of the two a colour is being checked against; either can be left out. */
787
+ type Checked = { light: boolean; dark: boolean };
788
+
789
+ // Kept between openings, so a check turned off stays off while the theme is worked on.
790
+ let lastChecked: Checked = { light: true, dark: true };
791
+
792
+ /** The element's size, kept as it changes. */
793
+ const useSize = <T extends HTMLElement>() => {
794
+ const ref = useRef<T>(null);
795
+ const [size, setSize] = useState({ width: 0, height: 0 });
796
+ useLayoutEffect(() => {
797
+ const element = ref.current;
798
+ if (!element) return;
799
+ const measure = () => setSize({ width: element.clientWidth, height: element.clientHeight });
800
+ measure();
801
+ const observer = new ResizeObserver(measure);
802
+ observer.observe(element);
803
+ return () => observer.disconnect();
804
+ }, []);
805
+ return [ref, size] as const;
806
+ };
807
+
808
+ /* ---------- The plane ---------- */
809
+
810
+ /**
811
+ * A plane of colour at one hue as a 2D slider, whichever model it is drawn in: how vivid across,
812
+ * how light up. A press anywhere picks there and a drag follows; the arrows move a step (Shift,
813
+ * five). With the theme's surfaces given, the colours that fail as a fill against either are
814
+ * dotted over, up to the line where 3:1 is kept.
815
+ */
816
+ const Plane = ({
817
+ paint,
818
+ paintKey,
819
+ linearAt,
820
+ at,
821
+ fill,
822
+ label,
823
+ surfaces,
824
+ onPickAt,
825
+ onRelease,
826
+ handleRef,
827
+ }: {
828
+ /** Draws the plane on its canvas. */
829
+ paint: (canvas: HTMLCanvasElement) => void;
830
+ /** Changes when the plane has to be drawn again: its model and hue. */
831
+ paintKey: string;
832
+ linearAt: LinearAt;
833
+ /** Where the colour sits: across and up, 0 to 1. */
834
+ at: { across: number; up: number };
835
+ /** The colour itself, for the handle. */
836
+ fill: string;
837
+ /** What the two axes are, for a screen reader. */
838
+ label: string;
839
+ surfaces?: Partial<Surfaces>;
840
+ onPickAt: (across: number, up: number) => void;
841
+ /** The hand has let go. */
842
+ onRelease: () => void;
843
+ handleRef: RefObject<HTMLDivElement | null>;
844
+ }) => {
845
+ const [planeRef, size] = useSize<HTMLDivElement>();
846
+ const canvasRef = useRef<HTMLCanvasElement>(null);
847
+ const [dragging, setDragging] = useState(false);
848
+ const dots = useId();
849
+
850
+ // Repainted for a new model or hue, or once the plane has a size.
851
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the painter is new each render; its key says when it draws something else
852
+ useLayoutEffect(() => {
853
+ if (canvasRef.current && size.width > 0) paint(canvasRef.current);
854
+ }, [paintKey, size.width]);
855
+
856
+ const light = surfaces?.light;
857
+ const dark = surfaces?.dark;
858
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the plane's colours change with its key
859
+ const lines = useMemo(
860
+ () =>
861
+ size.width > 0
862
+ ? [light, dark].flatMap(surface =>
863
+ surface ? [contrastPath(linearAt, surface, size.width, size.height)] : [],
864
+ )
865
+ : [],
866
+ [paintKey, size.width, size.height, light, dark],
867
+ );
868
+
869
+ // Where on the handle it was taken, so taking it by its edge does not jump it to the pointer.
870
+ const grip = useRef({ x: 0, y: 0 });
871
+
872
+ const pickAt = (event: PointerEvent<HTMLDivElement>) => {
873
+ const rect = event.currentTarget.getBoundingClientRect();
874
+ const x = event.clientX - grip.current.x - rect.left;
875
+ const y = event.clientY - grip.current.y - rect.top;
876
+ onPickAt(clamp(x / rect.width, 0, 1), clamp(1 - y / rect.height, 0, 1));
877
+ };
878
+
879
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
880
+ const far = event.shiftKey ? 5 : 1;
881
+ const move: Record<string, [number, number]> = {
882
+ ArrowUp: [0, 0.01],
883
+ ArrowDown: [0, -0.01],
884
+ ArrowRight: [0.01, 0],
885
+ ArrowLeft: [-0.01, 0],
886
+ };
887
+ const delta = move[event.key];
888
+ if (!delta) return;
889
+ event.preventDefault();
890
+ onPickAt(clamp(at.across + delta[0] * far, 0, 1), clamp(at.up + delta[1] * far, 0, 1));
891
+ };
892
+
893
+ return (
894
+ <div
895
+ className="relative h-44 w-full cursor-crosshair touch-none select-none"
896
+ onLostPointerCapture={() => {
897
+ setDragging(false);
898
+ onRelease();
899
+ }}
900
+ onPointerDown={event => {
901
+ if (event.button !== 0) return;
902
+ event.preventDefault();
903
+ event.currentTarget.setPointerCapture(event.pointerId);
904
+ const handle = handleRef.current;
905
+ const box = handle?.getBoundingClientRect();
906
+ grip.current =
907
+ box && event.target === handle
908
+ ? {
909
+ x: event.clientX - (box.left + box.width / 2),
910
+ y: event.clientY - (box.top + box.height / 2),
911
+ }
912
+ : { x: 0, y: 0 };
913
+ handle?.focus({ preventScroll: true });
914
+ setDragging(true);
915
+ pickAt(event);
916
+ }}
917
+ onPointerMove={event => {
918
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) pickAt(event);
919
+ }}
920
+ ref={planeRef}
921
+ >
922
+ <div
923
+ className={cn(
924
+ 'absolute inset-0 overflow-hidden rounded-item bg-neutral-950/3',
925
+ // A faint inner edge, so the plane keeps its outline against the popup.
926
+ "after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:ring-1 after:ring-neutral-950/10 after:ring-inset after:content-['']",
927
+ )}
928
+ >
929
+ <canvas aria-hidden className="absolute inset-0 size-full" ref={canvasRef} />
930
+ {lines.length > 0 && (
931
+ <svg
932
+ aria-hidden="true"
933
+ className="absolute inset-0 size-full"
934
+ viewBox={`0 0 ${size.width} ${size.height}`}
935
+ >
936
+ {/* Where a fill fails is dotted over, and the threshold is the dots' edge. */}
937
+ <defs>
938
+ <pattern height="4" id={dots} patternUnits="userSpaceOnUse" width="4">
939
+ <circle cx="1" cy="1" fill="rgb(255 255 255 / 0.5)" r="0.7" />
940
+ </pattern>
941
+ </defs>
942
+ {lines.map(threshold => (
943
+ <g key={threshold.line}>
944
+ <path d={threshold.area} fill={`url(#${dots})`} />
945
+ <path
946
+ d={threshold.line}
947
+ fill="none"
948
+ stroke="rgb(0 0 0 / 0.3)"
949
+ strokeWidth={2.5}
950
+ />
951
+ <path
952
+ d={threshold.line}
953
+ fill="none"
954
+ stroke="white"
955
+ strokeWidth={1}
956
+ />
957
+ </g>
958
+ ))}
959
+ </svg>
960
+ )}
961
+ </div>
962
+ <div
963
+ aria-label={label}
964
+ aria-valuemax={100}
965
+ aria-valuemin={0}
966
+ aria-valuenow={Math.round(at.up * 100)}
967
+ aria-valuetext={`${Math.round(at.up * 100)}% up, ${Math.round(at.across * 100)}% across`}
968
+ className={cn(
969
+ '-translate-1/2 absolute size-3.5 rounded-full border-2 border-white ring-1 ring-black/25',
970
+ 'outline-none focus-visible:outline-2 focus-visible:outline-focus focus-visible:outline-solid focus-visible:outline-offset-2',
971
+ // It grows a touch while held, so the hand feels it take the colour.
972
+ 'transition-[scale] duration-150 ease-out-strong motion-reduce:transition-none',
973
+ dragging ? 'scale-125 cursor-grabbing' : 'cursor-grab',
974
+ )}
975
+ onKeyDown={onKeyDown}
976
+ ref={handleRef}
977
+ role="slider"
978
+ style={{
979
+ left: `${at.across * 100}%`,
980
+ top: `${(1 - at.up) * 100}%`,
981
+ background: fill,
982
+ }}
983
+ tabIndex={0}
984
+ />
985
+ </div>
986
+ );
987
+ };
988
+
989
+ /* ---------- The picker ---------- */
990
+
991
+ /** A page that follows a write within this (two frames and a little) keeps up live. */
992
+ const LIVE_MS = 50;
993
+ /** Otherwise a write waits for the hand to rest this long, or to let go. */
994
+ const REST_MS = 120;
995
+
996
+ /**
997
+ * Writes the accent out at the pace the page can take. Every write re-themes the page and its
998
+ * preview; where that is quick, each frame writes, and where it is slow (a long frame would stall the
999
+ * handle) a drag writes when the hand rests or lets go, while the picker itself stays live. The
1000
+ * hexes sent and not yet seen back are kept in order: a value that is none of them came from outside.
1001
+ */
1002
+ const useWriter = (
1003
+ value: string,
1004
+ onChange: (hex: string) => void,
1005
+ onOutside: (hex: string) => void,
1006
+ ) => {
1007
+ const change = useRef(onChange);
1008
+ change.current = onChange;
1009
+ const outside = useRef(onOutside);
1010
+ outside.current = onOutside;
1011
+ // The page's cost is unknown until a first write comes back, so a first drag waits for a rest.
1012
+ const state = useRef({
1013
+ pending: null as string | null,
1014
+ frame: 0,
1015
+ timer: 0,
1016
+ cost: Number.POSITIVE_INFINITY,
1017
+ at: 0,
1018
+ });
1019
+ const sent = useRef<string[]>([]);
1020
+ const seen = useRef(value);
1021
+
1022
+ const send = () => {
1023
+ const w = state.current;
1024
+ w.frame = 0;
1025
+ const out = w.pending;
1026
+ w.pending = null;
1027
+ if (!out || out === seen.current) return;
1028
+ sent.current.push(out);
1029
+ w.at = performance.now();
1030
+ startTransition(() => change.current(out));
1031
+ };
1032
+
1033
+ const soon = () => {
1034
+ const w = state.current;
1035
+ clearTimeout(w.timer);
1036
+ w.timer = 0;
1037
+ if (!w.frame) w.frame = requestAnimationFrame(send);
1038
+ };
1039
+
1040
+ /** Queues a hex; `now` for a single step (a family, a release), not one frame of a drag. */
1041
+ const write = (hex: string, now = false) => {
1042
+ const w = state.current;
1043
+ w.pending = hex;
1044
+ if (now || w.cost < LIVE_MS) return soon();
1045
+ clearTimeout(w.timer);
1046
+ w.timer = window.setTimeout(soon, REST_MS);
1047
+ };
1048
+
1049
+ /** Sends what is waiting at once: the hand has let go. */
1050
+ const flush = () => {
1051
+ if (state.current.pending) soon();
1052
+ };
1053
+
1054
+ // Closing sends whatever is still waiting, so the last colour is never lost.
1055
+ useEffect(
1056
+ () => () => {
1057
+ const w = state.current;
1058
+ cancelAnimationFrame(w.frame);
1059
+ clearTimeout(w.timer);
1060
+ const last = w.pending;
1061
+ w.pending = null;
1062
+ if (last && last !== seen.current) change.current(last);
1063
+ },
1064
+ [],
1065
+ );
1066
+
1067
+ // A value back from the picker says how long the page took; one from outside moves the picker.
1068
+ useEffect(() => {
1069
+ if (value === seen.current) return;
1070
+ seen.current = value;
1071
+ const at = sent.current.indexOf(value);
1072
+ if (at < 0) {
1073
+ sent.current = [];
1074
+ outside.current(value);
1075
+ return;
1076
+ }
1077
+ sent.current.splice(0, at + 1);
1078
+ // The first frame after the commit tells how long the page took to follow.
1079
+ const started = state.current.at;
1080
+ requestAnimationFrame(time => {
1081
+ state.current.cost = time - started;
1082
+ });
1083
+ }, [value]);
1084
+
1085
+ return { write, flush };
1086
+ };
1087
+
1088
+ type PickerProps = {
1089
+ value: string;
1090
+ onChange: (hex: string) => void;
1091
+ /** The colour as it moves, before the page has taken it. */
1092
+ onLive: (hex: string) => void;
1093
+ /** What the colour is, for the labels of its controls. */
1094
+ label: string;
1095
+ hue: RefObject<number | undefined>;
1096
+ handleRef: RefObject<HTMLDivElement | null>;
1097
+ /** The theme's light and dark surface: with them the picker says how the colour reads as a fill. */
1098
+ surfaces?: Surfaces;
1099
+ };
1100
+
1101
+ /**
1102
+ * One surface's reading, and the switch for its check: the ratio, cut not rounded, and whether a
1103
+ * fill passes on it. Off, the ratio still shows, quietly, and the plane stops marking that surface.
1104
+ */
1105
+ const Reading = ({
1106
+ label,
1107
+ ratio,
1108
+ on,
1109
+ onToggle,
1110
+ }: {
1111
+ label: string;
1112
+ ratio: number;
1113
+ on: boolean;
1114
+ onToggle: () => void;
1115
+ }) => (
1116
+ <button
1117
+ aria-pressed={on}
1118
+ className={cn(
1119
+ '-mx-1.5 flex h-7 cursor-pointer items-center gap-1.5 rounded-chip px-1.5 transition-[background-color,opacity] duration-150 hover:bg-neutral-950/5',
1120
+ 'focus-visible:outline-2 focus-visible:outline-focus focus-visible:outline-solid',
1121
+ !on && 'opacity-50',
1122
+ )}
1123
+ onClick={onToggle}
1124
+ title={on ? `Stop checking ${label.toLowerCase()}` : `Check ${label.toLowerCase()}`}
1125
+ type="button"
1126
+ >
1127
+ <StatusDot tone={!on ? 'neutral' : ratio >= FILL ? 'success' : 'error'} />
1128
+ <span className={cn('text-neutral-600', !on && 'line-through')}>{label}</span>
1129
+ <span className="font-medium text-neutral-950 tabular-nums">
1130
+ {(Math.trunc(ratio * 100) / 100).toFixed(2)}:1
1131
+ </span>
1132
+ </button>
1133
+ );
1134
+
1135
+ /** The hue wheel as sRGB's models turn it, for the band under an HSB or HSL plane. */
1136
+ const srgbHueBand =
1137
+ 'linear-gradient(90deg, #f00, #ff0 16.67%, #0f0 33.33%, #0ff 50%, #00f 66.67%, #f0f 83.33%, #f00)';
1138
+
1139
+ const PickerBody = ({ value, onChange, onLive, label, hue, handleRef, surfaces }: PickerProps) => {
1140
+ // The colour as picked: its chroma may run past the edge after a turn of hue, and comes back
1141
+ // when the hue does. What is shown and written is the colour fitted inside sRGB.
1142
+ const [picked, setPicked] = useState(() => fromHex(value, hue.current));
1143
+ const color = fit(picked);
1144
+ const hex = oklchToHex(color);
1145
+ const { write, flush } = useWriter(value, onChange, next =>
1146
+ setPicked(previous => fromHex(next, previous.h)),
1147
+ );
1148
+
1149
+ // The notation the value is written in is the model the plane is drawn in.
1150
+ const [format, setFormat] = useState<ColorFormat>(sharedFormat);
1151
+ const model = modelOf(format);
1152
+
1153
+ const [checked, setChecked] = useState<Checked>(lastChecked);
1154
+ const toggle = (mode: keyof Checked) =>
1155
+ setChecked(now => {
1156
+ lastChecked = { ...now, [mode]: !now[mode] };
1157
+ return lastChecked;
1158
+ });
1159
+
1160
+ const pick = (next: Oklch, now = false) => {
1161
+ setPicked(next);
1162
+ hue.current = next.h;
1163
+ const out = oklchToHex(fit(next));
1164
+ onLive(out);
1165
+ write(out, now);
1166
+ };
1167
+
1168
+ // On an sRGB plane the place picked is kept as picked: a hex forgets its hue at grey and its
1169
+ // saturation at black, and the handle would jump there if it were read back from the hex.
1170
+ const kept = useRef<{ hex: string; model: Model; h: number; s: number; u: number } | null>(
1171
+ null,
1172
+ );
1173
+ const place = (() => {
1174
+ if (model === 'oklch') return null;
1175
+ const last = kept.current;
1176
+ if (last && last.model === model && sameHex(last.hex, hex)) return last;
1177
+ const read = fromSrgb(model, channelsOf(hex));
1178
+ const flat = model === 'hsb' ? read.u < 0.004 : read.u < 0.004 || read.u > 0.996;
1179
+ return {
1180
+ hex,
1181
+ model,
1182
+ h: read.s < 0.004 || flat ? (last?.h ?? read.h) : read.h,
1183
+ s: flat && last?.model === model ? last.s : read.s,
1184
+ u: read.u,
1185
+ };
1186
+ })();
1187
+ const pickSrgb = (h: number, s: number, u: number, now = false) => {
1188
+ if (model === 'oklch') return;
1189
+ const out = hexOf(srgbAt(model, h, s, u));
1190
+ kept.current = { hex: out, model, h, s, u };
1191
+ pick(fromHex(out, picked.h), now);
1192
+ };
1193
+
1194
+ // The plane in the model picked: what paints it, what its colours are, where the colour sits.
1195
+ const most = edge(color.l, color.h);
1196
+ const plane =
1197
+ model === 'oklch' || !place
1198
+ ? {
1199
+ key: `oklch-${picked.h}`,
1200
+ label: 'Lightness and chroma',
1201
+ paint: (canvas: HTMLCanvasElement) => paintPlane(canvas, picked.h),
1202
+ linearAt: (across: number, up: number) =>
1203
+ toLinearSrgb({ l: up, c: across * edge(up, picked.h), h: picked.h }),
1204
+ at: { across: most > 1e-4 ? clamp(color.c / most, 0, 1) : 0, up: color.l },
1205
+ onPickAt: (across: number, up: number) =>
1206
+ pick({ l: up, c: across * edge(up, picked.h), h: picked.h }),
1207
+ }
1208
+ : {
1209
+ key: `${model}-${place.h}`,
1210
+ label: model === 'hsb' ? 'Brightness and saturation' : 'Lightness and saturation',
1211
+ paint: (canvas: HTMLCanvasElement) => paintSrgbPlane(canvas, model, place.h),
1212
+ linearAt: (across: number, up: number) =>
1213
+ srgbAt(model, place.h, across, up).map(decode) as Channels,
1214
+ at: { across: place.s, up: place.u },
1215
+ onPickAt: (across: number, up: number) => pickSrgb(place.h, across, up),
1216
+ };
1217
+
1218
+ return (
1219
+ <>
1220
+ {/* How the colour reads as a fill leads, as the ratio leads a contrast checker. */}
1221
+ {surfaces && (
1222
+ <div
1223
+ className="flex items-center justify-between gap-3 whitespace-nowrap"
1224
+ title="As a fill (a checked box, a switch) on the theme's light and dark surface. A fill needs 3:1; the dotted colours miss it. Click one to stop checking it."
1225
+ >
1226
+ <Reading
1227
+ label="On light"
1228
+ on={checked.light}
1229
+ onToggle={() => toggle('light')}
1230
+ ratio={wcagContrast(color, surfaces.light)}
1231
+ />
1232
+ <Reading
1233
+ label="On dark"
1234
+ on={checked.dark}
1235
+ onToggle={() => toggle('dark')}
1236
+ ratio={wcagContrast(color, surfaces.dark)}
1237
+ />
1238
+ </div>
1239
+ )}
1240
+ <Plane
1241
+ at={plane.at}
1242
+ fill={hex}
1243
+ handleRef={handleRef}
1244
+ label={plane.label}
1245
+ linearAt={plane.linearAt}
1246
+ onPickAt={plane.onPickAt}
1247
+ onRelease={flush}
1248
+ paint={plane.paint}
1249
+ paintKey={plane.key}
1250
+ surfaces={
1251
+ surfaces && {
1252
+ light: checked.light ? surfaces.light : undefined,
1253
+ dark: checked.dark ? surfaces.dark : undefined,
1254
+ }
1255
+ }
1256
+ />
1257
+ {/* A drag on the hue lets go here as well; the pointer's release bubbles up from the slider. */}
1258
+ <div onPointerUp={flush}>
1259
+ {model === 'oklch' || !place ? (
1260
+ <BandSlider
1261
+ display={`${Math.round(picked.h)}°`}
1262
+ knob={hueKnob(picked.h)}
1263
+ label="Hue"
1264
+ max={360}
1265
+ min={0}
1266
+ onValueChange={h => pick({ ...picked, h })}
1267
+ step={1}
1268
+ track={hueBand}
1269
+ value={picked.h}
1270
+ />
1271
+ ) : (
1272
+ <BandSlider
1273
+ display={`${Math.round(place.h)}°`}
1274
+ knob={`hsl(${place.h} 100% 50%)`}
1275
+ label="Hue"
1276
+ max={360}
1277
+ min={0}
1278
+ onValueChange={h => pickSrgb(h, place.s, place.u)}
1279
+ step={1}
1280
+ track={srgbHueBand}
1281
+ value={place.h}
1282
+ />
1283
+ )}
1284
+ </div>
1285
+ {/* The value by hand; its notation is also the plane's model. */}
1286
+ <ColorField
1287
+ format={format}
1288
+ label={label}
1289
+ onChange={next => pick(fromHex(next, picked.h), true)}
1290
+ onFormat={setFormat}
1291
+ value={hex}
1292
+ />
1293
+ </>
1294
+ );
1295
+ };
1296
+
1297
+ export type ColorPickerProps = {
1298
+ /** The colour as hex. */
1299
+ value: string;
1300
+ onChange: (hex: string) => void;
1301
+ /** What the colour is, for the labels of its controls: "Primary", "Label colour". */
1302
+ label?: string;
1303
+ /**
1304
+ * The light and the dark surface the colour sits on as a fill, as hex. With them the picker
1305
+ * leads with the contrast on each, and dots over the colours that miss 3:1 against either.
1306
+ */
1307
+ contrast?: { light: string; dark: string };
1308
+ /** On the well, for one that is not the 34px square: a swatch in a strip, a dot in a row. */
1309
+ className?: string;
1310
+ };
1311
+
1312
+ /**
1313
+ * A colour's well, opening its picker: a plane at one hue, the hue, and the value by hand in hex,
1314
+ * rgb, hsl or oklch. The notation picked is also the model the plane is drawn in.
1315
+ */
1316
+ export const ColorPicker = ({
1317
+ value,
1318
+ onChange,
1319
+ label = 'Colour',
1320
+ contrast,
1321
+ className,
1322
+ }: ColorPickerProps) => {
1323
+ // The hue last picked, so a grey (whose own hue means nothing) reopens where it was left.
1324
+ const hue = useRef<number | undefined>(undefined);
1325
+ // The plane's handle takes the focus on opening, so the arrows move the colour at once.
1326
+ const handleRef = useRef<HTMLDivElement>(null);
1327
+ // The well shows the colour as it moves; once the page has a value of its own again, that.
1328
+ const [live, setLive] = useState<string>();
1329
+ const [shownFor, setShownFor] = useState(value);
1330
+ if (shownFor !== value) {
1331
+ setShownFor(value);
1332
+ setLive(undefined);
1333
+ }
1334
+
1335
+ const onLight = contrast?.light;
1336
+ const onDark = contrast?.dark;
1337
+ const surfaces = useMemo(
1338
+ () =>
1339
+ onLight && onDark
1340
+ ? {
1341
+ light: hexToOklch(onLight) ?? { l: 1, c: 0, h: 0 },
1342
+ dark: hexToOklch(onDark) ?? { l: 0, c: 0, h: 0 },
1343
+ }
1344
+ : undefined,
1345
+ [onLight, onDark],
1346
+ );
1347
+
1348
+ return (
1349
+ <Popover>
1350
+ <PopoverTrigger
1351
+ aria-label={`Pick the ${label.toLowerCase()}`}
1352
+ className={cn(
1353
+ // The box is Input's: the same border, shadow and corners, so it sits in a row
1354
+ // of controls as one of them rather than as a slab of colour.
1355
+ 'size-control shrink-0 cursor-pointer rounded-control border border-neutral-200 p-[3px] shadow-control transition-[border-color] duration-150 hover:border-neutral-300',
1356
+ 'outline-none focus-visible:outline-2 focus-visible:outline-focus focus-visible:outline-solid focus-visible:outline-offset-2',
1357
+ 'data-popup-open:outline-2 data-popup-open:outline-neutral-300 data-popup-open:outline-solid data-popup-open:outline-offset-2',
1358
+ className,
1359
+ )}
1360
+ data-slot="color-picker"
1361
+ >
1362
+ {/* The colour inset in the box, as the segmented control insets its segment: a fixed
1363
+ 3px at every size, with its corner the box's less that inset. No edge of its own:
1364
+ the box's border is the one that holds it. */}
1365
+ <span
1366
+ aria-hidden
1367
+ className="block size-full rounded-[calc(var(--radius-control)-3px)]"
1368
+ data-slot="color-picker-swatch"
1369
+ style={{ background: live ?? value }}
1370
+ />
1371
+ </PopoverTrigger>
1372
+ <PopoverContent align="start" aria-label={label} initialFocus={handleRef}>
1373
+ <PickerBody
1374
+ handleRef={handleRef}
1375
+ hue={hue}
1376
+ label={label}
1377
+ onChange={onChange}
1378
+ onLive={setLive}
1379
+ surfaces={surfaces}
1380
+ value={value}
1381
+ />
1382
+ </PopoverContent>
1383
+ </Popover>
1384
+ );
1385
+ };