react-color#ColorResult TypeScript Examples

The following examples show how to use react-color#ColorResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From imove with MIT License 6 votes vote down vote up
ColorPicker: React.FC<IProps> = (props) => {
  const { color, onChangeComplete: changeCb } = props;
  const [curColor, setCurColor] = useState(color);

  // life
  useEffect(() => setCurColor(color), [color]);

  // events
  const onChange = (color: ColorResult): void => setCurColor(color.hex);
  const onChangeComplete = (color: ColorResult): void => changeCb(color.hex);

  return (
    <SketchPicker
      color={curColor}
      onChange={onChange}
      onChangeComplete={onChangeComplete}
    />
  );
}
Example #2
Source File: SpectrumPalette.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
SpectrumPalette: React.FunctionComponent<SpectrumPaletteProps> = ({ color, onChange, theme }) => {
  return (
    <div>
      <SpectrumPicker
        color={tinycolor(getColorFromHexRgbOrName(color)).toRgb()}
        onChange={(a: ColorResult) => {
          onChange(tinycolor(a.rgb).toString());
        }}
        theme={theme}
      />
      <ColorInput theme={theme} color={color} onChange={onChange} style={{ marginTop: '16px' }} />
    </div>
  );
}
Example #3
Source File: AvatarUI.tsx    From avalon.ist with MIT License 5 votes vote down vote up
handleHighlight(color: ColorResult) {
    this.setState({ currentHighlight: color.rgb });
    if (this.state.highlightChat) {
      this.highlightChat();
    }
  }
Example #4
Source File: ColorInput.tsx    From next-right-now-admin with MIT License 5 votes vote down vote up
ColorInput = (props: Props) => {
  console.debug('ColorInput.props', props);
  const {
    label,
    source,
    options,
    picker = 'Twitter',
    record,
  } = props;
  const Picker = ReactColor[`${picker}Picker`];

  const {
    input: { name, onChange },
    meta: { touched, error },
    isRequired,
  } = useInput(props);
  const [show, setShow]: [boolean, Function] = useState(false);

  return (
    <div>
      <div
        onClick={() => setShow(!show)}
      >
        <ColorField
          source={source}
          record={record}
        />
      </div>
      {
        show ? (
          <div
            css={css`
              position: absolute;
              z-index: 2;
            `}
          >
            <div
              css={css`
                  position: fixed;
                  top: 0; bottom: 0;
                  left: 0; right: 0;
                `}
            />
            <Picker
              {...options}
              color={get(record, source)}
              onChange={(color: ColorResult) => {
                const { hex } = color;

                onChange(hex);
                setShow(false);
                record[source] = hex;
              }}
            />
          </div>
        ) : null
      }
    </div>
  );
}
Example #5
Source File: ColorEditorItem.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function LegacyColorPick(
  props: ColorEditorItemProps,
  ref: React.Ref<any>
) {
  const [value, setValue] = useState(props.value);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setValue(props.value);
  }, [props.value]);

  const handleChangeComplete = (color: ColorResult) => {
    setValue(color.hex);
    props.onChange(color.hex);
  };

  const handleClick = () => {
    setVisible(true);
  };

  return (
    <div className={styles.colorContainer}>
      <div className={styles.colorCube} onClick={handleClick}>
        <div
          className={styles.colorContent}
          style={{ backgroundColor: value }}
        />
      </div>
      {visible && (
        <div className={styles.popover}>
          <div className={styles.cover} onClick={() => setVisible(false)} />
          <SketchPicker
            width="230px"
            ref={ref}
            color={value}
            onChangeComplete={handleChangeComplete}
            presetColors={getPresetColors(COLORS_MAP)}
          />
        </div>
      )}
    </div>
  );
}
Example #6
Source File: button-bg-color.tsx    From fantasy-editor with MIT License 5 votes vote down vote up
ButtonBgColor: FunctionComponent<Props> = props => {
  const [visible, setVisible] = useState(false);
  const editor = useSlate();
  const {
    editor: { removeColor },
  } = useLocale();
  const [color, setColor] = useState<string>('#1890ff');
  const [mark, setMark] = useState<Range | null>(null);

  const handleColorChange = (v: ColorResult) => {
    setColor(v.hex);
    setVisible(false);
    if (mark) {
      ReactEditor.focus(editor);
      Transforms.select(editor, mark);
      if (isMarkActive(editor, MARK_BG_COLOR) && v.hex === '#fff') {
        editor.removeMark(MARK_BG_COLOR);
      } else {
        editor.addMark(MARK_BG_COLOR, v.hex);
      }
    }
  };

  const cleanColor = () => {
    editor.removeMark(MARK_BG_COLOR);
    setVisible(false);
  };

  const show = () => {
    const { selection } = editor;
    setMark(selection);
    setVisible(true);
  };

  const overlay = (
    <div className={classNames('fc-btn-bg-content', 'ant-dropdown-menu')} onMouseDown={e => e.stopPropagation()}>
      <div className="fc-btn-bg-header" onClick={cleanColor}>
        <IconClear />
        <span>{removeColor}</span>
      </div>
      <SketchPicker disableAlpha={true} color={color} onChange={handleColorChange} />
    </div>
  );

  return (
    <Dropdown
      trigger={['click']}
      overlay={overlay}
      visible={visible}
      overlayClassName="fc-btn-bg-overlay"
      onVisibleChange={setVisible}
      disabled={isBlockActive(editor, BLOCK_CODE)}
    >
      <DropdownButton width={45} onMouseDown={show}
                      disabled={isBlockActive(editor, BLOCK_CODE)}>
        <IconBgColor />
      </DropdownButton>
    </Dropdown>
  );
}
Example #7
Source File: button-font-color.tsx    From fantasy-editor with MIT License 5 votes vote down vote up
ButtonFontColor: FunctionComponent<Props> = props => {
  const [visible, setVisible] = useState(false);
  const editor = useSlate();
  const {
    editor: { removeColor },
  } = useLocale();
  const [color, setColor] = useState<string>('#1890ff');
  const [mark, setMark] = useState<Range | null>(null);

  const handleColorChange = (v: ColorResult) => {
    setColor(v.hex);
    setVisible(false);
    if (mark) {
      ReactEditor.focus(editor);
      Transforms.select(editor, mark);
      if (isMarkActive(editor, MARK_COLOR) && v.hex === '#000000') {
        editor.removeMark(MARK_COLOR);
      } else {
        editor.addMark(MARK_COLOR, v.hex);
      }
    }
  };

  const cleanColor = () => {
    editor.removeMark(MARK_COLOR);
    setVisible(false);
  };

  const show = () => {
    const { selection } = editor;
    setMark(selection);
    setVisible(true);
  };

  const overlay = (
    <div className={classNames('fc-btn-font-content', 'ant-dropdown-menu')} onMouseDown={e => e.stopPropagation()}>
      <div className="fc-btn-font-header" onClick={cleanColor}>
        <IconClear />
        <span>{removeColor}</span>
      </div>
      <SketchPicker disableAlpha={true} color={color} onChange={handleColorChange} />
    </div>
  );

  return (
    <Dropdown
      trigger={['click']}
      overlay={overlay}
      visible={visible}
      overlayClassName="fc-btn-font-overlay"
      onVisibleChange={setVisible}
      disabled={isBlockActive(editor, BLOCK_CODE)}
    >
      <DropdownButton width={45} onMouseDown={show}
                      disabled={isBlockActive(editor, BLOCK_CODE)}>
        <IconFontColor />
      </DropdownButton>
    </Dropdown>
  );
}
Example #8
Source File: ChromeColorPicker.tsx    From datart with Apache License 2.0 5 votes vote down vote up
toChangeValue = (data: ColorResult) => {
  const { r, g, b, a } = data.rgb;
  return `rgba(${r}, ${g}, ${b}, ${a})`;
}
Example #9
Source File: ColorPicker.tsx    From easy-email with MIT License 4 votes vote down vote up
export function ColorPicker(props: ColorPickerProps) {
  const { colors: presetColors, addCurrentColor } =
    useContext(PresetColorsContext);
  const [color, setColor] = useState('');
  const { value = '', onChange, children, showInput = true } = props;

  useEffect(() => {
    setColor(value);
  }, [value]);

  const onChangeComplete = useCallback(
    (color: ColorResult, event: React.ChangeEvent<HTMLInputElement>) => {
      if (event.target.value && event.target.value.replace('#', '').length < 6)
        return;
      const newColor = color.hex;
      setColor(newColor);
      onChange?.(newColor);
      addCurrentColor(newColor);
    },
    [addCurrentColor, onChange]
  );

  const onInputChange = useCallback(
    (value: string) => {
      setColor(value);
      onChange?.(value);
      addCurrentColor(value);
    },
    [addCurrentColor, onChange]
  );
  return (
    <div style={{ flex: 1, display: 'flex' }}>
      <Popover
        title={props.label}
        trigger='click'
        {...props}
        content={(
          <div className={styles.colorPicker}>
            <SketchPicker
              presetColors={presetColors}
              color={color}
              disableAlpha
              onChangeComplete={onChangeComplete}
            />
          </div>
        )}
      >
        {children || (
          <div
            style={{
              display: 'inline-block',
              height: 32,
              width: 32,
              boxSizing: 'border-box',
              padding: 4,
              border: '1px solid var(--color-neutral-3, rgb(229, 230, 235))',
              borderRadius: showInput ? undefined : 4,
              fontSize: 0,
              borderRight: showInput ? 'none' : undefined,
              position: 'relative',
              cursor: 'pointer',
            }}
          >
            {props.value ? (
              <span
                style={{
                  position: 'relative',
                  display: 'block',
                  border:
                    '1px solid var(--color-neutral-3, rgb(229, 230, 235))',

                  borderRadius: 2,
                  width: '100%',
                  height: '100%',
                  textAlign: 'center',
                  backgroundColor: value,
                }}
              />
            ) : (
              <img
                style={{
                  maxWidth: '100%',
                  maxHeight: '100%',
                  filter:
                    'invert(  0.78  )  drop-shadow(0 0px 0 rgb(0 0 0 / 45%))',
                }}
                src={getImg('AttributePanel_02')}
              />
            )}
          </div>
        )}
      </Popover>
      {showInput && (
        <Input
          value={props.value}
          style={{ outline: 'none', flex: 1 }}
          onChange={onInputChange}
        />
      )}
    </div>
  );
}
Example #10
Source File: Background.tsx    From yugong with MIT License 4 votes vote down vote up
BackgroundCommon: React.FC<Props> = ({
  onChange,
  defaultBGCommonData,
  defaultBGGradient,
  updateKey,
  unit,
}) => {
  // commonBackground
  const [commonData, setCommonData] =
    useState<BackgroundCommonTypesOfStyleItems>({});
  const {
    imageUrl,
    backgroundColor,
    positionX,
    positionY,
    sizeX,
    sizeY,
    repeat,
  } = commonData;
  useEffect(() => {
    const data = { ...(defaultBGCommonData || {}) };
    setCommonData(data);
  }, [defaultBGCommonData, updateKey]);

  const onChangeBackgroundCommon = useCallback(
    (type: ChangeType) =>
      (
        result:
          | string
          | UnitType
          | {
              name: "color";
              value: ColorResult | undefined;
            }
      ) => {
        const data: BackgroundCommonTypesOfStyleItems = { ...commonData };
        data[type] = result as string & UnitType;

        if (type === "backgroundColor") {
          const setResult = result as {
            name: "color";
            value: ColorResult | undefined;
          };
          data[type] =
            setResult.value && `rgba(${setResult.value.rgb.r}, ${setResult.value.rgb.g}, ${setResult.value.rgb.b}, ${setResult.value.rgb.a})`;
        }

        setCommonData(data);
        if (onChange instanceof Function) {
          onChange({
            type: "backgroundCommon",
            values: data,
          });
        }
      },
    [commonData, onChange]
  );

  const onChangeBg = useCallback(
    (result) => {
      const data: BackgroundCommonTypesOfStyleItems = { ...commonData };
      data.positionX = result[0];
      data.positionY = result[1];
      setCommonData(data);
      if (onChange instanceof Function) {
        onChange({
          type: "backgroundCommon",
          values: data,
        });
      }
    },
    [commonData, onChange]
  );

  // gradientBackground
  const [gradientData, setGradientData] =
    useState<BackgroundGradientTypesOfStyleItems>({});
  useEffect(() => {
    const data = { ...(defaultBGGradient || {}) };
    setGradientData(data);
  }, [defaultBGGradient, updateKey]);
  const { gradient, gradientDirections } = gradientData || {};

  const [tabState, setTabState] = useState("common");

  const onChangeTab = useCallback((e) => {
    setTabState(e.target.value);
  }, []);

  const onChangeGradient = useCallback(
    (gradient) => {
      onChange({
        type: "backgroundGradient",
        values: gradient,
      });
    },
    [onChange]
  );

  const onChangeUnit = useCallback(
    (type: "sizeX" | "sizeY" | "positionX" | "positionY") =>
      (value: UnitType) => {
        const data: BackgroundCommonTypesOfStyleItems = { ...commonData };
        data[type] = value;
        setCommonData(data);
        if (onChange instanceof Function) {
          onChange({
            type: "backgroundCommon",
            values: data,
          });
        }
      },
    [commonData, onChange]
  );

  const renderCommon = () => (
    <>
      <Row className={s.row}>
        <Col span={12}>
          <Upload
            label="背景图片"
            onChange={onChangeBackgroundCommon("imageUrl")}
            defaultImg={imageUrl}
          />
        </Col>
        <Col span={12}>
          <UnitInput
              label="背景宽度"
              min={0}
              max={100000}
              onChange={onChangeUnit("sizeX")}
              defaultValue={sizeX}
            />
        </Col>
      </Row>
      <Row className={s.row}>
        <Col span={12}>
          <Select
            label="平铺方式"
            value={repeat}
            optionsData={{
              "no-repeat": "不平铺",
              repeat: "平铺",
              "repeat-x": "横向平铺",
              "repeat-y": "纵向平铺",
            }}
            onChange={onChangeBackgroundCommon("repeat") as any}
          />
        </Col>
        <Col span={12}>
          <UnitInput
            label="背景高度"
            min={0}
            max={100000}
            onChange={onChangeUnit("sizeY")}
            defaultValue={sizeY}
          />
        </Col>
      </Row>
      <Row className={s.row}>
        <Col span={12}>
          <QuadrangularSelect
            label="背景位置"
            unit={unit}
            defaultData={[positionX, positionY]}
            onChange={onChangeBg}
          />
        </Col>
        <Col span={12}>
          <Row className={s.row}>
            <Col span={24}>
            <UnitInput
                  label="横向位置"
                  min={0}
                  max={100000}
                  onChange={onChangeUnit("positionX")}
                  defaultValue={positionX}
                />
            </Col>
          </Row>
          <Row className={s.row} key={2}>
            <Col span={24}>
              <UnitInput
                label="纵向位置"
                min={0}
                max={100000}
                onChange={onChangeUnit("positionY")}
                defaultValue={positionY}
              />
            </Col>
          </Row>
        </Col>
      </Row>
    </>
  );

  const renderGradient = () => (
    <>
      <Row className={s.row}>
        <Col span={24}>
          <GradientSlider
            onChange={onChangeGradient}
            defaultData={{ gradient, gradientDirections }}
          />
        </Col>
      </Row>
    </>
  );
  return (
    <>
      <Row className={s.row}>
        <Col span={12}>
          <Color
            label="背景颜色"
            onChange={onChangeBackgroundCommon("backgroundColor")}
            defaultColor={backgroundColor}
          />
        </Col>
      </Row>
      <Row className={s.row}>
        <Col span={24}>
          <Radio.Group
            defaultValue={tabState}
            className={s.tab}
            onChange={onChangeTab}
          >
            <Radio.Button value="common">图片背景</Radio.Button>
            <Radio.Button value="gradient">渐变背景</Radio.Button>
          </Radio.Group>
        </Col>
      </Row>
      {tabState === "common" ? renderCommon() : null}
      {tabState === "gradient" ? renderGradient() : null}
    </>
  );
}
Example #11
Source File: Color.tsx    From yugong with MIT License 4 votes vote down vote up
Color: React.FC<Props> = ({
    defaultColor,
    label,
    onChange,
    children,
    span,
    ...other
}) => {
    const [displayColorPicker, setDisplayColorPicker] = useState(false);
    const [color, setColor] = useState<RGBColor>();
    const [pickWrapStyle, setPickWrapStyle] = useState({});
    const picker = useRef(null);

    useEffect(() => {
        if (defaultColor) {
            const optColor: any = {};
            const temp = parse(defaultColor);
            if (temp.space) {
                optColor.r = temp.values[0];
                optColor.g = temp.values[1];
                optColor.b = temp.values[2];
                optColor.a = temp.alpha;
                setColor(optColor);
            }
        } else {
            setColor(undefined);
        }
    }, [defaultColor]);

    const handleClick = useCallback(
        (e) => {
            setDisplayColorPicker(!displayColorPicker);
            const style: any = {
                position: 'absolute',
            };

            const width = document.body.offsetWidth,
                height = document.body.offsetHeight,
                sWidth = 270,
                sHeight = 350,
                X = e.screenX,
                Y = e.screenY;

            // 1、判断拾色器的宽度小于窗口宽度
            if (width > sWidth) {
                if (X + sWidth > width) {
                    style.position = 'fixed';
                    style.right = `10px`;
                }
            }
            // 2、判断拾色器的高度大于窗口高度
            if (height > sHeight) {
                if (Y + sHeight > height) {
                    style.position = 'fixed';
                    style.bottom = `10px`;
                }
            }
            setPickWrapStyle(style);
        },
        [displayColorPicker]
    );

    const handleClose = useCallback(() => {
        setDisplayColorPicker(false);
    }, []);

    /**
     * 高频编辑防抖处理
     */
     const refChange = useSafeCallback(onChange);
     const onChangeDebounce = useMemo(
        () =>
            throttle((value) => {
                refChange(value);
            }, 500),
        [refChange]
    );


    const handleChange = useCallback(
        (color: ColorResult | 'inherit') => {
          let colorResult: any = color;
            if (color === 'inherit') {
                colorResult = undefined;
                setColor(undefined);
            } else {
                setColor(color.rgb);
            }

            onChangeDebounce({
                name: 'color',
                value: colorResult,
            });
        },
        [onChangeDebounce]
    );

    
    const renderColor = () => {
        return (
            <>
                {displayColorPicker ? (
                    <div className={s.popover}>
                        <div className={s.cover} onClick={handleClose} />
                        <div
                            className={s.wrap}
                            style={pickWrapStyle}
                            ref={picker}
                            onClick={(e) => e.stopPropagation()}
                        >
                            <SketchPicker
                                color={color || undefined}
                                width="250px"
                                onChange={handleChange}
                                className={s.picker}
                                presetColors={[
                                    '#f44336',
                                    '#e91e63',
                                    '#9c27b0',
                                    '#673ab7',
                                    '#3f51b5',
                                    '#2196f3',
                                    '#03a9f4',
                                    '#00bcd4',
                                    '#009688',
                                    '#4caf50',
                                    '#8bc34a',
                                    '#cddc39',
                                    '#ffeb3b',
                                    '#ffc107',
                                    '#ff9800',
                                    '#ff5722',
                                    '#aaaaaa',
                                    '#000000',
                                    '#fff',
                                    'transparent',
                                ]}
                            />
                            <div
                                onClick={() => handleChange('inherit')}
                                className={s.inherit}
                            >
                                移除
                            </div>
                        </div>
                    </div>
                ) : null}
            </>
        );
    };

    const displayColor = color && `rgba(${(color as any).r}, ${(color as any).g}, ${
      (color as any).b
  }, ${(color as any).a})`

    return (
        <>
            {children ? (
                <>
                    <span {...other} onClick={handleClick}>
                        {children}
                    </span>
                    {renderColor()}
                </>
            ) : (
                <Row className={s.row} gutter={4}>
                    <Col className={s.label} span={span?.label || 7}>
                        {label || ''}
                    </Col>
                    <Col span={ span?.value || 17}>
                        <div className={s.swatch} onClick={handleClick}>
                            {color ? (
                                <div
                                    className={s.color}
                                    style={{
                                        backgroundColor: displayColor,
                                    }}
                                />
                            ) : (
                                <div className={ClassNames(s.color, s.empty)}>
                                    <BgColorsOutlined />
                                </div>
                            )}
                            {renderColor()}
                        </div>
                    </Col>
                </Row>
            )}
        </>
    );
}
Example #12
Source File: editor-color-item.tsx    From geist-ui with MIT License 4 votes vote down vote up
EditorColorItem: React.FC<React.PropsWithChildren<Props>> = ({ keyName }) => {
  const theme = useTheme()
  const { updateCustomTheme } = useConfigs()
  const label = `${keyName}`
  const mainColor = useMemo(() => theme.palette[keyName], [theme.palette, keyName])
  const randomColors = useMemo(() => getRandomColors(), [])
  const colorChangeHandler = ({ hex }: ColorResult) => {
    updateCustomTheme({
      palette: { [keyName]: hex },
    })
  }

  const popoverContent = (color: string) => (
    <TwitterPicker
      triangle="hide"
      color={color}
      onChangeComplete={colorChangeHandler}
      colors={randomColors}
    />
  )
  return (
    <Popover
      content={() => popoverContent(mainColor)}
      portalClassName="editor-popover"
      offset={3}>
      <div className="editor-item">
        <div className="dot-box">
          <span className="dot" />
        </div>
        {label}
        <style jsx>{`
          .editor-item {
            background-color: transparent;
            width: auto;
            padding: 0 ${theme.layout.gapHalf};
            line-height: 2rem;
            display: inline-flex;
            align-items: center;
            border: 1px solid ${theme.palette.border};
            border-radius: ${theme.layout.radius};
            color: ${theme.palette.accents_5};
            margin-right: 0.75rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: color 200ms ease;
          }

          :global(.editor-popover .inner) {
            padding: 0 !important;
          }

          :global(.editor-popover .twitter-picker) {
            box-shadow: none !important;
            border: 0 !important;
            background: transparent !important;
          }

          .editor-item:hover {
            color: ${theme.palette.accents_8};
          }

          .editor-item:hover .dot {
            transform: scale(1);
          }

          .dot-box,
          .dot {
            display: inline-flex;
            justify-content: center;
            align-items: center;
          }

          .dot-box {
            width: 1rem;
            height: 1rem;
            margin-right: 0.75rem;
          }

          .dot {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: ${mainColor};
            transform: scale(0.8);
            transition: transform 200ms ease;
          }
        `}</style>
      </div>
    </Popover>
  )
}