import { crc32 } from 'crc' ; import Vibrant from 'node-vibrant' ; import React from 'react' ; import { robotHash } from './robots' ; function _hash ( s ) { return crc32 ( s ) ; } export class ColorManager { readonly conflictHighlight = '#f44336' ; async robotPrimaryColor ( fleet , name , model , image ? ) { const key = robotHash ( name , fleet ) ; if ( this . _robotColorCache [ key ] ) { return this . _robotColorCache [ key ] ; } if ( ! image ) { this . _robotColorCache [ key ] = this . _robotColorFromId ( fleet , name , model ) ; return this . _robotColorCache [ key ] ; } else { try { const palette = await Vibrant . from ( image ) . getSwatches ( ) ; const rgb = palette . Vibrant ?. getRgb ( ) ; if ( rgb ) { const colorHolder = `rgb(${ rgb [ 0 ] }, ${ rgb [ 1 ] }, ${ rgb [ 2 ] })` ; this . _robotColorCache [ key ] = colorHolder ; return colorHolder ; } } catch ( e ) { console . warn ( `unable to get color from image, falling back to color from id (${ ( e as Error ) . message })` ) ; } return this . robotPrimaryColor ( fleet , name , model ) ; } } private static _getLightColor ( firstNumber , secondNumber ) { const hue = 50 + ( firstNumber % 220 ) ; const satlum = secondNumber % 2500 ; const saturation = 50 + ( satlum % 50 ) ; const luminance = 25 + satlum / 50 ; return `hsl(${ hue }, ${ saturation }%, ${ luminance }%)` ; } private _robotColorFromId ( fleet , name , model ) { const modelHash = _hash ( model ) ; const nameHash = _hash ( name ) ; return ColorManager . _getLightColor ( modelHash , nameHash ) ; } private _robotColorCache : Record < string , string > = { } ; } export default ColorManager ; export const ColorContext = React . createContext ( new ColorManager ( ) ) ;