colors.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. * Convert hex color to basic color name using HSL analysis.
  48. * Used as fallback when hex is not in the runtime catalog.
  49. */
  50. export function hexToColorName(hex: string | null | undefined): string {
  51. if (!hex || hex.length < 6) return 'Unknown';
  52. const cleanHex = hex.replace('#', '');
  53. const r = parseInt(cleanHex.substring(0, 2), 16);
  54. const g = parseInt(cleanHex.substring(2, 4), 16);
  55. const b = parseInt(cleanHex.substring(4, 6), 16);
  56. const max = Math.max(r, g, b) / 255;
  57. const min = Math.min(r, g, b) / 255;
  58. const l = (max + min) / 2;
  59. let h = 0;
  60. let s = 0;
  61. if (max !== min) {
  62. const d = max - min;
  63. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  64. const rNorm = r / 255, gNorm = g / 255, bNorm = b / 255;
  65. if (max === rNorm) h = ((gNorm - bNorm) / d + (gNorm < bNorm ? 6 : 0)) / 6;
  66. else if (max === gNorm) h = ((bNorm - rNorm) / d + 2) / 6;
  67. else h = ((rNorm - gNorm) / d + 4) / 6;
  68. }
  69. h = h * 360;
  70. if (l < 0.15) return 'Black';
  71. if (l > 0.85) return 'White';
  72. if (s < 0.15) {
  73. if (l < 0.4) return 'Dark Gray';
  74. if (l > 0.6) return 'Light Gray';
  75. return 'Gray';
  76. }
  77. // Brown is orange/yellow hue with lower lightness
  78. if (h >= 15 && h < 45 && l < 0.45) return 'Brown';
  79. if (h >= 45 && h < 70 && l < 0.40) return 'Brown';
  80. if (h < 15 || h >= 345) return 'Red';
  81. if (h < 45) return 'Orange';
  82. if (h < 70) return 'Yellow';
  83. if (h < 150) return 'Green';
  84. if (h < 200) return 'Cyan';
  85. if (h < 260) return 'Blue';
  86. if (h < 290) return 'Purple';
  87. return 'Pink';
  88. }
  89. /**
  90. * Get color name from hex color.
  91. * Looks up the runtime color catalog (backend-sourced), then falls back to HSL.
  92. */
  93. export function getColorName(hexColor: string): string {
  94. if (!hexColor) return hexToColorName(hexColor);
  95. const hex = hexColor.replace('#', '').toLowerCase().substring(0, 6);
  96. const mapped = runtimeColorCatalog[hex];
  97. if (mapped) return mapped;
  98. return hexToColorName(hexColor);
  99. }
  100. /**
  101. * Resolve a spool's display color name.
  102. * Tries: stored color_name (if it's a readable name) → runtime catalog via rgba → null.
  103. * Detects Bambu internal codes (e.g. "A06-D0") and ignores them in favor of hex lookup
  104. * because the same code is not globally unique across material families (#857).
  105. */
  106. export function resolveSpoolColorName(colorName: string | null, rgba: string | null): string | null {
  107. // If color_name looks like a readable name (no pattern like "X00-Y0"), use it directly
  108. if (colorName && !/^[A-Z]\d+-[A-Z]\d+$/.test(colorName)) {
  109. return colorName;
  110. }
  111. // Try hex color lookup from rgba via the runtime catalog
  112. if (rgba && rgba.length >= 6) {
  113. const hex = rgba.substring(0, 6).toLowerCase();
  114. const mapped = runtimeColorCatalog[hex];
  115. if (mapped) return mapped;
  116. }
  117. // Return null (displayed as "-") — better than showing a code
  118. return null;
  119. }
  120. /**
  121. * Parse an RGBA hex string (e.g., "FF0000FF") to a CSS rgba() color.
  122. * Returns null for empty, all-zero, or fully transparent colors.
  123. */
  124. export function parseFilamentColor(rgba: string): string | null {
  125. if (!rgba || rgba === '00000000' || rgba.length < 6) return null;
  126. const r = rgba.slice(0, 2);
  127. const g = rgba.slice(2, 4);
  128. const b = rgba.slice(4, 6);
  129. const a = rgba.length >= 8 ? parseInt(rgba.slice(6, 8), 16) / 255 : 1;
  130. if (a === 0) return null;
  131. return `rgba(${parseInt(r, 16)}, ${parseInt(g, 16)}, ${parseInt(b, 16)}, ${a})`;
  132. }
  133. /**
  134. * Check if a hex color is light (for choosing text contrast).
  135. * Uses luminance formula: 0.299*R + 0.587*G + 0.114*B.
  136. */
  137. export function isLightColor(hex: string | null): boolean {
  138. if (!hex || hex.length < 6) return false;
  139. const cleanHex = hex.replace('#', '');
  140. const r = parseInt(cleanHex.slice(0, 2), 16);
  141. const g = parseInt(cleanHex.slice(2, 4), 16);
  142. const b = parseInt(cleanHex.slice(4, 6), 16);
  143. return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6;
  144. }