shelving
Version:
Toolkit for using data in JavaScript.
33 lines (32 loc) • 2.73 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/solid";
import { omitDictionaryItem, withDictionaryItem } from "../../util/dictionary.js";
import { splitMessage } from "../../util/error.js";
import { formatUnit } from "../../util/format.js";
import { omitProp } from "../../util/object.js";
import { Flex } from "../style/Flex.js";
import { Button } from "./Button.js";
import { ButtonInput } from "./ButtonInput.js";
import { SchemaInput } from "./SchemaInput.js";
import { TextInput } from "./TextInput.js";
export function DictionaryInput({ name,
// title,
placeholder, required = false, disabled = false, message = "", value = {}, onValue, one = "item", many = `${one}s`, min = 0, max = Number.POSITIVE_INFINITY, items, }) {
const messages = splitMessage(message);
const length = Object.keys(value).length;
const disableRemove = disabled || length <= min;
const addNewItem = () => onValue({ ...value, [one]: items.value });
return (_jsxs(Flex, { column: true, children: [length ? (Object.entries(value).map(([k, v], i) => {
const r = i.toString();
const message = messages[r];
return (_jsxs(Flex, { children: [_jsx(TextInput, { name: `${r}-key`, value: k, onValue: x => {
// Delete the dictionary item with `currentKey` and add a new one with `nextKey`
if (!x || x === k)
return;
onValue(withDictionaryItem(omitDictionaryItem(value, k), x, v));
k = x; // Update this so it works until content is re-rendered.
}, message: message, disabled: disabled }), _jsx(SchemaInput, { name: `${r}-value`, schema: items, value: v, onValue: x => onValue(withDictionaryItem(value, k, x)), message: message, disabled: disabled }), _jsx(Button, { onClick: () => onValue(omitProp(value, k)), disabled: disableRemove, title: disableRemove ? `Minimum ${formatUnit(min, one, { unitDisplay: "long", one, many })}` : `Remove ${one}`, children: _jsx(XMarkIcon, {}) })] }, r));
})) : (_jsx(ButtonInput, { onClick: addNewItem, name: name, required: required && min > 1, disabled: disabled, children: placeholder })), _jsxs(Flex, { children: [_jsxs(Button //
, { onClick: addNewItem, disabled: disabled || (typeof max === "number" && length >= max), small: true, children: [_jsx(PlusIcon, {}), " Add ", one] }), length && min < 1 ? (_jsxs(Button //
, { onClick: () => onValue({}), small: true, children: [_jsx(XMarkIcon, {}), " Clear ", many] })) : null] })] }));
}