UNPKG

@turbo-red/strapi-plugin-lookup-enum

Version:

Like enum field, but options are extracted from a field provided by a single-type content.

114 lines (113 loc) 3.36 kB
import { jsx, jsxs } from "react/jsx-runtime"; import { MultiSelectOption, SingleSelectOption, Field, MultiSelect, SingleSelect } from "@strapi/design-system"; import { getFetchClient } from "@strapi/strapi/admin"; import { useState, useEffect } from "react"; import { useIntl } from "react-intl"; function isMessageDescriptor(message) { return message?.id !== void 0; } const makeDynamicEnum = (multiSelect) => (props) => { const { value, onChange, name, label, required, hint, attribute, placeholder, disabled, type, error } = props; const configuration = attribute.options; const { formatMessage } = useIntl(); const [isLoading, setIsLoading] = useState(false); const [options, setOptions] = useState([]); const [optionsLoadingError, setLoadingError] = useState(); const translate = (message) => isMessageDescriptor(message) ? formatMessage(message) : message; const loadEnumOptions = async () => { if (isLoading) return; setIsLoading(true); try { const { get } = getFetchClient(); const res = await get( `/content-manager/single-types/${configuration.lookupSingleType}` ); if (!res.status || res.status < 400) { const optionsString = res.data.data[configuration.lookupField]; if (optionsString) { setOptions(optionsString.match(/\S+/g) || []); } } else { setLoadingError(`Error, code: ${res.status}`); } } catch (err) { setLoadingError(err?.message || err?.toString()); } finally { setIsLoading(false); } }; useEffect(() => { loadEnumOptions(); }, []); const handleSelectChange = (value2) => onChange({ target: { name, type, value: value2 } }); const clear = (event) => { event.stopPropagation(); event.preventDefault(); onChange({ target: { name, type } }); }; const selectOptionsList = options.map((opt) => { return multiSelect ? /* @__PURE__ */ jsx(MultiSelectOption, { value: opt, children: opt }, opt) : /* @__PURE__ */ jsx(SingleSelectOption, { value: opt, children: opt }, opt); }); return /* @__PURE__ */ jsxs( Field.Root, { name, id: name, hint: translate(hint), error: translate(error || optionsLoadingError), required, children: [ /* @__PURE__ */ jsx(Field.Label, { children: translate(label) }), multiSelect ? /* @__PURE__ */ jsx( MultiSelect, { placeholder: translate(placeholder), name, onChange: (value2) => handleSelectChange(value2), value, disabled, required, onClear: clear, withTags: true, children: selectOptionsList } ) : /* @__PURE__ */ jsx( SingleSelect, { placeholder: translate(placeholder), name, onChange: (value2) => handleSelectChange(`${value2}`), value, disabled, required, onClear: clear, children: selectOptionsList } ), /* @__PURE__ */ jsx(Field.Hint, {}), /* @__PURE__ */ jsx(Field.Error, {}) ] } ); }; export { makeDynamicEnum as default, makeDynamicEnum }; //# sourceMappingURL=DynamicEnum-Lh31j-z3.mjs.map