displayHex.ts 983 B

12345678910111213141516171819
  1. /**
  2. * The hex to print next to a swatch in the slot picker (#3159).
  3. *
  4. * Shown because two slots whose colour names resolved the same way -- both
  5. * "Orange", one a beige -- are otherwise indistinguishable in the list, and
  6. * comparing them against the slice's colour is the reason the picker exists.
  7. *
  8. * Alpha is kept only when it carries information: a translucent spool prints
  9. * all eight digits, an opaque one prints six, so a Clear filament is not shown
  10. * as if it were solid. Returns null for anything unreadable, and the caller
  11. * then prints no hex rather than a misleading one.
  12. */
  13. export function displayHex(color: string | null | undefined): string | null {
  14. if (!color) return null;
  15. const clean = color.trim().replace(/^#/, '');
  16. if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(clean)) return null;
  17. const keepAlpha = clean.length === 8 && clean.substring(6, 8).toLowerCase() !== 'ff';
  18. return `#${(keepAlpha ? clean : clean.substring(0, 6)).toUpperCase()}`;
  19. }