colors.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Runtime color-name catalog, populated once at app startup by ColorCatalogProvider
  2. // from /api/inventory/colors/map. The backend color_catalog table is the single
  3. // source of truth — no hardcoded hex→name tables live on the frontend anymore.
  4. //
  5. // Keyed by lowercase 6-char hex (no leading '#'). Lookups before the provider has
  6. // fetched the catalog fall through to hexToColorName (HSL-based bucketing). A
  7. // subscribe/getSnapshot pair lets React components re-render via
  8. // useSyncExternalStore when the catalog loads, so pages that mount before the
  9. // fetch resolves (InventoryPage, PrintersPage) update to the catalog name once it
  10. // arrives instead of staying stuck on the HSL fallback.
  11. let runtimeColorCatalog: Record<string, string> = {};
  12. let catalogVersion = 0;
  13. const catalogListeners = new Set<() => void>();
  14. export function setColorCatalog(map: Record<string, string>): void {
  15. // Normalize keys to lowercase 6-char hex (no '#'), defensively. Backend already
  16. // does this, but the frontend contract is explicit so callers from tests or
  17. // future integrations can't accidentally break lookups.
  18. const normalized: Record<string, string> = {};
  19. for (const [key, value] of Object.entries(map)) {
  20. if (!key || !value) continue;
  21. const hex = key.replace('#', '').toLowerCase().slice(0, 6);
  22. if (hex.length === 6) normalized[hex] = value;
  23. }
  24. runtimeColorCatalog = normalized;
  25. catalogVersion += 1;
  26. // Snapshot listeners to avoid mutation-during-iteration if a listener unsubscribes.
  27. for (const listener of Array.from(catalogListeners)) {
  28. listener();
  29. }
  30. }
  31. export function subscribeColorCatalog(listener: () => void): () => void {
  32. catalogListeners.add(listener);
  33. return () => {
  34. catalogListeners.delete(listener);
  35. };
  36. }
  37. export function getColorCatalogVersion(): number {
  38. return catalogVersion;
  39. }
  40. /** Test-only hook: reset the catalog to empty so unit tests can exercise fallbacks. */
  41. export function __resetColorCatalogForTests(): void {
  42. runtimeColorCatalog = {};
  43. catalogVersion = 0;
  44. catalogListeners.clear();
  45. }
  46. /**
  47. * Colour families, in the order the Inventory's Color column sorts them (#2729).
  48. *
  49. * Chromatic families run in rainbow order with Brown after them (it is a dark
  50. * orange by hue and would otherwise split the oranges in half), then the
  51. * neutrals light-to-dark, then Clear.
  52. */
  53. export const COLOR_FAMILY_ORDER = [
  54. 'Red',
  55. 'Orange',
  56. 'Yellow',
  57. 'Green',
  58. 'Cyan',
  59. 'Blue',
  60. 'Purple',
  61. 'Pink',
  62. 'Brown',
  63. 'White',
  64. 'Light Gray',
  65. 'Gray',
  66. 'Dark Gray',
  67. 'Black',
  68. 'Clear',
  69. ] as const;
  70. export type ColorFamily = (typeof COLOR_FAMILY_ORDER)[number];
  71. /** Families whose hue carries no meaning — see ``colorSortKey``. */
  72. const ACHROMATIC_FAMILIES = new Set<ColorFamily>([
  73. 'White',
  74. 'Light Gray',
  75. 'Gray',
  76. 'Dark Gray',
  77. 'Black',
  78. 'Clear',
  79. ]);
  80. interface Hsl {
  81. h: number;
  82. s: number;
  83. l: number;
  84. }
  85. /** Parse 6/8-char hex (with or without '#') to HSL, or null if unparseable. */
  86. function hexToHsl(hex: string | null | undefined): Hsl | null {
  87. if (!hex || hex.length < 6) return null;
  88. const cleanHex = hex.replace('#', '');
  89. const r = parseInt(cleanHex.substring(0, 2), 16);
  90. const g = parseInt(cleanHex.substring(2, 4), 16);
  91. const b = parseInt(cleanHex.substring(4, 6), 16);
  92. if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null;
  93. const max = Math.max(r, g, b) / 255;
  94. const min = Math.min(r, g, b) / 255;
  95. const l = (max + min) / 2;
  96. let h = 0;
  97. let s = 0;
  98. if (max !== min) {
  99. const d = max - min;
  100. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  101. const rNorm = r / 255, gNorm = g / 255, bNorm = b / 255;
  102. if (max === rNorm) h = ((gNorm - bNorm) / d + (gNorm < bNorm ? 6 : 0)) / 6;
  103. else if (max === gNorm) h = ((bNorm - rNorm) / d + 2) / 6;
  104. else h = ((rNorm - gNorm) / d + 4) / 6;
  105. }
  106. return { h: h * 360, s, l };
  107. }
  108. /**
  109. * Classify a hex colour into one of ``COLOR_FAMILY_ORDER``, or null if the
  110. * value can't be parsed.
  111. *
  112. * This is the single source of truth for both the fallback colour *name* shown
  113. * when a hex isn't in the catalog and the *order* the Color column sorts in, so
  114. * the two cannot drift into disagreeing about what counts as brown or grey.
  115. */
  116. export function colorFamily(hex: string | null | undefined): ColorFamily | null {
  117. if (!hex || hex.length < 6) return null;
  118. const cleanHex = hex.replace('#', '');
  119. // Alpha=00 → fully transparent. Classify as 'Clear' before looking at RGB,
  120. // otherwise #00000000 (Bambu's transparent code) would come out 'Black' (#1545).
  121. if (cleanHex.length === 8 && cleanHex.substring(6, 8).toLowerCase() === '00') {
  122. return 'Clear';
  123. }
  124. const hsl = hexToHsl(cleanHex);
  125. if (!hsl) return null;
  126. const { h, s, l } = hsl;
  127. if (l < 0.15) return 'Black';
  128. if (l > 0.85) return 'White';
  129. if (s < 0.15) {
  130. if (l < 0.4) return 'Dark Gray';
  131. if (l > 0.6) return 'Light Gray';
  132. return 'Gray';
  133. }
  134. // Brown is orange/yellow hue with lower lightness
  135. if (h >= 15 && h < 45 && l < 0.45) return 'Brown';
  136. if (h >= 45 && h < 70 && l < 0.40) return 'Brown';
  137. if (h < 15 || h >= 345) return 'Red';
  138. if (h < 45) return 'Orange';
  139. if (h < 70) return 'Yellow';
  140. if (h < 150) return 'Green';
  141. if (h < 200) return 'Cyan';
  142. if (h < 260) return 'Blue';
  143. if (h < 290) return 'Purple';
  144. return 'Pink';
  145. }
  146. /**
  147. * Convert hex color to basic color name using HSL analysis.
  148. * Used as fallback when hex is not in the runtime catalog.
  149. */
  150. export function hexToColorName(hex: string | null | undefined): string {
  151. return colorFamily(hex) ?? 'Unknown';
  152. }
  153. /**
  154. * Sort key placing a spool colour in rainbow order (#2729, reporter @macwhiz).
  155. *
  156. * Returns a fixed-width string so it drops into the Inventory table's existing
  157. * ``string | number`` comparison with no extra plumbing, ascending = Red first.
  158. *
  159. * The issue asked for a straight hue → saturation → lightness sort, which does
  160. * not survive contact with a real inventory: a near-neutral still has a hue and
  161. * it can be anything. Measured against a 30-spool inventory, Titan Gray
  162. * (5F6367, hue 210°, saturation 0.04) landed between Sky Blue and Purple, and
  163. * 8B8889 (hue 340°, saturation 0.01) landed between Purple and Burgundy Red.
  164. * Black, white and silver happen to clump correctly — zero saturation sorts
  165. * first within hue 0 — but anything a shade off neutral flies into the colours.
  166. *
  167. * So the family from ``colorFamily`` leads, and the continuous sort the issue
  168. * asked for runs inside each family. Within a neutral family hue is discarded
  169. * rather than sorted on, for the same reason it is not trusted to pick the
  170. * family: ordering greys by 210° vs 340° is ordering them by noise. Neutrals go
  171. * light-to-dark instead, matching the order of the families themselves.
  172. *
  173. * Unparseable or missing colours sort last in ascending order, so a spool with
  174. * no colour recorded never leads the list.
  175. */
  176. export function colorSortKey(rgba: string | null | undefined): string {
  177. const family = colorFamily(rgba);
  178. if (!family) return '99|0000|0000|0000';
  179. const rank = String(COLOR_FAMILY_ORDER.indexOf(family)).padStart(2, '0');
  180. const hsl = hexToHsl(rgba) ?? { h: 0, s: 0, l: 0 };
  181. const pad4 = (n: number) => String(Math.round(n)).padStart(4, '0');
  182. if (ACHROMATIC_FAMILIES.has(family)) {
  183. // Lightness descending, so lighter shades lead within the family just as
  184. // White leads Black across families. Hue is deliberately zeroed.
  185. return `${rank}|0000|${pad4(1000 - hsl.l * 1000)}|${pad4(hsl.s * 1000)}`;
  186. }
  187. return `${rank}|${pad4(hsl.h * 10)}|${pad4(hsl.s * 1000)}|${pad4(hsl.l * 1000)}`;
  188. }
  189. /**
  190. * Get color name from hex color.
  191. * Looks up the runtime color catalog (backend-sourced), then falls back to HSL.
  192. */
  193. export function getColorName(hexColor: string): string {
  194. if (!hexColor) return hexToColorName(hexColor);
  195. const clean = hexColor.replace('#', '').toLowerCase();
  196. if (clean.length === 8 && clean.substring(6, 8) === '00') return 'Clear';
  197. const hex = clean.substring(0, 6);
  198. const mapped = runtimeColorCatalog[hex];
  199. if (mapped) return mapped;
  200. return hexToColorName(hexColor);
  201. }
  202. /**
  203. * Resolve a spool's display color name.
  204. * Tries: stored color_name (if it's a readable name) → runtime catalog via rgba → null.
  205. * Detects Bambu internal codes (e.g. "A06-D0") and ignores them in favor of hex lookup
  206. * because the same code is not globally unique across material families (#857).
  207. */
  208. export function resolveSpoolColorName(colorName: string | null, rgba: string | null): string | null {
  209. // If color_name looks like a readable name (no pattern like "X00-Y0"), use it directly
  210. if (colorName && !/^[A-Z]\d+-[A-Z]\d+$/.test(colorName)) {
  211. return colorName;
  212. }
  213. if (rgba && rgba.length >= 6) {
  214. const clean = rgba.replace('#', '').toLowerCase();
  215. // Transparent rgba: don't fall through to RGB-based lookup that would
  216. // return 'Black' for #00000000 (#1545).
  217. if (clean.length === 8 && clean.substring(6, 8) === '00') return 'Clear';
  218. const hex = clean.substring(0, 6);
  219. const mapped = runtimeColorCatalog[hex];
  220. if (mapped) return mapped;
  221. }
  222. // Return null (displayed as "-") — better than showing a code
  223. return null;
  224. }
  225. /**
  226. * Build a hex string suitable for SVG `fill=` / props that take a single
  227. * colour value. Preserves the alpha byte when alpha < FF so a transparent
  228. * spool renders translucent in SVG / CSS rather than collapsing to solid
  229. * black (#1545). Null / malformed input falls back to `#808080`.
  230. *
  231. * Prefer `getSwatchStyle` for `style` objects that paint a div background —
  232. * that helper paints a visible checkerboard under transparent fills.
  233. */
  234. export function spoolColorString(rgba: string | null | undefined): string {
  235. if (!rgba) return '#808080';
  236. const clean = rgba.replace(/^#/, '');
  237. if (clean.length < 6) return '#808080';
  238. if (clean.length >= 8 && clean.substring(6, 8).toLowerCase() !== 'ff') {
  239. return `#${clean.substring(0, 8)}`;
  240. }
  241. return `#${clean.substring(0, 6)}`;
  242. }
  243. /**
  244. * Build an inline-style object for a simple filament swatch (a div / button
  245. * background) given a spool's rgba. Opaque colours return a plain
  246. * `backgroundColor`; transparent (alpha=00) returns a small checkerboard
  247. * pattern so the user can see the swatch instead of an invisible element
  248. * (#1545). Null / unparseable input falls back to the neutral `#808080` used
  249. * elsewhere in the codebase.
  250. *
  251. * Use this anywhere a quick swatch was previously painted via
  252. * `style={{ backgroundColor: '#' + rgba.slice(0, 6) }}` — alpha-stripping
  253. * silently turned `Clear` spools into solid black.
  254. *
  255. * NOTE: `FilamentSwatch` already paints a richer checkerboard underlay
  256. * automatically for translucent colours; prefer that for new code and use
  257. * this helper only when retro-fitting an existing simple swatch site.
  258. */
  259. export function getSwatchStyle(rgba: string | null | undefined): {
  260. backgroundColor?: string;
  261. backgroundImage?: string;
  262. backgroundSize?: string;
  263. } {
  264. if (!rgba) return { backgroundColor: '#808080' };
  265. const clean = rgba.replace(/^#/, '');
  266. if (clean.length < 6) return { backgroundColor: '#808080' };
  267. if (clean.length >= 8 && clean.substring(6, 8).toLowerCase() === '00') {
  268. return {
  269. backgroundImage: 'repeating-conic-gradient(#979797 0% 25%, #f5f5f5 0% 50%)',
  270. backgroundSize: '8px 8px',
  271. };
  272. }
  273. return { backgroundColor: `#${clean.substring(0, 6)}` };
  274. }
  275. /**
  276. * Parse an RGBA hex string (e.g., "FF0000FF") to a CSS rgba() color.
  277. * Returns null for empty, all-zero, or fully transparent colors.
  278. */
  279. export function parseFilamentColor(rgba: string): string | null {
  280. if (!rgba || rgba === '00000000' || rgba.length < 6) return null;
  281. const r = rgba.slice(0, 2);
  282. const g = rgba.slice(2, 4);
  283. const b = rgba.slice(4, 6);
  284. const a = rgba.length >= 8 ? parseInt(rgba.slice(6, 8), 16) / 255 : 1;
  285. if (a === 0) return null;
  286. return `rgba(${parseInt(r, 16)}, ${parseInt(g, 16)}, ${parseInt(b, 16)}, ${a})`;
  287. }
  288. /**
  289. * Check if a hex color is light (for choosing text contrast).
  290. * Uses luminance formula: 0.299*R + 0.587*G + 0.114*B.
  291. */
  292. export function isLightColor(hex: string | null): boolean {
  293. if (!hex || hex.length < 6) return false;
  294. const cleanHex = hex.replace('#', '');
  295. // Transparent swatches are painted over the light/mid-gray checkerboard
  296. // underlay, so treat them as light for text-contrast purposes (#1545).
  297. if (cleanHex.length === 8 && cleanHex.slice(6, 8).toLowerCase() === '00') return true;
  298. const r = parseInt(cleanHex.slice(0, 2), 16);
  299. const g = parseInt(cleanHex.slice(2, 4), 16);
  300. const b = parseInt(cleanHex.slice(4, 6), 16);
  301. return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6;
  302. }