@create-figma-plugin/ui
Version:
Production-grade Preact components that replicate the Figma UI design
45 lines • 2.63 kB
JavaScript
import { h } from 'preact';
import { useCallback } from 'preact/hooks';
import { Inline } from '../../layout/inline/inline.js';
import { Stack } from '../../layout/stack/stack.js';
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 './radio-buttons.module.css';
export const RadioButtons = createComponent(function ({ disabled = false, direction = 'vertical', onChange = noop, onCommand, onKeyDown = noop, onValueChange = noop, options, propagateEscapeKeyDown = true, space, value, ...rest }, ref) {
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]);
const body = options.map(function (option, index) {
const children = typeof option.children === 'undefined'
? `${option.value}`
: option.children;
const isOptionDisabled = disabled === true || option.disabled === true;
const checked = value === option.value;
return (h("label", { key: index, class: createClassName([
styles.radioButton,
isOptionDisabled === true ? styles.disabled : null
]) },
h("input", { ...rest, checked: checked === true, 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 }),
h("div", { class: styles.children }, children)));
});
return (h("div", { ref: ref, class: styles.radioButtons }, direction === 'vertical' ? (h(Stack, { space: typeof space === 'undefined' ? 'small' : space }, body)) : (h(Inline, { space: typeof space === 'undefined' ? 'medium' : space }, body))));
});
//# sourceMappingURL=radio-buttons.js.map