UNPKG

@create-figma-plugin/ui

Version:

Production-grade Preact components that replicate the Figma UI design

40 lines 2.21 kB
import { h } from 'preact'; import { useCallback } from 'preact/hooks'; import { createClassName } from '../../utilities/create-class-name.js'; import { createComponent } from '../../utilities/create-component.js'; import { noop } from '../../utilities/no-op.js'; import { ITEM_ID_DATA_ATTRIBUTE_NAME } from '../../utilities/private/constants.js'; import styles from './segmented-control.module.css'; export const SegmentedControl = createComponent(function ({ disabled = false, onChange = noop, onKeyDown = noop, onValueChange = noop, options, propagateEscapeKeyDown = true, value, ...rest }) { const handleChange = useCallback(function (event) { onChange(event); const id = event.currentTarget.getAttribute(ITEM_ID_DATA_ATTRIBUTE_NAME); if (id === null) { throw new Error('`id` is `null`'); } const newValue = options[parseInt(id, 10)].value; onValueChange(newValue); }, [onChange, onValueChange, options]); const handleKeyDown = useCallback(function (event) { onKeyDown(event); if (event.key === 'Escape') { if (propagateEscapeKeyDown === false) { event.stopPropagation(); } event.currentTarget.blur(); } }, [onKeyDown, propagateEscapeKeyDown]); return (h("div", { class: createClassName([ styles.segmentedControl, disabled === true ? styles.disabled : null ]) }, options.map(function (option, index) { const children = typeof option.children === 'undefined' ? `${option.value}` : option.children; const isOptionDisabled = disabled === true || option.disabled === true; return (h("label", { key: index }, h("input", { ...rest, checked: value === option.value, class: styles.input, disabled: isOptionDisabled === true, onChange: handleChange, onKeyDown: handleKeyDown, tabIndex: 0, type: "radio", value: `${option.value}`, [ITEM_ID_DATA_ATTRIBUTE_NAME]: `${index}` }), h("div", { class: styles.box }, typeof children === 'string' ? (h("div", { class: styles.text }, children)) : (children)))); }))); }); //# sourceMappingURL=segmented-control.js.map