UNPKG

@gechiui/components

Version:
169 lines (151 loc) 3.43 kB
import { createElement, Fragment } from "@gechiui/element"; /** * External dependencies */ /** * GeChiUI dependencies */ import { useCopyToClipboard } from '@gechiui/compose'; import { useState, useEffect, useRef } from '@gechiui/element'; import { __ } from '@gechiui/i18n'; /** * Internal dependencies */ import { Text } from '../text'; import { Flex, FlexItem } from '../flex'; import { Tooltip } from '../ui/tooltip'; import { space } from '../ui/utils/space'; const ValueDisplay = _ref => { let { values } = _ref; return createElement(Fragment, null, values.map(_ref2 => { let [value, abbreviation] = _ref2; return createElement(FlexItem, { key: abbreviation, isBlock: true, display: "flex" }, createElement(Text, { color: "blue" }, abbreviation), createElement(Text, null, value)); })); }; const HslDisplay = _ref3 => { let { color, enableAlpha } = _ref3; const { h, s, l, a } = color.toHsl(); const values = [[Math.floor(h), 'H'], [Math.round(s * 100), 'S'], [Math.round(l * 100), 'L']]; if (enableAlpha) { values.push([Math.round(a * 100), 'A']); } return createElement(ValueDisplay, { values: values }); }; const RgbDisplay = _ref4 => { let { color, enableAlpha } = _ref4; const { r, g, b, a } = color.toRgb(); const values = [[r, 'R'], [g, 'G'], [b, 'B']]; if (enableAlpha) { values.push([Math.round(a * 100), 'A']); } return createElement(ValueDisplay, { values: values }); }; const HexDisplay = _ref5 => { let { color } = _ref5; const colorWithoutHash = color.toHex().slice(1).toUpperCase(); return createElement(FlexItem, null, createElement(Text, { color: "blue" }, "#"), createElement(Text, null, colorWithoutHash)); }; const getComponent = colorType => { switch (colorType) { case 'hsl': return HslDisplay; case 'rgb': return RgbDisplay; default: case 'hex': return HexDisplay; } }; export const ColorDisplay = _ref6 => { let { color, colorType, enableAlpha } = _ref6; const [copiedColor, setCopiedColor] = useState(null); const copyTimer = useRef(); const props = { color, enableAlpha }; const Component = getComponent(colorType); const copyRef = useCopyToClipboard(() => { switch (colorType) { case 'hsl': { return color.toHslString(); } case 'rgb': { return color.toRgbString(); } default: case 'hex': { return color.toHex(); } } }, () => { if (copyTimer.current) { clearTimeout(copyTimer.current); } setCopiedColor(color.toHex()); copyTimer.current = setTimeout(() => { setCopiedColor(null); copyTimer.current = undefined; }, 3000); }); useEffect(() => { // clear copyTimer on component unmount. return () => { if (copyTimer.current) { clearTimeout(copyTimer.current); } }; }, []); return createElement(Tooltip, { content: createElement(Text, { color: "white" }, copiedColor === color.toHex() ? __('已复制!') : __('复制')) }, createElement(Flex, { justify: "flex-start", gap: space(1), ref: copyRef, style: { height: 30 } }, createElement(Component, props))); }; //# sourceMappingURL=color-display.js.map