All files / react-classic/src/components ColorPicker.tsx

100% Statements 40/40
100% Branches 15/15
100% Functions 2/2
100% Lines 40/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50  1x   1x     1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x 17x   17x 5x 5x 5x 17x 17x   17x 17x 17x 17x 17x 17x 17x 3x 2x 2x   3x 3x 17x 17x 17x 17x   17x  
import type { Bindable } from '../index.js';
import { debugRender, useValue } from '../index.js';
import type { WritableKeys } from '@anchorlib/core';
import { useMemo, useRef } from 'react';
import type { InputProps } from './Types.js';
 
export function ColorPicker<T extends Bindable, K extends WritableKeys<T>>({
  bind,
  name,
  value,
  inherits,
  onChange,
  children,
  className,
  placeholder,
  ...props
}: InputProps<T, K>) {
  const ref = useRef<HTMLLabelElement>(null);
  debugRender(ref);
 
  const inheritedPlaceholder: string | undefined = useMemo(() => {
    if (!Array.isArray(inherits) || !inherits.length) return undefined;
 
    for (const ref of inherits) {
      const refValue = ref?.[name as never];
      if (refValue !== undefined) return refValue as string;
    }
  }, [bind, name, value]);
  const current = (useValue(bind, name) ?? value ?? inheritedPlaceholder ?? placeholder ?? '#000000') as string;
 
  return (
    <label ref={ref} className={className} style={{ backgroundColor: current }}>
      <input
        type={'color'}
        name={name as string}
        value={current}
        onChange={(e) => {
          if (bind) {
            bind[name] = e.target.value as never;
          }
 
          onChange?.(e);
        }}
        {...props}
      />
      {children}
    </label>
  );
}