diff --git a/assets/flash-notifications-bundle.js b/assets/flash-notifications-bundle.js index 81801d956..57318458c 100644 --- a/assets/flash-notifications-bundle.js +++ b/assets/flash-notifications-bundle.js @@ -1,4 +1,4 @@ -import { u as useToast, r as reactExports, j as jsxRuntimeExports, N as Notification, T as Title, C as Close, a9 as FLASH_NOTIFICATIONS_KEY, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme } from 'shared'; +import { k as useToast, r as reactExports, j as jsxRuntimeExports, N as Notification, T as Title, l as Close, a9 as FLASH_NOTIFICATIONS_KEY, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme } from 'shared'; function FlashNotifications({ notifications, closeLabel, }) { const { addToast } = useToast(); diff --git a/assets/index-bundle.js b/assets/index-bundle.js new file mode 100644 index 000000000..990349aef --- /dev/null +++ b/assets/index-bundle.js @@ -0,0 +1,518 @@ +import { r as reactExports, j as jsxRuntimeExports, i as Field, af as Checkbox$1, k as Label, S as Span, H as Hint, M as Message, s as styled, u as useTranslation, ag as MediaInput, ah as SvgCreditCardStroke, ai as Datepicker, I as Input$1, aj as debounce, F as Field$1, L as Label$1, V as Hint$1, C as Combobox, O as Option, W as Message$1, ak as OptGroup, d as useToast, N as Notification, e as Title, f as Close, al as Textarea } from 'shared'; + +function Checkbox({ field, onChange }) { + const { label, error, value, name, required, description } = field; + const [checkboxValue, setCheckboxValue] = reactExports.useState(value); + const handleChange = (e) => { + const { checked } = e.target; + setCheckboxValue(checked); + onChange(checked); + }; + return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: "off" }), jsxRuntimeExports.jsxs(Checkbox$1, { name: name, required: required, defaultChecked: value, value: checkboxValue ? "on" : "off", onChange: handleChange, children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } }))] }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); +} + +/** + * When there is an error in the credit card field, the backend returns a redacted value with the last 4 digits prefixed with some Xs. + * This function removes the Xs from the value and returns the last 4 digits of the credit card + * + * @param value The value returned by the backend with last 4 digits prefixed with some Xs + * @returns The last 4 digits of the credit card + */ +function getLastDigits(value) { + return value ? value.replaceAll("X", "") : ""; +} +const DigitsHintSpan = styled(Span) ` + margin-left: ${(props) => props.theme.space.xxs}; + font-weight: ${(props) => props.theme.fontWeights.medium}; +`; +function CreditCard({ field, onChange }) { + const { t } = useTranslation(); + const { label, error, value, name, required, description } = field; + const digits = getLastDigits(value); + return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" }), jsxRuntimeExports.jsx(DigitsHintSpan, { children: t("new-request-form.credit-card-digits-hint", "(Last 4 digits)") })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(MediaInput, { start: jsxRuntimeExports.jsx(SvgCreditCardStroke, {}), name: name, type: "text", value: digits, onChange: (e) => onChange(e.target.value), validation: error ? "error" : undefined, required: required, maxLength: 4, placeholder: "XXXX" }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); +} + +function DatePicker({ field, locale, valueFormat, onChange, }) { + const { label, error, value, name, required, description } = field; + const [date, setDate] = reactExports.useState(value ? new Date(value) : undefined); + const formatDate = (value) => { + if (value === undefined) { + return ""; + } + const isoString = value.toISOString(); + return valueFormat === "dateTime" ? isoString : isoString.split("T")[0]; + }; + const handleChange = (date) => { + // Set the time to 12:00:00 as this is also the expected behavior across Support and the API + const newDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0)); + setDate(newDate); + const dateString = formatDate(newDate); + if (dateString !== undefined) { + onChange(dateString); + } + }; + const handleInputChange = (e) => { + // Allow field to be cleared + if (e.target.value === "") { + setDate(undefined); + onChange(""); + } + }; + return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Datepicker, { value: date, onChange: handleChange, locale: locale, children: jsxRuntimeExports.jsx(Input$1, { required: required, lang: locale, onChange: handleInputChange, validation: error ? "error" : undefined }) }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error }), jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: formatDate(date) })] })); +} + +function Input({ field, onChange }) { + const { label, error, value, name, required, description, type } = field; + const stepProp = {}; + const inputType = type === "integer" || type === "decimal" ? "number" : "text"; + if (type === "integer") + stepProp.step = "1"; + if (type === "decimal") + stepProp.step = "any"; + const autocomplete = type === "anonymous_requester_email" ? "email" : undefined; + return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Input$1, { name: name, type: inputType, defaultValue: value, validation: error ? "error" : undefined, required: required, onChange: (e) => { + onChange && onChange(e.target.value); + }, autoComplete: autocomplete, ...stepProp }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); +} + +function EmptyValueOption() { + const { t } = useTranslation(); + return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "-" }), jsxRuntimeExports.jsx(Span, { hidden: true, children: t("ticket-fields.dropdown.empty-option", "Select an option") })] })); +} + +function getCustomObjectKey(targetType) { + return targetType.replace("zen:custom_object:", ""); +} +const EMPTY_OPTION = { + value: "", + name: "-", +}; +function LookupField({ field, userId, organizationId, onChange, }) { + const { id: fieldId, label, error, value, name, required, description, relationship_target_type, } = field; + const [options, setOptions] = reactExports.useState([]); + const [selectedOption, setSelectedOption] = reactExports.useState(null); + const [inputValue, setInputValue] = reactExports.useState(value); + const [isLoadingOptions, setIsLoadingOptions] = reactExports.useState(false); + const { t } = useTranslation(); + const customObjectKey = getCustomObjectKey(relationship_target_type); + const loadingOption = { + name: t("ticket-fields.lookup-field.loading-options", "Loading items..."), + id: "loading", + }; + const noResultsOption = { + name: t("ticket-fields.lookup-field.no-matches-found", "No matches found"), + id: "no-results", + }; + const fetchSelectedOption = reactExports.useCallback(async (selectionValue) => { + try { + const res = await fetch(`/api/v2/custom_objects/${customObjectKey}/records/${selectionValue}`); + if (res.ok) { + const { custom_object_record } = await res.json(); + const newSelectedOption = { + name: custom_object_record.name, + value: custom_object_record.id, + }; + setSelectedOption(newSelectedOption); + setInputValue(custom_object_record.name); + } + } + catch (error) { + console.error(error); + } + }, [customObjectKey]); + const fetchOptions = reactExports.useCallback(async (inputValue) => { + const searchParams = new URLSearchParams(); + searchParams.set("name", inputValue.toLocaleLowerCase()); + searchParams.set("source", "zen:ticket"); + searchParams.set("field_id", fieldId.toString()); + searchParams.set("requester_id", userId.toString()); + if (organizationId !== null) + searchParams.set("organization_id", organizationId); + setIsLoadingOptions(true); + try { + const response = await fetch(`/api/v2/custom_objects/${customObjectKey}/records/autocomplete?${searchParams.toString()}`); + const data = await response.json(); + if (response.ok) { + let fetchedOptions = data.custom_object_records.map(({ name, id }) => ({ + name, + value: id, + })); + if (selectedOption) { + fetchedOptions = fetchedOptions.filter((option) => option.value !== selectedOption.value); + fetchedOptions = [selectedOption, ...fetchedOptions]; + } + setOptions(fetchedOptions); + } + else { + setOptions([]); + } + } + catch (error) { + console.error(error); + } + finally { + setIsLoadingOptions(false); + } + }, [customObjectKey, fieldId, organizationId, selectedOption, userId]); + const debouncedFetchOptions = reactExports.useMemo(() => debounce(fetchOptions, 300), [fetchOptions]); + reactExports.useEffect(() => { + return () => debouncedFetchOptions.cancel(); + }, [debouncedFetchOptions]); + const handleChange = reactExports.useCallback(({ inputValue, selectionValue }) => { + if (selectionValue !== undefined) { + if (selectionValue == "") { + setSelectedOption(EMPTY_OPTION); + setInputValue(EMPTY_OPTION.name); + setOptions([]); + onChange(EMPTY_OPTION.value); + } + else { + const selectedOption = options.find((option) => option.value === selectionValue); + if (selectedOption) { + setInputValue(selectedOption.name); + setSelectedOption(selectedOption); + setOptions([selectedOption]); + onChange(selectedOption.value); + } + } + } + if (inputValue !== undefined) { + setInputValue(inputValue); + debouncedFetchOptions(inputValue); + } + }, [debouncedFetchOptions, onChange, options]); + reactExports.useEffect(() => { + if (value) { + fetchSelectedOption(value); + } + }, []); //we don't set dependency array as we want this hook to be called only once + const onFocus = () => { + setInputValue(""); + fetchOptions("*"); + }; + return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { inputProps: { required }, "data-test-id": "lookup-field-combobox", validation: error ? "error" : undefined, inputValue: inputValue, selectionValue: selectedOption?.value, isAutocomplete: true, placeholder: t("ticket-fields.lookup-field.placeholder", "Search {{label}}", { label: label.toLowerCase() }), onFocus: onFocus, onChange: handleChange, renderValue: () => selectedOption ? selectedOption?.name : EMPTY_OPTION.name, children: [selectedOption?.name !== EMPTY_OPTION.name && (jsxRuntimeExports.jsx(Option, { value: "", label: "-", children: jsxRuntimeExports.jsx(EmptyValueOption, {}) })), isLoadingOptions && (jsxRuntimeExports.jsx(Option, { isDisabled: true, value: loadingOption.name }, loadingOption.id)), !isLoadingOptions && + inputValue?.length > 0 && + options.length === 0 && (jsxRuntimeExports.jsx(Option, { isDisabled: true, value: noResultsOption.name }, noResultsOption.id)), !isLoadingOptions && + options.length !== 0 && + options.map((option) => (jsxRuntimeExports.jsx(Option, { value: option.value, label: option.name, "data-test-id": `option-${option.name}` }, option.value)))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error }), jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: selectedOption?.value })] })); +} + +/** + * The root group is identified by an empty string, to avoid possible clashes with a level with + * a "Root" name. + */ +const ROOT_GROUP_IDENTIFIER = "[]"; +function getGroupIdentifier(names) { + return `[${names.join("::")}]`; +} +function isGroupIdentifier(name) { + return name.startsWith("[") && name.endsWith("]"); +} +function getGroupAndOptionNames(input) { + const namesList = input.split("::"); + return [namesList.slice(0, -1), namesList.slice(-1)[0]]; +} +function buildSubGroupOptions(groupNames) { + const parentGroupNames = groupNames.slice(0, -1); + const parentGroupIdentifier = getGroupIdentifier(parentGroupNames); + const name = groupNames[groupNames.length - 1]; + return { + type: "SubGroup", + name, + backOption: { + type: "previous", + label: "Back", + value: parentGroupIdentifier, + }, + options: [], + }; +} +/** + * Maps a flat list of options to a nested structure + * + * For example, given the following options: + * [ + * { "name": "Bass::Fender::Precision", "value": "bass__fender__precision" }, + * { "name": "Bass::Fender::Jazz", "value": "bass__fender__jazz" } + * { "name": "Drums", "value": "drums" }, + * ] + * + * The following nested structure will be returned: + * { + * "[]": { + * "type": "RootGroup", + * "options": [ + * { "label": "Bass", "value": "[Bass]", type: "next" }, + * { "label": "Drums", "value": "drums" }, + * ] + * }, + * "[Bass]": { + * "type": "SubGroup", + * "name": "Bass", + * "backOption": { "type": "previous", "label": "Back", "value": "[]" }, + * "options": [ + * { "label": "Fender", "value": "[Bass::Fender]", type: "next" }, + * ] + * }, + * "[Bass::Fender]": { + * "type": "SubGroup", + * "name": "Fender", + * "backOption": { "type": "previous", "label": "Back", "value": "[Bass]" }, + * "options": [ + * { "menuLabel": "Precision", "label": "Bass > Fender > Precision", "value": "bass__fender__precision" }, + * { "menuLabel": "Jazz", "label": "Bass > Fender > Jazz", "value": "bass__fender__jazz" }, + * ] + * } + * } + * + * @param options original field options + * @param hasEmptyOption if true, adds an empty option to the root group + * @returns nested options + */ +function buildNestedOptions(options, hasEmptyOption) { + const result = { + [ROOT_GROUP_IDENTIFIER]: { + type: "RootGroup", + options: hasEmptyOption ? [{ label: "-", value: "" }] : [], + }, + }; + options.forEach((option) => { + const { name, value } = option; + if (!name.includes("::")) { + result[ROOT_GROUP_IDENTIFIER].options.push({ + value, + label: name, + }); + } + else { + const [groupNames, optionName] = getGroupAndOptionNames(name); + const groupIdentifier = getGroupIdentifier(groupNames); + if (!result[groupIdentifier]) { + result[groupIdentifier] = buildSubGroupOptions(groupNames); + } + result[groupIdentifier]?.options.push({ + value, + label: name.split("::").join(" > "), + menuLabel: optionName, + }); + // creates next options for each parent group, if they don't already exists + for (let i = 0; i < groupNames.length; i++) { + const parentGroupNames = groupNames.slice(0, i); + const nextGroupNames = groupNames.slice(0, i + 1); + const parentGroupIdentifier = getGroupIdentifier(parentGroupNames); + const nextGroupIdentifier = getGroupIdentifier(nextGroupNames); + if (!result[parentGroupIdentifier]) { + result[parentGroupIdentifier] = + buildSubGroupOptions(parentGroupNames); + } + if (result[parentGroupIdentifier]?.options.find((o) => o.value === nextGroupIdentifier) === undefined) { + result[parentGroupIdentifier]?.options.push({ + type: "next", + label: nextGroupNames[nextGroupNames.length - 1], + value: nextGroupIdentifier, + }); + } + } + } + }); + return result; +} +/** + * When one or more options are selected, the Combobox component renders the label + * for an option in the input, searching for an option passed as a child with the + * same value as the selected option. + * + * In the first render we are passing only the root group options as children, + * and if we already have some selected values from a SubGroup, the component is not + * able to find the label for the selected option. + * + * We therefore need to pass all the non-navigation options as children in the first render. + * The passed options are cached by the Combobox component, so we can safely remove them + * after the first render and pass only the root group options. + */ +function getInitialGroup(nestedOptions) { + const result = { + type: "RootGroup", + options: [], + }; + Object.values(nestedOptions).forEach(({ options }) => { + result.options.push(...options.filter(({ type }) => type === undefined)); + }); + return result; +} +function useNestedOptions({ options, hasEmptyOption, }) { + const nestedOptions = reactExports.useMemo(() => buildNestedOptions(options, hasEmptyOption), [options, hasEmptyOption]); + const [currentGroup, setCurrentGroup] = reactExports.useState(getInitialGroup(nestedOptions)); + reactExports.useEffect(() => { + setCurrentGroup(nestedOptions[ROOT_GROUP_IDENTIFIER]); + }, [nestedOptions]); + const setCurrentGroupByIdentifier = (identifier) => { + const group = nestedOptions[identifier]; + if (group) { + setCurrentGroup(group); + } + }; + return { + currentGroup, + isGroupIdentifier, + setCurrentGroupByIdentifier, + }; +} + +function MultiSelect({ field }) { + const { label, options, error, value, name, required, description } = field; + const { currentGroup, isGroupIdentifier, setCurrentGroupByIdentifier } = useNestedOptions({ + options, + hasEmptyOption: false, + }); + const [selectedValues, setSelectValues] = reactExports.useState(value || []); + const wrapperRef = reactExports.useRef(null); + reactExports.useEffect(() => { + if (wrapperRef.current && required) { + const combobox = wrapperRef.current.querySelector("[role=combobox]"); + combobox?.setAttribute("aria-required", "true"); + } + }, [wrapperRef, required]); + const handleChange = (changes) => { + if (Array.isArray(changes.selectionValue)) { + const lastSelectedItem = changes.selectionValue.slice(-1).toString(); + if (isGroupIdentifier(lastSelectedItem)) { + setCurrentGroupByIdentifier(lastSelectedItem); + } + else { + setSelectValues(changes.selectionValue); + } + } + }; + return (jsxRuntimeExports.jsxs(Field$1, { children: [selectedValues.map((selectedValue) => (jsxRuntimeExports.jsx("input", { type: "hidden", name: `${name}[]`, value: selectedValue }, selectedValue))), jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { ref: wrapperRef, isMultiselectable: true, inputProps: { required }, isEditable: false, validation: error ? "error" : undefined, onChange: handleChange, selectionValue: selectedValues, maxHeight: "auto", children: [currentGroup.type === "SubGroup" && (jsxRuntimeExports.jsx(Option, { ...currentGroup.backOption })), currentGroup.type === "SubGroup" ? (jsxRuntimeExports.jsx(OptGroup, { "aria-label": currentGroup.name, children: currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option, children: option.menuLabel ?? option.label }, option.value))) })) : (currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option }, option.value))))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error })] })); +} + +function Tagger({ field, onChange }) { + const { label, options, error, value, name, required, description } = field; + const { currentGroup, isGroupIdentifier, setCurrentGroupByIdentifier } = useNestedOptions({ + options, + hasEmptyOption: true, + }); + const selectionValue = value ?? ""; + const [isExpanded, setIsExpanded] = reactExports.useState(false); + const wrapperRef = reactExports.useRef(null); + reactExports.useEffect(() => { + if (wrapperRef.current && required) { + const combobox = wrapperRef.current.querySelector("[role=combobox]"); + combobox?.setAttribute("aria-required", "true"); + } + }, [wrapperRef, required]); + const handleChange = (changes) => { + if (typeof changes.selectionValue === "string" && + isGroupIdentifier(changes.selectionValue)) { + setCurrentGroupByIdentifier(changes.selectionValue); + return; + } + if (typeof changes.selectionValue === "string") { + onChange(changes.selectionValue); + } + if (changes.isExpanded !== undefined) { + setIsExpanded(changes.isExpanded); + } + }; + return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { ref: wrapperRef, inputProps: { required, name }, isEditable: false, validation: error ? "error" : undefined, onChange: handleChange, selectionValue: selectionValue, inputValue: selectionValue, renderValue: ({ selection }) => selection?.label ?? jsxRuntimeExports.jsx(EmptyValueOption, {}), isExpanded: isExpanded, children: [currentGroup.type === "SubGroup" && (jsxRuntimeExports.jsx(Option, { ...currentGroup.backOption })), currentGroup.type === "SubGroup" ? (jsxRuntimeExports.jsx(OptGroup, { "aria-label": currentGroup.name, children: currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option, children: option.menuLabel ?? option.label }, option.value))) })) : (currentGroup.options.map((option) => option.value === "" ? (jsxRuntimeExports.jsx(Option, { ...option, children: jsxRuntimeExports.jsx(EmptyValueOption, {}) }, option.value)) : (jsxRuntimeExports.jsx(Option, { ...option }, option.value))))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error })] })); +} + +function useWysiwyg({ hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, }) { + const isInitializedRef = reactExports.useRef(false); + const { addToast } = useToast(); + const { t } = useTranslation(); + return reactExports.useCallback(async (ref) => { + if (hasWysiwyg && ref && !isInitializedRef.current) { + isInitializedRef.current = true; + const { createEditor } = await import('wysiwyg').then(function (n) { return n.m; }); + const editor = await createEditor(ref, { + editorType: "supportRequests", + hasAtMentions, + userRole, + brandId, + baseLocale, + }); + const notifications = editor.plugins.get("Notification"); + // Handle generic notifications and errors with "toast" notifications + notifications.on("show", (event, data) => { + event.stop(); // Prevent the default notification from being shown via window.alert + const message = data.message instanceof Error + ? data.message.message + : data.message; + const { type, title } = data; + addToast(({ close }) => (jsxRuntimeExports.jsxs(Notification, { type: type, children: [jsxRuntimeExports.jsx(Title, { children: title }), message, jsxRuntimeExports.jsx(Close, { "aria-label": t("new-request-form.close-label", "Close"), onClick: close })] }))); + }); + } + }, [hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, addToast, t]); +} + +const StyledField = styled(Field) ` + .ck.ck-editor { + margin-top: ${(props) => props.theme.space.xs}; + } +`; +const StyledMessage = styled(Message) ` + .ck.ck-editor + & { + margin-top: ${(props) => props.theme.space.xs}; + } +`; +function TextArea({ field, hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, onChange, }) { + const { label, error, value, name, required, description } = field; + const ref = useWysiwyg({ + hasWysiwyg, + baseLocale, + hasAtMentions, + userRole, + brandId, + }); + return (jsxRuntimeExports.jsxs(StyledField, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Textarea, { ref: ref, name: name, defaultValue: value, validation: error ? "error" : undefined, required: required, onChange: (e) => onChange(e.target.value), rows: 6, isResizable: true }), error && jsxRuntimeExports.jsx(StyledMessage, { validation: "error", children: error })] })); +} + +const isCustomField = (field) => { + return (field.name.startsWith("custom_field_") || + field.name.startsWith("request[custom_fields]")); +}; +const systemType = [ + "subject", + "description", + "status", + "custom_status", + "type", + "priority", + "basic_priority", + "assignee", + "group", + "tickettype", +]; +const TicketFields = ({ fields, baseLocale, hasAtMentions, userRole, userId, defaultOrganizationId, organizationField, brandId, handleChange, }) => { + return (jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fields.map((field) => { + switch (field.type) { + case "text": + case "integer": + case "decimal": + case "regexp": + return (jsxRuntimeExports.jsx(Input, { field: field, onChange: (value) => handleChange(field, value) }, field.name)); + case "partialcreditcard": + return (jsxRuntimeExports.jsx(CreditCard, { field: field, onChange: (value) => handleChange(field, value) })); + case "textarea": + return (jsxRuntimeExports.jsx(TextArea, { field: field, hasWysiwyg: false, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, brandId: brandId, onChange: (value) => handleChange(field, value) }, field.name)); + case "checkbox": + return (jsxRuntimeExports.jsx(Checkbox, { field: field, onChange: (value) => handleChange(field, value) })); + case "date": + return (jsxRuntimeExports.jsx(DatePicker, { field: field, locale: baseLocale, valueFormat: "date", onChange: (value) => handleChange(field, value) })); + case "multiselect": + return jsxRuntimeExports.jsx(MultiSelect, { field: field }); + case "tagger": + return (jsxRuntimeExports.jsx(Tagger, { field: field, onChange: (value) => handleChange(field, value) }, field.name)); + case "lookup": + return (jsxRuntimeExports.jsx(LookupField, { field: field, userId: userId, organizationId: organizationField !== undefined + ? organizationField?.value + : defaultOrganizationId, onChange: (value) => handleChange(field, value) }, field.name)); + default: + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + } + }) })); +}; + +export { DatePicker as D, EmptyValueOption as E, Input as I, TextArea as T, TicketFields as a, getCustomObjectKey as g, isCustomField as i, systemType as s }; diff --git a/assets/new-request-form-bundle.js b/assets/new-request-form-bundle.js index c04781d82..46cfbdccb 100644 --- a/assets/new-request-form-bundle.js +++ b/assets/new-request-form-bundle.js @@ -1,292 +1,5 @@ -import { j as jsxRuntimeExports, F as Field, L as Label, S as Span, H as Hint, I as Input$1, M as Message, r as reactExports, u as useToast, a as useTranslation, N as Notification, T as Title, C as Close, s as styled, b as Textarea, d as Field$1, e as Label$1, f as Hint$1, h as Combobox, O as Option, i as Message$1, k as Checkbox$1, l as OptGroup, p as purify, m as FileList, n as File, o as Tooltip, P as Progress, A as Anchor, q as mime, t as useDropzone, v as FileUpload, D as Datepicker, w as useGrid, x as focusStyles, y as FauxInput, z as Tag, B as SvgAlertWarningStroke, E as MediaInput, G as SvgCreditCardStroke, $ as $e, J as getColorV8, K as Header, Q as SvgCheckCircleStroke, R as useModalContainer, U as Modal, V as Body, W as Accordion, X as Paragraph, Y as Footer$1, Z as FooterItem, _ as Button, a0 as Close$1, a1 as addFlashNotification, a2 as debounce, a3 as Alert, a4 as initI18next, a5 as loadTranslations, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme } from 'shared'; - -function Input({ field, onChange }) { - const { label, error, value, name, required, description, type } = field; - const stepProp = {}; - const inputType = type === "integer" || type === "decimal" ? "number" : "text"; - if (type === "integer") - stepProp.step = "1"; - if (type === "decimal") - stepProp.step = "any"; - const autocomplete = type === "anonymous_requester_email" ? "email" : undefined; - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Input$1, { name: name, type: inputType, defaultValue: value, validation: error ? "error" : undefined, required: required, onChange: (e) => { - onChange && onChange(e.target.value); - }, autoComplete: autocomplete, ...stepProp }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); -} - -function useWysiwyg({ hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, }) { - const isInitializedRef = reactExports.useRef(false); - const { addToast } = useToast(); - const { t } = useTranslation(); - return reactExports.useCallback(async (ref) => { - if (hasWysiwyg && ref && !isInitializedRef.current) { - isInitializedRef.current = true; - const { createEditor } = await import('wysiwyg').then(function (n) { return n.m; }); - const editor = await createEditor(ref, { - editorType: "supportRequests", - hasAtMentions, - userRole, - brandId, - baseLocale, - }); - const notifications = editor.plugins.get("Notification"); - // Handle generic notifications and errors with "toast" notifications - notifications.on("show", (event, data) => { - event.stop(); // Prevent the default notification from being shown via window.alert - const message = data.message instanceof Error - ? data.message.message - : data.message; - const { type, title } = data; - addToast(({ close }) => (jsxRuntimeExports.jsxs(Notification, { type: type, children: [jsxRuntimeExports.jsx(Title, { children: title }), message, jsxRuntimeExports.jsx(Close, { "aria-label": t("new-request-form.close-label", "Close"), onClick: close })] }))); - }); - } - }, [hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, addToast, t]); -} - -const StyledField = styled(Field) ` - .ck.ck-editor { - margin-top: ${(props) => props.theme.space.xs}; - } -`; -const StyledMessage = styled(Message) ` - .ck.ck-editor + & { - margin-top: ${(props) => props.theme.space.xs}; - } -`; -function TextArea({ field, hasWysiwyg, baseLocale, hasAtMentions, userRole, brandId, onChange, }) { - const { label, error, value, name, required, description } = field; - const ref = useWysiwyg({ - hasWysiwyg, - baseLocale, - hasAtMentions, - userRole, - brandId, - }); - return (jsxRuntimeExports.jsxs(StyledField, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Textarea, { ref: ref, name: name, defaultValue: value, validation: error ? "error" : undefined, required: required, onChange: (e) => onChange(e.target.value), rows: 6, isResizable: true }), error && jsxRuntimeExports.jsx(StyledMessage, { validation: "error", children: error })] })); -} - -function EmptyValueOption() { - const { t } = useTranslation(); - return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "-" }), jsxRuntimeExports.jsx(Span, { hidden: true, children: t("new-request-form.dropdown.empty-option", "Select an option") })] })); -} - -function DropDown({ field, onChange }) { - const { label, options, error, value, name, required, description } = field; - const selectionValue = value == null ? "" : value.toString(); - const wrapperRef = reactExports.useRef(null); - reactExports.useEffect(() => { - if (wrapperRef.current && required) { - const combobox = wrapperRef.current.querySelector("[role=combobox]"); - combobox?.setAttribute("aria-required", "true"); - } - }, [wrapperRef, required]); - return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { ref: wrapperRef, inputProps: { name, required }, isEditable: false, validation: error ? "error" : undefined, inputValue: selectionValue, selectionValue: selectionValue, renderValue: ({ selection }) => selection?.label || jsxRuntimeExports.jsx(EmptyValueOption, {}), onChange: ({ selectionValue }) => { - if (selectionValue !== undefined) { - onChange(selectionValue); - } - }, children: [!required && (jsxRuntimeExports.jsx(Option, { value: "", label: "-", children: jsxRuntimeExports.jsx(EmptyValueOption, {}) })), options.map((option) => (jsxRuntimeExports.jsx(Option, { value: option.value.toString(), label: option.name }, option.value)))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error })] })); -} - -function Checkbox({ field, onChange }) { - const { label, error, value, name, required, description } = field; - const [checkboxValue, setCheckboxValue] = reactExports.useState(value); - const handleChange = (e) => { - const { checked } = e.target; - setCheckboxValue(checked); - onChange(checked); - }; - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: "off" }), jsxRuntimeExports.jsxs(Checkbox$1, { name: name, required: required, defaultChecked: value, value: checkboxValue ? "on" : "off", onChange: handleChange, children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } }))] }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); -} - -/** - * The root group is identified by an empty string, to avoid possible clashes with a level with - * a "Root" name. - */ -const ROOT_GROUP_IDENTIFIER = "[]"; -function getGroupIdentifier(names) { - return `[${names.join("::")}]`; -} -function isGroupIdentifier(name) { - return name.startsWith("[") && name.endsWith("]"); -} -function getGroupAndOptionNames(input) { - const namesList = input.split("::"); - return [namesList.slice(0, -1), namesList.slice(-1)[0]]; -} -function buildSubGroupOptions(groupNames) { - const parentGroupNames = groupNames.slice(0, -1); - const parentGroupIdentifier = getGroupIdentifier(parentGroupNames); - const name = groupNames[groupNames.length - 1]; - return { - type: "SubGroup", - name, - backOption: { - type: "previous", - label: "Back", - value: parentGroupIdentifier, - }, - options: [], - }; -} -/** - * Maps a flat list of options to a nested structure - * - * For example, given the following options: - * [ - * { "name": "Bass::Fender::Precision", "value": "bass__fender__precision" }, - * { "name": "Bass::Fender::Jazz", "value": "bass__fender__jazz" } - * { "name": "Drums", "value": "drums" }, - * ] - * - * The following nested structure will be returned: - * { - * "[]": { - * "type": "RootGroup", - * "options": [ - * { "label": "Bass", "value": "[Bass]", type: "next" }, - * { "label": "Drums", "value": "drums" }, - * ] - * }, - * "[Bass]": { - * "type": "SubGroup", - * "name": "Bass", - * "backOption": { "type": "previous", "label": "Back", "value": "[]" }, - * "options": [ - * { "label": "Fender", "value": "[Bass::Fender]", type: "next" }, - * ] - * }, - * "[Bass::Fender]": { - * "type": "SubGroup", - * "name": "Fender", - * "backOption": { "type": "previous", "label": "Back", "value": "[Bass]" }, - * "options": [ - * { "menuLabel": "Precision", "label": "Bass > Fender > Precision", "value": "bass__fender__precision" }, - * { "menuLabel": "Jazz", "label": "Bass > Fender > Jazz", "value": "bass__fender__jazz" }, - * ] - * } - * } - * - * @param options original field options - * @param hasEmptyOption if true, adds an empty option to the root group - * @returns nested options - */ -function buildNestedOptions(options, hasEmptyOption) { - const result = { - [ROOT_GROUP_IDENTIFIER]: { - type: "RootGroup", - options: hasEmptyOption ? [{ label: "-", value: "" }] : [], - }, - }; - options.forEach((option) => { - const { name, value } = option; - if (!name.includes("::")) { - result[ROOT_GROUP_IDENTIFIER].options.push({ - value, - label: name, - }); - } - else { - const [groupNames, optionName] = getGroupAndOptionNames(name); - const groupIdentifier = getGroupIdentifier(groupNames); - if (!result[groupIdentifier]) { - result[groupIdentifier] = buildSubGroupOptions(groupNames); - } - result[groupIdentifier]?.options.push({ - value, - label: name.split("::").join(" > "), - menuLabel: optionName, - }); - // creates next options for each parent group, if they don't already exists - for (let i = 0; i < groupNames.length; i++) { - const parentGroupNames = groupNames.slice(0, i); - const nextGroupNames = groupNames.slice(0, i + 1); - const parentGroupIdentifier = getGroupIdentifier(parentGroupNames); - const nextGroupIdentifier = getGroupIdentifier(nextGroupNames); - if (!result[parentGroupIdentifier]) { - result[parentGroupIdentifier] = - buildSubGroupOptions(parentGroupNames); - } - if (result[parentGroupIdentifier]?.options.find((o) => o.value === nextGroupIdentifier) === undefined) { - result[parentGroupIdentifier]?.options.push({ - type: "next", - label: nextGroupNames[nextGroupNames.length - 1], - value: nextGroupIdentifier, - }); - } - } - } - }); - return result; -} -/** - * When one or more options are selected, the Combobox component renders the label - * for an option in the input, searching for an option passed as a child with the - * same value as the selected option. - * - * In the first render we are passing only the root group options as children, - * and if we already have some selected values from a SubGroup, the component is not - * able to find the label for the selected option. - * - * We therefore need to pass all the non-navigation options as children in the first render. - * The passed options are cached by the Combobox component, so we can safely remove them - * after the first render and pass only the root group options. - */ -function getInitialGroup(nestedOptions) { - const result = { - type: "RootGroup", - options: [], - }; - Object.values(nestedOptions).forEach(({ options }) => { - result.options.push(...options.filter(({ type }) => type === undefined)); - }); - return result; -} -function useNestedOptions({ options, hasEmptyOption, }) { - const nestedOptions = reactExports.useMemo(() => buildNestedOptions(options, hasEmptyOption), [options, hasEmptyOption]); - const [currentGroup, setCurrentGroup] = reactExports.useState(getInitialGroup(nestedOptions)); - reactExports.useEffect(() => { - setCurrentGroup(nestedOptions[ROOT_GROUP_IDENTIFIER]); - }, [nestedOptions]); - const setCurrentGroupByIdentifier = (identifier) => { - const group = nestedOptions[identifier]; - if (group) { - setCurrentGroup(group); - } - }; - return { - currentGroup, - isGroupIdentifier, - setCurrentGroupByIdentifier, - }; -} - -function MultiSelect({ field }) { - const { label, options, error, value, name, required, description } = field; - const { currentGroup, isGroupIdentifier, setCurrentGroupByIdentifier } = useNestedOptions({ - options, - hasEmptyOption: false, - }); - const [selectedValues, setSelectValues] = reactExports.useState(value || []); - const wrapperRef = reactExports.useRef(null); - reactExports.useEffect(() => { - if (wrapperRef.current && required) { - const combobox = wrapperRef.current.querySelector("[role=combobox]"); - combobox?.setAttribute("aria-required", "true"); - } - }, [wrapperRef, required]); - const handleChange = (changes) => { - if (Array.isArray(changes.selectionValue)) { - const lastSelectedItem = changes.selectionValue.slice(-1).toString(); - if (isGroupIdentifier(lastSelectedItem)) { - setCurrentGroupByIdentifier(lastSelectedItem); - } - else { - setSelectValues(changes.selectionValue); - } - } - }; - return (jsxRuntimeExports.jsxs(Field$1, { children: [selectedValues.map((selectedValue) => (jsxRuntimeExports.jsx("input", { type: "hidden", name: `${name}[]`, value: selectedValue }, selectedValue))), jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { ref: wrapperRef, isMultiselectable: true, inputProps: { required }, isEditable: false, validation: error ? "error" : undefined, onChange: handleChange, selectionValue: selectedValues, maxHeight: "auto", children: [currentGroup.type === "SubGroup" && (jsxRuntimeExports.jsx(Option, { ...currentGroup.backOption })), currentGroup.type === "SubGroup" ? (jsxRuntimeExports.jsx(OptGroup, { "aria-label": currentGroup.name, children: currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option, children: option.menuLabel ?? option.label }, option.value))) })) : (currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option }, option.value))))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error })] })); -} +import { r as reactExports, j as jsxRuntimeExports, c as Field, d as Label, f as Combobox, O as Option, p as purify, s as styled, u as useTranslation, q as FileList, t as File, v as Tooltip, P as Progress, A as Anchor, k as useToast, N as Notification, T as Title, l as Close, w as mime, x as useDropzone, F as Field$1, L as Label$1, M as Message, y as FileUpload, I as Input, z as useGrid, B as focusStyles, E as FauxInput, G as Tag, H as Hint, S as Span, J as SvgAlertWarningStroke, $ as $e, K as getColorV8, Q as Header, R as SvgCheckCircleStroke, U as useModalContainer, V as Modal, W as Body, X as Accordion, Y as Paragraph, Z as Footer$1, _ as FooterItem, a0 as Button, a1 as Close$1, a2 as addFlashNotification, a3 as Alert, a4 as initI18next, a5 as loadTranslations, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme } from 'shared'; +import { I as Input$1, D as DropDown, T as TextArea, a as TicketField } from 'ticket-fields'; const key = "return-focus-to-ticket-form-field"; function TicketFormField({ field, newRequestPath, }) { @@ -308,7 +21,7 @@ function TicketFormField({ field, newRequestPath, }) { ref.current?.firstChild?.focus(); } }, []); // eslint-disable-line react-hooks/exhaustive-deps - return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx("input", { type: "hidden", name: field.name, value: field.value }), field.options.length > 1 && (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsx(Label$1, { children: field.label }), jsxRuntimeExports.jsx(Combobox, { isEditable: false, onChange: handleChange, ref: ref, children: field.options.map((option) => (jsxRuntimeExports.jsx(Option, { value: option.value, label: option.name, isSelected: field.value === option.value, children: option.name }, option.value))) })] }))] })); + return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx("input", { type: "hidden", name: field.name, value: field.value }), field.options.length > 1 && (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsx(Label, { children: field.label }), jsxRuntimeExports.jsx(Combobox, { isEditable: false, onChange: handleChange, ref: ref, children: field.options.map((option) => (jsxRuntimeExports.jsx(Option, { value: option.value, label: option.name, isSelected: field.value === option.value, children: option.name }, option.value))) })] }))] })); } function ParentTicketField({ field, }) { @@ -623,7 +336,7 @@ function Attachments({ field }) { }); } }; - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsx(Label, { children: label }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error }), jsxRuntimeExports.jsxs(FileUpload, { ...getRootProps(), isDragging: isDragActive, children: [isDragActive ? (jsxRuntimeExports.jsx("span", { children: t("new-request-form.attachments.drop-files-label", "Drop files here") })) : (jsxRuntimeExports.jsx("span", { children: t("new-request-form.attachments.choose-file-label", "Choose a file or drag and drop here") })), jsxRuntimeExports.jsx(Input$1, { ...getInputProps() })] }), files.map((file) => (jsxRuntimeExports.jsx(FileListItem, { file: file, onRemove: () => { + return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsx(Label$1, { children: label }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error }), jsxRuntimeExports.jsxs(FileUpload, { ...getRootProps(), isDragging: isDragActive, children: [isDragActive ? (jsxRuntimeExports.jsx("span", { children: t("new-request-form.attachments.drop-files-label", "Drop files here") })) : (jsxRuntimeExports.jsx("span", { children: t("new-request-form.attachments.choose-file-label", "Choose a file or drag and drop here") })), jsxRuntimeExports.jsx(Input, { ...getInputProps() })] }), files.map((file) => (jsxRuntimeExports.jsx(FileListItem, { file: file, onRemove: () => { handleRemove(file); } }, file.status === "pending" ? file.id : file.value.id))), files.map((file) => file.status === "uploaded" && (jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: JSON.stringify(file.value) }, file.value.id)))] })); } @@ -671,35 +384,6 @@ function getVisibleFields(fields, endUserConditions) { }, []); } -function DatePicker({ field, locale, valueFormat, onChange, }) { - const { label, error, value, name, required, description } = field; - const [date, setDate] = reactExports.useState(value ? new Date(value) : undefined); - const formatDate = (value) => { - if (value === undefined) { - return ""; - } - const isoString = value.toISOString(); - return valueFormat === "dateTime" ? isoString : isoString.split("T")[0]; - }; - const handleChange = (date) => { - // Set the time to 12:00:00 as this is also the expected behavior across Support and the API - const newDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0)); - setDate(newDate); - const dateString = formatDate(newDate); - if (dateString !== undefined) { - onChange(dateString); - } - }; - const handleInputChange = (e) => { - // Allow field to be cleared - if (e.target.value === "") { - setDate(undefined); - onChange(""); - } - }; - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(Datepicker, { value: date, onChange: handleChange, locale: locale, children: jsxRuntimeExports.jsx(Input$1, { required: required, lang: locale, onChange: handleInputChange, validation: error ? "error" : undefined }) }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error }), jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: formatDate(date) })] })); -} - function useTagsInputContainer({ tags, onTagsChange, inputValue, onInputValueChange, inputRef, gridRowRef, i18n, }) { const [selectedIndex, setSelectedIndex] = reactExports.useState(0); const [announcement, setAnnouncement] = reactExports.useState(""); @@ -862,7 +546,7 @@ const InputMirror = styled(FauxInput) ` height: var(--line-height); line-height: var(--line-height); `; -const StyledInput = styled(Input$1) ` +const StyledInput = styled(Input) ` position: absolute; top: 0; left: 0; @@ -895,7 +579,7 @@ function CcField({ field }) { }, }); const renderTag = (index, isValid, email) => (jsxRuntimeExports.jsxs(StyledTag, { size: "large", "aria-label": t("new-request-form.cc-field.email-label", "{{email}} - Press Backspace to remove", { email }), hue: isValid ? undefined : "red", children: [!isValid && (jsxRuntimeExports.jsx(Tag.Avatar, { children: jsxRuntimeExports.jsx(SvgAlertWarningStroke, {}) })), jsxRuntimeExports.jsx("span", { children: email }), jsxRuntimeExports.jsx(Tag.Close, { ...getTagCloseProps(index) })] })); - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsx(Label, { children: label }), description && jsxRuntimeExports.jsx(Hint, { children: description }), jsxRuntimeExports.jsxs(Container$1, { ...getContainerProps(), children: [tags.length > 0 && (jsxRuntimeExports.jsx("span", { ...getGridProps({ + return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsx(Label$1, { children: label }), description && jsxRuntimeExports.jsx(Hint, { children: description }), jsxRuntimeExports.jsxs(Container$1, { ...getContainerProps(), children: [tags.length > 0 && (jsxRuntimeExports.jsx("span", { ...getGridProps({ "aria-label": t("new-request-form.cc-field.container-label", "Selected CC emails"), }), children: jsxRuntimeExports.jsx("span", { ref: gridRowRef, ...getGridRowProps(), children: tags.map((email, index) => { const isValid = EMAIL_REGEX.test(email); @@ -903,58 +587,6 @@ function CcField({ field }) { }) }) })), jsxRuntimeExports.jsxs(InputWrapper, { children: [jsxRuntimeExports.jsx(InputMirror, { isBare: true, "aria-hidden": "true", tabIndex: -1, children: inputValue }), jsxRuntimeExports.jsx(StyledInput, { ref: inputRef, isBare: true, ...getInputProps() })] })] }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error }), tags.map((email) => (jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: email }, email))), jsxRuntimeExports.jsx(Span, { hidden: true, ...getAnnouncementProps(), children: announcement })] })); } -/** - * When there is an error in the credit card field, the backend returns a redacted value with the last 4 digits prefixed with some Xs. - * This function removes the Xs from the value and returns the last 4 digits of the credit card - * - * @param value The value returned by the backend with last 4 digits prefixed with some Xs - * @returns The last 4 digits of the credit card - */ -function getLastDigits(value) { - return value ? value.replaceAll("X", "") : ""; -} -const DigitsHintSpan = styled(Span) ` - margin-left: ${(props) => props.theme.space.xxs}; - font-weight: ${(props) => props.theme.fontWeights.medium}; -`; -function CreditCard({ field, onChange }) { - const { t } = useTranslation(); - const { label, error, value, name, required, description } = field; - const digits = getLastDigits(value); - return (jsxRuntimeExports.jsxs(Field, { children: [jsxRuntimeExports.jsxs(Label, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" }), jsxRuntimeExports.jsx(DigitsHintSpan, { children: t("new-request-form.credit-card-digits-hint", "(Last 4 digits)") })] }), description && (jsxRuntimeExports.jsx(Hint, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsx(MediaInput, { start: jsxRuntimeExports.jsx(SvgCreditCardStroke, {}), name: name, type: "text", value: digits, onChange: (e) => onChange(e.target.value), validation: error ? "error" : undefined, required: required, maxLength: 4, placeholder: "XXXX" }), error && jsxRuntimeExports.jsx(Message, { validation: "error", children: error })] })); -} - -function Tagger({ field, onChange }) { - const { label, options, error, value, name, required, description } = field; - const { currentGroup, isGroupIdentifier, setCurrentGroupByIdentifier } = useNestedOptions({ - options, - hasEmptyOption: true, - }); - const selectionValue = value ?? ""; - const [isExpanded, setIsExpanded] = reactExports.useState(false); - const wrapperRef = reactExports.useRef(null); - reactExports.useEffect(() => { - if (wrapperRef.current && required) { - const combobox = wrapperRef.current.querySelector("[role=combobox]"); - combobox?.setAttribute("aria-required", "true"); - } - }, [wrapperRef, required]); - const handleChange = (changes) => { - if (typeof changes.selectionValue === "string" && - isGroupIdentifier(changes.selectionValue)) { - setCurrentGroupByIdentifier(changes.selectionValue); - return; - } - if (typeof changes.selectionValue === "string") { - onChange(changes.selectionValue); - } - if (changes.isExpanded !== undefined) { - setIsExpanded(changes.isExpanded); - } - }; - return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { ref: wrapperRef, inputProps: { required, name }, isEditable: false, validation: error ? "error" : undefined, onChange: handleChange, selectionValue: selectionValue, inputValue: selectionValue, renderValue: ({ selection }) => selection?.label ?? jsxRuntimeExports.jsx(EmptyValueOption, {}), isExpanded: isExpanded, children: [currentGroup.type === "SubGroup" && (jsxRuntimeExports.jsx(Option, { ...currentGroup.backOption })), currentGroup.type === "SubGroup" ? (jsxRuntimeExports.jsx(OptGroup, { "aria-label": currentGroup.name, children: currentGroup.options.map((option) => (jsxRuntimeExports.jsx(Option, { ...option, children: option.menuLabel ?? option.label }, option.value))) })) : (currentGroup.options.map((option) => option.value === "" ? (jsxRuntimeExports.jsx(Option, { ...option, children: jsxRuntimeExports.jsx(EmptyValueOption, {}) }, option.value)) : (jsxRuntimeExports.jsx(Option, { ...option }, option.value))))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error })] })); -} - function useDebounce(value, delayMs) { const [debouncedValue, setDebouncedValue] = reactExports.useState(value); reactExports.useEffect(() => { @@ -1129,123 +761,6 @@ function AnswerBotModal({ authToken, interactionAccessToken, articles, requestId }, children: t("new-request-form.answer-bot-modal.solve-request", "Yes, close my request") }) })] }), jsxRuntimeExports.jsx(Close$1, { "aria-label": t("new-request-form.close-label", "Close") })] })); } -function getCustomObjectKey(targetType) { - return targetType.replace("zen:custom_object:", ""); -} -const EMPTY_OPTION = { - value: "", - name: "-", -}; -function LookupField({ field, userId, organizationId, onChange, }) { - const { id: fieldId, label, error, value, name, required, description, relationship_target_type, } = field; - const [options, setOptions] = reactExports.useState([]); - const [selectedOption, setSelectedOption] = reactExports.useState(null); - const [inputValue, setInputValue] = reactExports.useState(value); - const [isLoadingOptions, setIsLoadingOptions] = reactExports.useState(false); - const { t } = useTranslation(); - const customObjectKey = getCustomObjectKey(relationship_target_type); - const loadingOption = { - name: t("new-request-form.lookup-field.loading-options", "Loading items..."), - id: "loading", - }; - const noResultsOption = { - name: t("new-request-form.lookup-field.no-matches-found", "No matches found"), - id: "no-results", - }; - const fetchSelectedOption = reactExports.useCallback(async (selectionValue) => { - try { - const res = await fetch(`/api/v2/custom_objects/${customObjectKey}/records/${selectionValue}`); - if (res.ok) { - const { custom_object_record } = await res.json(); - const newSelectedOption = { - name: custom_object_record.name, - value: custom_object_record.id, - }; - setSelectedOption(newSelectedOption); - setInputValue(custom_object_record.name); - } - } - catch (error) { - console.error(error); - } - }, [customObjectKey]); - const fetchOptions = reactExports.useCallback(async (inputValue) => { - const searchParams = new URLSearchParams(); - searchParams.set("name", inputValue.toLocaleLowerCase()); - searchParams.set("source", "zen:ticket"); - searchParams.set("field_id", fieldId.toString()); - searchParams.set("requester_id", userId.toString()); - if (organizationId !== null) - searchParams.set("organization_id", organizationId); - setIsLoadingOptions(true); - try { - const response = await fetch(`/api/v2/custom_objects/${customObjectKey}/records/autocomplete?${searchParams.toString()}`); - const data = await response.json(); - if (response.ok) { - let fetchedOptions = data.custom_object_records.map(({ name, id }) => ({ - name, - value: id, - })); - if (selectedOption) { - fetchedOptions = fetchedOptions.filter((option) => option.value !== selectedOption.value); - fetchedOptions = [selectedOption, ...fetchedOptions]; - } - setOptions(fetchedOptions); - } - else { - setOptions([]); - } - } - catch (error) { - console.error(error); - } - finally { - setIsLoadingOptions(false); - } - }, [customObjectKey, fieldId, organizationId, selectedOption, userId]); - const debouncedFetchOptions = reactExports.useMemo(() => debounce(fetchOptions, 300), [fetchOptions]); - reactExports.useEffect(() => { - return () => debouncedFetchOptions.cancel(); - }, [debouncedFetchOptions]); - const handleChange = reactExports.useCallback(({ inputValue, selectionValue }) => { - if (selectionValue !== undefined) { - if (selectionValue == "") { - setSelectedOption(EMPTY_OPTION); - setInputValue(EMPTY_OPTION.name); - setOptions([]); - onChange(EMPTY_OPTION.value); - } - else { - const selectedOption = options.find((option) => option.value === selectionValue); - if (selectedOption) { - setInputValue(selectedOption.name); - setSelectedOption(selectedOption); - setOptions([selectedOption]); - onChange(selectedOption.value); - } - } - } - if (inputValue !== undefined) { - setInputValue(inputValue); - debouncedFetchOptions(inputValue); - } - }, [debouncedFetchOptions, onChange, options]); - reactExports.useEffect(() => { - if (value) { - fetchSelectedOption(value); - } - }, []); //we don't set dependency array as we want this hook to be called only once - const onFocus = () => { - setInputValue(""); - fetchOptions("*"); - }; - return (jsxRuntimeExports.jsxs(Field$1, { children: [jsxRuntimeExports.jsxs(Label$1, { children: [label, required && jsxRuntimeExports.jsx(Span, { "aria-hidden": "true", children: "*" })] }), description && (jsxRuntimeExports.jsx(Hint$1, { dangerouslySetInnerHTML: { __html: description } })), jsxRuntimeExports.jsxs(Combobox, { inputProps: { required }, "data-test-id": "lookup-field-combobox", validation: error ? "error" : undefined, inputValue: inputValue, selectionValue: selectedOption?.value, isAutocomplete: true, placeholder: t("new-request-form.lookup-field.placeholder", "Search {{label}}", { label: label.toLowerCase() }), onFocus: onFocus, onChange: handleChange, renderValue: () => selectedOption ? selectedOption?.name : EMPTY_OPTION.name, children: [selectedOption?.name !== EMPTY_OPTION.name && (jsxRuntimeExports.jsx(Option, { value: "", label: "-", children: jsxRuntimeExports.jsx(EmptyValueOption, {}) })), isLoadingOptions && (jsxRuntimeExports.jsx(Option, { isDisabled: true, value: loadingOption.name }, loadingOption.id)), !isLoadingOptions && - inputValue?.length > 0 && - options.length === 0 && (jsxRuntimeExports.jsx(Option, { isDisabled: true, value: noResultsOption.name }, noResultsOption.id)), !isLoadingOptions && - options.length !== 0 && - options.map((option) => (jsxRuntimeExports.jsx(Option, { value: option.value, label: option.name, "data-test-id": `option-${option.name}` }, option.value)))] }), error && jsxRuntimeExports.jsx(Message$1, { validation: "error", children: error }), jsxRuntimeExports.jsx("input", { type: "hidden", name: name, value: selectedOption?.value })] })); -} - const StyledParagraph = styled(Paragraph) ` margin: ${(props) => props.theme.space.md} 0; `; @@ -1295,43 +810,17 @@ function NewRequestForm({ requestForm, wysiwyg, newRequestPath, parentId, parent } return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [parentId && (jsxRuntimeExports.jsx(StyledParagraph, { children: jsxRuntimeExports.jsx(Anchor, { href: parentIdPath, children: t("new-request-form.parent-request-link", "Follow-up to request {{parentId}}", { parentId: `\u202D#${parentId}\u202C`, - }) }) })), jsxRuntimeExports.jsx(StyledParagraph, { "aria-hidden": "true", children: t("new-request-form.required-fields-info", "Fields marked with an asterisk (*) are required.") }), jsxRuntimeExports.jsxs(Form, { ref: formRefCallback, action: action, method: http_method, acceptCharset: accept_charset, noValidate: true, onSubmit: handleSubmit, children: [errors && jsxRuntimeExports.jsx(Alert, { type: "error", children: errors }), parent_id_field && jsxRuntimeExports.jsx(ParentTicketField, { field: parent_id_field }), ticket_form_field.options.length > 0 && (jsxRuntimeExports.jsx(TicketFormField, { field: ticket_form_field, newRequestPath: newRequestPath })), emailField && jsxRuntimeExports.jsx(Input, { field: emailField }, emailField.name), ccField && jsxRuntimeExports.jsx(CcField, { field: ccField }), organizationField && (jsxRuntimeExports.jsx(DropDown, { field: organizationField, onChange: (value) => { + }) }) })), jsxRuntimeExports.jsx(StyledParagraph, { "aria-hidden": "true", children: t("new-request-form.required-fields-info", "Fields marked with an asterisk (*) are required.") }), jsxRuntimeExports.jsxs(Form, { ref: formRefCallback, action: action, method: http_method, acceptCharset: accept_charset, noValidate: true, onSubmit: handleSubmit, children: [errors && jsxRuntimeExports.jsx(Alert, { type: "error", children: errors }), parent_id_field && jsxRuntimeExports.jsx(ParentTicketField, { field: parent_id_field }), ticket_form_field.options.length > 0 && (jsxRuntimeExports.jsx(TicketFormField, { field: ticket_form_field, newRequestPath: newRequestPath })), emailField && jsxRuntimeExports.jsx(Input$1, { field: emailField }, emailField.name), ccField && jsxRuntimeExports.jsx(CcField, { field: ccField }), organizationField && (jsxRuntimeExports.jsx(DropDown, { field: organizationField, onChange: (value) => { handleOrganizationChange(value); } }, organizationField.name)), visibleFields.map((field) => { - switch (field.type) { - case "subject": - return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(Input, { field: field, onChange: (value) => handleChange(field, value) }, field.name), jsxRuntimeExports.jsx(SuggestedArticles, { query: field.value, locale: locale })] })); - case "text": - case "integer": - case "decimal": - case "regexp": - return (jsxRuntimeExports.jsx(Input, { field: field, onChange: (value) => handleChange(field, value) }, field.name)); - case "partialcreditcard": - return (jsxRuntimeExports.jsx(CreditCard, { field: field, onChange: (value) => handleChange(field, value) })); - case "description": - return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(TextArea, { field: field, hasWysiwyg: wysiwyg, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, brandId: brandId, onChange: (value) => handleChange(field, value) }, field.name), jsxRuntimeExports.jsx("input", { type: "hidden", name: description_mimetype_field.name, value: wysiwyg ? "text/html" : "text/plain" })] })); - case "textarea": - return (jsxRuntimeExports.jsx(TextArea, { field: field, hasWysiwyg: false, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, brandId: brandId, onChange: (value) => handleChange(field, value) }, field.name)); - case "priority": - case "basic_priority": - case "tickettype": - return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(DropDown, { field: field, onChange: (value) => handleChange(field, value) }, field.name), field.value === "task" && (jsxRuntimeExports.jsx(DatePicker, { field: dueDateField, locale: baseLocale, valueFormat: "dateTime", onChange: (value) => { - handleDueDateChange(value); - } }))] })); - case "checkbox": - return (jsxRuntimeExports.jsx(Checkbox, { field: field, onChange: (value) => handleChange(field, value) })); - case "date": - return (jsxRuntimeExports.jsx(DatePicker, { field: field, locale: baseLocale, valueFormat: "date", onChange: (value) => handleChange(field, value) })); - case "multiselect": - return jsxRuntimeExports.jsx(MultiSelect, { field: field }); - case "tagger": - return (jsxRuntimeExports.jsx(Tagger, { field: field, onChange: (value) => handleChange(field, value) }, field.name)); - case "lookup": - return (jsxRuntimeExports.jsx(LookupField, { field: field, userId: userId, organizationId: organizationField !== null - ? organizationField.value - : defaultOrganizationId, onChange: (value) => handleChange(field, value) }, field.name)); - default: - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + if (field.type === "subject") { + return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(Input$1, { field: field, onChange: (value) => handleChange(field, value) }, field.name), jsxRuntimeExports.jsx(SuggestedArticles, { query: field.value, locale: locale })] })); + } + else if (field.type === "description") { + return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(TextArea, { field: field, hasWysiwyg: wysiwyg, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, brandId: brandId, onChange: (value) => handleChange(field, value) }, field.name), jsxRuntimeExports.jsx("input", { type: "hidden", name: description_mimetype_field.name, value: wysiwyg ? "text/html" : "text/plain" })] })); + } + else { + return (jsxRuntimeExports.jsx(TicketField, { field: field, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, userId: userId, brandId: brandId, dueDateField: dueDateField, handleDueDateChange: handleDueDateChange, organizationField: organizationField, defaultOrganizationId: defaultOrganizationId, handleChange: handleChange }, field.name)); } }), attachments_field && jsxRuntimeExports.jsx(Attachments, { field: attachments_field }), inline_attachments_fields.map(({ type, name, value }, index) => (jsxRuntimeExports.jsx("input", { type: type, name: name, value: value }, index))), jsxRuntimeExports.jsx(Footer, { children: (ticket_form_field.options.length === 0 || ticket_form_field.value) && (jsxRuntimeExports.jsx(Button, { isPrimary: true, type: "submit", children: t("new-request-form.submit", "Submit") })) })] }), answerBot.auth_token && diff --git a/assets/service-catalog-bundle.js b/assets/service-catalog-bundle.js index d1a3561c2..5c0f6afae 100644 --- a/assets/service-catalog-bundle.js +++ b/assets/service-catalog-bundle.js @@ -1,4 +1,5 @@ -import { s as styled, J as getColorV8, j as jsxRuntimeExports, aa as SvgShapesFill, ab as Grid, ac as Col, ad as Row, ae as Skeleton, af as MD, ag as SM, a as useTranslation, ah as LG, A as Anchor, _ as Button, r as reactExports, ai as CursorPagination, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme, aj as XXXL, ak as SvgChevronUpFill, al as SvgChevronDownFill } from 'shared'; +import { s as styled, K as getColorV8, j as jsxRuntimeExports, aa as SvgShapesFill, ab as Grid, ac as Col, ad as Row, ae as Skeleton, af as MD, ag as SM, u as useTranslation, ah as LG, A as Anchor, a0 as Button, r as reactExports, ai as CursorPagination, a6 as reactDomExports, a7 as ThemeProviders, a8 as createTheme, aj as XXXL, ak as SvgChevronUpFill, al as SvgChevronDownFill } from 'shared'; +import { g as getCustomObjectKey, a as TicketField } from 'ticket-fields'; const ItemContainer = styled.a ` display: flex; @@ -54,7 +55,7 @@ const IconContainer = styled.div ` align-content: center; `; const ServiceCatalogListItem = ({ serviceItem, }) => { - return (jsxRuntimeExports.jsxs(ItemContainer, { href: "#", children: [jsxRuntimeExports.jsx(IconContainer, { children: jsxRuntimeExports.jsx(SvgShapesFill, {}) }), jsxRuntimeExports.jsxs(TextContainer$1, { children: [jsxRuntimeExports.jsx(ItemTitle$1, { children: serviceItem.name }), jsxRuntimeExports.jsx(ItemDescription, { children: serviceItem.description })] })] })); + return (jsxRuntimeExports.jsxs(ItemContainer, { href: "/hc/en-us/p/service_catalog_item", children: [jsxRuntimeExports.jsx(IconContainer, { children: jsxRuntimeExports.jsx(SvgShapesFill, {}) }), jsxRuntimeExports.jsxs(TextContainer$1, { children: [jsxRuntimeExports.jsx(ItemTitle$1, { children: serviceItem.name }), jsxRuntimeExports.jsx(ItemDescription, { children: serviceItem.description })] })] })); }; const SkeletonItem = styled.div ` @@ -132,7 +133,13 @@ function ServiceCatalogList({ helpCenterPath, }) { : `/api/v2/custom_objects/service_catalog_item/records?page[size]=16`); const data = await response.json(); if (response.ok) { - const records = data.custom_object_records.map(({ id, name, custom_object_fields, }) => ({ id, name, description: custom_object_fields.description })); + const records = data.custom_object_records.map(({ id, name, custom_object_fields, custom_object_key, }) => ({ + id, + name, + description: custom_object_fields.description, + form_id: custom_object_fields.form_id, + custom_object_key, + })); setMeta(data.meta); setServiceCatalogItems(records); setIsLoading(false); @@ -166,6 +173,89 @@ async function renderServiceCatalogList(container, settings, helpCenterPath) { reactDomExports.render(jsxRuntimeExports.jsx(ThemeProviders, { theme: createTheme(settings), children: jsxRuntimeExports.jsx(ServiceCatalogList, { helpCenterPath: helpCenterPath }) }), container); } +const formatField = (field) => { + const { id, type, description, title_in_portal, custom_field_options, required_in_portal, relationship_target_type, } = field; + return { + id, + type, + name: `custom_fields_${id}`, + description, + label: title_in_portal, + options: custom_field_options, + required: required_in_portal, + relationship_target_type, + error: null, + }; +}; +const isAssociatedLookupField = (field) => { + const customObjectKey = getCustomObjectKey(field.relationship_target_type); + return customObjectKey === "service_catalog_item"; +}; +const fetchTicketFields = async (form_id) => { + try { + const [formResponse, fieldsResponse] = await Promise.all([ + fetch(`/api/v2/ticket_forms/${form_id}`), + fetch(`/api/v2/ticket_fields`), + ]); + if (!formResponse.ok) { + throw new Error("Error fetching form data"); + } + if (!fieldsResponse.ok) { + throw new Error("Error fetching fields data"); + } + const formData = await formResponse.json(); + const fieldsData = await fieldsResponse.json(); + const ids = formData.ticket_form.ticket_field_ids; + const ticketFieldsData = fieldsData.ticket_fields.filter((field) => ids.includes(field.id)); + const requestFields = ticketFieldsData + .map((ticketField) => { + if (ticketField.type === "lookup" && + isAssociatedLookupField(ticketField)) { + return null; + } + else { + return formatField(ticketField); + } + }) + .filter(Boolean); + return requestFields; + } + catch (error) { + console.error("Error fetching ticket fields:", error); + return []; + } +}; +function useItemFormFields(serviceCatalogItem) { + const [requestFields, setRequestFields] = reactExports.useState([]); + reactExports.useEffect(() => { + const fetchAndSetFields = async () => { + try { + await fetchTicketFields(serviceCatalogItem.form_id).then((ticketFields) => setRequestFields(ticketFields)); + } + catch (error) { + console.error("Error fetching ticket fields:", error); + } + }; + fetchAndSetFields(); + }, [serviceCatalogItem.form_id]); + const handleChange = reactExports.useCallback((field, value) => { + setRequestFields(requestFields.map((ticketField) => ticketField.name === field.name + ? { ...ticketField, value } + : ticketField)); + }, [requestFields]); + return { requestFields, handleChange }; +} + +const Form = styled.form ` + display: flex; + flex-direction: column; + gap: ${(props) => props.theme.space.md}; +`; +const ItemRequestForm = ({ requestFields, baseLocale, hasAtMentions, userRole, userId, brandId, defaultOrganizationId, handleChange, }) => { + return (jsxRuntimeExports.jsx(Form, { children: requestFields !== undefined && + requestFields.map((field) => (jsxRuntimeExports.jsx(TicketField, { field: field, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, userId: userId, brandId: brandId, defaultOrganizationId: defaultOrganizationId, handleChange: handleChange }, field.id))) })); +}; + const ItemTitle = styled(XXXL) ` font-weight: ${(props) => props.theme.fontWeights.semibold}; `; @@ -195,6 +285,16 @@ const Container = styled.div ` `; const LeftColumn = styled.div ` flex: 2; + display: flex; + flex-direction: column; + gap: ${(props) => props.theme.space.lg}; + margin-right: ${(props) => props.theme.space.xl}; + + @media (max-width: ${(props) => props.theme.breakpoints.md}) { + margin-right: 0; + } +`; +const DescriptionWrapper = styled.div ` border-bottom: ${(props) => props.theme.borders.sm} ${(props) => getColorV8("grey", 300, props.theme)}; padding-bottom: ${(props) => props.theme.space.lg}; @@ -204,6 +304,13 @@ const LeftColumn = styled.div ` margin-right: 0; } `; +const FromFieldsWrapper = styled.div ` + margin-right: ${(props) => props.theme.space.xl}; + + @media (max-width: ${(props) => props.theme.breakpoints.md}) { + margin-right: 0; + } +`; const RightColumn = styled.div ` flex: 1; margin-left: ${(props) => props.theme.space.xl}; @@ -212,6 +319,10 @@ const RightColumn = styled.div ` position: sticky; bottom: 0; margin-left: 0; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; } `; const ToggleButton = styled(Button) ` @@ -228,26 +339,37 @@ const ButtonWrapper = styled.div ` display: flex; flex-direction: column; align-items: center; + bottom: 0; + left: 0; + right: 0; + width: 100%; @media (max-width: ${(props) => props.theme.breakpoints.md}) { position: sticky; - bottom: 0; + top: 0; background: ${(props) => props.theme.colors.background}; - padding: ${(props) => props.theme.space.md}; + padding: ${(props) => props.theme.space.lg}; border: none; border-top: ${(props) => props.theme.borders.sm} ${(props) => getColorV8("grey", 300, props.theme)}; + width: 100vw; + left: 0; + right: 0; } `; -function ServiceCatalogItemPage({ serviceCatalogItem, }) { +function ServiceCatalogItemPage({ serviceCatalogItem, baseLocale, hasAtMentions, userRole, organizations, userId, brandId, }) { const [isExpanded, setIsExpanded] = reactExports.useState(false); + const { requestFields, handleChange } = useItemFormFields(serviceCatalogItem); const { t } = useTranslation(); + const defaultOrganizationId = organizations.length > 0 && organizations[0]?.id + ? organizations[0]?.id?.toString() + : null; const toggleDescription = () => { setIsExpanded(!isExpanded); }; - return (jsxRuntimeExports.jsxs(Container, { children: [jsxRuntimeExports.jsxs(LeftColumn, { children: [jsxRuntimeExports.jsx(ItemTitle, { tag: "h1", children: serviceCatalogItem.name }), jsxRuntimeExports.jsx(CollapsibleDescription, { expanded: isExpanded, children: serviceCatalogItem.description }), jsxRuntimeExports.jsxs(ToggleButton, { "aria-hidden": "true", isLink: true, onClick: toggleDescription, children: [isExpanded - ? t("service-catalog.item.read-less", "Read less") - : t("service-catalog.item.read-more", "Read more"), jsxRuntimeExports.jsx(Button.EndIcon, { children: isExpanded ? jsxRuntimeExports.jsx(SvgChevronUpFill, {}) : jsxRuntimeExports.jsx(SvgChevronDownFill, {}) })] })] }), jsxRuntimeExports.jsx(RightColumn, { children: jsxRuntimeExports.jsx(ButtonWrapper, { children: jsxRuntimeExports.jsx(Button, { isPrimary: true, size: "large", isStretched: true, children: t("service-catalog.item.submit-button", "Submit request") }) }) })] })); + return (jsxRuntimeExports.jsxs(Container, { children: [jsxRuntimeExports.jsxs(LeftColumn, { children: [jsxRuntimeExports.jsxs(DescriptionWrapper, { children: [jsxRuntimeExports.jsx(ItemTitle, { tag: "h1", children: serviceCatalogItem.name }), jsxRuntimeExports.jsx(CollapsibleDescription, { expanded: isExpanded, children: serviceCatalogItem.description }), jsxRuntimeExports.jsxs(ToggleButton, { isLink: true, onClick: toggleDescription, children: [isExpanded + ? t("service-catalog.item.read-less", "Read less") + : t("service-catalog.item.read-more", "Read more"), jsxRuntimeExports.jsx(Button.EndIcon, { children: isExpanded ? jsxRuntimeExports.jsx(SvgChevronUpFill, {}) : jsxRuntimeExports.jsx(SvgChevronDownFill, {}) })] })] }), jsxRuntimeExports.jsx(FromFieldsWrapper, { children: jsxRuntimeExports.jsx(ItemRequestForm, { requestFields: requestFields, baseLocale: baseLocale, hasAtMentions: hasAtMentions, userRole: userRole, userId: userId, brandId: brandId, defaultOrganizationId: defaultOrganizationId, handleChange: handleChange }) })] }), jsxRuntimeExports.jsx(RightColumn, { children: jsxRuntimeExports.jsx(ButtonWrapper, { children: jsxRuntimeExports.jsx(Button, { isPrimary: true, size: "large", isStretched: true, children: t("service-catalog.item.submit-button", "Submit request") }) }) })] })); } //data mocked for now @@ -255,9 +377,14 @@ const serviceCatalogItem = { id: 1, name: "Apple MacBook Pro", description: "Request for a new Apple MacBook Pro. The MacBook Pro is equipped with Apple's powerful M3 Pro chip, featuring a 12-core CPU, 18-core GPU, and a 16-core Neural Engine, making it ideal for high-performance tasks. It comes with a 140W USB-C power adapter, three Thunderbolt 4 ports, HDMI, SDXC card slot, headphone jack, and MagSafe 3 port. The backlit Magic Keyboard with Touch ID enhances security and usability. Exclusively for Engineering, Design, and Marketing departments, the 16-inch model includes up to 36+ GB of memory and 1+ TB of storage, while other departments can request machines with up to 36 GB of memory and 512 GB of storage.", + form_id: "8448527509374", }; -async function renderServiceCatalogItem(container, settings) { - reactDomExports.render(jsxRuntimeExports.jsx(ThemeProviders, { theme: createTheme(settings), children: jsxRuntimeExports.jsx(ServiceCatalogItemPage, { serviceCatalogItem: serviceCatalogItem }) }), container); +async function renderServiceCatalogItem(container, settings, props) { + const extendedProps = { + ...props, + serviceCatalogItem: serviceCatalogItem, + }; + reactDomExports.render(jsxRuntimeExports.jsx(ThemeProviders, { theme: createTheme(settings), children: jsxRuntimeExports.jsx(ServiceCatalogItemPage, { ...extendedProps }) }), container); } export { renderServiceCatalogItem, renderServiceCatalogList }; diff --git a/assets/shared-bundle.js b/assets/shared-bundle.js index c456375c0..3cb7a6fe0 100644 --- a/assets/shared-bundle.js +++ b/assets/shared-bundle.js @@ -9950,2100 +9950,2376 @@ const useField = _ref => { hasMessage: PropTypes.bool }); -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ +let e=e=>"object"==typeof e&&null!=e&&1===e.nodeType,t=(e,t)=>(!t||"hidden"!==e)&&("visible"!==e&&"clip"!==e),n=(e,n)=>{if(e.clientHeight{let t=(e=>{if(!e.ownerDocument||!e.ownerDocument.defaultView)return null;try{return e.ownerDocument.defaultView.frameElement}catch(e){return null}})(e);return !!t&&(t.clientHeightot||o>e&&r=t&&d>=n?o-e-l:r>t&&dn?r-t+i:0,i=e=>{let t=e.parentElement;return null==t?e.getRootNode().host||null:t};var o=(t,o)=>{var r,d,h,f,u,s;if("undefined"==typeof document)return [];let{scrollMode:a,block:c,inline:g,boundary:m,skipOverflowHiddenElements:p}=o,w="function"==typeof m?m:e=>e!==m;if(!e(t))throw new TypeError("Invalid target");let W=document.scrollingElement||document.documentElement,H=[],b=t;for(;e(b)&&w(b);){if(b=i(b),b===W){H.push(b);break}null!=b&&b===document.body&&n(b)&&!n(document.documentElement)||null!=b&&n(b,p)&&H.push(b);}let v=null!=(d=null==(r=window.visualViewport)?void 0:r.width)?d:innerWidth,y=null!=(f=null==(h=window.visualViewport)?void 0:h.height)?f:innerHeight,E=null!=(u=window.scrollX)?u:pageXOffset,M=null!=(s=window.scrollY)?s:pageYOffset,{height:x,width:I,top:C,right:R,bottom:T,left:V}=t.getBoundingClientRect(),k="start"===c||"nearest"===c?C:"end"===c?T:C+x/2,B="center"===g?V+I/2:"end"===g?R:V,D=[];for(let e=0;e=0&&V>=0&&T<=y&&R<=v&&C>=o&&T<=d&&V>=h&&R<=r)return D;let f=getComputedStyle(t),u=parseInt(f.borderLeftWidth,10),s=parseInt(f.borderTopWidth,10),m=parseInt(f.borderRightWidth,10),p=parseInt(f.borderBottomWidth,10),w=0,b=0,O="offsetWidth"in t?t.offsetWidth-t.clientWidth-u-m:0,X="offsetHeight"in t?t.offsetHeight-t.clientHeight-s-p:0,Y="offsetWidth"in t?0===t.offsetWidth?0:i/t.offsetWidth:0,L="offsetHeight"in t?0===t.offsetHeight?0:n/t.offsetHeight:0;if(W===t)w="start"===c?k:"end"===c?k-y:"nearest"===c?l(M,M+y,y,s,p,M+k,M+k+x,x):k-y/2,b="start"===g?B:"center"===g?B-v/2:"end"===g?B-v:l(E,E+v,v,u,m,E+B,E+B+I,I),w=Math.max(0,w+M),b=Math.max(0,b+E);else {w="start"===c?k-o-s:"end"===c?k-d+p+X:"nearest"===c?l(o,d,n,s,p+X,k,k+x,x):k-(o+n/2)+X/2,b="start"===g?B-h-u:"center"===g?B-(h+i/2)+O/2:"end"===g?B-r+m+O:l(h,r,i,u,m+O,B,B+I,I);let{scrollLeft:e,scrollTop:f}=t;w=Math.max(0,Math.min(f+w/L,t.scrollHeight-n/L+X)),b=Math.max(0,Math.min(e+b/Y,t.scrollWidth-i/Y+O)),k+=f-w,B+=e-b;}D.push({el:t,top:w,left:b});}return D}; -const FieldContext$1 = reactExports.createContext(undefined); -const useFieldContext$1 = () => { - const fieldContext = reactExports.useContext(FieldContext$1); - return fieldContext; +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1u = 'forms.field'; -const StyledField$1 = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$1u, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledField", - componentId: "sc-12gzfsu-0" -})(["position:relative;direction:", ";margin:0;border:0;padding:0;font-size:0;", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => retrieveComponentStyles(COMPONENT_ID$1u, props)); -StyledField$1.defaultProps = { - theme: DEFAULT_THEME -}; +var idCounter$2 = 0; +function noop$1() {} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1t = 'forms.input_label'; -const StyledLabel$1 = styled.label.attrs(props => ({ - 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1t, - 'data-garden-version': props['data-garden-version'] || '8.76.2' -})).withConfig({ - displayName: "StyledLabel", - componentId: "sc-2utmsz-0" -})(["direction:", ";vertical-align:middle;line-height:", ";color:", ";font-size:", ";font-weight:", ";&[hidden]{display:", ";vertical-align:", ";text-indent:", ";font-size:", ";", ";}", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.space.base * 5, props.theme.fontSizes.md), props => getColorV8('foreground', 600 , props.theme), props => props.theme.fontSizes.md, props => props.isRegular ? props.theme.fontWeights.regular : props.theme.fontWeights.semibold, props => props.isRadio ? 'inline-block' : 'inline', props => props.isRadio && 'top', props => props.isRadio && '-100%', props => props.isRadio && '0', props => !props.isRadio && hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$1t, props)); -StyledLabel$1.defaultProps = { - theme: DEFAULT_THEME -}; + * Scroll node into view if necessary + * @param {HTMLElement} node the element that should scroll into view + * @param {HTMLElement} menuNode the menu element of the component + */ +function scrollIntoView(node, menuNode) { + if (!node) { + return; + } + var actions = o(node, { + boundary: menuNode, + block: 'nearest', + scrollMode: 'if-needed' + }); + actions.forEach(function (_ref) { + var el = _ref.el, + top = _ref.top, + left = _ref.left; + el.scrollTop = top; + el.scrollLeft = left; + }); +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1s = 'forms.input_hint'; -const StyledHint$1 = styled.div.attrs(props => ({ - 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1s, - 'data-garden-version': props['data-garden-version'] || '8.76.2' -})).withConfig({ - displayName: "StyledHint", - componentId: "sc-17c2wu8-0" -})(["direction:", ";display:block;vertical-align:middle;line-height:", ";color:", ";font-size:", ";", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.space.base * 5, props.theme.fontSizes.md), props => getColorV8('neutralHue', 600, props.theme), props => props.theme.fontSizes.md, props => retrieveComponentStyles(COMPONENT_ID$1s, props)); -StyledHint$1.defaultProps = { - theme: DEFAULT_THEME -}; + * @param {HTMLElement} parent the parent node + * @param {HTMLElement} child the child node + * @param {Window} environment The window context where downshift renders. + * @return {Boolean} whether the parent is the child or the child is in the parent + */ +function isOrContainsNode(parent, child, environment) { + var result = parent === child || child instanceof environment.Node && parent.contains && parent.contains(child); + return result; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _g$4, _circle$7; -function _extends$N() { _extends$N = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$N.apply(this, arguments); } -var SvgAlertErrorStroke$1 = function SvgAlertErrorStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$N({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _g$4 || (_g$4 = /*#__PURE__*/reactExports.createElement("g", { - fill: "none", - stroke: "currentColor" - }, /*#__PURE__*/reactExports.createElement("circle", { - cx: 7.5, - cy: 8.5, - r: 7 - }), /*#__PURE__*/reactExports.createElement("path", { - strokeLinecap: "round", - d: "M7.5 4.5V9" - }))), _circle$7 || (_circle$7 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 7.5, - cy: 12, - r: 1, - fill: "currentColor" - }))); -}; + * Simple debounce implementation. Will call the given + * function once after the time given has passed since + * it was last called. + * @param {Function} fn the function to call after the time + * @param {Number} time the time to wait + * @return {Function} the debounced function + */ +function debounce$3(fn, time) { + var timeoutId; + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + } + function wrapper() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + cancel(); + timeoutId = setTimeout(function () { + timeoutId = null; + fn.apply(void 0, args); + }, time); + } + wrapper.cancel = cancel; + return wrapper; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _path$F, _circle$6; -function _extends$M() { _extends$M = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$M.apply(this, arguments); } -var SvgAlertWarningStroke$1 = function SvgAlertWarningStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$M({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$F || (_path$F = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M.88 13.77L7.06 1.86c.19-.36.7-.36.89 0l6.18 11.91c.17.33-.07.73-.44.73H1.32c-.37 0-.61-.4-.44-.73zM7.5 6v3.5" - })), _circle$6 || (_circle$6 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 7.5, - cy: 12, - r: 1, - fill: "currentColor" - }))); -}; + * This is intended to be used to compose event handlers. + * They are executed in order until one of them sets + * `event.preventDownshiftDefault = true`. + * @param {...Function} fns the event handler functions + * @return {Function} the event handler to add to an element + */ +function callAllEventHandlers() { + for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + fns[_key2] = arguments[_key2]; + } + return function (event) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return fns.some(function (fn) { + if (fn) { + fn.apply(void 0, [event].concat(args)); + } + return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault; + }); + }; +} +function handleRefs() { + for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + refs[_key4] = arguments[_key4]; + } + return function (node) { + refs.forEach(function (ref) { + if (typeof ref === 'function') { + ref(node); + } else if (ref) { + ref.current = node; + } + }); + }; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * This generates a unique ID for an instance of Downshift + * @return {String} the unique ID + */ +function generateId() { + return String(idCounter$2++); +} -var _g$3; -function _extends$L() { _extends$L = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$L.apply(this, arguments); } -var SvgCheckCircleStroke$2 = function SvgCheckCircleStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$L({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _g$3 || (_g$3 = /*#__PURE__*/reactExports.createElement("g", { - fill: "none", - stroke: "currentColor" - }, /*#__PURE__*/reactExports.createElement("path", { - strokeLinecap: "round", - strokeLinejoin: "round", - d: "M4 9l2.5 2.5 5-5" - }), /*#__PURE__*/reactExports.createElement("circle", { - cx: 7.5, - cy: 8.5, - r: 7 - })))); -}; +/** + * Default implementation for status message. Only added when menu is open. + * Will specify if there are results in the list, and if so, how many, + * and what keys are relevant. + * + * @param {Object} param the downshift state and other relevant properties + * @return {String} the a11y status message + */ +function getA11yStatusMessage$1(_ref2) { + var isOpen = _ref2.isOpen, + resultCount = _ref2.resultCount, + previousResultCount = _ref2.previousResultCount; + if (!isOpen) { + return ''; + } + if (!resultCount) { + return 'No results are available.'; + } + if (resultCount !== previousResultCount) { + return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter key to select."; + } + return ''; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * This will perform a shallow merge of the given state object + * with the state coming from props + * (for the controlled component scenario) + * This is used in state updater functions so they're referencing + * the right state regardless of where it comes from. + * + * @param {Object} state The state of the component/hook. + * @param {Object} props The props that may contain controlled values. + * @returns {Object} The merged controlled state. + */ +function getState(state, props) { + return Object.keys(state).reduce(function (prevState, key) { + prevState[key] = isControlledProp(props, key) ? props[key] : state[key]; + return prevState; + }, {}); +} -const MessageIcon = _ref => { - let { - children, - validation, - ...props - } = _ref; - let retVal; - if (validation === 'error') { - retVal = React__default.createElement(SvgAlertErrorStroke$1, props); - } else if (validation === 'success') { - retVal = React__default.createElement(SvgCheckCircleStroke$2, props); - } else if (validation === 'warning') { - retVal = React__default.createElement(SvgAlertWarningStroke$1, props); - } else { - retVal = React__default.cloneElement(reactExports.Children.only(children)); - } - return retVal; -}; -const COMPONENT_ID$1r = 'forms.input_message_icon'; -const StyledMessageIcon = styled(MessageIcon).attrs({ - 'data-garden-id': COMPONENT_ID$1r, - 'data-garden-version': '8.76.2', - 'aria-hidden': null -}).withConfig({ - displayName: "StyledMessageIcon", - componentId: "sc-1ph2gba-0" -})(["width:", ";height:", ";", ";"], props => props.theme.iconSizes.md, props => props.theme.iconSizes.md, props => retrieveComponentStyles(COMPONENT_ID$1r, props)); -StyledMessageIcon.defaultProps = { - theme: DEFAULT_THEME -}; +/** + * This determines whether a prop is a "controlled prop" meaning it is + * state which is controlled by the outside of this component rather + * than within this component. + * + * @param {Object} props The props that may contain controlled values. + * @param {String} key the key to check + * @return {Boolean} whether it is a controlled controlled prop + */ +function isControlledProp(props, key) { + return props[key] !== undefined; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Normalizes the 'key' property of a KeyboardEvent in IE/Edge + * @param {Object} event a keyboardEvent object + * @return {String} keyboard key + */ +function normalizeArrowKey(event) { + var key = event.key, + keyCode = event.keyCode; + /* istanbul ignore next (ie) */ + if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) { + return "Arrow" + key; + } + return key; +} -const validationStyles = props => { - const rtl = props.theme.rtl; - const padding = math$1(`${props.theme.space.base} * 2px + ${props.theme.iconSizes.md}`); - let color; - if (props.validation === 'error') { - color = getColorV8('dangerHue', 600, props.theme); - } else if (props.validation === 'success') { - color = getColorV8('successHue', 600, props.theme); - } else if (props.validation === 'warning') { - color = getColorV8('warningHue', 700, props.theme); - } else { - color = getColorV8('neutralHue', 700, props.theme); +/** + * Returns the next non-disabled highlightedIndex value. + * + * @param {number} start The current highlightedIndex. + * @param {number} offset The offset from the current highlightedIndex to start searching. + * @param {unknown[]} items The items array. + * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. + * @param {boolean?} circular If the search reaches the end, if it can search again starting from the other end. + * @returns {number} The next highlightedIndex. + */ +function getHighlightedIndex(start, offset, items, isItemDisabled, circular) { + if (circular === void 0) { + circular = false; } - return Ne(["padding-", ":", ";color:", ";"], rtl ? 'right' : 'left', props.validation && padding, color); -}; -const COMPONENT_ID$1q = 'forms.input_message'; -const StyledMessage$1 = styled.div.attrs(props => ({ - 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1q, - 'data-garden-version': props['data-garden-version'] || '8.76.2' -})).withConfig({ - displayName: "StyledMessage", - componentId: "sc-30hgg7-0" -})(["direction:", ";display:inline-block;position:relative;vertical-align:middle;line-height:", ";font-size:", ";", ";& ", "{position:absolute;top:-1px;", ":0;}", ":not([hidden]) + &{display:block;margin-top:", ";}", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.iconSizes.md, props.theme.fontSizes.sm), props => props.theme.fontSizes.sm, props => validationStyles(props), StyledMessageIcon, props => props.theme.rtl ? 'right' : 'left', StyledLabel$1, props => math$1(`${props.theme.space.base} * 1px`), props => retrieveComponentStyles(COMPONENT_ID$1q, props)); -StyledMessage$1.defaultProps = { - theme: DEFAULT_THEME -}; + var count = items.length; + if (count === 0) { + return -1; + } + var itemsLastIndex = count - 1; + if (typeof start !== 'number' || start < 0 || start > itemsLastIndex) { + start = offset > 0 ? -1 : itemsLastIndex + 1; + } + var current = start + offset; + if (current < 0) { + current = circular ? itemsLastIndex : 0; + } else if (current > itemsLastIndex) { + current = circular ? 0 : itemsLastIndex; + } + var highlightedIndex = getNonDisabledIndex(current, offset < 0, items, isItemDisabled, circular); + if (highlightedIndex === -1) { + return start >= count ? -1 : start; + } + return highlightedIndex; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1p = 'forms.input'; -const isInvalid = validation => { - return validation === 'warning' || validation === 'error'; -}; -const colorStyles$p = props => { - const HUE = 'primaryHue'; - const SHADE = 600; - const placeholderColor = getColorV8('neutralHue', SHADE - 200, props.theme); - let borderColor; - let hoverBorderColor; - let focusBorderColor; - let focusRingHue = HUE; - let focusRingShade = SHADE; - if (props.validation) { - let hue = HUE; - if (props.validation === 'success') { - hue = 'successHue'; - } else if (props.validation === 'warning') { - hue = 'warningHue'; - focusRingShade = 700; - } else if (props.validation === 'error') { - hue = 'dangerHue'; - } - borderColor = getColorV8(hue, SHADE, props.theme); - hoverBorderColor = borderColor; - focusBorderColor = borderColor; - focusRingHue = hue; - } else { - borderColor = getColorV8('neutralHue', SHADE - 300, props.theme); - hoverBorderColor = getColorV8('primaryHue', SHADE, props.theme); - focusBorderColor = hoverBorderColor; - } - const readOnlyBackgroundColor = getColorV8('neutralHue', SHADE - 500, props.theme); - const readOnlyBorderColor = getColorV8('neutralHue', SHADE - 300, props.theme); - const disabledBackgroundColor = readOnlyBackgroundColor; - const disabledBorderColor = getColorV8('neutralHue', SHADE - 400, props.theme); - const disabledForegroundColor = getColorV8('neutralHue', SHADE - 200, props.theme); - let controlledBorderColor = borderColor; - if (props.isFocused) { - controlledBorderColor = focusBorderColor; - } - if (props.isHovered) { - controlledBorderColor = hoverBorderColor; + * Returns the next non-disabled highlightedIndex value. + * + * @param {number} start The current highlightedIndex. + * @param {boolean} backwards If true, it will search backwards from the start. + * @param {unknown[]} items The items array. + * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. + * @param {boolean} circular If the search reaches the end, if it can search again starting from the other end. + * @returns {number} The next non-disabled index. + */ +function getNonDisabledIndex(start, backwards, items, isItemDisabled, circular) { + if (circular === void 0) { + circular = false; } - return Ne(["border-color:", ";background-color:", ";color:", ";&::placeholder{color:", ";}&[readonly],&[aria-readonly='true']{border-color:", ";background-color:", ";}&:hover{border-color:", ";}", " &:disabled,&[aria-disabled='true']{border-color:", ";background-color:", ";color:", ";}"], controlledBorderColor, props.isBare ? 'transparent' : getColorV8('background', 600 , props.theme), getColorV8('foreground', 600 , props.theme), placeholderColor, readOnlyBorderColor, !props.isBare && readOnlyBackgroundColor, hoverBorderColor, focusStyles({ - theme: props.theme, - inset: props.focusInset, - condition: !props.isBare, - hue: focusRingHue, - shade: focusRingShade, - styles: { - borderColor: focusBorderColor + var count = items.length; + if (backwards) { + for (var index = start; index >= 0; index--) { + if (!isItemDisabled(items[index], index)) { + return index; + } } - }), disabledBorderColor, !props.isBare && disabledBackgroundColor, disabledForegroundColor); -}; -const sizeStyles$q = props => { - const fontSize = props.theme.fontSizes.md; - const paddingHorizontal = `${props.theme.space.base * 3}px`; - let height; - let paddingVertical; - let browseFontSize; - let swatchHeight; - if (props.isCompact) { - height = `${props.theme.space.base * 8}px`; - paddingVertical = `${props.theme.space.base * 1.5}px`; - browseFontSize = math$1(`${props.theme.fontSizes.sm} - 1`); - swatchHeight = `${props.theme.space.base * 6}px`; } else { - height = `${props.theme.space.base * 10}px`; - paddingVertical = `${props.theme.space.base * 2.5}px`; - browseFontSize = props.theme.fontSizes.sm; - swatchHeight = `${props.theme.space.base * 7}px`; + for (var _index = start; _index < count; _index++) { + if (!isItemDisabled(items[_index], _index)) { + return _index; + } + } } - const lineHeight = math$1(`${height} - (${paddingVertical} * 2) - (${props.theme.borderWidths.sm} * 2)`); - const padding = props.isBare ? '0' : `${em$1(paddingVertical, fontSize)} ${em$1(paddingHorizontal, fontSize)}`; - const swatchMarginVertical = math$1(`(${lineHeight} - ${swatchHeight}) / 2`); - const swatchMarginHorizontal = math$1(`${paddingVertical} + ${swatchMarginVertical} - ${paddingHorizontal}`); - return Ne(["padding:", ";min-height:", ";line-height:", ";font-size:", ";&::-ms-browse{font-size:", ";}&[type='date'],&[type='datetime-local'],&[type='file'],&[type='month'],&[type='time'],&[type='week']{max-height:", ";}&[type='file']{line-height:1;}@supports (-ms-ime-align:auto){&[type='color']{padding:", ";}}&::-moz-color-swatch{margin-top:", ";margin-left:", ";width:calc(100% + ", ");height:", ";}&::-webkit-color-swatch{margin:", " ", ";}", ":not([hidden]) + &&,", " + &&,", " + &&,&& + ", ",&& ~ ", "{margin-top:", "px;}"], padding, props.isBare ? '1em' : height, getLineHeight(lineHeight, fontSize), fontSize, browseFontSize, height, props.isCompact ? '0 2px' : '1px 3px', swatchMarginVertical, swatchMarginHorizontal, math$1(`${swatchMarginHorizontal} * -2`), swatchHeight, swatchMarginVertical, swatchMarginHorizontal, StyledLabel$1, StyledHint$1, StyledMessage$1, StyledHint$1, StyledMessage$1, props.theme.space.base * (props.isCompact ? 1 : 2)); -}; -const StyledTextInput = styled.input.attrs(props => ({ - 'data-garden-id': COMPONENT_ID$1p, - 'data-garden-version': '8.76.2', - 'aria-invalid': isInvalid(props.validation) -})).withConfig({ - displayName: "StyledTextInput", - componentId: "sc-k12n8x-0" -})(["appearance:none;transition:border-color 0.25s ease-in-out,box-shadow 0.1s ease-in-out,background-color 0.25s ease-in-out,color 0.25s ease-in-out,z-index 0.25s ease-in-out;direction:", ";border:", ";border-radius:", ";width:100%;box-sizing:border-box;vertical-align:middle;font-family:inherit;&::-ms-browse{border-radius:", ";}&::-ms-clear,&::-ms-reveal{display:none;}&::-moz-color-swatch{border:none;border-radius:", ";}&::-webkit-color-swatch{border:none;border-radius:", ";}&::-webkit-color-swatch-wrapper{padding:0;}&::-webkit-clear-button,&::-webkit-inner-spin-button,&::-webkit-search-cancel-button,&::-webkit-search-results-button{display:none;}&::-webkit-datetime-edit{direction:", ";line-height:1;}&::placeholder{opacity:1;}&:invalid{box-shadow:none;}&[type='file']::-ms-value{display:none;}@media screen and (min--moz-device-pixel-ratio:0){&[type='number']{appearance:textfield;}}", ";", ";&:disabled{cursor:default;}", ";"], props => props.theme.rtl && 'rtl', props => props.isBare ? 'none' : props.theme.borders.sm, props => props.isBare ? '0' : props.theme.borderRadii.md, props => props.theme.borderRadii.sm, props => props.theme.borderRadii.sm, props => props.theme.borderRadii.sm, props => props.theme.rtl && 'rtl', props => sizeStyles$q(props), props => colorStyles$p(props), props => retrieveComponentStyles(COMPONENT_ID$1p, props)); -StyledTextInput.defaultProps = { - theme: DEFAULT_THEME -}; + if (circular) { + return getNonDisabledIndex(backwards ? count - 1 : 0, backwards, items, isItemDisabled); + } + return -1; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Checks if event target is within the downshift elements. + * + * @param {EventTarget} target Target to check. + * @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc). + * @param {Window} environment The window context where downshift renders. + * @param {boolean} checkActiveElement Whether to also check activeElement. + * + * @returns {boolean} Whether or not the target is within downshift elements. + */ +function targetWithinDownshift(target, downshiftElements, environment, checkActiveElement) { + if (checkActiveElement === void 0) { + checkActiveElement = true; + } + return downshiftElements.some(function (contextNode) { + return contextNode && (isOrContainsNode(contextNode, target, environment) || checkActiveElement && isOrContainsNode(contextNode, environment.document.activeElement, environment)); + }); +} -const COMPONENT_ID$1o = 'forms.textarea'; -const hiddenStyles = ` - visibility: hidden; - position: absolute; - overflow: hidden; - height: 0; - top: 0; - left: 0; - transform: translateZ(0); -`; -const StyledTextarea = styled(StyledTextInput).attrs({ - as: 'textarea', - 'data-garden-id': COMPONENT_ID$1o, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTextarea", - componentId: "sc-wxschl-0" -})(["resize:", ";overflow:auto;", ";", ";"], props => props.isResizable ? 'vertical' : 'none', props => props.isHidden && hiddenStyles, props => retrieveComponentStyles(COMPONENT_ID$1o, props)); -StyledTextarea.defaultProps = { - theme: DEFAULT_THEME -}; +var cleanupStatus = debounce$3(function (documentProp) { + getStatusDiv(documentProp).textContent = ''; +}, 500); /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1n = 'forms.media_figure'; -const colorStyles$o = props => { - let shade = 600; - if (props.isDisabled) { - shade = 400; - } else if (props.isHovered || props.isFocused) { - shade = 700; - } - return Ne(["color:", ";"], getColorV8('neutralHue', shade, props.theme)); -}; -const sizeStyles$p = props => { - const size = props.theme.iconSizes.md; - const marginFirst = `1px ${props.theme.space.base * 2}px auto 0`; - const marginLast = `1px 0 auto ${props.theme.space.base * 2}px`; - let margin; - if (props.position === 'start') { - margin = props.theme.rtl ? marginLast : marginFirst; - } else { - margin = props.theme.rtl ? marginFirst : marginLast; + * @param {String} status the status message + * @param {Object} documentProp document passed by the user. + */ +function setStatus(status, documentProp) { + var div = getStatusDiv(documentProp); + if (!status) { + return; } - return Ne(["margin:", ";width:", ";height:", ";"], margin, size, size); -}; -const StyledTextMediaFigure = styled( -_ref => { - let { - children, - position, - isHovered, - isFocused, - isDisabled, - isRotated, - theme, - ...props - } = _ref; - return React__default.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$1n, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTextMediaFigure", - componentId: "sc-1qepknj-0" -})(["transform:", ";transition:transform 0.25s ease-in-out,color 0.25s ease-in-out;", ";", " ", ";"], props => props.isRotated && `rotate(${props.theme.rtl ? '-' : '+'}180deg)`, props => colorStyles$o(props), props => sizeStyles$p(props), props => retrieveComponentStyles(COMPONENT_ID$1n, props)); -StyledTextMediaFigure.defaultProps = { - theme: DEFAULT_THEME -}; + div.textContent = status; + cleanupStatus(documentProp); +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1m = 'forms.faux_input'; -const VALIDATION_HUES = { - success: 'successHue', - warning: 'warningHue', - error: 'dangerHue' -}; -function getValidationHue(validation) { - let defaultHue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'primaryHue'; - if (validation) { - return VALIDATION_HUES[validation]; + * Get the status node or create it if it does not already exist. + * @param {Object} documentProp document passed by the user. + * @return {HTMLElement} the status node. + */ +function getStatusDiv(documentProp) { + if (documentProp === void 0) { + documentProp = document; } - return defaultHue; -} -const colorStyles$n = props => { - const { - theme, - validation, - focusInset, - isBare, - isFocused - } = props; - return Ne(["", ""], focusStyles({ - theme, - inset: focusInset, - condition: !isBare, - hue: getValidationHue(validation), - shade: validation === 'warning' ? 700 : 600, - selector: isFocused ? '&' : '&:focus-within', - styles: { - borderColor: getColorV8(getValidationHue(validation), 600, theme) - } - })); -}; -const StyledTextFauxInput = styled(StyledTextInput).attrs(props => ({ - as: 'div', - 'aria-readonly': props.isReadOnly, - 'aria-disabled': props.isDisabled, - 'data-garden-id': COMPONENT_ID$1m, - 'data-garden-version': '8.76.2' -})).withConfig({ - displayName: "StyledTextFauxInput", - componentId: "sc-yqw7j9-0" -})(["display:", ";align-items:", ";cursor:", ";overflow:hidden;", " & > ", "{vertical-align:", ";", "{box-shadow:unset;}}& > ", "{flex-shrink:", ";}", ";"], props => props.mediaLayout ? 'inline-flex' : 'inline-block', props => props.mediaLayout && 'baseline', props => props.mediaLayout && !props.isDisabled ? 'text' : 'default', colorStyles$n, StyledTextInput, props => !props.mediaLayout && 'baseline', SELECTOR_FOCUS_VISIBLE, StyledTextMediaFigure, props => props.mediaLayout && '0', props => retrieveComponentStyles(COMPONENT_ID$1m, props)); -StyledTextFauxInput.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + var statusDiv = documentProp.getElementById('a11y-status-message'); + if (statusDiv) { + return statusDiv; + } + statusDiv = documentProp.createElement('div'); + statusDiv.setAttribute('id', 'a11y-status-message'); + statusDiv.setAttribute('role', 'status'); + statusDiv.setAttribute('aria-live', 'polite'); + statusDiv.setAttribute('aria-relevant', 'additions text'); + Object.assign(statusDiv.style, { + border: '0', + clip: 'rect(0 0 0 0)', + height: '1px', + margin: '-1px', + overflow: 'hidden', + padding: '0', + position: 'absolute', + width: '1px' + }); + documentProp.body.appendChild(statusDiv); + return statusDiv; +} -const COMPONENT_ID$1l = 'forms.media_input'; -const StyledTextMediaInput = styled(StyledTextInput).attrs({ - 'data-garden-id': COMPONENT_ID$1l, - 'data-garden-version': '8.76.2', - isBare: true -}).withConfig({ - displayName: "StyledTextMediaInput", - componentId: "sc-12i9xfi-0" -})(["flex-grow:1;", ";"], props => retrieveComponentStyles(COMPONENT_ID$1l, props)); -StyledTextMediaInput.defaultProps = { - theme: DEFAULT_THEME +var _excluded$3 = ["isInitialMount", "highlightedIndex", "items", "environment"]; +var dropdownDefaultStateValues = { + highlightedIndex: -1, + isOpen: false, + selectedItem: null, + inputValue: '' }; +function callOnChangeProps(action, state, newState) { + var props = action.props, + type = action.type; + var changes = {}; + Object.keys(state).forEach(function (key) { + invokeOnChangeHandler(key, action, state, newState); + if (newState[key] !== state[key]) { + changes[key] = newState[key]; + } + }); + if (props.onStateChange && Object.keys(changes).length) { + props.onStateChange(_extends$U({ + type: type + }, changes)); + } +} +function invokeOnChangeHandler(key, action, state, newState) { + var props = action.props, + type = action.type; + var handler = "on" + capitalizeString(key) + "Change"; + if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) { + props[handler](_extends$U({ + type: type + }, newState)); + } +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1k = 'forms.radio_label'; -const sizeStyles$o = props => { - const size = props.theme.space.base * 4; - const padding = size + props.theme.space.base * 2; - const lineHeight = props.theme.space.base * 5; - return Ne(["padding-", ":", "px;&[hidden]{padding-", ":", "px;line-height:", "px;}"], props.theme.rtl ? 'right' : 'left', padding, props.theme.rtl ? 'right' : 'left', size, lineHeight); -}; -const StyledRadioLabel = styled(StyledLabel$1).attrs({ - 'data-garden-id': COMPONENT_ID$1k, - 'data-garden-version': '8.76.2', - isRadio: true -}).withConfig({ - displayName: "StyledRadioLabel", - componentId: "sc-1aq2e5t-0" -})(["display:inline-block;position:relative;cursor:pointer;", ";", ";"], props => sizeStyles$o(props), props => retrieveComponentStyles(COMPONENT_ID$1k, props)); -StyledRadioLabel.defaultProps = { - theme: DEFAULT_THEME -}; + * Default state reducer that returns the changes. + * + * @param {Object} s state. + * @param {Object} a action with changes. + * @returns {Object} changes. + */ +function stateReducer(s, a) { + return a.changes; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1j = 'forms.checkbox_label'; -const StyledCheckLabel = styled(StyledRadioLabel).attrs({ - 'data-garden-id': COMPONENT_ID$1j, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledCheckLabel", - componentId: "sc-x7nr1-0" -})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1j, props)); -StyledCheckLabel.defaultProps = { - theme: DEFAULT_THEME -}; + * Returns a message to be added to aria-live region when item is selected. + * + * @param {Object} selectionParameters Parameters required to build the message. + * @returns {string} The a11y message. + */ +function getA11ySelectionMessage(selectionParameters) { + var selectedItem = selectionParameters.selectedItem, + itemToStringLocal = selectionParameters.itemToString; + return selectedItem ? itemToStringLocal(selectedItem) + " has been selected." : ''; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Debounced call for updating the a11y message. + */ +var updateA11yStatus = debounce$3(function (getA11yMessage, document) { + setStatus(getA11yMessage(), document); +}, 200); -const COMPONENT_ID$1i = 'forms.radio_hint'; -const StyledRadioHint = styled(StyledHint$1).attrs({ - 'data-garden-id': COMPONENT_ID$1i, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledRadioHint", - componentId: "sc-eo8twg-0" -})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 6px`), props => retrieveComponentStyles(COMPONENT_ID$1i, props)); -StyledRadioHint.defaultProps = { - theme: DEFAULT_THEME +// istanbul ignore next +var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? reactExports.useLayoutEffect : reactExports.useEffect; + +// istanbul ignore next +var useElementIds = 'useId' in React__default // Avoid conditional useId call +? function useElementIds(_ref) { + var id = _ref.id, + labelId = _ref.labelId, + menuId = _ref.menuId, + getItemId = _ref.getItemId, + toggleButtonId = _ref.toggleButtonId, + inputId = _ref.inputId; + // Avoid conditional useId call + var reactId = "downshift-" + React__default.useId(); + if (!id) { + id = reactId; + } + var elementIdsRef = reactExports.useRef({ + labelId: labelId || id + "-label", + menuId: menuId || id + "-menu", + getItemId: getItemId || function (index) { + return id + "-item-" + index; + }, + toggleButtonId: toggleButtonId || id + "-toggle-button", + inputId: inputId || id + "-input" + }); + return elementIdsRef.current; +} : function useElementIds(_ref2) { + var _ref2$id = _ref2.id, + id = _ref2$id === void 0 ? "downshift-" + generateId() : _ref2$id, + labelId = _ref2.labelId, + menuId = _ref2.menuId, + getItemId = _ref2.getItemId, + toggleButtonId = _ref2.toggleButtonId, + inputId = _ref2.inputId; + var elementIdsRef = reactExports.useRef({ + labelId: labelId || id + "-label", + menuId: menuId || id + "-menu", + getItemId: getItemId || function (index) { + return id + "-item-" + index; + }, + toggleButtonId: toggleButtonId || id + "-toggle-button", + inputId: inputId || id + "-input" + }); + return elementIdsRef.current; }; +function getItemAndIndex(itemProp, indexProp, items, errorMessage) { + var item, index; + if (itemProp === undefined) { + if (indexProp === undefined) { + throw new Error(errorMessage); + } + item = items[indexProp]; + index = indexProp; + } else { + index = indexProp === undefined ? items.indexOf(itemProp) : indexProp; + item = itemProp; + } + return [item, index]; +} +function itemToString(item) { + return item ? String(item) : ''; +} +function capitalizeString(string) { + return "" + string.slice(0, 1).toUpperCase() + string.slice(1); +} +function useLatestRef$1(val) { + var ref = reactExports.useRef(val); + // technically this is not "concurrent mode safe" because we're manipulating + // the value during render (so it's not idempotent). However, the places this + // hook is used is to support memoizing callbacks which will be called + // *during* render, so we need the latest values *during* render. + // If not for this, then we'd probably want to use useLayoutEffect instead. + ref.current = val; + return ref; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1h = 'forms.checkbox_hint'; -const StyledCheckHint = styled(StyledRadioHint).attrs({ - 'data-garden-id': COMPONENT_ID$1h, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledCheckHint", - componentId: "sc-1kl8e8c-0" -})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1h, props)); -StyledCheckHint.defaultProps = { - theme: DEFAULT_THEME + * Computes the controlled state using a the previous state, props, + * two reducers, one from downshift and an optional one from the user. + * Also calls the onChange handlers for state values that have changed. + * + * @param {Function} reducer Reducer function from downshift. + * @param {Object} initialState Initial state of the hook. + * @param {Object} props The hook props. + * @returns {Array} An array with the state and an action dispatcher. + */ +function useEnhancedReducer(reducer, initialState, props) { + var prevStateRef = reactExports.useRef(); + var actionRef = reactExports.useRef(); + var enhancedReducer = reactExports.useCallback(function (state, action) { + actionRef.current = action; + state = getState(state, action.props); + var changes = reducer(state, action); + var newState = action.props.stateReducer(state, _extends$U({}, action, { + changes: changes + })); + return newState; + }, [reducer]); + var _useReducer = reactExports.useReducer(enhancedReducer, initialState), + state = _useReducer[0], + dispatch = _useReducer[1]; + var propsRef = useLatestRef$1(props); + var dispatchWithProps = reactExports.useCallback(function (action) { + return dispatch(_extends$U({ + props: propsRef.current + }, action)); + }, [propsRef]); + var action = actionRef.current; + reactExports.useEffect(function () { + if (action && prevStateRef.current && prevStateRef.current !== state) { + callOnChangeProps(action, getState(prevStateRef.current, action.props), state); + } + prevStateRef.current = state; + }, [state, props, action]); + return [state, dispatchWithProps]; +} +var defaultProps$3 = { + itemToString: itemToString, + stateReducer: stateReducer, + getA11ySelectionMessage: getA11ySelectionMessage, + scrollIntoView: scrollIntoView, + environment: /* istanbul ignore next (ssr) */ + typeof window === 'undefined' ? {} : window }; +function getDefaultValue$1(props, propKey, defaultStateValues) { + if (defaultStateValues === void 0) { + defaultStateValues = dropdownDefaultStateValues; + } + var defaultValue = props["default" + capitalizeString(propKey)]; + if (defaultValue !== undefined) { + return defaultValue; + } + return defaultStateValues[propKey]; +} +function getInitialValue$1(props, propKey, defaultStateValues) { + if (defaultStateValues === void 0) { + defaultStateValues = dropdownDefaultStateValues; + } + var value = props[propKey]; + if (value !== undefined) { + return value; + } + var initialValue = props["initial" + capitalizeString(propKey)]; + if (initialValue !== undefined) { + return initialValue; + } + return getDefaultValue$1(props, propKey, defaultStateValues); +} +function getInitialState$2(props) { + var selectedItem = getInitialValue$1(props, 'selectedItem'); + var isOpen = getInitialValue$1(props, 'isOpen'); + var highlightedIndex = getInitialValue$1(props, 'highlightedIndex'); + var inputValue = getInitialValue$1(props, 'inputValue'); + return { + highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex, + isOpen: isOpen, + selectedItem: selectedItem, + inputValue: inputValue + }; +} +function getHighlightedIndexOnOpen(props, state, offset) { + var items = props.items, + initialHighlightedIndex = props.initialHighlightedIndex, + defaultHighlightedIndex = props.defaultHighlightedIndex; + var selectedItem = state.selectedItem, + highlightedIndex = state.highlightedIndex; + if (items.length === 0) { + return -1; + } + + // initialHighlightedIndex will give value to highlightedIndex on initial state only. + if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) { + return initialHighlightedIndex; + } + if (defaultHighlightedIndex !== undefined) { + return defaultHighlightedIndex; + } + if (selectedItem) { + return items.indexOf(selectedItem); + } + if (offset === 0) { + return -1; + } + return offset < 0 ? items.length - 1 : 0; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Reuse the movement tracking of mouse and touch events. + * + * @param {boolean} isOpen Whether the dropdown is open or not. + * @param {Array} downshiftElementRefs Downshift element refs to track movement (toggleButton, menu etc.) + * @param {Object} environment Environment where component/hook exists. + * @param {Function} handleBlur Handler on blur from mouse or touch. + * @returns {Object} Ref containing whether mouseDown or touchMove event is happening + */ +function useMouseAndTouchTracker(isOpen, downshiftElementRefs, environment, handleBlur) { + var mouseAndTouchTrackersRef = reactExports.useRef({ + isMouseDown: false, + isTouchMove: false + }); + reactExports.useEffect(function () { + if ((environment == null ? void 0 : environment.addEventListener) == null) { + return; + } -const COMPONENT_ID$1g = 'forms.radio'; -const colorStyles$m = props => { - const SHADE = 600; - const borderColor = getColorV8('neutralHue', SHADE - 300, props.theme); - const backgroundColor = getColorV8('background', 600 , props.theme); - const iconColor = backgroundColor; - const hoverBackgroundColor = getColorV8('primaryHue', SHADE, props.theme, 0.08); - const hoverBorderColor = getColorV8('primaryHue', SHADE, props.theme); - const focusBorderColor = hoverBorderColor; - const activeBackgroundColor = getColorV8('primaryHue', SHADE, props.theme, 0.2); - const activeBorderColor = focusBorderColor; - const checkedBorderColor = focusBorderColor; - const checkedBackgroundColor = checkedBorderColor; - const checkedHoverBorderColor = getColorV8('primaryHue', SHADE + 100, props.theme); - const checkedHoverBackgroundColor = checkedHoverBorderColor; - const checkedActiveBorderColor = getColorV8('primaryHue', SHADE + 200, props.theme); - const checkedActiveBackgroundColor = checkedActiveBorderColor; - const disabledBackgroundColor = getColorV8('neutralHue', SHADE - 400, props.theme); - return Ne(["& ~ ", "::before{border-color:", ";background-color:", ";}& ~ ", " > svg{color:", ";}& ~ ", ":hover::before{border-color:", ";background-color:", ";}", " & ~ ", ":active::before{border-color:", ";background-color:", ";}&:checked ~ ", "::before{border-color:", ";background-color:", ";}&:enabled:checked ~ ", ":hover::before{border-color:", ";background-color:", ";}&:enabled:checked ~ ", ":active::before{border-color:", ";background-color:", ";}&:disabled ~ ", "::before{border-color:transparent;background-color:", ";}"], StyledRadioLabel, borderColor, backgroundColor, StyledRadioLabel, iconColor, StyledRadioLabel, hoverBorderColor, hoverBackgroundColor, focusStyles({ - theme: props.theme, - styles: { - borderColor: focusBorderColor - }, - selector: `&:focus-visible ~ ${StyledRadioLabel}::before, &[data-garden-focus-visible='true'] ~ ${StyledRadioLabel}::before` - }), StyledRadioLabel, activeBorderColor, activeBackgroundColor, StyledRadioLabel, checkedBorderColor, checkedBackgroundColor, StyledRadioLabel, checkedHoverBorderColor, checkedHoverBackgroundColor, StyledRadioLabel, checkedActiveBorderColor, checkedActiveBackgroundColor, StyledRadioLabel, disabledBackgroundColor); -}; -const sizeStyles$n = props => { - const lineHeight = `${props.theme.space.base * 5}px`; - const size = `${props.theme.space.base * 4}px`; - const top = math$1(`(${lineHeight} - ${size}) / 2`); - const iconSize = props.theme.iconSizes.sm; - const iconPosition = math$1(`(${size} - ${iconSize}) / 2`); - const iconTop = math$1(`${iconPosition} + ${top}`); - const marginTop = `${props.theme.space.base * (props.isCompact ? 1 : 2)}px`; - return Ne(["top:", ";width:", ";height:", ";& ~ ", "::before{top:", ";background-size:", ";width:", ";height:", ";box-sizing:border-box;}& ~ ", " > svg{top:", ";", ":", ";width:", ";height:", ";}&& ~ ", " ~ ", "{margin-top:", ";}"], top, size, size, StyledRadioLabel, top, props.theme.iconSizes.sm, size, size, StyledRadioLabel, iconTop, props.theme.rtl ? 'right' : 'left', iconPosition, iconSize, iconSize, StyledRadioLabel, StyledMessage$1, marginTop); -}; -const StyledRadioInput = styled.input.attrs({ - 'data-garden-id': COMPONENT_ID$1g, - 'data-garden-version': '8.76.2', - type: 'radio' -}).withConfig({ - displayName: "StyledRadioInput", - componentId: "sc-qsavpv-0" -})(["position:absolute;opacity:0;margin:0;& ~ ", "::before{position:absolute;", ":0;transition:border-color .25s ease-in-out,box-shadow .1s ease-in-out,background-color .25s ease-in-out,color .25s ease-in-out;border:", ";border-radius:50%;background-repeat:no-repeat;background-position:center;content:'';}& ~ ", " > svg{position:absolute;}", ";&:focus ~ ", "::before{outline:none;}& ~ ", ":active::before{transition:border-color 0.1s ease-in-out,background-color 0.1s ease-in-out,color 0.1s ease-in-out;}", ";&:disabled ~ ", "{cursor:default;}", ";"], StyledRadioLabel, props => props.theme.rtl ? 'right' : 'left', props => props.theme.borders.sm, StyledRadioLabel, props => sizeStyles$n(props), StyledRadioLabel, StyledRadioLabel, props => colorStyles$m(props), StyledRadioLabel, props => retrieveComponentStyles(COMPONENT_ID$1g, props)); -StyledRadioInput.defaultProps = { - theme: DEFAULT_THEME -}; + // The same strategy for checking if a click occurred inside or outside downshift + // as in downshift.js. + var onMouseDown = function onMouseDown() { + mouseAndTouchTrackersRef.current.isMouseDown = true; + }; + var onMouseUp = function onMouseUp(event) { + mouseAndTouchTrackersRef.current.isMouseDown = false; + if (isOpen && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) { + return ref.current; + }), environment)) { + handleBlur(); + } + }; + var onTouchStart = function onTouchStart() { + mouseAndTouchTrackersRef.current.isTouchMove = false; + }; + var onTouchMove = function onTouchMove() { + mouseAndTouchTrackersRef.current.isTouchMove = true; + }; + var onTouchEnd = function onTouchEnd(event) { + if (isOpen && !mouseAndTouchTrackersRef.current.isTouchMove && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) { + return ref.current; + }), environment, false)) { + handleBlur(); + } + }; + environment.addEventListener('mousedown', onMouseDown); + environment.addEventListener('mouseup', onMouseUp); + environment.addEventListener('touchstart', onTouchStart); + environment.addEventListener('touchmove', onTouchMove); + environment.addEventListener('touchend', onTouchEnd); -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + // eslint-disable-next-line consistent-return + return function cleanup() { + environment.removeEventListener('mousedown', onMouseDown); + environment.removeEventListener('mouseup', onMouseUp); + environment.removeEventListener('touchstart', onTouchStart); + environment.removeEventListener('touchmove', onTouchMove); + environment.removeEventListener('touchend', onTouchEnd); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen, environment]); + return mouseAndTouchTrackersRef; +} -const COMPONENT_ID$1f = 'forms.checkbox'; -const colorStyles$l = props => { - const SHADE = 600; - const indeterminateBorderColor = getColorV8('primaryHue', SHADE, props.theme); - const indeterminateBackgroundColor = indeterminateBorderColor; - const indeterminateActiveBorderColor = getColorV8('primaryHue', SHADE + 100, props.theme); - const indeterminateActiveBackgroundColor = indeterminateActiveBorderColor; - const indeterminateDisabledBackgroundColor = getColorV8('neutralHue', SHADE - 400, props.theme); - return Ne(["&:indeterminate ~ ", "::before{border-color:", ";background-color:", ";}&:enabled:indeterminate ~ ", ":active::before{border-color:", ";background-color:", ";}&:disabled:indeterminate ~ ", "::before{border-color:transparent;background-color:", ";}"], StyledCheckLabel, indeterminateBorderColor, indeterminateBackgroundColor, StyledCheckLabel, indeterminateActiveBorderColor, indeterminateActiveBackgroundColor, StyledCheckLabel, indeterminateDisabledBackgroundColor); +/* istanbul ignore next */ +// eslint-disable-next-line import/no-mutable-exports +var useGetterPropsCalledChecker = function useGetterPropsCalledChecker() { + return noop$1; }; -const StyledCheckInput = styled(StyledRadioInput).attrs({ - 'data-garden-id': COMPONENT_ID$1f, - 'data-garden-version': '8.76.2', - type: 'checkbox' -}).withConfig({ - displayName: "StyledCheckInput", - componentId: "sc-176jxxe-0" -})(["& ~ ", "::before{border-radius:", ";}", ";", ";"], StyledCheckLabel, props => props.theme.borderRadii.md, props => colorStyles$l(props), props => retrieveComponentStyles(COMPONENT_ID$1f, props)); -StyledCheckInput.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ +function useA11yMessageSetter(getA11yMessage, dependencyArray, _ref3) { + var isInitialMount = _ref3.isInitialMount, + highlightedIndex = _ref3.highlightedIndex, + items = _ref3.items, + environment = _ref3.environment, + rest = _objectWithoutPropertiesLoose$1(_ref3, _excluded$3); + // Sets a11y status message on changes in state. + reactExports.useEffect(function () { + if (isInitialMount || false) { + return; + } + updateA11yStatus(function () { + return getA11yMessage(_extends$U({ + highlightedIndex: highlightedIndex, + highlightedItem: items[highlightedIndex], + resultCount: items.length + }, rest)); + }, environment.document); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, dependencyArray); +} +function useScrollIntoView(_ref4) { + var highlightedIndex = _ref4.highlightedIndex, + isOpen = _ref4.isOpen, + itemRefs = _ref4.itemRefs, + getItemNodeFromIndex = _ref4.getItemNodeFromIndex, + menuElement = _ref4.menuElement, + scrollIntoViewProp = _ref4.scrollIntoView; + // used not to scroll on highlight by mouse. + var shouldScrollRef = reactExports.useRef(true); + // Scroll on highlighted item if change comes from keyboard. + useIsomorphicLayoutEffect(function () { + if (highlightedIndex < 0 || !isOpen || !Object.keys(itemRefs.current).length) { + return; + } + if (shouldScrollRef.current === false) { + shouldScrollRef.current = true; + } else { + scrollIntoViewProp(getItemNodeFromIndex(highlightedIndex), menuElement); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [highlightedIndex]); + return shouldScrollRef; +} -const COMPONENT_ID$1e = 'forms.radio_message'; -const StyledRadioMessage = styled(StyledMessage$1).attrs({ - 'data-garden-id': COMPONENT_ID$1e, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledRadioMessage", - componentId: "sc-1pmi0q8-0" -})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 6px`), props => retrieveComponentStyles(COMPONENT_ID$1e, props)); -StyledRadioMessage.defaultProps = { - theme: DEFAULT_THEME -}; +// eslint-disable-next-line import/no-mutable-exports +var useControlPropsValidator = noop$1; /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Handles selection on Enter / Alt + ArrowUp. Closes the menu and resets the highlighted index, unless there is a highlighted. + * In that case, selects the item and resets to defaults for open state and highlighted idex. + * @param {Object} props The useCombobox props. + * @param {number} highlightedIndex The index from the state. + * @param {boolean} inputValue Also return the input value for state. + * @returns The changes for the state. + */ +function getChangesOnSelection(props, highlightedIndex, inputValue) { + var _props$items; + if (inputValue === void 0) { + inputValue = true; + } + var shouldSelect = ((_props$items = props.items) == null ? void 0 : _props$items.length) && highlightedIndex >= 0; + return _extends$U({ + isOpen: false, + highlightedIndex: -1 + }, shouldSelect && _extends$U({ + selectedItem: props.items[highlightedIndex], + isOpen: getDefaultValue$1(props, 'isOpen'), + highlightedIndex: getDefaultValue$1(props, 'highlightedIndex') + }, inputValue && { + inputValue: props.itemToString(props.items[highlightedIndex]) + })); +} -const COMPONENT_ID$1d = 'forms.checkbox_message'; -const StyledCheckMessage = styled(StyledRadioMessage).attrs({ - 'data-garden-id': COMPONENT_ID$1d, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledCheckMessage", - componentId: "sc-s4p6kd-0" -})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1d, props)); -StyledCheckMessage.defaultProps = { - theme: DEFAULT_THEME +// Shared between all exports. +var commonPropTypes = { + environment: PropTypes.shape({ + addEventListener: PropTypes.func.isRequired, + removeEventListener: PropTypes.func.isRequired, + document: PropTypes.shape({ + createElement: PropTypes.func.isRequired, + getElementById: PropTypes.func.isRequired, + activeElement: PropTypes.any.isRequired, + body: PropTypes.any.isRequired + }).isRequired, + Node: PropTypes.func.isRequired + }), + itemToString: PropTypes.func, + stateReducer: PropTypes.func }; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _path$E; -function _extends$K() { _extends$K = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$K.apply(this, arguments); } -var SvgCheckSmFill = function SvgCheckSmFill(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$K({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$E || (_path$E = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - strokeLinejoin: "round", - strokeWidth: 2, - d: "M3 6l2 2 4-4" - }))); -}; +// Shared between useSelect, useCombobox, Downshift. +var commonDropdownPropTypes = _extends$U({}, commonPropTypes, { + getA11yStatusMessage: PropTypes.func, + highlightedIndex: PropTypes.number, + defaultHighlightedIndex: PropTypes.number, + initialHighlightedIndex: PropTypes.number, + isOpen: PropTypes.bool, + defaultIsOpen: PropTypes.bool, + initialIsOpen: PropTypes.bool, + selectedItem: PropTypes.any, + initialSelectedItem: PropTypes.any, + defaultSelectedItem: PropTypes.any, + id: PropTypes.string, + labelId: PropTypes.string, + menuId: PropTypes.string, + getItemId: PropTypes.func, + toggleButtonId: PropTypes.string, + onSelectedItemChange: PropTypes.func, + onHighlightedIndexChange: PropTypes.func, + onStateChange: PropTypes.func, + onIsOpenChange: PropTypes.func, + scrollIntoView: PropTypes.func +}); +function downshiftCommonReducer(state, action, stateChangeTypes) { + var type = action.type, + props = action.props; + var changes; + switch (type) { + case stateChangeTypes.ItemMouseMove: + changes = { + highlightedIndex: action.disabled ? -1 : action.index + }; + break; + case stateChangeTypes.MenuMouseLeave: + changes = { + highlightedIndex: -1 + }; + break; + case stateChangeTypes.ToggleButtonClick: + case stateChangeTypes.FunctionToggleMenu: + changes = { + isOpen: !state.isOpen, + highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0) + }; + break; + case stateChangeTypes.FunctionOpenMenu: + changes = { + isOpen: true, + highlightedIndex: getHighlightedIndexOnOpen(props, state, 0) + }; + break; + case stateChangeTypes.FunctionCloseMenu: + changes = { + isOpen: false + }; + break; + case stateChangeTypes.FunctionSetHighlightedIndex: + changes = { + highlightedIndex: action.highlightedIndex + }; + break; + case stateChangeTypes.FunctionSetInputValue: + changes = { + inputValue: action.inputValue + }; + break; + case stateChangeTypes.FunctionReset: + changes = { + highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), + isOpen: getDefaultValue$1(props, 'isOpen'), + selectedItem: getDefaultValue$1(props, 'selectedItem'), + inputValue: getDefaultValue$1(props, 'inputValue') + }; + break; + default: + throw new Error('Reducer called without proper action type.'); + } + return _extends$U({}, state, changes); +} +// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment +__assign(__assign({}, commonDropdownPropTypes), { items: PropTypes.array.isRequired, isItemDisabled: PropTypes.func, getA11ySelectionMessage: PropTypes.func }); /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Default implementation for status message. Only added when menu is open. + * Will specift if there are results in the list, and if so, how many, + * and what keys are relevant. + * + * @param {Object} param the downshift state and other relevant properties + * @return {String} the a11y status message + */ +function getA11yStatusMessage(_a) { + var isOpen = _a.isOpen, resultCount = _a.resultCount, previousResultCount = _a.previousResultCount; + if (!isOpen) { + return ''; + } + if (!resultCount) { + return 'No results are available.'; + } + if (resultCount !== previousResultCount) { + return "".concat(resultCount, " result").concat(resultCount === 1 ? ' is' : 's are', " available, use up and down arrow keys to navigate. Press Enter or Space Bar keys to select."); + } + return ''; +} +__assign(__assign({}, defaultProps$3), { getA11yStatusMessage: getA11yStatusMessage, isItemDisabled: function () { + return false; + } }); -const COMPONENT_ID$1c = 'forms.check_svg'; -const StyledCheckSvg = styled(SvgCheckSmFill).attrs({ - 'data-garden-id': COMPONENT_ID$1c, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledCheckSvg", - componentId: "sc-fvxetk-0" -})(["transition:opacity 0.25s ease-in-out;opacity:0;pointer-events:none;", ":checked ~ ", " > &{opacity:1;}", ":indeterminate ~ ", " > &{opacity:0;}", ";"], StyledCheckInput, StyledCheckLabel, StyledCheckInput, StyledCheckLabel, props => retrieveComponentStyles(COMPONENT_ID$1c, props)); -StyledCheckSvg.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _path$D; -function _extends$J() { _extends$J = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$J.apply(this, arguments); } -var SvgDashFill = function SvgDashFill(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$J({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$D || (_path$D = /*#__PURE__*/reactExports.createElement("path", { - stroke: "currentColor", - strokeLinecap: "round", - strokeWidth: 2, - d: "M3 6h6" - }))); -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1b = 'forms.dash_svg'; -const StyledDashSvg = styled(SvgDashFill).attrs({ - 'data-garden-id': COMPONENT_ID$1b, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledDashSvg", - componentId: "sc-z3vq71-0" -})(["transition:opacity 0.25s ease-in-out;opacity:0;pointer-events:none;", ":indeterminate ~ ", " > &{opacity:1;}", ";"], StyledCheckInput, StyledCheckLabel, props => retrieveComponentStyles(COMPONENT_ID$1b, props)); -StyledDashSvg.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$1a = 'forms.file_upload'; -const colorStyles$k = props => { - const baseColor = getColorV8('primaryHue', 600, props.theme); - const hoverColor = getColorV8('primaryHue', 700, props.theme); - const activeColor = getColorV8('primaryHue', 800, props.theme); - const disabledBackgroundColor = getColorV8('neutralHue', 200, props.theme); - const disabledForegroundColor = getColorV8('neutralHue', 400, props.theme); - return Ne(["border-color:", ";background-color:", ";color:", ";&:hover{border-color:", ";background-color:", ";color:", ";}", " &:active{border-color:", ";background-color:", ";color:", ";}&[aria-disabled='true']{border-color:", ";background-color:", ";color:", ";}"], props.isDragging ? activeColor : getColorV8('neutralHue', 600, props.theme), props.isDragging && rgba$1(baseColor, 0.2), props.isDragging ? activeColor : baseColor, hoverColor, rgba$1(baseColor, 0.08), hoverColor, focusStyles({ - theme: props.theme, - hue: baseColor - }), activeColor, rgba$1(baseColor, 0.2), activeColor, disabledForegroundColor, disabledBackgroundColor, disabledForegroundColor); -}; -const sizeStyles$m = props => { - const marginTop = `${props.theme.space.base * (props.isCompact ? 1 : 2)}px`; - const paddingHorizontal = `${props.isCompact ? 2 : 4}em`; - const paddingVertical = math$1(`${props.theme.space.base * (props.isCompact ? 2.5 : 5)} - ${props.theme.borderWidths.sm}`); - const fontSize = props.theme.fontSizes.md; - const lineHeight = getLineHeight(props.theme.space.base * 5, fontSize); - return Ne(["padding:", " ", ";min-width:4em;line-height:", ";font-size:", ";", ":not([hidden]) + &&,", " + &&,", " + &&,&& + ", ",&& + ", "{margin-top:", ";}"], paddingVertical, paddingHorizontal, lineHeight, fontSize, StyledLabel$1, StyledHint$1, StyledMessage$1, StyledHint$1, StyledMessage$1, marginTop); -}; -const StyledFileUpload = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$1a, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileUpload", - componentId: "sc-1rodjgn-0" -})(["display:flex;align-items:center;justify-content:center;box-sizing:border-box;direction:", ";transition:border-color 0.25s ease-in-out,box-shadow 0.1s ease-in-out,background-color 0.25s ease-in-out,color 0.25s ease-in-out;border:dashed ", ";border-radius:", ";cursor:pointer;text-align:center;user-select:none;", ";&[aria-disabled='true']{cursor:default;}", ";", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => props.theme.borderWidths.sm, props => props.theme.borderRadii.md, sizeStyles$m, colorStyles$k, props => retrieveComponentStyles(COMPONENT_ID$1a, props)); -StyledFileUpload.defaultProps = { - theme: DEFAULT_THEME -}; +var InputKeyDownArrowDown = 0; +var InputKeyDownArrowUp = 1; +var InputKeyDownEscape = 2; +var InputKeyDownHome = 3; +var InputKeyDownEnd = 4; +var InputKeyDownPageUp = 5; +var InputKeyDownPageDown = 6; +var InputKeyDownEnter = 7; +var InputChange = 8; +var InputBlur = 9; +var InputClick = 10; +var MenuMouseLeave = 11; +var ItemMouseMove = 12; +var ItemClick = 13; +var ToggleButtonClick = 14; +var FunctionToggleMenu = 15; +var FunctionOpenMenu = 16; +var FunctionCloseMenu = 17; +var FunctionSetHighlightedIndex = 18; +var FunctionSelectItem = 19; +var FunctionSetInputValue = 20; +var FunctionReset$1 = 21; +var ControlledPropUpdatedSelectedItem = 22; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ +var stateChangeTypes$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + InputKeyDownArrowDown: InputKeyDownArrowDown, + InputKeyDownArrowUp: InputKeyDownArrowUp, + InputKeyDownEscape: InputKeyDownEscape, + InputKeyDownHome: InputKeyDownHome, + InputKeyDownEnd: InputKeyDownEnd, + InputKeyDownPageUp: InputKeyDownPageUp, + InputKeyDownPageDown: InputKeyDownPageDown, + InputKeyDownEnter: InputKeyDownEnter, + InputChange: InputChange, + InputBlur: InputBlur, + InputClick: InputClick, + MenuMouseLeave: MenuMouseLeave, + ItemMouseMove: ItemMouseMove, + ItemClick: ItemClick, + ToggleButtonClick: ToggleButtonClick, + FunctionToggleMenu: FunctionToggleMenu, + FunctionOpenMenu: FunctionOpenMenu, + FunctionCloseMenu: FunctionCloseMenu, + FunctionSetHighlightedIndex: FunctionSetHighlightedIndex, + FunctionSelectItem: FunctionSelectItem, + FunctionSetInputValue: FunctionSetInputValue, + FunctionReset: FunctionReset$1, + ControlledPropUpdatedSelectedItem: ControlledPropUpdatedSelectedItem +}); -const COMPONENT_ID$19 = 'forms.file.close'; -const StyledFileClose = styled.button.attrs({ - 'data-garden-id': COMPONENT_ID$19, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileClose", - componentId: "sc-1m31jbf-0" -})(["display:flex;flex-shrink:0;align-items:center;justify-content:center;transition:opacity 0.25s ease-in-out;opacity:0.8;border:none;background:transparent;cursor:pointer;color:", ";appearance:none;&:hover{opacity:0.9;}&:focus{outline:none;}", ";"], props => getColorV8('foreground', 600 , props.theme), props => retrieveComponentStyles(COMPONENT_ID$19, props)); -StyledFileClose.defaultProps = { - theme: DEFAULT_THEME -}; +function getInitialState$1(props) { + var initialState = getInitialState$2(props); + var selectedItem = initialState.selectedItem; + var inputValue = initialState.inputValue; + if (inputValue === '' && selectedItem && props.defaultInputValue === undefined && props.initialInputValue === undefined && props.inputValue === undefined) { + inputValue = props.itemToString(selectedItem); + } + return _extends$U({}, initialState, { + inputValue: inputValue + }); +} +_extends$U({}, commonDropdownPropTypes, { + items: PropTypes.array.isRequired, + isItemDisabled: PropTypes.func, + selectedItemChanged: PropTypes.func, + getA11ySelectionMessage: PropTypes.func, + inputValue: PropTypes.string, + defaultInputValue: PropTypes.string, + initialInputValue: PropTypes.string, + inputId: PropTypes.string, + onInputValueChange: PropTypes.func +}); /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * The useCombobox version of useControlledReducer, which also + * checks if the controlled prop selectedItem changed between + * renders. If so, it will also update inputValue with its + * string equivalent. It uses the common useEnhancedReducer to + * compute the rest of the state. + * + * @param {Function} reducer Reducer function from downshift. + * @param {Object} initialState Initial state of the hook. + * @param {Object} props The hook props. + * @returns {Array} An array with the state and an action dispatcher. + */ +function useControlledReducer(reducer, initialState, props) { + var previousSelectedItemRef = reactExports.useRef(); + var _useEnhancedReducer = useEnhancedReducer(reducer, initialState, props), + state = _useEnhancedReducer[0], + dispatch = _useEnhancedReducer[1]; -const COMPONENT_ID$18 = 'forms.file'; -const colorStyles$j = props => { - let borderColor; - let focusBorderColor; - let foregroundColor; - if (props.validation === 'success') { - borderColor = getColorV8('successHue', 600, props.theme); - focusBorderColor = borderColor; - foregroundColor = borderColor; - } else if (props.validation === 'error') { - borderColor = getColorV8('dangerHue', 600, props.theme); - focusBorderColor = borderColor; - foregroundColor = borderColor; - } else { - borderColor = getColorV8('neutralHue', 300, props.theme); - focusBorderColor = getColorV8('primaryHue', 600, props.theme); - foregroundColor = getColorV8('foreground', 600 , props.theme); - } - return Ne(["border-color:", ";color:", ";", ""], borderColor, foregroundColor, focusStyles({ - theme: props.theme, - inset: props.focusInset, - hue: focusBorderColor, - styles: { - borderColor: focusBorderColor + // ToDo: if needed, make same approach as selectedItemChanged from Downshift. + reactExports.useEffect(function () { + if (!isControlledProp(props, 'selectedItem')) { + return; } - })); -}; -const sizeStyles$l = props => { - const size = `${props.theme.space.base * (props.isCompact ? 7 : 10)}px`; - const spacing = `${props.theme.space.base * (props.isCompact ? 2 : 3)}px`; - const fontSize = props.theme.fontSizes.md; - const lineHeight = getLineHeight(props.theme.space.base * 5, fontSize); - return ` - box-sizing: border-box; - border: ${props.theme.borders.sm}; - border-radius: ${props.theme.borderRadii.md}; - padding: 0 ${spacing}; - height: ${size}; - line-height: ${lineHeight}; - font-size: ${fontSize}; - - & > span { - width: 100%; + if (props.selectedItemChanged(previousSelectedItemRef.current, props.selectedItem)) { + dispatch({ + type: ControlledPropUpdatedSelectedItem, + inputValue: props.itemToString(props.selectedItem) + }); } + previousSelectedItemRef.current = state.selectedItem === previousSelectedItemRef.current ? props.selectedItem : state.selectedItem; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [state.selectedItem, props.selectedItem]); + return [getState(state, props), dispatch]; +} +var defaultProps$1 = _extends$U({}, defaultProps$3, { + selectedItemChanged: function selectedItemChanged(prevItem, item) { + return prevItem !== item; + }, + getA11yStatusMessage: getA11yStatusMessage$1, + isItemDisabled: function isItemDisabled() { + return false; + } +}); - & > ${StyledFileClose} { - width: ${size}; - height: ${size}; - margin-${props.theme.rtl ? 'left' : 'right'}: -${spacing}; - } - `; -}; -const StyledFile = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$18, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFile", - componentId: "sc-195lzp1-0" -})(["display:flex;position:relative;flex-wrap:nowrap;align-items:center;transition:box-shadow 0.1s ease-in-out;", ";", ";& > span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}& > [role='progressbar']{position:absolute;bottom:0;left:0;transition:opacity 0.2s ease-in-out;margin:0;border-top-left-radius:0;border-top-right-radius:0;width:100%;& > div{border-top-", "-radius:0;}}& > [role='progressbar'][aria-valuenow='0'],& > [role='progressbar'][aria-valuenow='100']{opacity:0;}", ";"], sizeStyles$l, colorStyles$j, props => props.theme.rtl ? 'right' : 'left', props => retrieveComponentStyles(COMPONENT_ID$18, props)); -StyledFile.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$17 = 'forms.file.delete'; -const StyledFileDelete = styled(StyledFileClose).attrs({ - 'data-garden-id': COMPONENT_ID$17, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileDelete", - componentId: "sc-a8nnhx-0" -})(["color:", ";", ";"], props => getColorV8('dangerHue', 600, props.theme), props => retrieveComponentStyles(COMPONENT_ID$17, props)); -StyledFileDelete.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$16 = 'forms.file.icon'; -const StyledFileIcon = styled(_ref => { - let { - children, - isCompact, - theme, - ...props - } = _ref; - return React__default.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$16, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileIcon", - componentId: "sc-7b3q0c-0" -})(["flex-shrink:0;width:", ";margin-", ":", "px;", ";"], props => props.isCompact ? props.theme.iconSizes.sm : props.theme.iconSizes.md, props => props.theme.rtl ? 'left' : 'right', props => props.theme.space.base * 2, props => retrieveComponentStyles(COMPONENT_ID$16, props)); -StyledFileIcon.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ +/* eslint-disable complexity */ +function downshiftUseComboboxReducer(state, action) { + var _props$items; + var type = action.type, + props = action.props, + altKey = action.altKey; + var changes; + switch (type) { + case ItemClick: + changes = { + isOpen: getDefaultValue$1(props, 'isOpen'), + highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), + selectedItem: props.items[action.index], + inputValue: props.itemToString(props.items[action.index]) + }; + break; + case InputKeyDownArrowDown: + if (state.isOpen) { + changes = { + highlightedIndex: getHighlightedIndex(state.highlightedIndex, 1, props.items, props.isItemDisabled, true) + }; + } else { + changes = { + highlightedIndex: altKey && state.selectedItem == null ? -1 : getHighlightedIndexOnOpen(props, state, 1), + isOpen: props.items.length >= 0 + }; + } + break; + case InputKeyDownArrowUp: + if (state.isOpen) { + if (altKey) { + changes = getChangesOnSelection(props, state.highlightedIndex); + } else { + changes = { + highlightedIndex: getHighlightedIndex(state.highlightedIndex, -1, props.items, props.isItemDisabled, true) + }; + } + } else { + changes = { + highlightedIndex: getHighlightedIndexOnOpen(props, state, -1), + isOpen: props.items.length >= 0 + }; + } + break; + case InputKeyDownEnter: + changes = getChangesOnSelection(props, state.highlightedIndex); + break; + case InputKeyDownEscape: + changes = _extends$U({ + isOpen: false, + highlightedIndex: -1 + }, !state.isOpen && { + selectedItem: null, + inputValue: '' + }); + break; + case InputKeyDownPageUp: + changes = { + highlightedIndex: getHighlightedIndex(state.highlightedIndex, -10, props.items, props.isItemDisabled, true) + }; + break; + case InputKeyDownPageDown: + changes = { + highlightedIndex: getHighlightedIndex(state.highlightedIndex, 10, props.items, props.isItemDisabled, true) + }; + break; + case InputKeyDownHome: + changes = { + highlightedIndex: getNonDisabledIndex(0, false, props.items, props.isItemDisabled) + }; + break; + case InputKeyDownEnd: + changes = { + highlightedIndex: getNonDisabledIndex(props.items.length - 1, true, props.items, props.isItemDisabled) + }; + break; + case InputBlur: + changes = _extends$U({ + isOpen: false, + highlightedIndex: -1 + }, state.highlightedIndex >= 0 && ((_props$items = props.items) == null ? void 0 : _props$items.length) && action.selectItem && { + selectedItem: props.items[state.highlightedIndex], + inputValue: props.itemToString(props.items[state.highlightedIndex]) + }); + break; + case InputChange: + changes = { + isOpen: true, + highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), + inputValue: action.inputValue + }; + break; + case InputClick: + changes = { + isOpen: !state.isOpen, + highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0) + }; + break; + case FunctionSelectItem: + changes = { + selectedItem: action.selectedItem, + inputValue: props.itemToString(action.selectedItem) + }; + break; + case ControlledPropUpdatedSelectedItem: + changes = { + inputValue: action.inputValue + }; + break; + default: + return downshiftCommonReducer(state, action, stateChangeTypes$1); + } + return _extends$U({}, state, changes); +} +/* eslint-enable complexity */ -const COMPONENT_ID$15 = 'forms.file_list'; -const StyledFileList = styled.ul.attrs({ - 'data-garden-id': COMPONENT_ID$15, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileList", - componentId: "sc-gbahjg-0" -})(["margin:0;padding:0;list-style:none;", ";"], props => retrieveComponentStyles(COMPONENT_ID$15, props)); -StyledFileList.defaultProps = { - theme: DEFAULT_THEME -}; +var _excluded$1 = ["onMouseLeave", "refKey", "ref"], + _excluded2$1 = ["item", "index", "refKey", "ref", "onMouseMove", "onMouseDown", "onClick", "onPress", "disabled"], + _excluded3$1 = ["onClick", "onPress", "refKey", "ref"], + _excluded4$1 = ["onKeyDown", "onChange", "onInput", "onBlur", "onChangeText", "onClick", "refKey", "ref"]; +useCombobox$1.stateChangeTypes = stateChangeTypes$1; +function useCombobox$1(userProps) { + if (userProps === void 0) { + userProps = {}; + } + // Props defaults and destructuring. + var props = _extends$U({}, defaultProps$1, userProps); + var items = props.items, + scrollIntoView = props.scrollIntoView, + environment = props.environment, + getA11yStatusMessage = props.getA11yStatusMessage, + getA11ySelectionMessage = props.getA11ySelectionMessage, + itemToString = props.itemToString; + // Initial state depending on controlled props. + var initialState = getInitialState$1(props); + var _useControlledReducer = useControlledReducer(downshiftUseComboboxReducer, initialState, props), + state = _useControlledReducer[0], + dispatch = _useControlledReducer[1]; + var isOpen = state.isOpen, + highlightedIndex = state.highlightedIndex, + selectedItem = state.selectedItem, + inputValue = state.inputValue; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + // Element refs. + var menuRef = reactExports.useRef(null); + var itemRefs = reactExports.useRef({}); + var inputRef = reactExports.useRef(null); + var toggleButtonRef = reactExports.useRef(null); + var isInitialMountRef = reactExports.useRef(true); + // prevent id re-generation between renders. + var elementIds = useElementIds(props); + // used to keep track of how many items we had on previous cycle. + var previousResultCountRef = reactExports.useRef(); + // utility callback to get item element. + var latest = useLatestRef$1({ + state: state, + props: props + }); + var getItemNodeFromIndex = reactExports.useCallback(function (index) { + return itemRefs.current[elementIds.getItemId(index)]; + }, [elementIds]); -const COMPONENT_ID$14 = 'forms.file_list.item'; -const StyledFileListItem = styled.li.attrs({ - 'data-garden-id': COMPONENT_ID$14, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFileListItem", - componentId: "sc-1ova3lo-0" -})(["&:not(:first-child),", " ~ ", " > &:first-child{margin-top:", "px;}", ";"], StyledFileUpload, StyledFileList, props => props.theme.space.base * 2, props => retrieveComponentStyles(COMPONENT_ID$14, props)); -StyledFileListItem.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _circle$5; -function _extends$I() { _extends$I = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$I.apply(this, arguments); } -var SvgCircleSmFill$1 = function SvgCircleSmFill(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$I({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _circle$5 || (_circle$5 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 6, - cy: 6, - r: 2, - fill: "currentColor" - }))); -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$13 = 'forms.radio_svg'; -const StyledRadioSvg = styled(SvgCircleSmFill$1).attrs({ - 'data-garden-id': COMPONENT_ID$13, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledRadioSvg", - componentId: "sc-1r1qtr1-0" -})(["transition:opacity 0.25s ease-in-out;opacity:0;", ":checked ~ ", " > &{opacity:1;}", ";"], StyledRadioInput, StyledRadioLabel, props => retrieveComponentStyles(COMPONENT_ID$13, props)); -StyledRadioSvg.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$12 = 'forms.toggle_label'; -const sizeStyles$k = props => { - const size = props.theme.space.base * 10; - const padding = size + props.theme.space.base * 2; - return Ne(["padding-", ":", "px;&[hidden]{padding-", ":", "px;}"], props.theme.rtl ? 'right' : 'left', padding, props.theme.rtl ? 'right' : 'left', size); -}; -const StyledToggleLabel = styled(StyledCheckLabel).attrs({ - 'data-garden-id': COMPONENT_ID$12, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledToggleLabel", - componentId: "sc-e0asdk-0" -})(["", ";", ";"], props => sizeStyles$k(props), props => retrieveComponentStyles(COMPONENT_ID$12, props)); -StyledToggleLabel.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$11 = 'forms.toggle_hint'; -const StyledToggleHint = styled(StyledHint$1).attrs({ - 'data-garden-id': COMPONENT_ID$11, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledToggleHint", - componentId: "sc-nziggu-0" -})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 12px`), props => retrieveComponentStyles(COMPONENT_ID$11, props)); -StyledToggleHint.defaultProps = { - theme: DEFAULT_THEME -}; + // Effects. + // Sets a11y status message on changes in state. + useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], _extends$U({ + isInitialMount: isInitialMountRef.current, + previousResultCount: previousResultCountRef.current, + items: items, + environment: environment, + itemToString: itemToString + }, state)); + // Sets a11y status message on changes in selectedItem. + useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], _extends$U({ + isInitialMount: isInitialMountRef.current, + previousResultCount: previousResultCountRef.current, + items: items, + environment: environment, + itemToString: itemToString + }, state)); + // Scroll on highlighted item if change comes from keyboard. + var shouldScrollRef = useScrollIntoView({ + menuElement: menuRef.current, + highlightedIndex: highlightedIndex, + isOpen: isOpen, + itemRefs: itemRefs, + scrollIntoView: scrollIntoView, + getItemNodeFromIndex: getItemNodeFromIndex + }); + useControlPropsValidator({ + isInitialMount: isInitialMountRef.current, + props: props, + state: state + }); + // Focus the input on first render if required. + reactExports.useEffect(function () { + var focusOnOpen = getInitialValue$1(props, 'isOpen'); + if (focusOnOpen && inputRef.current) { + inputRef.current.focus(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + reactExports.useEffect(function () { + if (isInitialMountRef.current) { + return; + } + previousResultCountRef.current = items.length; + }); + // Add mouse/touch events to document. + var mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [inputRef, menuRef, toggleButtonRef], environment, function () { + dispatch({ + type: InputBlur, + selectItem: false + }); + }); + var setGetterPropCallInfo = useGetterPropsCalledChecker(); + // Make initial ref false. + reactExports.useEffect(function () { + isInitialMountRef.current = false; + return function () { + isInitialMountRef.current = true; + }; + }, []); + // Reset itemRefs on close. + reactExports.useEffect(function () { + var _environment$document; + if (!isOpen) { + itemRefs.current = {}; + } else if (((_environment$document = environment.document) == null ? void 0 : _environment$document.activeElement) !== inputRef.current) { + var _inputRef$current; + inputRef == null || (_inputRef$current = inputRef.current) == null ? void 0 : _inputRef$current.focus(); + } + }, [isOpen, environment]); -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + /* Event handler functions */ + var inputKeyDownHandlers = reactExports.useMemo(function () { + return { + ArrowDown: function ArrowDown(event) { + event.preventDefault(); + dispatch({ + type: InputKeyDownArrowDown, + altKey: event.altKey + }); + }, + ArrowUp: function ArrowUp(event) { + event.preventDefault(); + dispatch({ + type: InputKeyDownArrowUp, + altKey: event.altKey + }); + }, + Home: function Home(event) { + if (!latest.current.state.isOpen) { + return; + } + event.preventDefault(); + dispatch({ + type: InputKeyDownHome + }); + }, + End: function End(event) { + if (!latest.current.state.isOpen) { + return; + } + event.preventDefault(); + dispatch({ + type: InputKeyDownEnd + }); + }, + Escape: function Escape(event) { + var latestState = latest.current.state; + if (latestState.isOpen || latestState.inputValue || latestState.selectedItem || latestState.highlightedIndex > -1) { + event.preventDefault(); + dispatch({ + type: InputKeyDownEscape + }); + } + }, + Enter: function Enter(event) { + var latestState = latest.current.state; + // if closed or no highlighted index, do nothing. + if (!latestState.isOpen || event.which === 229 // if IME composing, wait for next Enter keydown event. + ) { + return; + } + event.preventDefault(); + dispatch({ + type: InputKeyDownEnter + }); + }, + PageUp: function PageUp(event) { + if (latest.current.state.isOpen) { + event.preventDefault(); + dispatch({ + type: InputKeyDownPageUp + }); + } + }, + PageDown: function PageDown(event) { + if (latest.current.state.isOpen) { + event.preventDefault(); + dispatch({ + type: InputKeyDownPageDown + }); + } + } + }; + }, [dispatch, latest]); -const COMPONENT_ID$10 = 'forms.toggle_message'; -const StyledToggleMessage = styled(StyledMessage$1).attrs({ - 'data-garden-id': COMPONENT_ID$10, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledToggleMessage", - componentId: "sc-13vuvl1-0" -})(["padding-", ":", ";& ", "{", ":", ";}", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 12px`), StyledMessageIcon, props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 10px - ${props.theme.iconSizes.md}`), props => retrieveComponentStyles(COMPONENT_ID$10, props)); -StyledToggleMessage.defaultProps = { - theme: DEFAULT_THEME -}; + // Getter props. + var getLabelProps = reactExports.useCallback(function (labelProps) { + return _extends$U({ + id: elementIds.labelId, + htmlFor: elementIds.inputId + }, labelProps); + }, [elementIds]); + var getMenuProps = reactExports.useCallback(function (_temp, _temp2) { + var _extends2; + var _ref = _temp === void 0 ? {} : _temp, + onMouseLeave = _ref.onMouseLeave, + _ref$refKey = _ref.refKey, + refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey, + ref = _ref.ref, + rest = _objectWithoutPropertiesLoose$1(_ref, _excluded$1); + var _ref2 = _temp2 === void 0 ? {} : _temp2; + _ref2.suppressRefError; + return _extends$U((_extends2 = {}, _extends2[refKey] = handleRefs(ref, function (menuNode) { + menuRef.current = menuNode; + }), _extends2.id = elementIds.menuId, _extends2.role = 'listbox', _extends2['aria-labelledby'] = rest && rest['aria-label'] ? undefined : "" + elementIds.labelId, _extends2.onMouseLeave = callAllEventHandlers(onMouseLeave, function () { + dispatch({ + type: MenuMouseLeave + }); + }), _extends2), rest); + }, [dispatch, setGetterPropCallInfo, elementIds]); + var getItemProps = reactExports.useCallback(function (_temp3) { + var _extends3, _ref4; + var _ref3 = _temp3 === void 0 ? {} : _temp3, + itemProp = _ref3.item, + indexProp = _ref3.index, + _ref3$refKey = _ref3.refKey, + refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey, + ref = _ref3.ref, + onMouseMove = _ref3.onMouseMove, + onMouseDown = _ref3.onMouseDown, + onClick = _ref3.onClick; + _ref3.onPress; + var disabledProp = _ref3.disabled, + rest = _objectWithoutPropertiesLoose$1(_ref3, _excluded2$1); + if (disabledProp !== undefined) { + console.warn('Passing "disabled" as an argument to getItemProps is not supported anymore. Please use the isItemDisabled prop from useCombobox.'); + } + var _latest$current = latest.current, + latestProps = _latest$current.props, + latestState = _latest$current.state; + var _getItemAndIndex = getItemAndIndex(itemProp, indexProp, latestProps.items, 'Pass either item or index to getItemProps!'), + item = _getItemAndIndex[0], + index = _getItemAndIndex[1]; + var disabled = latestProps.isItemDisabled(item, index); + var onSelectKey = 'onClick'; + var customClickHandler = onClick; + var itemHandleMouseMove = function itemHandleMouseMove() { + if (index === latestState.highlightedIndex) { + return; + } + shouldScrollRef.current = false; + dispatch({ + type: ItemMouseMove, + index: index, + disabled: disabled + }); + }; + var itemHandleClick = function itemHandleClick() { + dispatch({ + type: ItemClick, + index: index + }); + }; + var itemHandleMouseDown = function itemHandleMouseDown(e) { + return e.preventDefault(); + }; + return _extends$U((_extends3 = {}, _extends3[refKey] = handleRefs(ref, function (itemNode) { + if (itemNode) { + itemRefs.current[elementIds.getItemId(index)] = itemNode; + } + }), _extends3['aria-disabled'] = disabled, _extends3['aria-selected'] = "" + (index === latestState.highlightedIndex), _extends3.id = elementIds.getItemId(index), _extends3.role = 'option', _extends3), !disabled && (_ref4 = {}, _ref4[onSelectKey] = callAllEventHandlers(customClickHandler, itemHandleClick), _ref4), { + onMouseMove: callAllEventHandlers(onMouseMove, itemHandleMouseMove), + onMouseDown: callAllEventHandlers(onMouseDown, itemHandleMouseDown) + }, rest); + }, [dispatch, latest, shouldScrollRef, elementIds]); + var getToggleButtonProps = reactExports.useCallback(function (_temp4) { + var _extends4; + var _ref5 = _temp4 === void 0 ? {} : _temp4, + onClick = _ref5.onClick; + _ref5.onPress; + var _ref5$refKey = _ref5.refKey, + refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey, + ref = _ref5.ref, + rest = _objectWithoutPropertiesLoose$1(_ref5, _excluded3$1); + var latestState = latest.current.state; + var toggleButtonHandleClick = function toggleButtonHandleClick() { + dispatch({ + type: ToggleButtonClick + }); + }; + return _extends$U((_extends4 = {}, _extends4[refKey] = handleRefs(ref, function (toggleButtonNode) { + toggleButtonRef.current = toggleButtonNode; + }), _extends4['aria-controls'] = elementIds.menuId, _extends4['aria-expanded'] = latestState.isOpen, _extends4.id = elementIds.toggleButtonId, _extends4.tabIndex = -1, _extends4), !rest.disabled && _extends$U({}, { + onClick: callAllEventHandlers(onClick, toggleButtonHandleClick) + }), rest); + }, [dispatch, latest, elementIds]); + var getInputProps = reactExports.useCallback(function (_temp5, _temp6) { + var _extends5; + var _ref6 = _temp5 === void 0 ? {} : _temp5, + onKeyDown = _ref6.onKeyDown, + onChange = _ref6.onChange, + onInput = _ref6.onInput, + onBlur = _ref6.onBlur; + _ref6.onChangeText; + var onClick = _ref6.onClick, + _ref6$refKey = _ref6.refKey, + refKey = _ref6$refKey === void 0 ? 'ref' : _ref6$refKey, + ref = _ref6.ref, + rest = _objectWithoutPropertiesLoose$1(_ref6, _excluded4$1); + var _ref7 = _temp6 === void 0 ? {} : _temp6; + _ref7.suppressRefError; + var latestState = latest.current.state; + var inputHandleKeyDown = function inputHandleKeyDown(event) { + var key = normalizeArrowKey(event); + if (key && inputKeyDownHandlers[key]) { + inputKeyDownHandlers[key](event); + } + }; + var inputHandleChange = function inputHandleChange(event) { + dispatch({ + type: InputChange, + inputValue: event.target.value + }); + }; + var inputHandleBlur = function inputHandleBlur(event) { + /* istanbul ignore else */ + if (latestState.isOpen && !mouseAndTouchTrackersRef.current.isMouseDown) { + var isBlurByTabChange = event.relatedTarget === null && environment.document.activeElement !== environment.document.body; + dispatch({ + type: InputBlur, + selectItem: !isBlurByTabChange + }); + } + }; + var inputHandleClick = function inputHandleClick() { + dispatch({ + type: InputClick + }); + }; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + /* istanbul ignore next (preact) */ + var onChangeKey = 'onChange'; + var eventHandlers = {}; + if (!rest.disabled) { + var _eventHandlers; + eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, inputHandleBlur), _eventHandlers.onClick = callAllEventHandlers(onClick, inputHandleClick), _eventHandlers); + } + return _extends$U((_extends5 = {}, _extends5[refKey] = handleRefs(ref, function (inputNode) { + inputRef.current = inputNode; + }), _extends5['aria-activedescendant'] = latestState.isOpen && latestState.highlightedIndex > -1 ? elementIds.getItemId(latestState.highlightedIndex) : '', _extends5['aria-autocomplete'] = 'list', _extends5['aria-controls'] = elementIds.menuId, _extends5['aria-expanded'] = latestState.isOpen, _extends5['aria-labelledby'] = rest && rest['aria-label'] ? undefined : elementIds.labelId, _extends5.autoComplete = 'off', _extends5.id = elementIds.inputId, _extends5.role = 'combobox', _extends5.value = latestState.inputValue, _extends5), eventHandlers, rest); + }, [setGetterPropCallInfo, latest, elementIds, inputKeyDownHandlers, dispatch, mouseAndTouchTrackersRef, environment]); -var _circle$4; -function _extends$H() { _extends$H = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$H.apply(this, arguments); } -var SvgCircleSmFill = function SvgCircleSmFill(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$H({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _circle$4 || (_circle$4 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 8, - cy: 8, - r: 6, - fill: "currentColor" - }))); -}; + // returns + var toggleMenu = reactExports.useCallback(function () { + dispatch({ + type: FunctionToggleMenu + }); + }, [dispatch]); + var closeMenu = reactExports.useCallback(function () { + dispatch({ + type: FunctionCloseMenu + }); + }, [dispatch]); + var openMenu = reactExports.useCallback(function () { + dispatch({ + type: FunctionOpenMenu + }); + }, [dispatch]); + var setHighlightedIndex = reactExports.useCallback(function (newHighlightedIndex) { + dispatch({ + type: FunctionSetHighlightedIndex, + highlightedIndex: newHighlightedIndex + }); + }, [dispatch]); + var selectItem = reactExports.useCallback(function (newSelectedItem) { + dispatch({ + type: FunctionSelectItem, + selectedItem: newSelectedItem + }); + }, [dispatch]); + var setInputValue = reactExports.useCallback(function (newInputValue) { + dispatch({ + type: FunctionSetInputValue, + inputValue: newInputValue + }); + }, [dispatch]); + var reset = reactExports.useCallback(function () { + dispatch({ + type: FunctionReset$1 + }); + }, [dispatch]); + return { + // prop getters. + getItemProps: getItemProps, + getLabelProps: getLabelProps, + getMenuProps: getMenuProps, + getInputProps: getInputProps, + getToggleButtonProps: getToggleButtonProps, + // actions. + toggleMenu: toggleMenu, + openMenu: openMenu, + closeMenu: closeMenu, + setHighlightedIndex: setHighlightedIndex, + setInputValue: setInputValue, + selectItem: selectItem, + reset: reset, + // state. + highlightedIndex: highlightedIndex, + isOpen: isOpen, + selectedItem: selectedItem, + inputValue: inputValue + }; +} /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$$ = 'forms.toggle_svg'; -const StyledToggleSvg = styled(SvgCircleSmFill).attrs({ - 'data-garden-id': COMPONENT_ID$$, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledToggleSvg", - componentId: "sc-162xbyx-0" -})(["transition:all 0.15s ease-in-out;", ";"], props => retrieveComponentStyles(COMPONENT_ID$$, props)); -StyledToggleSvg.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Field$1 = React__default.forwardRef((props, ref) => { - const [hasHint, setHasHint] = reactExports.useState(false); - const [hasMessage, setHasMessage] = reactExports.useState(false); - const [isLabelActive, setIsLabelActive] = reactExports.useState(false); - const [isLabelHovered, setIsLabelHovered] = reactExports.useState(false); - const multiThumbRangeRef = reactExports.useRef(null); - const { - getInputProps, - getMessageProps, - ...propGetters - } = useField({ - idPrefix: props.id, - hasHint, - hasMessage - }); - const fieldProps = reactExports.useMemo(() => ({ - ...propGetters, - getInputProps, - getMessageProps, - isLabelActive, - setIsLabelActive, - isLabelHovered, - setIsLabelHovered, - hasHint, - setHasHint, - hasMessage, - setHasMessage, - multiThumbRangeRef - }), [propGetters, getInputProps, getMessageProps, isLabelActive, isLabelHovered, hasHint, hasMessage]); - return React__default.createElement(FieldContext$1.Provider, { - value: fieldProps - }, React__default.createElement(StyledField$1, Object.assign({}, props, { - ref: ref - }))); + * Returns a message to be added to aria-live region when item is removed. + * + * @param {Object} selectionParameters Parameters required to build the message. + * @returns {string} The a11y message. + */ +function getA11yRemovalMessage(selectionParameters) { + var removedSelectedItem = selectionParameters.removedSelectedItem, + itemToStringLocal = selectionParameters.itemToString; + return itemToStringLocal(removedSelectedItem) + " has been removed."; +} +_extends$U({}, commonPropTypes, { + selectedItems: PropTypes.array, + initialSelectedItems: PropTypes.array, + defaultSelectedItems: PropTypes.array, + getA11yRemovalMessage: PropTypes.func, + activeIndex: PropTypes.number, + initialActiveIndex: PropTypes.number, + defaultActiveIndex: PropTypes.number, + onActiveIndexChange: PropTypes.func, + onSelectedItemsChange: PropTypes.func, + keyNavigationNext: PropTypes.string, + keyNavigationPrevious: PropTypes.string +}); +({ + itemToString: defaultProps$3.itemToString, + stateReducer: defaultProps$3.stateReducer, + environment: defaultProps$3.environment, + getA11yRemovalMessage: getA11yRemovalMessage, + keyNavigationNext: 'ArrowRight', + keyNavigationPrevious: 'ArrowLeft' }); -Field$1.displayName = 'Field'; /** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ + * Copyright Zendesk, Inc. + * + * Use of this source code is governed under the Apache License, Version 2.0 + * found at http://www.apache.org/licenses/LICENSE-2.0. + */ -const FieldsetContext = reactExports.createContext(undefined); -const useFieldsetContext = () => { - const fieldsetContext = reactExports.useContext(FieldsetContext); - return fieldsetContext; +const typeMap = { + [useCombobox$1.stateChangeTypes.FunctionCloseMenu]: 'fn:setExpansion', + [useCombobox$1.stateChangeTypes.FunctionOpenMenu]: 'fn:setExpansion', + [useCombobox$1.stateChangeTypes.FunctionToggleMenu]: 'fn:setExpansion', + [useCombobox$1.stateChangeTypes.FunctionReset]: 'fn:reset', + [useCombobox$1.stateChangeTypes.FunctionSelectItem]: 'fn:setSelectionValue', + [useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex]: 'fn:setActiveIndex', + [useCombobox$1.stateChangeTypes.FunctionSetInputValue]: 'fn:setInputValue', + [useCombobox$1.stateChangeTypes.InputBlur]: 'input:blur', + [useCombobox$1.stateChangeTypes.InputChange]: 'input:change', + [useCombobox$1.stateChangeTypes.InputClick]: 'input:click', + [useCombobox$1.stateChangeTypes.InputKeyDownArrowDown]: `input:keyDown:${KEYS$2.DOWN}`, + [useCombobox$1.stateChangeTypes.InputKeyDownArrowUp]: `input:keyDown:${KEYS$2.UP}`, + [useCombobox$1.stateChangeTypes.InputKeyDownEnd]: `input:keyDown:${KEYS$2.END}`, + [useCombobox$1.stateChangeTypes.InputKeyDownEnter]: `input:keyDown:${KEYS$2.ENTER}`, + [useCombobox$1.stateChangeTypes.InputKeyDownEscape]: `input:keyDown:${KEYS$2.ESCAPE}`, + [useCombobox$1.stateChangeTypes.InputKeyDownHome]: `input:keyDown:${KEYS$2.HOME}`, + [useCombobox$1.stateChangeTypes.InputKeyDownPageDown]: `input:keyDown:${KEYS$2.PAGE_DOWN}`, + [useCombobox$1.stateChangeTypes.InputKeyDownPageUp]: `input:keyDown:${KEYS$2.PAGE_UP}`, + [useCombobox$1.stateChangeTypes.ItemClick]: 'option:click', + [useCombobox$1.stateChangeTypes.ItemMouseMove]: 'option:mouseMove', + [useCombobox$1.stateChangeTypes.MenuMouseLeave]: 'listbox:mouseLeave', + [useCombobox$1.stateChangeTypes.ToggleButtonClick]: 'toggle:click' }; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const InputContext = reactExports.createContext(undefined); -const useInputContext = () => { - return reactExports.useContext(InputContext); +const toType = downshiftType => { + return typeMap[downshiftType] || downshiftType; +}; +const toLabel = (labels, value) => { + if (value === undefined) { + return ''; + } + const key = typeof value === 'string' ? value : JSON.stringify(value); + return labels[key]; }; -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Hint$1 = React__default.forwardRef((props, ref) => { - const { +const useCombobox = _ref => { + let { + idPrefix, + triggerRef, + inputRef, + listboxRef, + isAutocomplete, + isMultiselectable, + isEditable = true, + disabled, hasHint, - setHasHint, - getHintProps - } = useFieldContext$1() || {}; - const type = useInputContext(); - reactExports.useEffect(() => { - if (!hasHint && setHasHint) { - setHasHint(true); - } - return () => { - if (hasHint && setHasHint) { - setHasHint(false); + hasMessage, + options = [], + inputValue, + selectionValue, + isExpanded, + defaultExpanded, + initialExpanded, + activeIndex, + defaultActiveIndex, + initialActiveIndex, + onChange = () => undefined, + environment + } = _ref; + const win = environment || window; + const [triggerContainsInput, setTriggerContainsInput] = reactExports.useState(); + const [downshiftInputValue, setDownshiftInputValue] = reactExports.useState(inputValue); + const [matchValue, setMatchValue] = reactExports.useState(''); + const useInputValueRef = reactExports.useRef(true); + const matchTimeoutRef = reactExports.useRef(); + const previousStateRef = reactExports.useRef(); + const prefix = useId$2(idPrefix); + const idRef = reactExports.useRef({ + label: `${prefix}--label`, + hint: `${prefix}--hint`, + trigger: `${prefix}--trigger`, + input: `${prefix}--input`, + listbox: `${prefix}--listbox`, + message: `${prefix}--message`, + getOptionId: (index, isDisabled, isHidden) => `${prefix}--option${isDisabled ? '-disabled' : ''}${isHidden ? '-hidden' : ''}-${index}` + }); + const labels = reactExports.useMemo(() => ({}), []); + const selectedValues = reactExports.useMemo(() => [], []); + const disabledValues = reactExports.useMemo(() => [], []); + const hiddenValues = reactExports.useMemo(() => [], []); + const values = reactExports.useMemo(() => { + const retVal = []; + const setValues = option => { + if (option.disabled || option.hidden) { + if (option.disabled && !disabledValues.includes(option.value)) { + disabledValues.push(option.value); + } + if (option.hidden && !hiddenValues.includes(option.value)) { + hiddenValues.push(option.value); + } + } else { + retVal.push(option.value); + const disabledIndex = disabledValues.indexOf(option.value); + if (disabledIndex !== -1) { + disabledValues.splice(disabledIndex, 1); + } + const hiddenIndex = hiddenValues.indexOf(option.value); + if (hiddenIndex !== -1) { + hiddenValues.splice(hiddenIndex, 1); + } + } + if (option.selected && !selectedValues.includes(option.value)) { + selectedValues.push(option.value); } + const key = typeof option.value === 'string' ? option.value : JSON.stringify(option.value); + labels[key] = option.label || key; }; - }, [hasHint, setHasHint]); - let HintComponent; - if (type === 'checkbox') { - HintComponent = StyledCheckHint; - } else if (type === 'radio') { - HintComponent = StyledRadioHint; - } else if (type === 'toggle') { - HintComponent = StyledToggleHint; + options.forEach(option => { + if ('options' in option) { + option.options.forEach(setValues); + } else { + setValues(option); + } + }); + return retVal; + }, [options, disabledValues, hiddenValues, selectedValues, labels]); + const initialSelectionValue = isMultiselectable ? selectedValues : selectedValues[0]; + const initialInputValue = isMultiselectable ? '' : toLabel(labels, initialSelectionValue); + const _defaultActiveIndex = reactExports.useMemo(() => { + if (defaultActiveIndex === undefined) { + return isAutocomplete && isEditable ? 0 : undefined; + } + return defaultActiveIndex; + }, [defaultActiveIndex, isAutocomplete, isEditable]); + if (useInputValueRef.current && inputValue !== downshiftInputValue) { + setDownshiftInputValue(inputValue); } else { - HintComponent = StyledHint$1; - } - let combinedProps = props; - if (getHintProps) { - combinedProps = getHintProps(combinedProps); + useInputValueRef.current = true; } - return React__default.createElement(HintComponent, Object.assign({ - ref: ref - }, combinedProps)); -}); -Hint$1.displayName = 'Hint'; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Label$2 = React__default.forwardRef((props, ref) => { - const fieldContext = useFieldContext$1(); - const fieldsetContext = useFieldsetContext(); - const type = useInputContext(); - let combinedProps = props; - if (fieldContext) { - combinedProps = fieldContext.getLabelProps(combinedProps); - if (type === undefined) { - const { - setIsLabelActive, - setIsLabelHovered, - multiThumbRangeRef - } = fieldContext; - combinedProps = { - ...combinedProps, - onMouseUp: composeEventHandlers$5(props.onMouseUp, () => { - setIsLabelActive(false); - }), - onMouseDown: composeEventHandlers$5(props.onMouseDown, () => { - setIsLabelActive(true); - }), - onMouseEnter: composeEventHandlers$5(props.onMouseEnter, () => { - setIsLabelHovered(true); - }), - onMouseLeave: composeEventHandlers$5(props.onMouseLeave, () => { - setIsLabelHovered(false); - }), - onClick: composeEventHandlers$5(props.onClick, () => { - multiThumbRangeRef.current && multiThumbRangeRef.current.focus(); - }) - }; + if (selectionValue === undefined || selectionValue === null) { + if (!isMultiselectable && selectedValues.length > 1) { + throw new Error('Error: expected useCombobox `options` to have no more than one selected.'); } } - if (fieldsetContext) { - combinedProps = { - ...combinedProps, - isRegular: combinedProps.isRegular === undefined ? true : combinedProps.isRegular - }; + if (selectionValue !== undefined && selectionValue !== null) { + if (isMultiselectable && !Array.isArray(selectionValue)) { + throw new Error('Error: expected multiselectable useCombobox `selectionValue` to be an array.'); + } else if (!isMultiselectable && Array.isArray(selectionValue)) { + throw new Error('Error: expected useCombobox `selectionValue` not to be an array.'); + } } - if (type === 'radio') { - return React__default.createElement(StyledRadioLabel, Object.assign({ - ref: ref - }, combinedProps), React__default.createElement(StyledRadioSvg, null), props.children); - } else if (type === 'checkbox') { - const onLabelSelect = e => { - const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; - if (fieldContext && isFirefox && e.target instanceof Element) { - const inputId = e.target.getAttribute('for'); - if (!inputId) return; - const input = document.getElementById(inputId); - if (input && input.type === 'checkbox') { - if (e.shiftKey) { - input.click(); - input.checked = true; - } - input.focus(); + const handleDownshiftStateChange = reactExports.useCallback(_ref2 => { + let { + type, + isOpen, + selectedItem, + inputValue: _inputValue, + highlightedIndex + } = _ref2; + return onChange({ + type: toType(type), + ...(isOpen !== undefined && { + isExpanded: isOpen + }), + ...(selectedItem !== undefined && { + selectionValue: selectedItem + }), + ...(_inputValue !== undefined && { + inputValue: _inputValue + }), + ...(highlightedIndex !== undefined && { + activeIndex: highlightedIndex + }) + }); + }, [onChange]); + const stateReducer = (state, _ref3) => { + let { + type, + changes, + altKey + } = _ref3; + switch (type) { + case useCombobox$1.stateChangeTypes.ControlledPropUpdatedSelectedItem: + return state; + case useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex: + if (previousStateRef.current?.altKey) { + changes.highlightedIndex = -1; } - } - }; - combinedProps = { - ...combinedProps, - onClick: composeEventHandlers$5(combinedProps.onClick, onLabelSelect) - }; - return React__default.createElement(StyledCheckLabel, Object.assign({ - ref: ref - }, combinedProps), React__default.createElement(StyledCheckSvg, null), React__default.createElement(StyledDashSvg, null), props.children); - } else if (type === 'toggle') { - return React__default.createElement(StyledToggleLabel, Object.assign({ - ref: ref - }, combinedProps), React__default.createElement(StyledToggleSvg, null), props.children); - } - return React__default.createElement(StyledLabel$1, Object.assign({ - ref: ref - }, combinedProps)); -}); -Label$2.displayName = 'Label'; -Label$2.propTypes = { - isRegular: PropTypes.bool -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ -const VALIDATION = ['success', 'warning', 'error']; -const FILE_VALIDATION = ['success', 'error']; -const FILE_TYPE = ['pdf', 'zip', 'image', 'document', 'spreadsheet', 'presentation', 'generic']; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Message$1 = React__default.forwardRef((_ref, ref) => { - let { - validation, - validationLabel, - children, - ...props - } = _ref; - const { - hasMessage, - setHasMessage, - getMessageProps - } = useFieldContext$1() || {}; - const type = useInputContext(); - reactExports.useEffect(() => { - if (!hasMessage && setHasMessage) { - setHasMessage(true); + break; + case useCombobox$1.stateChangeTypes.FunctionCloseMenu: + case useCombobox$1.stateChangeTypes.InputBlur: + return { + ...state, + isOpen: type === useCombobox$1.stateChangeTypes.InputBlur && triggerContainsInput && isMultiselectable && state.isOpen || false + }; + case useCombobox$1.stateChangeTypes.InputClick: + if (!isAutocomplete) { + changes.isOpen = state.isOpen; + } + break; + case useCombobox$1.stateChangeTypes.InputKeyDownArrowDown: + case useCombobox$1.stateChangeTypes.FunctionOpenMenu: + if (state.isOpen !== changes.isOpen && !altKey) { + changes.highlightedIndex = 0; + } + break; + case useCombobox$1.stateChangeTypes.InputKeyDownArrowUp: + if (state.isOpen !== changes.isOpen) { + changes.highlightedIndex = values.length - 1; + } + break; + case useCombobox$1.stateChangeTypes.InputKeyDownEnter: + case useCombobox$1.stateChangeTypes.FunctionSelectItem: + case useCombobox$1.stateChangeTypes.ItemClick: + changes.highlightedIndex = state.highlightedIndex; + if (isMultiselectable) { + changes.isOpen = state.isOpen; + changes.inputValue = ''; + } + break; + case useCombobox$1.stateChangeTypes.InputKeyDownEscape: + return { + ...state, + isOpen: false + }; + case useCombobox$1.stateChangeTypes.InputKeyDownPageDown: + case useCombobox$1.stateChangeTypes.InputKeyDownPageUp: + return state; } - return () => { - if (hasMessage && setHasMessage) { - setHasMessage(false); + if (isMultiselectable && state.selectedItem !== changes.selectedItem) { + if (state.selectedItem !== undefined && state.selectedItem !== null && changes.selectedItem !== undefined && changes.selectedItem !== null) { + if (state.selectedItem.includes(changes.selectedItem)) { + changes.selectedItem = state.selectedItem.filter(value => value !== changes.selectedItem); + } else { + changes.selectedItem = [...state.selectedItem, changes.selectedItem]; + } + } else if (changes.selectedItem !== undefined && changes.selectedItem !== null) { + changes.selectedItem = [changes.selectedItem]; + } else { + changes.selectedItem = []; } + } + previousStateRef.current = { + type, + altKey, + ...state }; - }, [hasMessage, setHasMessage]); - let MessageComponent; - if (type === 'checkbox') { - MessageComponent = StyledCheckMessage; - } else if (type === 'radio') { - MessageComponent = StyledRadioMessage; - } else if (type === 'toggle') { - MessageComponent = StyledToggleMessage; - } else { - MessageComponent = StyledMessage$1; - } - let combinedProps = { - validation, - validationLabel, - ...props + return changes; }; - if (getMessageProps) { - combinedProps = getMessageProps(combinedProps); - } - const ariaLabel = useText(Message$1, combinedProps, 'validationLabel', validation, validation !== undefined); - return React__default.createElement(MessageComponent, Object.assign({ - ref: ref - }, combinedProps), validation && React__default.createElement(StyledMessageIcon, { - validation: validation, - "aria-label": ariaLabel - }), children); -}); -Message$1.displayName = 'Message'; -Message$1.propTypes = { - validation: PropTypes.oneOf(VALIDATION), - validationLabel: PropTypes.string -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Checkbox = React__default.forwardRef((_ref, ref) => { - let { - indeterminate, - children, - ...props - } = _ref; - const fieldsetContext = useFieldsetContext(); - const fieldContext = useFieldContext$1(); - const inputRef = inputElement => { - inputElement && (inputElement.indeterminate = indeterminate); - }; - const combinedRef = inputElement => { - [inputRef, ref].forEach(targetRef => { - if (targetRef) { - if (typeof targetRef === 'function') { - targetRef(inputElement); - } else { - targetRef.current = inputElement; - } - } + const transformValue = value => value ? toLabel(labels, value) : ''; + const { + selectedItem: _selectionValue, + isOpen: _isExpanded, + highlightedIndex: _activeIndex, + inputValue: _inputValue, + getToggleButtonProps: getDownshiftTriggerProps, + getInputProps: getDownshiftInputProps, + getMenuProps: getDownshiftListboxProps, + getItemProps: getDownshiftOptionProps, + closeMenu, + openMenu, + setHighlightedIndex, + selectItem + } = useCombobox$1({ + toggleButtonId: idRef.current.trigger, + menuId: idRef.current.listbox, + getItemId: idRef.current.getOptionId, + items: values, + inputValue: downshiftInputValue, + initialInputValue, + itemToString: transformValue , + selectedItem: selectionValue, + initialSelectedItem: initialSelectionValue, + isOpen: isExpanded, + defaultIsOpen: defaultExpanded, + initialIsOpen: initialExpanded, + highlightedIndex: activeIndex, + defaultHighlightedIndex: _defaultActiveIndex, + initialHighlightedIndex: initialActiveIndex, + onStateChange: handleDownshiftStateChange, + stateReducer, + environment: win + }); + const closeListbox = reactExports.useCallback(() => { + closeMenu(); + onChange({ + type: toType(useCombobox$1.stateChangeTypes.FunctionCloseMenu), + isExpanded: false }); - }; - let combinedProps = { - ref: combinedRef, - ...props, - ...fieldsetContext - }; - if (fieldContext) { - combinedProps = fieldContext.getInputProps(combinedProps); - } - return React__default.createElement(InputContext.Provider, { - value: "checkbox" - }, React__default.createElement(StyledCheckInput, combinedProps), children); -}); -Checkbox.displayName = 'Checkbox'; -Checkbox.propTypes = { - isCompact: PropTypes.bool, - indeterminate: PropTypes.bool -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const InputGroupContext = reactExports.createContext(undefined); -const useInputGroupContext = () => { - return reactExports.useContext(InputGroupContext); -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const Input = React__default.forwardRef((_ref, ref) => { - let { - onSelect, - ...props - } = _ref; - const fieldContext = useFieldContext$1(); - const inputGroupContext = useInputGroupContext(); - const onSelectHandler = props.readOnly ? composeEventHandlers$5(onSelect, event => { - event.currentTarget.select(); - }) : onSelect; - let combinedProps = { - ref, - onSelect: onSelectHandler, - ...props - }; - if (inputGroupContext) { - combinedProps = { - ...combinedProps, - isCompact: inputGroupContext.isCompact || combinedProps.isCompact, - focusInset: props.focusInset === undefined ? true : props.focusInset - }; - } - if (fieldContext) { - combinedProps = fieldContext.getInputProps(combinedProps); - } - return React__default.createElement(StyledTextInput, combinedProps); -}); -Input.propTypes = { - isCompact: PropTypes.bool, - isBare: PropTypes.bool, - focusInset: PropTypes.bool, - validation: PropTypes.oneOf(VALIDATION) -}; -Input.displayName = 'Input'; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const parseStyleValue = value => { - return parseInt(value, 10) || 0; -}; -const Textarea = React__default.forwardRef((_ref, ref) => { - let { - minRows, - maxRows, - style, - onChange, - onSelect, - ...props - } = _ref; - const fieldContext = useFieldContext$1(); - const textAreaRef = reactExports.useRef(); - const shadowTextAreaRef = reactExports.useRef(null); - const [state, setState] = reactExports.useState({ - overflow: false, - height: 0 + }, [closeMenu, onChange]); + const openListbox = reactExports.useCallback(() => { + openMenu(); + onChange({ + type: toType(useCombobox$1.stateChangeTypes.FunctionOpenMenu), + isExpanded: true + }); + }, [openMenu, onChange]); + const setActiveIndex = reactExports.useCallback(index => { + setHighlightedIndex(index); + onChange({ + type: toType(useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex), + activeIndex: index + }); + }, [onChange, setHighlightedIndex]); + const setDownshiftSelection = reactExports.useCallback(value => { + selectItem(value); + onChange({ + type: toType(useCombobox$1.stateChangeTypes.FunctionSelectItem), + selectionValue: value + }); + }, [onChange, selectItem]); + const { + getLabelProps: getFieldLabelProps, + getHintProps: getFieldHintProps, + getInputProps: getFieldInputProps, + getMessageProps: getFieldMessageProps + } = useField({ + hasHint, + hasMessage }); - const isControlled = props.value !== null && props.value !== undefined; - const isAutoResizable = (minRows !== undefined || maxRows !== undefined) && !props.isResizable; - const calculateHeight = reactExports.useCallback(() => { - if (!isAutoResizable) { - return; + reactExports.useLayoutEffect(() => { + if ((isAutocomplete || !isEditable) && _isExpanded && !previousStateRef.current?.isOpen && _selectionValue && !matchValue) { + const value = Array.isArray(_selectionValue) ? _selectionValue[_selectionValue.length - 1 + ] : _selectionValue; + const index = values.findIndex(current => current === value); + if (index !== -1) { + setActiveIndex(index); + } else if (_defaultActiveIndex !== undefined) { + setActiveIndex(_defaultActiveIndex); + } } - const textarea = textAreaRef.current; - const computedStyle = window.getComputedStyle(textarea); - const shadowTextArea = shadowTextAreaRef.current; - shadowTextArea.style.width = computedStyle.width; - shadowTextArea.value = textarea.value || textarea.placeholder || ' '; - const boxSizing = computedStyle.boxSizing; - const padding = parseStyleValue(computedStyle.paddingBottom) + parseStyleValue(computedStyle.paddingTop); - const border = parseStyleValue(computedStyle.borderTopWidth) + parseStyleValue(computedStyle.borderBottomWidth); - const innerHeight = shadowTextArea.scrollHeight - padding; - shadowTextArea.value = 'x'; - const singleRowHeight = shadowTextArea.scrollHeight - padding; - let outerHeight = innerHeight; - if (minRows) { - outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight); + }, [ + isAutocomplete, isEditable, _isExpanded, _selectionValue, _inputValue, values, _defaultActiveIndex, setActiveIndex]); + reactExports.useEffect( + () => setTriggerContainsInput(triggerRef.current?.contains(inputRef.current)), [triggerRef, inputRef]); + reactExports.useEffect(() => { + clearTimeout(matchTimeoutRef.current); + matchTimeoutRef.current = window.setTimeout(() => setMatchValue(''), 500); + return () => clearTimeout(matchTimeoutRef.current); + }, [matchValue]); + reactExports.useEffect(() => { + if (previousStateRef.current?.type === useCombobox$1.stateChangeTypes.FunctionSelectItem) { + if (isEditable) { + inputRef.current?.focus(); + } else { + triggerRef.current?.focus(); + } + previousStateRef.current = { + ...previousStateRef.current, + type: useCombobox$1.stateChangeTypes.InputClick + }; } - if (maxRows) { - outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight); + }); + reactExports.useEffect(() => { + if (isEditable && inputRef.current === win.document.activeElement) { + inputRef.current?.scrollIntoView && inputRef.current?.scrollIntoView({ + block: 'nearest' + }); } - outerHeight = Math.max(outerHeight, singleRowHeight); - const updatedHeight = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); - const overflow = Math.abs(outerHeight - innerHeight) <= 1; - setState(prevState => { - if (updatedHeight > 0 && Math.abs((prevState.height || 0) - updatedHeight) > 1 || prevState.overflow !== overflow) { - return { - overflow, - height: updatedHeight - }; - } - return prevState; + }, [inputRef, isEditable, win.document.activeElement]); + const getTriggerProps = reactExports.useCallback(function (_temp) { + let { + onBlur, + onClick, + onKeyDown, + ...other + } = _temp === void 0 ? {} : _temp; + const triggerProps = getDownshiftTriggerProps({ + 'data-garden-container-id': 'containers.combobox', + 'data-garden-container-version': '1.1.4', + onBlur, + onClick, + onKeyDown, + ref: triggerRef, + disabled, + ...other }); - }, [maxRows, minRows, textAreaRef, isAutoResizable]); - const onChangeHandler = reactExports.useCallback(e => { - if (!isControlled) { - calculateHeight(); - } - if (onChange) { - onChange(e); + const handleBlur = event => { + if (event.relatedTarget === null || !event.currentTarget?.contains(event.relatedTarget)) { + closeListbox(); + } + }; + if (isEditable && triggerContainsInput) { + const handleClick = event => { + if (disabled) { + event.preventDefault(); + } else if (isAutocomplete) { + triggerProps.onClick && triggerProps.onClick(event); + } else { + inputRef.current?.focus(); + } + }; + return { + ...triggerProps, + onBlur: composeEventHandlers$5(onBlur, handleBlur), + onClick: composeEventHandlers$5(onClick, handleClick), + 'aria-controls': isAutocomplete ? triggerProps['aria-controls'] : undefined, + 'aria-expanded': undefined, + 'aria-disabled': disabled || undefined, + disabled: undefined + }; + } else if (!isEditable) { + const { + 'aria-activedescendant': ariaActiveDescendant, + onKeyDown: onDownshiftKeyDown + } = getDownshiftInputProps({}, { + suppressRefError: true + }); + const handleKeyDown = event => { + event.stopPropagation(); + if (!_isExpanded && (event.key === KEYS$2.SPACE || event.key === KEYS$2.ENTER)) { + event.preventDefault(); + openListbox(); + } else if (_isExpanded && !matchValue && (event.key === KEYS$2.SPACE || event.key === KEYS$2.ENTER)) { + event.preventDefault(); + if (_activeIndex !== -1) { + setDownshiftSelection(values[_activeIndex]); + } + if (!isMultiselectable) { + closeListbox(); + } + } else if (/^(?:\S| ){1}$/u.test(event.key)) { + const _matchValue = `${matchValue}${event.key}`; + setMatchValue(_matchValue); + let offset = 0; + if (_isExpanded) { + if (_activeIndex !== -1) { + offset = _matchValue.length === 1 ? _activeIndex + 1 : _activeIndex; + } + } else { + openListbox(); + const offsetValue = Array.isArray(_selectionValue) ? _selectionValue[_selectionValue.length - 1 + ] : _selectionValue; + if (offsetValue !== null) { + offset = values.findIndex(current => current === offsetValue); + } + } + for (let index = 0; index < values.length; index++) { + const valueIndex = (index + offset) % values.length; + const value = values[valueIndex]; + if (toLabel(labels, value).toLowerCase().startsWith(_matchValue.toLowerCase())) { + setActiveIndex(valueIndex); + break; + } + } + } + }; + return { + ...triggerProps, + 'aria-activedescendant': ariaActiveDescendant, + 'aria-haspopup': 'listbox', + 'aria-labelledby': idRef.current.label, + 'aria-disabled': disabled || undefined, + disabled: undefined, + role: 'combobox', + onBlur: composeEventHandlers$5(onBlur, handleBlur), + onKeyDown: composeEventHandlers$5(onKeyDown, onDownshiftKeyDown, handleKeyDown), + tabIndex: disabled ? -1 : 0 + }; } - }, [calculateHeight, isControlled, onChange]); - reactExports.useLayoutEffect(() => { - calculateHeight(); - }); - const computedStyle = {}; - if (isAutoResizable) { - computedStyle.height = state.height; - computedStyle.overflow = state.overflow ? 'hidden' : undefined; - } - const onSelectHandler = props.readOnly ? composeEventHandlers$5(onSelect, event => { - event.currentTarget.select(); - }) : onSelect; - let combinedProps = { - ref: mergeRefs([textAreaRef, ref]), - rows: minRows, - onChange: onChangeHandler, - onSelect: onSelectHandler, - style: { - ...computedStyle, - ...style - }, - ...props - }; - if (fieldContext) { - combinedProps = fieldContext.getInputProps(combinedProps); - } - return React__default.createElement(React__default.Fragment, null, React__default.createElement(StyledTextarea, combinedProps), isAutoResizable && React__default.createElement(StyledTextarea, { - "aria-hidden": true, - readOnly: true, - isHidden: true, - className: props.className, - ref: shadowTextAreaRef, - tabIndex: -1, - isBare: props.isBare, - isCompact: props.isCompact, - style: style - })); -}); -Textarea.propTypes = { - isCompact: PropTypes.bool, - isBare: PropTypes.bool, - focusInset: PropTypes.bool, - isResizable: PropTypes.bool, - minRows: PropTypes.number, - maxRows: PropTypes.number, - validation: PropTypes.oneOf(VALIDATION) -}; -Textarea.displayName = 'Textarea'; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const StartIconComponent$1 = props => React__default.createElement(StyledTextMediaFigure, Object.assign({ - position: "start" -}, props)); -StartIconComponent$1.displayName = 'FauxInput.StartIcon'; -const StartIcon$1 = StartIconComponent$1; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const EndIconComponent = props => React__default.createElement(StyledTextMediaFigure, Object.assign({ - position: "end" -}, props)); -EndIconComponent.displayName = 'FauxInput.EndIcon'; -const EndIcon = EndIconComponent; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const FauxInputComponent = reactExports.forwardRef((_ref, ref) => { - let { - onFocus, - onBlur, - disabled, - readOnly, - isFocused: controlledIsFocused, + return triggerProps; + }, [getDownshiftTriggerProps, getDownshiftInputProps, triggerRef, disabled, _selectionValue, _isExpanded, _activeIndex, closeListbox, openListbox, setActiveIndex, setDownshiftSelection, matchValue, values, labels, triggerContainsInput, isAutocomplete, isEditable, isMultiselectable, inputRef]); + const getLabelProps = reactExports.useCallback(function (_temp2) { + let { + onClick, + ...other + } = _temp2 === void 0 ? {} : _temp2; + const { + htmlFor, + ...labelProps + } = getFieldLabelProps({ + id: idRef.current.label, + htmlFor: idRef.current.input, + ...other + }); + const handleClick = () => !isEditable && triggerRef.current?.focus(); + return { + ...labelProps, + onClick: composeEventHandlers$5(onClick, handleClick), + htmlFor: isEditable ? htmlFor : undefined + }; + }, [getFieldLabelProps, isEditable, triggerRef]); + const getHintProps = reactExports.useCallback(props => getFieldHintProps({ + id: idRef.current.hint, ...props - } = _ref; - const [isFocused, setIsFocused] = reactExports.useState(false); - const onFocusHandler = composeEventHandlers$5(onFocus, () => { - setIsFocused(true); - }); - const onBlurHandler = composeEventHandlers$5(onBlur, () => { - setIsFocused(false); - }); - return React__default.createElement(StyledTextFauxInput, Object.assign({ - onFocus: onFocusHandler, - onBlur: onBlurHandler, - isFocused: controlledIsFocused === undefined ? isFocused : controlledIsFocused, - isReadOnly: readOnly, - isDisabled: disabled, - tabIndex: disabled ? undefined : 0 - }, props, { - ref: ref - })); -}); -FauxInputComponent.displayName = 'FauxInput'; -FauxInputComponent.propTypes = { - isCompact: PropTypes.bool, - isBare: PropTypes.bool, - focusInset: PropTypes.bool, - disabled: PropTypes.bool, - readOnly: PropTypes.bool, - validation: PropTypes.oneOf(VALIDATION), - isFocused: PropTypes.bool, - isHovered: PropTypes.bool -}; -const FauxInput = FauxInputComponent; -FauxInput.EndIcon = EndIcon; -FauxInput.StartIcon = StartIcon$1; - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/** Used as references for various `Number` constants. */ -var NAN = 0 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; - -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; - -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max, - nativeMin = Math.min; - -/** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ -var now = function() { - return root.Date.now(); -}; - -/** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ -function debounce$2(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject$1(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - result = wait - timeSinceLastCall; - - return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); + }), [getFieldHintProps]); + const getInputProps = reactExports.useCallback(function (_temp3) { + let { + role = isEditable ? 'combobox' : null, + onChange: _onChange, + onClick, + onFocus, + ...other + } = _temp3 === void 0 ? {} : _temp3; + const inputProps = { + 'data-garden-container-id': 'containers.combobox.input', + 'data-garden-container-version': '1.1.4', + ref: inputRef, + role: role === null ? undefined : role, + onChange: _onChange, + onClick, + onFocus + }; + if (isEditable) { + const handleChange = event => { + if (inputValue !== undefined) { + setDownshiftInputValue(event.target.value); + useInputValueRef.current = false; + if (event.nativeEvent.isComposing) { + handleDownshiftStateChange({ + type: useCombobox$1.stateChangeTypes.InputChange, + inputValue: event.target.value + }); + } + } + }; + const handleClick = event => event.target instanceof Element && triggerRef.current?.contains(event.target) && event.stopPropagation(); + const describedBy = []; + if (hasHint) { + describedBy.push(idRef.current.hint); + } + if (hasMessage) { + describedBy.push(idRef.current.message); + } + return getDownshiftInputProps({ + ...inputProps, + disabled, + role, + 'aria-autocomplete': isAutocomplete ? 'list' : undefined, + onChange: composeEventHandlers$5(_onChange, handleChange), + onClick: composeEventHandlers$5(onClick, handleClick), + ...getFieldInputProps({ + id: idRef.current.input, + 'aria-labelledby': idRef.current.label, + 'aria-describedby': describedBy.length > 0 ? describedBy.join(' ') : undefined + }), + ...other + }); } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); + const downshiftInputProps = getDownshiftInputProps({ + ...inputProps, + disabled: true, + 'aria-autocomplete': undefined, + 'aria-activedescendant': undefined, + 'aria-controls': undefined, + 'aria-expanded': undefined, + 'aria-hidden': true, + 'aria-labelledby': undefined + }); + const handleFocus = () => { + if (!isEditable) { + triggerRef.current?.focus(); } - if (maxing) { - // Handle invocations in a tight loop. - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); + }; + return { + ...downshiftInputProps, + disabled, + readOnly: true, + tabIndex: -1, + onFocus: composeEventHandlers$5(onFocus, handleFocus), + ...other + }; + }, [getDownshiftInputProps, getFieldInputProps, handleDownshiftStateChange, hasHint, hasMessage, inputValue, inputRef, triggerRef, disabled, isAutocomplete, isEditable]); + const getTagProps = reactExports.useCallback(_ref4 => { + let { + option, + onClick, + onKeyDown, + ...other + } = _ref4; + const handleClick = event => event.target instanceof Element && triggerRef.current?.contains(event.target) && event.stopPropagation(); + const handleKeyDown = event => { + if (event.key === KEYS$2.BACKSPACE || event.key === KEYS$2.DELETE) { + setDownshiftSelection(option.value); + } else { + const triggerContainsTag = event.target instanceof Element && triggerRef.current?.contains(event.target); + if (triggerContainsTag && !isEditable) { + event.stopPropagation(); + } + if (triggerContainsTag && (event.key === KEYS$2.DOWN || event.key === KEYS$2.UP || event.key === KEYS$2.ESCAPE || !isEditable && (event.key === KEYS$2.ENTER || event.key === KEYS$2.SPACE))) { + const inputProps = getDownshiftInputProps(); + if (isEditable) { + inputRef.current?.focus(); + } else { + event.preventDefault(); + triggerRef.current?.focus(); + } + inputProps.onKeyDown && inputProps.onKeyDown(event); + } } + }; + return { + 'data-garden-container-id': 'containers.combobox.tag', + 'data-garden-container-version': '1.1.4', + onClick: composeEventHandlers$5(onClick, handleClick), + onKeyDown: composeEventHandlers$5(onKeyDown, handleKeyDown), + ...other + }; + }, [triggerRef, setDownshiftSelection, getDownshiftInputProps, isEditable, inputRef]); + const getListboxProps = reactExports.useCallback(_ref5 => { + let { + role = 'listbox', + ...other + } = _ref5; + return getDownshiftListboxProps({ + 'data-garden-container-id': 'containers.combobox.listbox', + 'data-garden-container-version': '1.1.4', + ref: listboxRef, + role, + 'aria-multiselectable': isMultiselectable ? true : undefined, + ...other + }); + }, [getDownshiftListboxProps, listboxRef, isMultiselectable]); + const getOptGroupProps = reactExports.useCallback(_ref6 => { + let { + role = 'group', + ...other + } = _ref6; + return { + 'data-garden-container-id': 'containers.combobox.optgroup', + 'data-garden-container-version': '1.1.4', + role: role === null ? undefined : role, + ...other + }; + }, []); + const getOptionProps = reactExports.useCallback(function (_temp4) { + let { + role = 'option', + option, + onMouseDown, + ...other + } = _temp4 === void 0 ? {} : _temp4; + const optionProps = { + 'data-garden-container-id': 'containers.combobox.option', + 'data-garden-container-version': '1.1.4', + role, + onMouseDown, + ...other + }; + let ariaSelected = false; + if (option?.value !== undefined) { + ariaSelected = Array.isArray(_selectionValue) ? _selectionValue?.includes(option?.value) : _selectionValue === option?.value; } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); + if (option?.hidden) { + return { + 'aria-disabled': option.disabled ? true : undefined, + 'aria-hidden': true, + 'aria-selected': ariaSelected, + id: option ? idRef.current.getOptionId(hiddenValues.indexOf(option.value), option.disabled, option.hidden) : undefined, + ...optionProps + }; } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; -} + if (option === undefined || option.disabled) { + const handleMouseDown = event => event.preventDefault(); + return { + 'aria-disabled': true, + 'aria-selected': ariaSelected, + id: option ? idRef.current.getOptionId(disabledValues.indexOf(option.value), option.disabled, option.hidden) : undefined, + ...optionProps, + onMouseDown: composeEventHandlers$5(onMouseDown, handleMouseDown) + }; + } + return getDownshiftOptionProps({ + item: option.value, + index: values.indexOf(option.value), + 'aria-disabled': undefined, + 'aria-hidden': undefined, + 'aria-selected': ariaSelected, + ...optionProps + }); + }, [getDownshiftOptionProps, disabledValues, hiddenValues, values, _selectionValue]); + const getMessageProps = reactExports.useCallback(props => getFieldMessageProps({ + id: idRef.current.message, + ...props + }), [getFieldMessageProps]); + const removeSelection = reactExports.useCallback(value => { + if (value === undefined) { + setDownshiftSelection(null); + } else { + const removeValue = typeof value === 'object' && 'value' in value ? value.value : value; + if (Array.isArray(_selectionValue) && _selectionValue.includes(removeValue)) { + setDownshiftSelection(removeValue); + } else if (_selectionValue === removeValue) { + setDownshiftSelection(null); + } else ; + } + }, [_selectionValue, setDownshiftSelection]); + const selection = reactExports.useMemo(() => { + if (Array.isArray(_selectionValue)) { + return _selectionValue.map(value => ({ + value, + label: labels[value], + disabled: disabledValues.includes(value), + hidden: hiddenValues.includes(value) + })); + } else if (_selectionValue) { + return { + value: _selectionValue, + label: toLabel(labels, _selectionValue), + disabled: disabledValues.includes(_selectionValue), + hidden: hiddenValues.includes(_selectionValue) + }; + } + return null; + }, [_selectionValue, disabledValues, hiddenValues, labels]); + return reactExports.useMemo(() => ({ + getLabelProps, + getHintProps, + getTriggerProps, + getInputProps, + getTagProps, + getListboxProps, + getOptGroupProps, + getOptionProps, + getMessageProps, + selection, + isExpanded: _isExpanded, + activeValue: values[_activeIndex], + inputValue: _inputValue, + removeSelection + }), [values, selection, _isExpanded, _activeIndex, _inputValue, getLabelProps, getHintProps, getTriggerProps, getInputProps, getTagProps, getListboxProps, getOptGroupProps, getOptionProps, getMessageProps, removeSelection]); +}; +({ + children: PropTypes.func, + render: PropTypes.func, + idPrefix: PropTypes.string, + triggerRef: PropTypes.any.isRequired, + inputRef: PropTypes.any.isRequired, + listboxRef: PropTypes.any.isRequired, + isAutocomplete: PropTypes.bool, + isMultiselectable: PropTypes.bool, + isEditable: PropTypes.bool, + disabled: PropTypes.bool, + hasHint: PropTypes.bool, + hasMessage: PropTypes.bool, + options: PropTypes.arrayOf(PropTypes.any).isRequired, + inputValue: PropTypes.string, + selectionValue: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), + isExpanded: PropTypes.bool, + defaultExpanded: PropTypes.bool, + initialExpanded: PropTypes.bool, + activeIndex: PropTypes.number, + defaultActiveIndex: PropTypes.number, + initialActiveIndex: PropTypes.number, + onChange: PropTypes.func, + environment: PropTypes.any +}); /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject$1(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject$1(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject$1(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} - -var lodash_debounce = debounce$2; +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -var debounce$3 = /*@__PURE__*/getDefaultExportFromCjs(lodash_debounce); +const FieldContext$1 = reactExports.createContext(undefined); +const useFieldContext$1 = () => { + const fieldContext = reactExports.useContext(FieldContext$1); + return fieldContext; +}; /** * Copyright Zendesk, Inc. @@ -12052,26 +12328,17 @@ var debounce$3 = /*@__PURE__*/getDefaultExportFromCjs(lodash_debounce); * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const FileUpload = React__default.forwardRef((_ref, ref) => { - let { - disabled, - ...props - } = _ref; - return ( - React__default.createElement(StyledFileUpload, Object.assign({ - ref: ref, - "aria-disabled": disabled - }, props, { - role: "button" - })) - ); -}); -FileUpload.propTypes = { - isDragging: PropTypes.bool, - isCompact: PropTypes.bool, - disabled: PropTypes.bool +const COMPONENT_ID$1u = 'forms.field'; +const StyledField$1 = styled.div.attrs({ + 'data-garden-id': COMPONENT_ID$1u, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledField", + componentId: "sc-12gzfsu-0" +})(["position:relative;direction:", ";margin:0;border:0;padding:0;font-size:0;", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => retrieveComponentStyles(COMPONENT_ID$1u, props)); +StyledField$1.defaultProps = { + theme: DEFAULT_THEME }; -FileUpload.displayName = 'FileUpload'; /** * Copyright Zendesk, Inc. @@ -12080,16 +12347,17 @@ FileUpload.displayName = 'FileUpload'; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const ItemComponent = reactExports.forwardRef((_ref, ref) => { - let { - ...props - } = _ref; - return React__default.createElement(StyledFileListItem, Object.assign({}, props, { - ref: ref - })); -}); -ItemComponent.displayName = 'FileList.Item'; -const Item = ItemComponent; +const COMPONENT_ID$1t = 'forms.input_label'; +const StyledLabel$1 = styled.label.attrs(props => ({ + 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1t, + 'data-garden-version': props['data-garden-version'] || '8.76.2' +})).withConfig({ + displayName: "StyledLabel", + componentId: "sc-2utmsz-0" +})(["direction:", ";vertical-align:middle;line-height:", ";color:", ";font-size:", ";font-weight:", ";&[hidden]{display:", ";vertical-align:", ";text-indent:", ";font-size:", ";", ";}", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.space.base * 5, props.theme.fontSizes.md), props => getColorV8('foreground', 600 , props.theme), props => props.theme.fontSizes.md, props => props.isRegular ? props.theme.fontWeights.regular : props.theme.fontWeights.semibold, props => props.isRadio ? 'inline-block' : 'inline', props => props.isRadio && 'top', props => props.isRadio && '-100%', props => props.isRadio && '0', props => !props.isRadio && hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$1t, props)); +StyledLabel$1.defaultProps = { + theme: DEFAULT_THEME +}; /** * Copyright Zendesk, Inc. @@ -12098,17 +12366,17 @@ const Item = ItemComponent; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const FileListComponent = reactExports.forwardRef((_ref, ref) => { - let { - ...props - } = _ref; - return React__default.createElement(StyledFileList, Object.assign({}, props, { - ref: ref - })); -}); -FileListComponent.displayName = 'FileList'; -const FileList = FileListComponent; -FileList.Item = Item; +const COMPONENT_ID$1s = 'forms.input_hint'; +const StyledHint$1 = styled.div.attrs(props => ({ + 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1s, + 'data-garden-version': props['data-garden-version'] || '8.76.2' +})).withConfig({ + displayName: "StyledHint", + componentId: "sc-17c2wu8-0" +})(["direction:", ";display:block;vertical-align:middle;line-height:", ";color:", ";font-size:", ";", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.space.base * 5, props.theme.fontSizes.md), props => getColorV8('neutralHue', 600, props.theme), props => props.theme.fontSizes.md, props => retrieveComponentStyles(COMPONENT_ID$1s, props)); +StyledHint$1.defaultProps = { + theme: DEFAULT_THEME +}; /** * Copyright Zendesk, Inc. @@ -12117,20 +12385,31 @@ FileList.Item = Item; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$C; -function _extends$G() { _extends$G = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$G.apply(this, arguments); } -var SvgXStroke$3 = function SvgXStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$G({ +var _g$4, _circle$7; +function _extends$N() { _extends$N = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$N.apply(this, arguments); } +var SvgAlertErrorStroke$1 = function SvgAlertErrorStroke(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$N({ xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, + width: 16, + height: 16, focusable: "false", - viewBox: "0 0 12 12", + viewBox: "0 0 16 16", "aria-hidden": "true" - }, props), _path$C || (_path$C = /*#__PURE__*/reactExports.createElement("path", { - stroke: "currentColor", + }, props), _g$4 || (_g$4 = /*#__PURE__*/reactExports.createElement("g", { + fill: "none", + stroke: "currentColor" + }, /*#__PURE__*/reactExports.createElement("circle", { + cx: 7.5, + cy: 8.5, + r: 7 + }), /*#__PURE__*/reactExports.createElement("path", { strokeLinecap: "round", - d: "M3 9l6-6m0 6L3 3" + d: "M7.5 4.5V9" + }))), _circle$7 || (_circle$7 = /*#__PURE__*/reactExports.createElement("circle", { + cx: 7.5, + cy: 12, + r: 1, + fill: "currentColor" }))); }; @@ -12141,20 +12420,26 @@ var SvgXStroke$3 = function SvgXStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$B; -function _extends$F() { _extends$F = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$F.apply(this, arguments); } -var SvgXStroke$2 = function SvgXStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$F({ +var _path$F, _circle$6; +function _extends$M() { _extends$M = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$M.apply(this, arguments); } +var SvgAlertWarningStroke$1 = function SvgAlertWarningStroke(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$M({ xmlns: "http://www.w3.org/2000/svg", width: 16, height: 16, focusable: "false", viewBox: "0 0 16 16", "aria-hidden": "true" - }, props), _path$B || (_path$B = /*#__PURE__*/reactExports.createElement("path", { + }, props), _path$F || (_path$F = /*#__PURE__*/reactExports.createElement("path", { + fill: "none", stroke: "currentColor", strokeLinecap: "round", - d: "M3 13L13 3m0 10L3 3" + d: "M.88 13.77L7.06 1.86c.19-.36.7-.36.89 0l6.18 11.91c.17.33-.07.73-.44.73H1.32c-.37 0-.61-.4-.44-.73zM7.5 6v3.5" + })), _circle$6 || (_circle$6 = /*#__PURE__*/reactExports.createElement("circle", { + cx: 7.5, + cy: 12, + r: 1, + fill: "currentColor" }))); }; @@ -12165,34 +12450,67 @@ var SvgXStroke$2 = function SvgXStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const FileContext = reactExports.createContext(undefined); -const useFileContext = () => { - return reactExports.useContext(FileContext); -}; - -/** -* Copyright Zendesk, Inc. +var _g$3; +function _extends$L() { _extends$L = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$L.apply(this, arguments); } +var SvgCheckCircleStroke$2 = function SvgCheckCircleStroke(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$L({ + xmlns: "http://www.w3.org/2000/svg", + width: 16, + height: 16, + focusable: "false", + viewBox: "0 0 16 16", + "aria-hidden": "true" + }, props), _g$3 || (_g$3 = /*#__PURE__*/reactExports.createElement("g", { + fill: "none", + stroke: "currentColor" + }, /*#__PURE__*/reactExports.createElement("path", { + strokeLinecap: "round", + strokeLinejoin: "round", + d: "M4 9l2.5 2.5 5-5" + }), /*#__PURE__*/reactExports.createElement("circle", { + cx: 7.5, + cy: 8.5, + r: 7 + })))); +}; + +/** +* Copyright Zendesk, Inc. * * Use of this source code is governed under the Apache License, Version 2.0 * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const CloseComponent$1 = React__default.forwardRef((props, ref) => { - const fileContext = useFileContext(); - const onMouseDown = composeEventHandlers$5(props.onMouseDown, event => event.preventDefault() - ); - const ariaLabel = useText(CloseComponent$1, props, 'aria-label', 'Close'); - return React__default.createElement(StyledFileClose, Object.assign({ - ref: ref, - "aria-label": ariaLabel - }, props, { - type: "button", - tabIndex: -1, - onMouseDown: onMouseDown - }), fileContext && fileContext.isCompact ? React__default.createElement(SvgXStroke$3, null) : React__default.createElement(SvgXStroke$2, null)); -}); -CloseComponent$1.displayName = 'File.Close'; -const Close$2 = CloseComponent$1; +const MessageIcon = _ref => { + let { + children, + validation, + ...props + } = _ref; + let retVal; + if (validation === 'error') { + retVal = React__default.createElement(SvgAlertErrorStroke$1, props); + } else if (validation === 'success') { + retVal = React__default.createElement(SvgCheckCircleStroke$2, props); + } else if (validation === 'warning') { + retVal = React__default.createElement(SvgAlertWarningStroke$1, props); + } else { + retVal = React__default.cloneElement(reactExports.Children.only(children)); + } + return retVal; +}; +const COMPONENT_ID$1r = 'forms.input_message_icon'; +const StyledMessageIcon = styled(MessageIcon).attrs({ + 'data-garden-id': COMPONENT_ID$1r, + 'data-garden-version': '8.76.2', + 'aria-hidden': null +}).withConfig({ + displayName: "StyledMessageIcon", + componentId: "sc-1ph2gba-0" +})(["width:", ";height:", ";", ";"], props => props.theme.iconSizes.md, props => props.theme.iconSizes.md, props => retrieveComponentStyles(COMPONENT_ID$1r, props)); +StyledMessageIcon.defaultProps = { + theme: DEFAULT_THEME +}; /** * Copyright Zendesk, Inc. @@ -12201,22 +12519,31 @@ const Close$2 = CloseComponent$1; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$A; -function _extends$E() { _extends$E = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$E.apply(this, arguments); } -var SvgTrashStroke$1 = function SvgTrashStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$E({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$A || (_path$A = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M4.5 2.5V1c0-.3.2-.5.5-.5h2c.3 0 .5.2.5.5v1.5M2 2.5h8m-5.5 7V5m3 4.5V5m-5-.5V11c0 .3.2.5.5.5h6c.3 0 .5-.2.5-.5V4.5" - }))); +const validationStyles = props => { + const rtl = props.theme.rtl; + const padding = math$1(`${props.theme.space.base} * 2px + ${props.theme.iconSizes.md}`); + let color; + if (props.validation === 'error') { + color = getColorV8('dangerHue', 600, props.theme); + } else if (props.validation === 'success') { + color = getColorV8('successHue', 600, props.theme); + } else if (props.validation === 'warning') { + color = getColorV8('warningHue', 700, props.theme); + } else { + color = getColorV8('neutralHue', 700, props.theme); + } + return Ne(["padding-", ":", ";color:", ";"], rtl ? 'right' : 'left', props.validation && padding, color); +}; +const COMPONENT_ID$1q = 'forms.input_message'; +const StyledMessage$1 = styled.div.attrs(props => ({ + 'data-garden-id': props['data-garden-id'] || COMPONENT_ID$1q, + 'data-garden-version': props['data-garden-version'] || '8.76.2' +})).withConfig({ + displayName: "StyledMessage", + componentId: "sc-30hgg7-0" +})(["direction:", ";display:inline-block;position:relative;vertical-align:middle;line-height:", ";font-size:", ";", ";& ", "{position:absolute;top:-1px;", ":0;}", ":not([hidden]) + &{display:block;margin-top:", ";}", ";"], props => props.theme.rtl && 'rtl', props => getLineHeight(props.theme.iconSizes.md, props.theme.fontSizes.sm), props => props.theme.fontSizes.sm, props => validationStyles(props), StyledMessageIcon, props => props.theme.rtl ? 'right' : 'left', StyledLabel$1, props => math$1(`${props.theme.space.base} * 1px`), props => retrieveComponentStyles(COMPONENT_ID$1q, props)); +StyledMessage$1.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12226,22 +12553,95 @@ var SvgTrashStroke$1 = function SvgTrashStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$z; -function _extends$D() { _extends$D = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$D.apply(this, arguments); } -var SvgTrashStroke = function SvgTrashStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$D({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$z || (_path$z = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M6.5 2.5V1c0-.3.2-.5.5-.5h2c.3 0 .5.2.5.5v1.5M3 2.5h10m-6.5 11v-8m3 8v-8m-6-1V15c0 .3.2.5.5.5h8c.3 0 .5-.2.5-.5V4.5" - }))); +const COMPONENT_ID$1p = 'forms.input'; +const isInvalid = validation => { + return validation === 'warning' || validation === 'error'; +}; +const colorStyles$p = props => { + const HUE = 'primaryHue'; + const SHADE = 600; + const placeholderColor = getColorV8('neutralHue', SHADE - 200, props.theme); + let borderColor; + let hoverBorderColor; + let focusBorderColor; + let focusRingHue = HUE; + let focusRingShade = SHADE; + if (props.validation) { + let hue = HUE; + if (props.validation === 'success') { + hue = 'successHue'; + } else if (props.validation === 'warning') { + hue = 'warningHue'; + focusRingShade = 700; + } else if (props.validation === 'error') { + hue = 'dangerHue'; + } + borderColor = getColorV8(hue, SHADE, props.theme); + hoverBorderColor = borderColor; + focusBorderColor = borderColor; + focusRingHue = hue; + } else { + borderColor = getColorV8('neutralHue', SHADE - 300, props.theme); + hoverBorderColor = getColorV8('primaryHue', SHADE, props.theme); + focusBorderColor = hoverBorderColor; + } + const readOnlyBackgroundColor = getColorV8('neutralHue', SHADE - 500, props.theme); + const readOnlyBorderColor = getColorV8('neutralHue', SHADE - 300, props.theme); + const disabledBackgroundColor = readOnlyBackgroundColor; + const disabledBorderColor = getColorV8('neutralHue', SHADE - 400, props.theme); + const disabledForegroundColor = getColorV8('neutralHue', SHADE - 200, props.theme); + let controlledBorderColor = borderColor; + if (props.isFocused) { + controlledBorderColor = focusBorderColor; + } + if (props.isHovered) { + controlledBorderColor = hoverBorderColor; + } + return Ne(["border-color:", ";background-color:", ";color:", ";&::placeholder{color:", ";}&[readonly],&[aria-readonly='true']{border-color:", ";background-color:", ";}&:hover{border-color:", ";}", " &:disabled,&[aria-disabled='true']{border-color:", ";background-color:", ";color:", ";}"], controlledBorderColor, props.isBare ? 'transparent' : getColorV8('background', 600 , props.theme), getColorV8('foreground', 600 , props.theme), placeholderColor, readOnlyBorderColor, !props.isBare && readOnlyBackgroundColor, hoverBorderColor, focusStyles({ + theme: props.theme, + inset: props.focusInset, + condition: !props.isBare, + hue: focusRingHue, + shade: focusRingShade, + styles: { + borderColor: focusBorderColor + } + }), disabledBorderColor, !props.isBare && disabledBackgroundColor, disabledForegroundColor); +}; +const sizeStyles$q = props => { + const fontSize = props.theme.fontSizes.md; + const paddingHorizontal = `${props.theme.space.base * 3}px`; + let height; + let paddingVertical; + let browseFontSize; + let swatchHeight; + if (props.isCompact) { + height = `${props.theme.space.base * 8}px`; + paddingVertical = `${props.theme.space.base * 1.5}px`; + browseFontSize = math$1(`${props.theme.fontSizes.sm} - 1`); + swatchHeight = `${props.theme.space.base * 6}px`; + } else { + height = `${props.theme.space.base * 10}px`; + paddingVertical = `${props.theme.space.base * 2.5}px`; + browseFontSize = props.theme.fontSizes.sm; + swatchHeight = `${props.theme.space.base * 7}px`; + } + const lineHeight = math$1(`${height} - (${paddingVertical} * 2) - (${props.theme.borderWidths.sm} * 2)`); + const padding = props.isBare ? '0' : `${em$1(paddingVertical, fontSize)} ${em$1(paddingHorizontal, fontSize)}`; + const swatchMarginVertical = math$1(`(${lineHeight} - ${swatchHeight}) / 2`); + const swatchMarginHorizontal = math$1(`${paddingVertical} + ${swatchMarginVertical} - ${paddingHorizontal}`); + return Ne(["padding:", ";min-height:", ";line-height:", ";font-size:", ";&::-ms-browse{font-size:", ";}&[type='date'],&[type='datetime-local'],&[type='file'],&[type='month'],&[type='time'],&[type='week']{max-height:", ";}&[type='file']{line-height:1;}@supports (-ms-ime-align:auto){&[type='color']{padding:", ";}}&::-moz-color-swatch{margin-top:", ";margin-left:", ";width:calc(100% + ", ");height:", ";}&::-webkit-color-swatch{margin:", " ", ";}", ":not([hidden]) + &&,", " + &&,", " + &&,&& + ", ",&& ~ ", "{margin-top:", "px;}"], padding, props.isBare ? '1em' : height, getLineHeight(lineHeight, fontSize), fontSize, browseFontSize, height, props.isCompact ? '0 2px' : '1px 3px', swatchMarginVertical, swatchMarginHorizontal, math$1(`${swatchMarginHorizontal} * -2`), swatchHeight, swatchMarginVertical, swatchMarginHorizontal, StyledLabel$1, StyledHint$1, StyledMessage$1, StyledHint$1, StyledMessage$1, props.theme.space.base * (props.isCompact ? 1 : 2)); +}; +const StyledTextInput = styled.input.attrs(props => ({ + 'data-garden-id': COMPONENT_ID$1p, + 'data-garden-version': '8.76.2', + 'aria-invalid': isInvalid(props.validation) +})).withConfig({ + displayName: "StyledTextInput", + componentId: "sc-k12n8x-0" +})(["appearance:none;transition:border-color 0.25s ease-in-out,box-shadow 0.1s ease-in-out,background-color 0.25s ease-in-out,color 0.25s ease-in-out,z-index 0.25s ease-in-out;direction:", ";border:", ";border-radius:", ";width:100%;box-sizing:border-box;vertical-align:middle;font-family:inherit;&::-ms-browse{border-radius:", ";}&::-ms-clear,&::-ms-reveal{display:none;}&::-moz-color-swatch{border:none;border-radius:", ";}&::-webkit-color-swatch{border:none;border-radius:", ";}&::-webkit-color-swatch-wrapper{padding:0;}&::-webkit-clear-button,&::-webkit-inner-spin-button,&::-webkit-search-cancel-button,&::-webkit-search-results-button{display:none;}&::-webkit-datetime-edit{direction:", ";line-height:1;}&::placeholder{opacity:1;}&:invalid{box-shadow:none;}&[type='file']::-ms-value{display:none;}@media screen and (min--moz-device-pixel-ratio:0){&[type='number']{appearance:textfield;}}", ";", ";&:disabled{cursor:default;}", ";"], props => props.theme.rtl && 'rtl', props => props.isBare ? 'none' : props.theme.borders.sm, props => props.isBare ? '0' : props.theme.borderRadii.md, props => props.theme.borderRadii.sm, props => props.theme.borderRadii.sm, props => props.theme.borderRadii.sm, props => props.theme.rtl && 'rtl', props => sizeStyles$q(props), props => colorStyles$p(props), props => retrieveComponentStyles(COMPONENT_ID$1p, props)); +StyledTextInput.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12251,22 +12651,27 @@ var SvgTrashStroke = function SvgTrashStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const DeleteComponent = React__default.forwardRef((props, ref) => { - const fileContext = useFileContext(); - const onMouseDown = composeEventHandlers$5(props.onMouseDown, event => event.preventDefault() - ); - const ariaLabel = useText(DeleteComponent, props, 'aria-label', 'Delete'); - return React__default.createElement(StyledFileDelete, Object.assign({ - ref: ref, - "aria-label": ariaLabel - }, props, { - type: "button", - tabIndex: -1, - onMouseDown: onMouseDown - }), fileContext && fileContext.isCompact ? React__default.createElement(SvgTrashStroke$1, null) : React__default.createElement(SvgTrashStroke, null)); -}); -DeleteComponent.displayName = 'File.Delete'; -const Delete = DeleteComponent; +const COMPONENT_ID$1o = 'forms.textarea'; +const hiddenStyles = ` + visibility: hidden; + position: absolute; + overflow: hidden; + height: 0; + top: 0; + left: 0; + transform: translateZ(0); +`; +const StyledTextarea = styled(StyledTextInput).attrs({ + as: 'textarea', + 'data-garden-id': COMPONENT_ID$1o, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledTextarea", + componentId: "sc-wxschl-0" +})(["resize:", ";overflow:auto;", ";", ";"], props => props.isResizable ? 'vertical' : 'none', props => props.isHidden && hiddenStyles, props => retrieveComponentStyles(COMPONENT_ID$1o, props)); +StyledTextarea.defaultProps = { + theme: DEFAULT_THEME +}; /** * Copyright Zendesk, Inc. @@ -12275,30 +12680,50 @@ const Delete = DeleteComponent; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$y, _rect$2; -function _extends$C() { _extends$C = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$C.apply(this, arguments); } -var SvgFilePdfStroke$1 = function SvgFilePdfStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$C({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$y || (_path$y = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M10.5 3.21V11a.5.5 0 01-.5.5H2a.5.5 0 01-.5-.5V1A.5.5 0 012 .5h5.79a.5.5 0 01.35.15l2.21 2.21a.5.5 0 01.15.35zM7.5.5V3a.5.5 0 00.5.5h2.5m-7 6h5" - })), _rect$2 || (_rect$2 = /*#__PURE__*/reactExports.createElement("rect", { - width: 6, - height: 3, - x: 3, - y: 5, - fill: "currentColor", - rx: 0.5, - ry: 0.5 - }))); +const COMPONENT_ID$1n = 'forms.media_figure'; +const colorStyles$o = props => { + let shade = 600; + if (props.isDisabled) { + shade = 400; + } else if (props.isHovered || props.isFocused) { + shade = 700; + } + return Ne(["color:", ";"], getColorV8('neutralHue', shade, props.theme)); +}; +const sizeStyles$p = props => { + const size = props.theme.iconSizes.md; + const marginFirst = `1px ${props.theme.space.base * 2}px auto 0`; + const marginLast = `1px 0 auto ${props.theme.space.base * 2}px`; + let margin; + if (props.position === 'start') { + margin = props.theme.rtl ? marginLast : marginFirst; + } else { + margin = props.theme.rtl ? marginFirst : marginLast; + } + return Ne(["margin:", ";width:", ";height:", ";"], margin, size, size); +}; +const StyledTextMediaFigure = styled( +_ref => { + let { + children, + position, + isHovered, + isFocused, + isDisabled, + isRotated, + theme, + ...props + } = _ref; + return React__default.cloneElement(reactExports.Children.only(children), props); +}).attrs({ + 'data-garden-id': COMPONENT_ID$1n, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledTextMediaFigure", + componentId: "sc-1qepknj-0" +})(["transform:", ";transition:transform 0.25s ease-in-out,color 0.25s ease-in-out;", ";", " ", ";"], props => props.isRotated && `rotate(${props.theme.rtl ? '-' : '+'}180deg)`, props => colorStyles$o(props), props => sizeStyles$p(props), props => retrieveComponentStyles(COMPONENT_ID$1n, props)); +StyledTextMediaFigure.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12308,22 +12733,51 @@ var SvgFilePdfStroke$1 = function SvgFilePdfStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$x; -function _extends$B() { _extends$B = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$B.apply(this, arguments); } -var SvgFileZipStroke$1 = function SvgFileZipStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$B({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$x || (_path$x = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M4.5.5v8m0-6h1m-2 1h1m0 1h1m-2 1h1m0 1h1m-2 1h1m6-4.29V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5" - }))); +const COMPONENT_ID$1m = 'forms.faux_input'; +const VALIDATION_HUES = { + success: 'successHue', + warning: 'warningHue', + error: 'dangerHue' +}; +function getValidationHue(validation) { + let defaultHue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'primaryHue'; + if (validation) { + return VALIDATION_HUES[validation]; + } + return defaultHue; +} +const colorStyles$n = props => { + const { + theme, + validation, + focusInset, + isBare, + isFocused + } = props; + return Ne(["", ""], focusStyles({ + theme, + inset: focusInset, + condition: !isBare, + hue: getValidationHue(validation), + shade: validation === 'warning' ? 700 : 600, + selector: isFocused ? '&' : '&:focus-within', + styles: { + borderColor: getColorV8(getValidationHue(validation), 600, theme) + } + })); +}; +const StyledTextFauxInput = styled(StyledTextInput).attrs(props => ({ + as: 'div', + 'aria-readonly': props.isReadOnly, + 'aria-disabled': props.isDisabled, + 'data-garden-id': COMPONENT_ID$1m, + 'data-garden-version': '8.76.2' +})).withConfig({ + displayName: "StyledTextFauxInput", + componentId: "sc-yqw7j9-0" +})(["display:", ";align-items:", ";cursor:", ";overflow:hidden;", " & > ", "{vertical-align:", ";", "{box-shadow:unset;}}& > ", "{flex-shrink:", ";}", ";"], props => props.mediaLayout ? 'inline-flex' : 'inline-block', props => props.mediaLayout && 'baseline', props => props.mediaLayout && !props.isDisabled ? 'text' : 'default', colorStyles$n, StyledTextInput, props => !props.mediaLayout && 'baseline', SELECTOR_FOCUS_VISIBLE, StyledTextMediaFigure, props => props.mediaLayout && '0', props => retrieveComponentStyles(COMPONENT_ID$1m, props)); +StyledTextFauxInput.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12333,28 +12787,17 @@ var SvgFileZipStroke$1 = function SvgFileZipStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$w, _circle$3; -function _extends$A() { _extends$A = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$A.apply(this, arguments); } -var SvgFileImageStroke$1 = function SvgFileImageStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$A({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$w || (_path$w = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - strokeLinejoin: "round", - d: "M10.5 3.21V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5m-7 6L5 8l1.5 1.5 1-1 1 1" - })), _circle$3 || (_circle$3 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 8, - cy: 6, - r: 1, - fill: "currentColor" - }))); +const COMPONENT_ID$1l = 'forms.media_input'; +const StyledTextMediaInput = styled(StyledTextInput).attrs({ + 'data-garden-id': COMPONENT_ID$1l, + 'data-garden-version': '8.76.2', + isBare: true +}).withConfig({ + displayName: "StyledTextMediaInput", + componentId: "sc-12i9xfi-0" +})(["flex-grow:1;", ";"], props => retrieveComponentStyles(COMPONENT_ID$1l, props)); +StyledTextMediaInput.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12364,22 +12807,23 @@ var SvgFileImageStroke$1 = function SvgFileImageStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$v; -function _extends$z() { _extends$z = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$z.apply(this, arguments); } -var SvgFileDocumentStroke$1 = function SvgFileDocumentStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$z({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$v || (_path$v = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M3.5 5.5h5m-5 2h5m-5 2h5m2-6.29V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5" - }))); +const COMPONENT_ID$1k = 'forms.radio_label'; +const sizeStyles$o = props => { + const size = props.theme.space.base * 4; + const padding = size + props.theme.space.base * 2; + const lineHeight = props.theme.space.base * 5; + return Ne(["padding-", ":", "px;&[hidden]{padding-", ":", "px;line-height:", "px;}"], props.theme.rtl ? 'right' : 'left', padding, props.theme.rtl ? 'right' : 'left', size, lineHeight); +}; +const StyledRadioLabel = styled(StyledLabel$1).attrs({ + 'data-garden-id': COMPONENT_ID$1k, + 'data-garden-version': '8.76.2', + isRadio: true +}).withConfig({ + displayName: "StyledRadioLabel", + componentId: "sc-1aq2e5t-0" +})(["display:inline-block;position:relative;cursor:pointer;", ";", ";"], props => sizeStyles$o(props), props => retrieveComponentStyles(COMPONENT_ID$1k, props)); +StyledRadioLabel.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12389,22 +12833,16 @@ var SvgFileDocumentStroke$1 = function SvgFileDocumentStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$u; -function _extends$y() { _extends$y = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$y.apply(this, arguments); } -var SvgFileSpreadsheetStroke$1 = function SvgFileSpreadsheetStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$y({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$u || (_path$u = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M3.5 5.5h1m-1 2h1m-1 2h1m2-4h2m-2 2h2m-2 2h2m2-6.29V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5" - }))); +const COMPONENT_ID$1j = 'forms.checkbox_label'; +const StyledCheckLabel = styled(StyledRadioLabel).attrs({ + 'data-garden-id': COMPONENT_ID$1j, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledCheckLabel", + componentId: "sc-x7nr1-0" +})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1j, props)); +StyledCheckLabel.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12414,21 +12852,16 @@ var SvgFileSpreadsheetStroke$1 = function SvgFileSpreadsheetStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$t; -function _extends$x() { _extends$x = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$x.apply(this, arguments); } -var SvgFilePresentationStroke$1 = function SvgFilePresentationStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$x({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$t || (_path$t = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - d: "M10.5 3.21V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM6 9.5h2c.28 0 .5-.22.5-.5V8c0-.28-.22-.5-.5-.5H6c-.28 0-.5.22-.5.5v1c0 .28.22.5.5.5zm-2-2h2c.28 0 .5-.22.5-.5V6c0-.28-.22-.5-.5-.5H4c-.28 0-.5.22-.5.5v1c0 .28.22.5.5.5zm3.5-7V3c0 .28.22.5.5.5h2.5" - }))); +const COMPONENT_ID$1i = 'forms.radio_hint'; +const StyledRadioHint = styled(StyledHint$1).attrs({ + 'data-garden-id': COMPONENT_ID$1i, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledRadioHint", + componentId: "sc-eo8twg-0" +})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 6px`), props => retrieveComponentStyles(COMPONENT_ID$1i, props)); +StyledRadioHint.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12438,21 +12871,16 @@ var SvgFilePresentationStroke$1 = function SvgFilePresentationStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$s; -function _extends$w() { _extends$w = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$w.apply(this, arguments); } -var SvgFileGenericStroke$1 = function SvgFileGenericStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$w({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$s || (_path$s = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - d: "M10.5 3.21V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5" - }))); +const COMPONENT_ID$1h = 'forms.checkbox_hint'; +const StyledCheckHint = styled(StyledRadioHint).attrs({ + 'data-garden-id': COMPONENT_ID$1h, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledCheckHint", + componentId: "sc-1kl8e8c-0" +})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1h, props)); +StyledCheckHint.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12462,28 +12890,52 @@ var SvgFileGenericStroke$1 = function SvgFileGenericStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _g$2; -function _extends$v() { _extends$v = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$v.apply(this, arguments); } -var SvgCheckCircleStroke$1 = function SvgCheckCircleStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$v({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _g$2 || (_g$2 = /*#__PURE__*/reactExports.createElement("g", { - fill: "none", - stroke: "currentColor" - }, /*#__PURE__*/reactExports.createElement("path", { - strokeLinecap: "round", - strokeLinejoin: "round", - d: "M3.5 6l2 2L9 4.5" - }), /*#__PURE__*/reactExports.createElement("circle", { - cx: 6, - cy: 6, - r: 5.5 - })))); +const COMPONENT_ID$1g = 'forms.radio'; +const colorStyles$m = props => { + const SHADE = 600; + const borderColor = getColorV8('neutralHue', SHADE - 300, props.theme); + const backgroundColor = getColorV8('background', 600 , props.theme); + const iconColor = backgroundColor; + const hoverBackgroundColor = getColorV8('primaryHue', SHADE, props.theme, 0.08); + const hoverBorderColor = getColorV8('primaryHue', SHADE, props.theme); + const focusBorderColor = hoverBorderColor; + const activeBackgroundColor = getColorV8('primaryHue', SHADE, props.theme, 0.2); + const activeBorderColor = focusBorderColor; + const checkedBorderColor = focusBorderColor; + const checkedBackgroundColor = checkedBorderColor; + const checkedHoverBorderColor = getColorV8('primaryHue', SHADE + 100, props.theme); + const checkedHoverBackgroundColor = checkedHoverBorderColor; + const checkedActiveBorderColor = getColorV8('primaryHue', SHADE + 200, props.theme); + const checkedActiveBackgroundColor = checkedActiveBorderColor; + const disabledBackgroundColor = getColorV8('neutralHue', SHADE - 400, props.theme); + return Ne(["& ~ ", "::before{border-color:", ";background-color:", ";}& ~ ", " > svg{color:", ";}& ~ ", ":hover::before{border-color:", ";background-color:", ";}", " & ~ ", ":active::before{border-color:", ";background-color:", ";}&:checked ~ ", "::before{border-color:", ";background-color:", ";}&:enabled:checked ~ ", ":hover::before{border-color:", ";background-color:", ";}&:enabled:checked ~ ", ":active::before{border-color:", ";background-color:", ";}&:disabled ~ ", "::before{border-color:transparent;background-color:", ";}"], StyledRadioLabel, borderColor, backgroundColor, StyledRadioLabel, iconColor, StyledRadioLabel, hoverBorderColor, hoverBackgroundColor, focusStyles({ + theme: props.theme, + styles: { + borderColor: focusBorderColor + }, + selector: `&:focus-visible ~ ${StyledRadioLabel}::before, &[data-garden-focus-visible='true'] ~ ${StyledRadioLabel}::before` + }), StyledRadioLabel, activeBorderColor, activeBackgroundColor, StyledRadioLabel, checkedBorderColor, checkedBackgroundColor, StyledRadioLabel, checkedHoverBorderColor, checkedHoverBackgroundColor, StyledRadioLabel, checkedActiveBorderColor, checkedActiveBackgroundColor, StyledRadioLabel, disabledBackgroundColor); +}; +const sizeStyles$n = props => { + const lineHeight = `${props.theme.space.base * 5}px`; + const size = `${props.theme.space.base * 4}px`; + const top = math$1(`(${lineHeight} - ${size}) / 2`); + const iconSize = props.theme.iconSizes.sm; + const iconPosition = math$1(`(${size} - ${iconSize}) / 2`); + const iconTop = math$1(`${iconPosition} + ${top}`); + const marginTop = `${props.theme.space.base * (props.isCompact ? 1 : 2)}px`; + return Ne(["top:", ";width:", ";height:", ";& ~ ", "::before{top:", ";background-size:", ";width:", ";height:", ";box-sizing:border-box;}& ~ ", " > svg{top:", ";", ":", ";width:", ";height:", ";}&& ~ ", " ~ ", "{margin-top:", ";}"], top, size, size, StyledRadioLabel, top, props.theme.iconSizes.sm, size, size, StyledRadioLabel, iconTop, props.theme.rtl ? 'right' : 'left', iconPosition, iconSize, iconSize, StyledRadioLabel, StyledMessage$1, marginTop); +}; +const StyledRadioInput = styled.input.attrs({ + 'data-garden-id': COMPONENT_ID$1g, + 'data-garden-version': '8.76.2', + type: 'radio' +}).withConfig({ + displayName: "StyledRadioInput", + componentId: "sc-qsavpv-0" +})(["position:absolute;opacity:0;margin:0;& ~ ", "::before{position:absolute;", ":0;transition:border-color .25s ease-in-out,box-shadow .1s ease-in-out,background-color .25s ease-in-out,color .25s ease-in-out;border:", ";border-radius:50%;background-repeat:no-repeat;background-position:center;content:'';}& ~ ", " > svg{position:absolute;}", ";&:focus ~ ", "::before{outline:none;}& ~ ", ":active::before{transition:border-color 0.1s ease-in-out,background-color 0.1s ease-in-out,color 0.1s ease-in-out;}", ";&:disabled ~ ", "{cursor:default;}", ";"], StyledRadioLabel, props => props.theme.rtl ? 'right' : 'left', props => props.theme.borders.sm, StyledRadioLabel, props => sizeStyles$n(props), StyledRadioLabel, StyledRadioLabel, props => colorStyles$m(props), StyledRadioLabel, props => retrieveComponentStyles(COMPONENT_ID$1g, props)); +StyledRadioInput.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12493,22 +12945,26 @@ var SvgCheckCircleStroke$1 = function SvgCheckCircleStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$r; -function _extends$u() { _extends$u = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$u.apply(this, arguments); } -var SvgFileErrorStroke$1 = function SvgFileErrorStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$u({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$r || (_path$r = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M10.5 3.21V11c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h5.79c.13 0 .26.05.35.15l2.21 2.21c.1.09.15.21.15.35zM7.5.5V3c0 .28.22.5.5.5h2.5M4 9.5l4-4m0 4l-4-4" - }))); +const COMPONENT_ID$1f = 'forms.checkbox'; +const colorStyles$l = props => { + const SHADE = 600; + const indeterminateBorderColor = getColorV8('primaryHue', SHADE, props.theme); + const indeterminateBackgroundColor = indeterminateBorderColor; + const indeterminateActiveBorderColor = getColorV8('primaryHue', SHADE + 100, props.theme); + const indeterminateActiveBackgroundColor = indeterminateActiveBorderColor; + const indeterminateDisabledBackgroundColor = getColorV8('neutralHue', SHADE - 400, props.theme); + return Ne(["&:indeterminate ~ ", "::before{border-color:", ";background-color:", ";}&:enabled:indeterminate ~ ", ":active::before{border-color:", ";background-color:", ";}&:disabled:indeterminate ~ ", "::before{border-color:transparent;background-color:", ";}"], StyledCheckLabel, indeterminateBorderColor, indeterminateBackgroundColor, StyledCheckLabel, indeterminateActiveBorderColor, indeterminateActiveBackgroundColor, StyledCheckLabel, indeterminateDisabledBackgroundColor); +}; +const StyledCheckInput = styled(StyledRadioInput).attrs({ + 'data-garden-id': COMPONENT_ID$1f, + 'data-garden-version': '8.76.2', + type: 'checkbox' +}).withConfig({ + displayName: "StyledCheckInput", + componentId: "sc-176jxxe-0" +})(["& ~ ", "::before{border-radius:", ";}", ";", ";"], StyledCheckLabel, props => props.theme.borderRadii.md, props => colorStyles$l(props), props => retrieveComponentStyles(COMPONENT_ID$1f, props)); +StyledCheckInput.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12518,30 +12974,16 @@ var SvgFileErrorStroke$1 = function SvgFileErrorStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$q, _rect$1; -function _extends$t() { _extends$t = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$t.apply(this, arguments); } -var SvgFilePdfStroke = function SvgFilePdfStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$t({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$q || (_path$q = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M14.5 4.2V15a.5.5 0 01-.5.5H2a.5.5 0 01-.5-.5V1A.5.5 0 012 .5h8.85a.5.5 0 01.36.15l3.15 3.2a.5.5 0 01.14.35zm-10 8.3h7m-7-2h7m-1-10V4a.5.5 0 00.5.5h3.5" - })), _rect$1 || (_rect$1 = /*#__PURE__*/reactExports.createElement("rect", { - width: 8, - height: 2, - x: 4, - y: 7, - fill: "currentColor", - rx: 0.5, - ry: 0.5 - }))); +const COMPONENT_ID$1e = 'forms.radio_message'; +const StyledRadioMessage = styled(StyledMessage$1).attrs({ + 'data-garden-id': COMPONENT_ID$1e, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledRadioMessage", + componentId: "sc-1pmi0q8-0" +})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 6px`), props => retrieveComponentStyles(COMPONENT_ID$1e, props)); +StyledRadioMessage.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12551,22 +12993,16 @@ var SvgFilePdfStroke = function SvgFilePdfStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$p; -function _extends$s() { _extends$s = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$s.apply(this, arguments); } -var SvgFileZipStroke = function SvgFileZipStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$s({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$p || (_path$p = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M6.5.5v11M5 2.5h1.5m0 1H8m-3 1h1.5m0 1H8m-3 1h1.5m0 1H8m-3 1h1.5m0 1H8m-3 1h1.5m8-6.3V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5" - }))); +const COMPONENT_ID$1d = 'forms.checkbox_message'; +const StyledCheckMessage = styled(StyledRadioMessage).attrs({ + 'data-garden-id': COMPONENT_ID$1d, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledCheckMessage", + componentId: "sc-s4p6kd-0" +})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$1d, props)); +StyledCheckMessage.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12576,26 +13012,23 @@ var SvgFileZipStroke = function SvgFileZipStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$o, _circle$2; -function _extends$r() { _extends$r = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$r.apply(this, arguments); } -var SvgFileImageStroke = function SvgFileImageStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$r({ +var _path$E; +function _extends$K() { _extends$K = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$K.apply(this, arguments); } +var SvgCheckSmFill = function SvgCheckSmFill(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$K({ xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, + width: 12, + height: 12, focusable: "false", - viewBox: "0 0 16 16", + viewBox: "0 0 12 12", "aria-hidden": "true" - }, props), _path$o || (_path$o = /*#__PURE__*/reactExports.createElement("path", { + }, props), _path$E || (_path$E = /*#__PURE__*/reactExports.createElement("path", { fill: "none", stroke: "currentColor", strokeLinecap: "round", - d: "M14.5 4.2V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5m-11 9l2.65-2.65c.2-.2.51-.2.71 0l1.79 1.79c.2.2.51.2.71 0l.79-.79c.2-.2.51-.2.71 0l1.65 1.65" - })), _circle$2 || (_circle$2 = /*#__PURE__*/reactExports.createElement("circle", { - cx: 10.5, - cy: 8.5, - r: 1.5, - fill: "currentColor" + strokeLinejoin: "round", + strokeWidth: 2, + d: "M3 6l2 2 4-4" }))); }; @@ -12606,22 +13039,16 @@ var SvgFileImageStroke = function SvgFileImageStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$n; -function _extends$q() { _extends$q = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$q.apply(this, arguments); } -var SvgFileDocumentStroke = function SvgFileDocumentStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$q({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$n || (_path$n = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M4.5 7.5h7m-7 1.97h7m-7 2h7m3-7.27V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5" - }))); +const COMPONENT_ID$1c = 'forms.check_svg'; +const StyledCheckSvg = styled(SvgCheckSmFill).attrs({ + 'data-garden-id': COMPONENT_ID$1c, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledCheckSvg", + componentId: "sc-fvxetk-0" +})(["transition:opacity 0.25s ease-in-out;opacity:0;pointer-events:none;", ":checked ~ ", " > &{opacity:1;}", ":indeterminate ~ ", " > &{opacity:0;}", ";"], StyledCheckInput, StyledCheckLabel, StyledCheckInput, StyledCheckLabel, props => retrieveComponentStyles(COMPONENT_ID$1c, props)); +StyledCheckSvg.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12631,21 +13058,21 @@ var SvgFileDocumentStroke = function SvgFileDocumentStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$m; -function _extends$p() { _extends$p = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$p.apply(this, arguments); } -var SvgFileSpreadsheetStroke = function SvgFileSpreadsheetStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$p({ +var _path$D; +function _extends$J() { _extends$J = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$J.apply(this, arguments); } +var SvgDashFill = function SvgDashFill(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$J({ xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, + width: 12, + height: 12, focusable: "false", - viewBox: "0 0 16 16", + viewBox: "0 0 12 12", "aria-hidden": "true" - }, props), _path$m || (_path$m = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", + }, props), _path$D || (_path$D = /*#__PURE__*/reactExports.createElement("path", { stroke: "currentColor", strokeLinecap: "round", - d: "M4.5 7.5h2m-2 2h2m-2 2h2m2-4h3m-3 2h3m-3 2h3m3-7.3V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5" + strokeWidth: 2, + d: "M3 6h6" }))); }; @@ -12656,21 +13083,16 @@ var SvgFileSpreadsheetStroke = function SvgFileSpreadsheetStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$l; -function _extends$o() { _extends$o = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$o.apply(this, arguments); } -var SvgFilePresentationStroke = function SvgFilePresentationStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$o({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$l || (_path$l = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - d: "M14.5 4.2V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5M7 9.5h4c.28 0 .5.22.5.5v3c0 .28-.22.5-.5.5H7c-.28 0-.5-.22-.5-.5v-3c0-.28.22-.5.5-.5zm-.5 2H5c-.28 0-.5-.22-.5-.5V8c0-.28.22-.5.5-.5h4c.28 0 .5.22.5.5v1.5" - }))); +const COMPONENT_ID$1b = 'forms.dash_svg'; +const StyledDashSvg = styled(SvgDashFill).attrs({ + 'data-garden-id': COMPONENT_ID$1b, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledDashSvg", + componentId: "sc-z3vq71-0" +})(["transition:opacity 0.25s ease-in-out;opacity:0;pointer-events:none;", ":indeterminate ~ ", " > &{opacity:1;}", ";"], StyledCheckInput, StyledCheckLabel, props => retrieveComponentStyles(COMPONENT_ID$1b, props)); +StyledDashSvg.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12680,21 +13102,35 @@ var SvgFilePresentationStroke = function SvgFilePresentationStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$k; -function _extends$n() { _extends$n = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$n.apply(this, arguments); } -var SvgFileGenericStroke = function SvgFileGenericStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$n({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$k || (_path$k = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - d: "M14.5 4.2V15c0 .28-.22.5-.5.5H2c-.28 0-.5-.22-.5-.5V1c0-.28.22-.5.5-.5h8.85c.13 0 .26.05.36.15l3.15 3.2c.09.1.14.22.14.35zm-4-3.7V4c0 .28.22.5.5.5h3.5" - }))); +const COMPONENT_ID$1a = 'forms.file_upload'; +const colorStyles$k = props => { + const baseColor = getColorV8('primaryHue', 600, props.theme); + const hoverColor = getColorV8('primaryHue', 700, props.theme); + const activeColor = getColorV8('primaryHue', 800, props.theme); + const disabledBackgroundColor = getColorV8('neutralHue', 200, props.theme); + const disabledForegroundColor = getColorV8('neutralHue', 400, props.theme); + return Ne(["border-color:", ";background-color:", ";color:", ";&:hover{border-color:", ";background-color:", ";color:", ";}", " &:active{border-color:", ";background-color:", ";color:", ";}&[aria-disabled='true']{border-color:", ";background-color:", ";color:", ";}"], props.isDragging ? activeColor : getColorV8('neutralHue', 600, props.theme), props.isDragging && rgba$1(baseColor, 0.2), props.isDragging ? activeColor : baseColor, hoverColor, rgba$1(baseColor, 0.08), hoverColor, focusStyles({ + theme: props.theme, + hue: baseColor + }), activeColor, rgba$1(baseColor, 0.2), activeColor, disabledForegroundColor, disabledBackgroundColor, disabledForegroundColor); +}; +const sizeStyles$m = props => { + const marginTop = `${props.theme.space.base * (props.isCompact ? 1 : 2)}px`; + const paddingHorizontal = `${props.isCompact ? 2 : 4}em`; + const paddingVertical = math$1(`${props.theme.space.base * (props.isCompact ? 2.5 : 5)} - ${props.theme.borderWidths.sm}`); + const fontSize = props.theme.fontSizes.md; + const lineHeight = getLineHeight(props.theme.space.base * 5, fontSize); + return Ne(["padding:", " ", ";min-width:4em;line-height:", ";font-size:", ";", ":not([hidden]) + &&,", " + &&,", " + &&,&& + ", ",&& + ", "{margin-top:", ";}"], paddingVertical, paddingHorizontal, lineHeight, fontSize, StyledLabel$1, StyledHint$1, StyledMessage$1, StyledHint$1, StyledMessage$1, marginTop); +}; +const StyledFileUpload = styled.div.attrs({ + 'data-garden-id': COMPONENT_ID$1a, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileUpload", + componentId: "sc-1rodjgn-0" +})(["display:flex;align-items:center;justify-content:center;box-sizing:border-box;direction:", ";transition:border-color 0.25s ease-in-out,box-shadow 0.1s ease-in-out,background-color 0.25s ease-in-out,color 0.25s ease-in-out;border:dashed ", ";border-radius:", ";cursor:pointer;text-align:center;user-select:none;", ";&[aria-disabled='true']{cursor:default;}", ";", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => props.theme.borderWidths.sm, props => props.theme.borderRadii.md, sizeStyles$m, colorStyles$k, props => retrieveComponentStyles(COMPONENT_ID$1a, props)); +StyledFileUpload.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12704,22 +13140,16 @@ var SvgFileGenericStroke = function SvgFileGenericStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -var _path$j; -function _extends$m() { _extends$m = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$m.apply(this, arguments); } -var SvgFileErrorStroke = function SvgFileErrorStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$m({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$j || (_path$j = /*#__PURE__*/reactExports.createElement("path", { - fill: "none", - stroke: "currentColor", - strokeLinecap: "round", - d: "M14.5 4.205V15a.5.5 0 01-.5.5H2a.5.5 0 01-.5-.5V1A.5.5 0 012 .5h8.853a.5.5 0 01.356.15l3.148 3.204a.5.5 0 01.143.35zM10.5.5V4a.5.5 0 00.5.5h3.5m-9 8l5-5m0 5l-5-5" - }))); +const COMPONENT_ID$19 = 'forms.file.close'; +const StyledFileClose = styled.button.attrs({ + 'data-garden-id': COMPONENT_ID$19, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileClose", + componentId: "sc-1m31jbf-0" +})(["display:flex;flex-shrink:0;align-items:center;justify-content:center;transition:opacity 0.25s ease-in-out;opacity:0.8;border:none;background:transparent;cursor:pointer;color:", ";appearance:none;&:hover{opacity:0.9;}&:focus{outline:none;}", ";"], props => getColorV8('foreground', 600 , props.theme), props => retrieveComponentStyles(COMPONENT_ID$19, props)); +StyledFileClose.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12729,27 +13159,67 @@ var SvgFileErrorStroke = function SvgFileErrorStroke(props) { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const fileIconsDefault = { - pdf: React__default.createElement(SvgFilePdfStroke, null), - zip: React__default.createElement(SvgFileZipStroke, null), - image: React__default.createElement(SvgFileImageStroke, null), - document: React__default.createElement(SvgFileDocumentStroke, null), - spreadsheet: React__default.createElement(SvgFileSpreadsheetStroke, null), - presentation: React__default.createElement(SvgFilePresentationStroke, null), - generic: React__default.createElement(SvgFileGenericStroke, null), - success: React__default.createElement(SvgCheckCircleStroke$2, null), - error: React__default.createElement(SvgFileErrorStroke, null) +const COMPONENT_ID$18 = 'forms.file'; +const colorStyles$j = props => { + let borderColor; + let focusBorderColor; + let foregroundColor; + if (props.validation === 'success') { + borderColor = getColorV8('successHue', 600, props.theme); + focusBorderColor = borderColor; + foregroundColor = borderColor; + } else if (props.validation === 'error') { + borderColor = getColorV8('dangerHue', 600, props.theme); + focusBorderColor = borderColor; + foregroundColor = borderColor; + } else { + borderColor = getColorV8('neutralHue', 300, props.theme); + focusBorderColor = getColorV8('primaryHue', 600, props.theme); + foregroundColor = getColorV8('foreground', 600 , props.theme); + } + return Ne(["border-color:", ";color:", ";", ""], borderColor, foregroundColor, focusStyles({ + theme: props.theme, + inset: props.focusInset, + hue: focusBorderColor, + styles: { + borderColor: focusBorderColor + } + })); }; -const fileIconsCompact = { - pdf: React__default.createElement(SvgFilePdfStroke$1, null), - zip: React__default.createElement(SvgFileZipStroke$1, null), - image: React__default.createElement(SvgFileImageStroke$1, null), - document: React__default.createElement(SvgFileDocumentStroke$1, null), - spreadsheet: React__default.createElement(SvgFileSpreadsheetStroke$1, null), - presentation: React__default.createElement(SvgFilePresentationStroke$1, null), - generic: React__default.createElement(SvgFileGenericStroke$1, null), - success: React__default.createElement(SvgCheckCircleStroke$1, null), - error: React__default.createElement(SvgFileErrorStroke$1, null) +const sizeStyles$l = props => { + const size = `${props.theme.space.base * (props.isCompact ? 7 : 10)}px`; + const spacing = `${props.theme.space.base * (props.isCompact ? 2 : 3)}px`; + const fontSize = props.theme.fontSizes.md; + const lineHeight = getLineHeight(props.theme.space.base * 5, fontSize); + return ` + box-sizing: border-box; + border: ${props.theme.borders.sm}; + border-radius: ${props.theme.borderRadii.md}; + padding: 0 ${spacing}; + height: ${size}; + line-height: ${lineHeight}; + font-size: ${fontSize}; + + & > span { + width: 100%; + } + + & > ${StyledFileClose} { + width: ${size}; + height: ${size}; + margin-${props.theme.rtl ? 'left' : 'right'}: -${spacing}; + } + `; +}; +const StyledFile = styled.div.attrs({ + 'data-garden-id': COMPONENT_ID$18, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFile", + componentId: "sc-195lzp1-0" +})(["display:flex;position:relative;flex-wrap:nowrap;align-items:center;transition:box-shadow 0.1s ease-in-out;", ";", ";& > span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}& > [role='progressbar']{position:absolute;bottom:0;left:0;transition:opacity 0.2s ease-in-out;margin:0;border-top-left-radius:0;border-top-right-radius:0;width:100%;& > div{border-top-", "-radius:0;}}& > [role='progressbar'][aria-valuenow='0'],& > [role='progressbar'][aria-valuenow='100']{opacity:0;}", ";"], sizeStyles$l, colorStyles$j, props => props.theme.rtl ? 'right' : 'left', props => retrieveComponentStyles(COMPONENT_ID$18, props)); +StyledFile.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -12759,40 +13229,44 @@ const fileIconsCompact = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const FileComponent = reactExports.forwardRef((_ref, ref) => { +const COMPONENT_ID$17 = 'forms.file.delete'; +const StyledFileDelete = styled(StyledFileClose).attrs({ + 'data-garden-id': COMPONENT_ID$17, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileDelete", + componentId: "sc-a8nnhx-0" +})(["color:", ";", ";"], props => getColorV8('dangerHue', 600, props.theme), props => retrieveComponentStyles(COMPONENT_ID$17, props)); +StyledFileDelete.defaultProps = { + theme: DEFAULT_THEME +}; + +/** +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ + +const COMPONENT_ID$16 = 'forms.file.icon'; +const StyledFileIcon = styled(_ref => { let { children, - type, isCompact, - focusInset, - validation, + theme, ...props } = _ref; - const fileContextValue = reactExports.useMemo(() => ({ - isCompact - }), [isCompact]); - const validationType = validation || type; - return React__default.createElement(FileContext.Provider, { - value: fileContextValue - }, React__default.createElement(StyledFile, Object.assign({}, props, { - isCompact: isCompact, - focusInset: focusInset, - validation: validation, - ref: ref - }), validationType && React__default.createElement(StyledFileIcon, { - isCompact: isCompact - }, isCompact ? fileIconsCompact[validationType] : fileIconsDefault[validationType]), reactExports.Children.map(children, child => typeof child === 'string' ? React__default.createElement("span", null, child) : child))); -}); -FileComponent.displayName = 'File'; -FileComponent.propTypes = { - focusInset: PropTypes.bool, - isCompact: PropTypes.bool, - type: PropTypes.oneOf(FILE_TYPE), - validation: PropTypes.oneOf(FILE_VALIDATION) + return React__default.cloneElement(reactExports.Children.only(children), props); +}).attrs({ + 'data-garden-id': COMPONENT_ID$16, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileIcon", + componentId: "sc-7b3q0c-0" +})(["flex-shrink:0;width:", ";margin-", ":", "px;", ";"], props => props.isCompact ? props.theme.iconSizes.sm : props.theme.iconSizes.md, props => props.theme.rtl ? 'left' : 'right', props => props.theme.space.base * 2, props => retrieveComponentStyles(COMPONENT_ID$16, props)); +StyledFileIcon.defaultProps = { + theme: DEFAULT_THEME }; -const File = FileComponent; -File.Close = Close$2; -File.Delete = Delete; /** * Copyright Zendesk, Inc. @@ -12801,102 +13275,17 @@ File.Delete = Delete; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const MediaInput = React__default.forwardRef((_ref, ref) => { - let { - start, - end, - disabled, - isCompact, - isBare, - focusInset, - readOnly, - validation, - wrapperProps = {}, - wrapperRef, - onSelect, - ...props - } = _ref; - const fieldContext = useFieldContext$1(); - const inputRef = reactExports.useRef(); - const [isFocused, setIsFocused] = reactExports.useState(false); - const [isHovered, setIsHovered] = reactExports.useState(false); - const { - onClick, - onFocus, - onBlur, - onMouseOver, - onMouseOut, - ...otherWrapperProps - } = wrapperProps; - const onFauxInputClickHandler = composeEventHandlers$5(onClick, () => { - inputRef.current && inputRef.current.focus(); - }); - const onFauxInputFocusHandler = composeEventHandlers$5(onFocus, () => { - setIsFocused(true); - }); - const onFauxInputBlurHandler = composeEventHandlers$5(onBlur, () => { - setIsFocused(false); - }); - const onFauxInputMouseOverHandler = composeEventHandlers$5(onMouseOver, () => { - setIsHovered(true); - }); - const onFauxInputMouseOutHandler = composeEventHandlers$5(onMouseOut, () => { - setIsHovered(false); - }); - const onSelectHandler = readOnly ? composeEventHandlers$5(onSelect, event => { - event.currentTarget.select(); - }) : onSelect; - let combinedProps = { - disabled, - readOnly, - ref: mergeRefs([inputRef, ref]), - onSelect: onSelectHandler, - ...props - }; - let isLabelHovered; - if (fieldContext) { - combinedProps = fieldContext.getInputProps(combinedProps); - isLabelHovered = fieldContext.isLabelHovered; - } - return React__default.createElement(FauxInput, Object.assign({ - tabIndex: null, - onClick: onFauxInputClickHandler, - onFocus: onFauxInputFocusHandler, - onBlur: onFauxInputBlurHandler, - onMouseOver: onFauxInputMouseOverHandler, - onMouseOut: onFauxInputMouseOutHandler, - disabled: disabled, - isFocused: isFocused, - isHovered: isHovered || isLabelHovered, - isCompact: isCompact, - isBare: isBare, - focusInset: focusInset, - readOnly: readOnly, - validation: validation, - mediaLayout: true - }, otherWrapperProps, { - ref: wrapperRef - }), start && React__default.createElement(FauxInput.StartIcon, { - isDisabled: disabled, - isFocused: isFocused, - isHovered: isHovered || isLabelHovered - }, start), React__default.createElement(StyledTextMediaInput, combinedProps), end && React__default.createElement(FauxInput.EndIcon, { - isDisabled: disabled, - isFocused: isFocused, - isHovered: isHovered || isLabelHovered - }, end)); -}); -MediaInput.propTypes = { - isCompact: PropTypes.bool, - isBare: PropTypes.bool, - focusInset: PropTypes.bool, - validation: PropTypes.oneOf(VALIDATION), - start: PropTypes.node, - end: PropTypes.node, - wrapperProps: PropTypes.object, - wrapperRef: PropTypes.any +const COMPONENT_ID$15 = 'forms.file_list'; +const StyledFileList = styled.ul.attrs({ + 'data-garden-id': COMPONENT_ID$15, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileList", + componentId: "sc-gbahjg-0" +})(["margin:0;padding:0;list-style:none;", ";"], props => retrieveComponentStyles(COMPONENT_ID$15, props)); +StyledFileList.defaultProps = { + theme: DEFAULT_THEME }; -MediaInput.displayName = 'MediaInput'; /** * Copyright Zendesk, Inc. @@ -12904,8 +13293,18 @@ MediaInput.displayName = 'MediaInput'; * Use of this source code is governed under the Apache License, Version 2.0 * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const SIZE$3 = ['small', 'medium', 'large']; -['inherit', ...SIZE$3]; + +const COMPONENT_ID$14 = 'forms.file_list.item'; +const StyledFileListItem = styled.li.attrs({ + 'data-garden-id': COMPONENT_ID$14, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledFileListItem", + componentId: "sc-1ova3lo-0" +})(["&:not(:first-child),", " ~ ", " > &:first-child{margin-top:", "px;}", ";"], StyledFileUpload, StyledFileList, props => props.theme.space.base * 2, props => retrieveComponentStyles(COMPONENT_ID$14, props)); +StyledFileListItem.defaultProps = { + theme: DEFAULT_THEME +}; /** * Copyright Zendesk, Inc. @@ -12914,59 +13313,22 @@ const SIZE$3 = ['small', 'medium', 'large']; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const COMPONENT_ID$_ = 'typography.font'; -[...SIZE$3, 'extralarge', '2xlarge', '3xlarge']; -const THEME_SIZES = { - small: 'sm', - medium: 'md', - large: 'lg', - extralarge: 'xl', - '2xlarge': 'xxl', - '3xlarge': 'xxxl' -}; -const fontStyles = props => { - const monospace = props.isMonospace && ['inherit', 'small', 'medium', 'large'].indexOf(props.size) !== -1; - const fontFamily = monospace && props.theme.fonts.mono; - const direction = props.theme.rtl ? 'rtl' : 'ltr'; - let fontSize; - let fontWeight; - let lineHeight; - let color; - if (monospace) { - if (props.size === 'inherit') { - fontSize = 'calc(1em - 1px)'; - lineHeight = 'normal'; - } else { - const themeSize = THEME_SIZES[props.size]; - fontSize = math$1(`${props.theme.fontSizes[themeSize]} - 1px`); - lineHeight = math$1(`${props.theme.lineHeights[themeSize]} - 1px`); - } - } else if (props.size !== 'inherit') { - const themeSize = THEME_SIZES[props.size]; - fontSize = props.theme.fontSizes[themeSize]; - lineHeight = props.theme.lineHeights[themeSize]; - } - if (props.isBold === true) { - fontWeight = props.theme.fontWeights.semibold; - } else if (props.isBold === false || props.size !== 'inherit') { - fontWeight = props.theme.fontWeights.regular; - } - if (props.hue) { - const shade = props.hue === 'yellow' ? 700 : 600; - color = getColorV8(props.hue, shade, props.theme); - } - return Ne(["line-height:", ";color:", ";font-family:", ";font-size:", ";font-weight:", ";direction:", ";"], lineHeight, color, fontFamily, fontSize, fontWeight, direction); -}; -const StyledFont = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$_, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFont", - componentId: "sc-1iildbo-0" -})(["", ";&[hidden]{display:inline;", ";}", ";"], props => !props.hidden && fontStyles(props), hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$_, props)); -StyledFont.defaultProps = { - theme: DEFAULT_THEME, - size: 'inherit' +var _circle$5; +function _extends$I() { _extends$I = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$I.apply(this, arguments); } +var SvgCircleSmFill$1 = function SvgCircleSmFill(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$I({ + xmlns: "http://www.w3.org/2000/svg", + width: 12, + height: 12, + focusable: "false", + viewBox: "0 0 12 12", + "aria-hidden": "true" + }, props), _circle$5 || (_circle$5 = /*#__PURE__*/reactExports.createElement("circle", { + cx: 6, + cy: 6, + r: 2, + fill: "currentColor" + }))); }; /** @@ -12976,27 +13338,15 @@ StyledFont.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const COMPONENT_ID$Z = 'typography.icon'; -const sizeStyles$j = props => { - const margin = props.isStart && `${props.theme.space.base * 2}px`; - const size = props.theme.iconSizes.md; - return Ne(["margin-", ":", ";width:", ";height:", ";"], props.theme.rtl ? 'left' : 'right', margin, size, size); -}; -const StyledIcon$1 = styled(_ref => { - let { - children, - isStart, - ...props - } = _ref; - return React__default.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$Z, +const COMPONENT_ID$13 = 'forms.radio_svg'; +const StyledRadioSvg = styled(SvgCircleSmFill$1).attrs({ + 'data-garden-id': COMPONENT_ID$13, 'data-garden-version': '8.76.2' }).withConfig({ - displayName: "StyledIcon", - componentId: "sc-10rfb5b-0" -})(["position:relative;top:-1px;vertical-align:middle;", ";", ";"], props => sizeStyles$j(props), props => retrieveComponentStyles(COMPONENT_ID$Z, props)); -StyledIcon$1.defaultProps = { + displayName: "StyledRadioSvg", + componentId: "sc-1r1qtr1-0" +})(["transition:opacity 0.25s ease-in-out;opacity:0;", ":checked ~ ", " > &{opacity:1;}", ";"], StyledRadioInput, StyledRadioLabel, props => retrieveComponentStyles(COMPONENT_ID$13, props)); +StyledRadioSvg.defaultProps = { theme: DEFAULT_THEME }; @@ -13007,15 +13357,20 @@ StyledIcon$1.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const COMPONENT_ID$Y = 'typography.paragraph'; -const StyledParagraph$1 = styled.p.attrs({ - 'data-garden-id': COMPONENT_ID$Y, +const COMPONENT_ID$12 = 'forms.toggle_label'; +const sizeStyles$k = props => { + const size = props.theme.space.base * 10; + const padding = size + props.theme.space.base * 2; + return Ne(["padding-", ":", "px;&[hidden]{padding-", ":", "px;}"], props.theme.rtl ? 'right' : 'left', padding, props.theme.rtl ? 'right' : 'left', size); +}; +const StyledToggleLabel = styled(StyledCheckLabel).attrs({ + 'data-garden-id': COMPONENT_ID$12, 'data-garden-version': '8.76.2' }).withConfig({ - displayName: "StyledParagraph", - componentId: "sc-zkuftz-0" -})(["margin:0;padding:0;direction:", ";& + &,blockquote + &{margin-top:", ";}", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => props.theme.lineHeights[THEME_SIZES[props.size]], props => retrieveComponentStyles(COMPONENT_ID$Y, props)); -StyledParagraph$1.defaultProps = { + displayName: "StyledToggleLabel", + componentId: "sc-e0asdk-0" +})(["", ";", ";"], props => sizeStyles$k(props), props => retrieveComponentStyles(COMPONENT_ID$12, props)); +StyledToggleLabel.defaultProps = { theme: DEFAULT_THEME }; @@ -13026,25 +13381,16 @@ StyledParagraph$1.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const SM = reactExports.forwardRef((_ref, ref) => { - let { - tag, - ...other - } = _ref; - return React__default.createElement(StyledFont, Object.assign({ - as: tag, - ref: ref, - size: "small" - }, other)); -}); -SM.displayName = 'SM'; -SM.propTypes = { - tag: PropTypes.any, - isBold: PropTypes.bool, - isMonospace: PropTypes.bool -}; -SM.defaultProps = { - tag: 'div' +const COMPONENT_ID$11 = 'forms.toggle_hint'; +const StyledToggleHint = styled(StyledHint$1).attrs({ + 'data-garden-id': COMPONENT_ID$11, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledToggleHint", + componentId: "sc-nziggu-0" +})(["padding-", ":", ";", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 12px`), props => retrieveComponentStyles(COMPONENT_ID$11, props)); +StyledToggleHint.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -13054,25 +13400,16 @@ SM.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const MD = reactExports.forwardRef((_ref, ref) => { - let { - tag, - ...other - } = _ref; - return React__default.createElement(StyledFont, Object.assign({ - as: tag, - ref: ref, - size: "medium" - }, other)); -}); -MD.displayName = 'MD'; -MD.propTypes = { - tag: PropTypes.any, - isBold: PropTypes.bool, - isMonospace: PropTypes.bool -}; -MD.defaultProps = { - tag: 'div' +const COMPONENT_ID$10 = 'forms.toggle_message'; +const StyledToggleMessage = styled(StyledMessage$1).attrs({ + 'data-garden-id': COMPONENT_ID$10, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledToggleMessage", + componentId: "sc-13vuvl1-0" +})(["padding-", ":", ";& ", "{", ":", ";}", ";"], props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 12px`), StyledMessageIcon, props => props.theme.rtl ? 'right' : 'left', props => math$1(`${props.theme.space.base} * 10px - ${props.theme.iconSizes.md}`), props => retrieveComponentStyles(COMPONENT_ID$10, props)); +StyledToggleMessage.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -13082,25 +13419,41 @@ MD.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const LG = reactExports.forwardRef((_ref, ref) => { - let { - tag, - ...other - } = _ref; - return React__default.createElement(StyledFont, Object.assign({ - as: tag, - ref: ref, - size: "large" - }, other)); -}); -LG.displayName = 'LG'; -LG.propTypes = { - tag: PropTypes.any, - isBold: PropTypes.bool, - isMonospace: PropTypes.bool +var _circle$4; +function _extends$H() { _extends$H = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$H.apply(this, arguments); } +var SvgCircleSmFill = function SvgCircleSmFill(props) { + return /*#__PURE__*/reactExports.createElement("svg", _extends$H({ + xmlns: "http://www.w3.org/2000/svg", + width: 16, + height: 16, + focusable: "false", + viewBox: "0 0 16 16", + "aria-hidden": "true" + }, props), _circle$4 || (_circle$4 = /*#__PURE__*/reactExports.createElement("circle", { + cx: 8, + cy: 8, + r: 6, + fill: "currentColor" + }))); }; -LG.defaultProps = { - tag: 'div' + +/** +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ + +const COMPONENT_ID$$ = 'forms.toggle_svg'; +const StyledToggleSvg = styled(SvgCircleSmFill).attrs({ + 'data-garden-id': COMPONENT_ID$$, + 'data-garden-version': '8.76.2' +}).withConfig({ + displayName: "StyledToggleSvg", + componentId: "sc-162xbyx-0" +})(["transition:all 0.15s ease-in-out;", ";"], props => retrieveComponentStyles(COMPONENT_ID$$, props)); +StyledToggleSvg.defaultProps = { + theme: DEFAULT_THEME }; /** @@ -13110,25 +13463,42 @@ LG.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const XXXL = reactExports.forwardRef((_ref, ref) => { - let { - tag, - ...other - } = _ref; - return React__default.createElement(StyledFont, Object.assign({ - as: tag, - ref: ref, - size: "3xlarge" - }, other)); +const Field$1 = React__default.forwardRef((props, ref) => { + const [hasHint, setHasHint] = reactExports.useState(false); + const [hasMessage, setHasMessage] = reactExports.useState(false); + const [isLabelActive, setIsLabelActive] = reactExports.useState(false); + const [isLabelHovered, setIsLabelHovered] = reactExports.useState(false); + const multiThumbRangeRef = reactExports.useRef(null); + const { + getInputProps, + getMessageProps, + ...propGetters + } = useField({ + idPrefix: props.id, + hasHint, + hasMessage + }); + const fieldProps = reactExports.useMemo(() => ({ + ...propGetters, + getInputProps, + getMessageProps, + isLabelActive, + setIsLabelActive, + isLabelHovered, + setIsLabelHovered, + hasHint, + setHasHint, + hasMessage, + setHasMessage, + multiThumbRangeRef + }), [propGetters, getInputProps, getMessageProps, isLabelActive, isLabelHovered, hasHint, hasMessage]); + return React__default.createElement(FieldContext$1.Provider, { + value: fieldProps + }, React__default.createElement(StyledField$1, Object.assign({}, props, { + ref: ref + }))); }); -XXXL.displayName = 'XXXL'; -XXXL.propTypes = { - tag: PropTypes.any, - isBold: PropTypes.bool -}; -XXXL.defaultProps = { - tag: 'div' -}; +Field$1.displayName = 'Field'; /** * Copyright Zendesk, Inc. @@ -13137,15 +13507,10 @@ XXXL.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const Paragraph = reactExports.forwardRef((props, ref) => React__default.createElement(StyledParagraph$1, Object.assign({ - ref: ref -}, props))); -Paragraph.displayName = 'Paragraph'; -Paragraph.propTypes = { - size: PropTypes.oneOf(SIZE$3) -}; -Paragraph.defaultProps = { - size: 'medium' +const FieldsetContext = reactExports.createContext(undefined); +const useFieldsetContext = () => { + const fieldsetContext = reactExports.useContext(FieldsetContext); + return fieldsetContext; }; /** @@ -13155,11 +13520,10 @@ Paragraph.defaultProps = { * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const StartIconComponent = props => React__default.createElement(StyledIcon$1, Object.assign({ - isStart: true -}, props)); -StartIconComponent.displayName = 'Span.StartIcon'; -const StartIcon = StartIconComponent; +const InputContext = reactExports.createContext(undefined); +const useInputContext = () => { + return reactExports.useContext(InputContext); +}; /** * Copyright Zendesk, Inc. @@ -13168,9 +13532,42 @@ const StartIcon = StartIconComponent; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const IconComponent = props => React__default.createElement(StyledIcon$1, props); -IconComponent.displayName = 'Span.Icon'; -const Icon = IconComponent; +const Hint$1 = React__default.forwardRef((props, ref) => { + const { + hasHint, + setHasHint, + getHintProps + } = useFieldContext$1() || {}; + const type = useInputContext(); + reactExports.useEffect(() => { + if (!hasHint && setHasHint) { + setHasHint(true); + } + return () => { + if (hasHint && setHasHint) { + setHasHint(false); + } + }; + }, [hasHint, setHasHint]); + let HintComponent; + if (type === 'checkbox') { + HintComponent = StyledCheckHint; + } else if (type === 'radio') { + HintComponent = StyledRadioHint; + } else if (type === 'toggle') { + HintComponent = StyledToggleHint; + } else { + HintComponent = StyledHint$1; + } + let combinedProps = props; + if (getHintProps) { + combinedProps = getHintProps(combinedProps); + } + return React__default.createElement(HintComponent, Object.assign({ + ref: ref + }, combinedProps)); +}); +Hint$1.displayName = 'Hint'; /** * Copyright Zendesk, Inc. @@ -13179,6972 +13576,4508 @@ const Icon = IconComponent; * found at http://www.apache.org/licenses/LICENSE-2.0. */ -const SpanComponent = reactExports.forwardRef((_ref, ref) => { - let { - tag, - ...other - } = _ref; - return React__default.createElement(StyledFont, Object.assign({ - as: tag, - ref: ref, - size: "inherit" - }, other)); +const Label$2 = React__default.forwardRef((props, ref) => { + const fieldContext = useFieldContext$1(); + const fieldsetContext = useFieldsetContext(); + const type = useInputContext(); + let combinedProps = props; + if (fieldContext) { + combinedProps = fieldContext.getLabelProps(combinedProps); + if (type === undefined) { + const { + setIsLabelActive, + setIsLabelHovered, + multiThumbRangeRef + } = fieldContext; + combinedProps = { + ...combinedProps, + onMouseUp: composeEventHandlers$5(props.onMouseUp, () => { + setIsLabelActive(false); + }), + onMouseDown: composeEventHandlers$5(props.onMouseDown, () => { + setIsLabelActive(true); + }), + onMouseEnter: composeEventHandlers$5(props.onMouseEnter, () => { + setIsLabelHovered(true); + }), + onMouseLeave: composeEventHandlers$5(props.onMouseLeave, () => { + setIsLabelHovered(false); + }), + onClick: composeEventHandlers$5(props.onClick, () => { + multiThumbRangeRef.current && multiThumbRangeRef.current.focus(); + }) + }; + } + } + if (fieldsetContext) { + combinedProps = { + ...combinedProps, + isRegular: combinedProps.isRegular === undefined ? true : combinedProps.isRegular + }; + } + if (type === 'radio') { + return React__default.createElement(StyledRadioLabel, Object.assign({ + ref: ref + }, combinedProps), React__default.createElement(StyledRadioSvg, null), props.children); + } else if (type === 'checkbox') { + const onLabelSelect = e => { + const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; + if (fieldContext && isFirefox && e.target instanceof Element) { + const inputId = e.target.getAttribute('for'); + if (!inputId) return; + const input = document.getElementById(inputId); + if (input && input.type === 'checkbox') { + if (e.shiftKey) { + input.click(); + input.checked = true; + } + input.focus(); + } + } + }; + combinedProps = { + ...combinedProps, + onClick: composeEventHandlers$5(combinedProps.onClick, onLabelSelect) + }; + return React__default.createElement(StyledCheckLabel, Object.assign({ + ref: ref + }, combinedProps), React__default.createElement(StyledCheckSvg, null), React__default.createElement(StyledDashSvg, null), props.children); + } else if (type === 'toggle') { + return React__default.createElement(StyledToggleLabel, Object.assign({ + ref: ref + }, combinedProps), React__default.createElement(StyledToggleSvg, null), props.children); + } + return React__default.createElement(StyledLabel$1, Object.assign({ + ref: ref + }, combinedProps)); }); -SpanComponent.displayName = 'Span'; -SpanComponent.propTypes = { - tag: PropTypes.any, - isBold: PropTypes.bool, - isMonospace: PropTypes.bool, - hue: PropTypes.string -}; -SpanComponent.defaultProps = { - tag: 'span' -}; -const Span = SpanComponent; -Span.Icon = Icon; -Span.StartIcon = StartIcon; - -let e=e=>"object"==typeof e&&null!=e&&1===e.nodeType,t=(e,t)=>(!t||"hidden"!==e)&&("visible"!==e&&"clip"!==e),n=(e,n)=>{if(e.clientHeight{let t=(e=>{if(!e.ownerDocument||!e.ownerDocument.defaultView)return null;try{return e.ownerDocument.defaultView.frameElement}catch(e){return null}})(e);return !!t&&(t.clientHeightot||o>e&&r=t&&d>=n?o-e-l:r>t&&dn?r-t+i:0,i=e=>{let t=e.parentElement;return null==t?e.getRootNode().host||null:t};var o=(t,o)=>{var r,d,h,f,u,s;if("undefined"==typeof document)return [];let{scrollMode:a,block:c,inline:g,boundary:m,skipOverflowHiddenElements:p}=o,w="function"==typeof m?m:e=>e!==m;if(!e(t))throw new TypeError("Invalid target");let W=document.scrollingElement||document.documentElement,H=[],b=t;for(;e(b)&&w(b);){if(b=i(b),b===W){H.push(b);break}null!=b&&b===document.body&&n(b)&&!n(document.documentElement)||null!=b&&n(b,p)&&H.push(b);}let v=null!=(d=null==(r=window.visualViewport)?void 0:r.width)?d:innerWidth,y=null!=(f=null==(h=window.visualViewport)?void 0:h.height)?f:innerHeight,E=null!=(u=window.scrollX)?u:pageXOffset,M=null!=(s=window.scrollY)?s:pageYOffset,{height:x,width:I,top:C,right:R,bottom:T,left:V}=t.getBoundingClientRect(),k="start"===c||"nearest"===c?C:"end"===c?T:C+x/2,B="center"===g?V+I/2:"end"===g?R:V,D=[];for(let e=0;e=0&&V>=0&&T<=y&&R<=v&&C>=o&&T<=d&&V>=h&&R<=r)return D;let f=getComputedStyle(t),u=parseInt(f.borderLeftWidth,10),s=parseInt(f.borderTopWidth,10),m=parseInt(f.borderRightWidth,10),p=parseInt(f.borderBottomWidth,10),w=0,b=0,O="offsetWidth"in t?t.offsetWidth-t.clientWidth-u-m:0,X="offsetHeight"in t?t.offsetHeight-t.clientHeight-s-p:0,Y="offsetWidth"in t?0===t.offsetWidth?0:i/t.offsetWidth:0,L="offsetHeight"in t?0===t.offsetHeight?0:n/t.offsetHeight:0;if(W===t)w="start"===c?k:"end"===c?k-y:"nearest"===c?l(M,M+y,y,s,p,M+k,M+k+x,x):k-y/2,b="start"===g?B:"center"===g?B-v/2:"end"===g?B-v:l(E,E+v,v,u,m,E+B,E+B+I,I),w=Math.max(0,w+M),b=Math.max(0,b+E);else {w="start"===c?k-o-s:"end"===c?k-d+p+X:"nearest"===c?l(o,d,n,s,p+X,k,k+x,x):k-(o+n/2)+X/2,b="start"===g?B-h-u:"center"===g?B-(h+i/2)+O/2:"end"===g?B-r+m+O:l(h,r,i,u,m+O,B,B+I,I);let{scrollLeft:e,scrollTop:f}=t;w=Math.max(0,Math.min(f+w/L,t.scrollHeight-n/L+X)),b=Math.max(0,Math.min(e+b/Y,t.scrollWidth-i/Y+O)),k+=f-w,B+=e-b;}D.push({el:t,top:w,left:b});}return D}; - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +Label$2.displayName = 'Label'; +Label$2.propTypes = { + isRegular: PropTypes.bool }; -var idCounter$2 = 0; -function noop$1() {} - /** - * Scroll node into view if necessary - * @param {HTMLElement} node the element that should scroll into view - * @param {HTMLElement} menuNode the menu element of the component - */ -function scrollIntoView(node, menuNode) { - if (!node) { - return; - } - var actions = o(node, { - boundary: menuNode, - block: 'nearest', - scrollMode: 'if-needed' - }); - actions.forEach(function (_ref) { - var el = _ref.el, - top = _ref.top, - left = _ref.left; - el.scrollTop = top; - el.scrollLeft = left; - }); -} +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ +const VALIDATION = ['success', 'warning', 'error']; +const FILE_VALIDATION = ['success', 'error']; +const FILE_TYPE = ['pdf', 'zip', 'image', 'document', 'spreadsheet', 'presentation', 'generic']; /** - * @param {HTMLElement} parent the parent node - * @param {HTMLElement} child the child node - * @param {Window} environment The window context where downshift renders. - * @return {Boolean} whether the parent is the child or the child is in the parent - */ -function isOrContainsNode(parent, child, environment) { - var result = parent === child || child instanceof environment.Node && parent.contains && parent.contains(child); - return result; -} +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -/** - * Simple debounce implementation. Will call the given - * function once after the time given has passed since - * it was last called. - * @param {Function} fn the function to call after the time - * @param {Number} time the time to wait - * @return {Function} the debounced function - */ -function debounce$1(fn, time) { - var timeoutId; - function cancel() { - if (timeoutId) { - clearTimeout(timeoutId); +const Message$1 = React__default.forwardRef((_ref, ref) => { + let { + validation, + validationLabel, + children, + ...props + } = _ref; + const { + hasMessage, + setHasMessage, + getMessageProps + } = useFieldContext$1() || {}; + const type = useInputContext(); + reactExports.useEffect(() => { + if (!hasMessage && setHasMessage) { + setHasMessage(true); } + return () => { + if (hasMessage && setHasMessage) { + setHasMessage(false); + } + }; + }, [hasMessage, setHasMessage]); + let MessageComponent; + if (type === 'checkbox') { + MessageComponent = StyledCheckMessage; + } else if (type === 'radio') { + MessageComponent = StyledRadioMessage; + } else if (type === 'toggle') { + MessageComponent = StyledToggleMessage; + } else { + MessageComponent = StyledMessage$1; } - function wrapper() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - cancel(); - timeoutId = setTimeout(function () { - timeoutId = null; - fn.apply(void 0, args); - }, time); + let combinedProps = { + validation, + validationLabel, + ...props + }; + if (getMessageProps) { + combinedProps = getMessageProps(combinedProps); } - wrapper.cancel = cancel; - return wrapper; -} + const ariaLabel = useText(Message$1, combinedProps, 'validationLabel', validation, validation !== undefined); + return React__default.createElement(MessageComponent, Object.assign({ + ref: ref + }, combinedProps), validation && React__default.createElement(StyledMessageIcon, { + validation: validation, + "aria-label": ariaLabel + }), children); +}); +Message$1.displayName = 'Message'; +Message$1.propTypes = { + validation: PropTypes.oneOf(VALIDATION), + validationLabel: PropTypes.string +}; /** - * This is intended to be used to compose event handlers. - * They are executed in order until one of them sets - * `event.preventDownshiftDefault = true`. - * @param {...Function} fns the event handler functions - * @return {Function} the event handler to add to an element - */ -function callAllEventHandlers() { - for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - fns[_key2] = arguments[_key2]; - } - return function (event) { - for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - return fns.some(function (fn) { - if (fn) { - fn.apply(void 0, [event].concat(args)); - } - return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault; - }); - }; -} -function handleRefs() { - for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - refs[_key4] = arguments[_key4]; - } - return function (node) { - refs.forEach(function (ref) { - if (typeof ref === 'function') { - ref(node); - } else if (ref) { - ref.current = node; +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ + +const Checkbox = React__default.forwardRef((_ref, ref) => { + let { + indeterminate, + children, + ...props + } = _ref; + const fieldsetContext = useFieldsetContext(); + const fieldContext = useFieldContext$1(); + const inputRef = inputElement => { + inputElement && (inputElement.indeterminate = indeterminate); + }; + const combinedRef = inputElement => { + [inputRef, ref].forEach(targetRef => { + if (targetRef) { + if (typeof targetRef === 'function') { + targetRef(inputElement); + } else { + targetRef.current = inputElement; + } } }); }; -} - -/** - * This generates a unique ID for an instance of Downshift - * @return {String} the unique ID - */ -function generateId() { - return String(idCounter$2++); -} - -/** - * Default implementation for status message. Only added when menu is open. - * Will specify if there are results in the list, and if so, how many, - * and what keys are relevant. - * - * @param {Object} param the downshift state and other relevant properties - * @return {String} the a11y status message - */ -function getA11yStatusMessage$1(_ref2) { - var isOpen = _ref2.isOpen, - resultCount = _ref2.resultCount, - previousResultCount = _ref2.previousResultCount; - if (!isOpen) { - return ''; - } - if (!resultCount) { - return 'No results are available.'; - } - if (resultCount !== previousResultCount) { - return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter key to select."; + let combinedProps = { + ref: combinedRef, + ...props, + ...fieldsetContext + }; + if (fieldContext) { + combinedProps = fieldContext.getInputProps(combinedProps); } - return ''; -} - -/** - * This will perform a shallow merge of the given state object - * with the state coming from props - * (for the controlled component scenario) - * This is used in state updater functions so they're referencing - * the right state regardless of where it comes from. - * - * @param {Object} state The state of the component/hook. - * @param {Object} props The props that may contain controlled values. - * @returns {Object} The merged controlled state. - */ -function getState(state, props) { - return Object.keys(state).reduce(function (prevState, key) { - prevState[key] = isControlledProp(props, key) ? props[key] : state[key]; - return prevState; - }, {}); -} + return React__default.createElement(InputContext.Provider, { + value: "checkbox" + }, React__default.createElement(StyledCheckInput, combinedProps), children); +}); +Checkbox.displayName = 'Checkbox'; +Checkbox.propTypes = { + isCompact: PropTypes.bool, + indeterminate: PropTypes.bool +}; /** - * This determines whether a prop is a "controlled prop" meaning it is - * state which is controlled by the outside of this component rather - * than within this component. - * - * @param {Object} props The props that may contain controlled values. - * @param {String} key the key to check - * @return {Boolean} whether it is a controlled controlled prop - */ -function isControlledProp(props, key) { - return props[key] !== undefined; -} +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -/** - * Normalizes the 'key' property of a KeyboardEvent in IE/Edge - * @param {Object} event a keyboardEvent object - * @return {String} keyboard key - */ -function normalizeArrowKey(event) { - var key = event.key, - keyCode = event.keyCode; - /* istanbul ignore next (ie) */ - if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) { - return "Arrow" + key; - } - return key; -} +const InputGroupContext = reactExports.createContext(undefined); +const useInputGroupContext = () => { + return reactExports.useContext(InputGroupContext); +}; /** - * Returns the next non-disabled highlightedIndex value. - * - * @param {number} start The current highlightedIndex. - * @param {number} offset The offset from the current highlightedIndex to start searching. - * @param {unknown[]} items The items array. - * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. - * @param {boolean?} circular If the search reaches the end, if it can search again starting from the other end. - * @returns {number} The next highlightedIndex. - */ -function getHighlightedIndex(start, offset, items, isItemDisabled, circular) { - if (circular === void 0) { - circular = false; - } - var count = items.length; - if (count === 0) { - return -1; - } - var itemsLastIndex = count - 1; - if (typeof start !== 'number' || start < 0 || start > itemsLastIndex) { - start = offset > 0 ? -1 : itemsLastIndex + 1; - } - var current = start + offset; - if (current < 0) { - current = circular ? itemsLastIndex : 0; - } else if (current > itemsLastIndex) { - current = circular ? 0 : itemsLastIndex; - } - var highlightedIndex = getNonDisabledIndex(current, offset < 0, items, isItemDisabled, circular); - if (highlightedIndex === -1) { - return start >= count ? -1 : start; - } - return highlightedIndex; -} +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -/** - * Returns the next non-disabled highlightedIndex value. - * - * @param {number} start The current highlightedIndex. - * @param {boolean} backwards If true, it will search backwards from the start. - * @param {unknown[]} items The items array. - * @param {(item: unknown, index: number) => boolean} isItemDisabled Function that tells if an item is disabled or not. - * @param {boolean} circular If the search reaches the end, if it can search again starting from the other end. - * @returns {number} The next non-disabled index. - */ -function getNonDisabledIndex(start, backwards, items, isItemDisabled, circular) { - if (circular === void 0) { - circular = false; - } - var count = items.length; - if (backwards) { - for (var index = start; index >= 0; index--) { - if (!isItemDisabled(items[index], index)) { - return index; - } - } - } else { - for (var _index = start; _index < count; _index++) { - if (!isItemDisabled(items[_index], _index)) { - return _index; - } - } +const Input = React__default.forwardRef((_ref, ref) => { + let { + onSelect, + ...props + } = _ref; + const fieldContext = useFieldContext$1(); + const inputGroupContext = useInputGroupContext(); + const onSelectHandler = props.readOnly ? composeEventHandlers$5(onSelect, event => { + event.currentTarget.select(); + }) : onSelect; + let combinedProps = { + ref, + onSelect: onSelectHandler, + ...props + }; + if (inputGroupContext) { + combinedProps = { + ...combinedProps, + isCompact: inputGroupContext.isCompact || combinedProps.isCompact, + focusInset: props.focusInset === undefined ? true : props.focusInset + }; } - if (circular) { - return getNonDisabledIndex(backwards ? count - 1 : 0, backwards, items, isItemDisabled); + if (fieldContext) { + combinedProps = fieldContext.getInputProps(combinedProps); } - return -1; -} + return React__default.createElement(StyledTextInput, combinedProps); +}); +Input.propTypes = { + isCompact: PropTypes.bool, + isBare: PropTypes.bool, + focusInset: PropTypes.bool, + validation: PropTypes.oneOf(VALIDATION) +}; +Input.displayName = 'Input'; /** - * Checks if event target is within the downshift elements. - * - * @param {EventTarget} target Target to check. - * @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc). - * @param {Window} environment The window context where downshift renders. - * @param {boolean} checkActiveElement Whether to also check activeElement. - * - * @returns {boolean} Whether or not the target is within downshift elements. - */ -function targetWithinDownshift(target, downshiftElements, environment, checkActiveElement) { - if (checkActiveElement === void 0) { - checkActiveElement = true; - } - return downshiftElements.some(function (contextNode) { - return contextNode && (isOrContainsNode(contextNode, target, environment) || checkActiveElement && isOrContainsNode(contextNode, environment.document.activeElement, environment)); - }); -} - -var cleanupStatus = debounce$1(function (documentProp) { - getStatusDiv(documentProp).textContent = ''; -}, 500); +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -/** - * @param {String} status the status message - * @param {Object} documentProp document passed by the user. - */ -function setStatus(status, documentProp) { - var div = getStatusDiv(documentProp); - if (!status) { - return; - } - div.textContent = status; - cleanupStatus(documentProp); -} - -/** - * Get the status node or create it if it does not already exist. - * @param {Object} documentProp document passed by the user. - * @return {HTMLElement} the status node. - */ -function getStatusDiv(documentProp) { - if (documentProp === void 0) { - documentProp = document; - } - var statusDiv = documentProp.getElementById('a11y-status-message'); - if (statusDiv) { - return statusDiv; - } - statusDiv = documentProp.createElement('div'); - statusDiv.setAttribute('id', 'a11y-status-message'); - statusDiv.setAttribute('role', 'status'); - statusDiv.setAttribute('aria-live', 'polite'); - statusDiv.setAttribute('aria-relevant', 'additions text'); - Object.assign(statusDiv.style, { - border: '0', - clip: 'rect(0 0 0 0)', - height: '1px', - margin: '-1px', - overflow: 'hidden', - padding: '0', - position: 'absolute', - width: '1px' - }); - documentProp.body.appendChild(statusDiv); - return statusDiv; -} - -var _excluded$3 = ["isInitialMount", "highlightedIndex", "items", "environment"]; -var dropdownDefaultStateValues = { - highlightedIndex: -1, - isOpen: false, - selectedItem: null, - inputValue: '' +const parseStyleValue = value => { + return parseInt(value, 10) || 0; }; -function callOnChangeProps(action, state, newState) { - var props = action.props, - type = action.type; - var changes = {}; - Object.keys(state).forEach(function (key) { - invokeOnChangeHandler(key, action, state, newState); - if (newState[key] !== state[key]) { - changes[key] = newState[key]; +const Textarea = React__default.forwardRef((_ref, ref) => { + let { + minRows, + maxRows, + style, + onChange, + onSelect, + ...props + } = _ref; + const fieldContext = useFieldContext$1(); + const textAreaRef = reactExports.useRef(); + const shadowTextAreaRef = reactExports.useRef(null); + const [state, setState] = reactExports.useState({ + overflow: false, + height: 0 + }); + const isControlled = props.value !== null && props.value !== undefined; + const isAutoResizable = (minRows !== undefined || maxRows !== undefined) && !props.isResizable; + const calculateHeight = reactExports.useCallback(() => { + if (!isAutoResizable) { + return; + } + const textarea = textAreaRef.current; + const computedStyle = window.getComputedStyle(textarea); + const shadowTextArea = shadowTextAreaRef.current; + shadowTextArea.style.width = computedStyle.width; + shadowTextArea.value = textarea.value || textarea.placeholder || ' '; + const boxSizing = computedStyle.boxSizing; + const padding = parseStyleValue(computedStyle.paddingBottom) + parseStyleValue(computedStyle.paddingTop); + const border = parseStyleValue(computedStyle.borderTopWidth) + parseStyleValue(computedStyle.borderBottomWidth); + const innerHeight = shadowTextArea.scrollHeight - padding; + shadowTextArea.value = 'x'; + const singleRowHeight = shadowTextArea.scrollHeight - padding; + let outerHeight = innerHeight; + if (minRows) { + outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight); + } + if (maxRows) { + outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight); } + outerHeight = Math.max(outerHeight, singleRowHeight); + const updatedHeight = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); + const overflow = Math.abs(outerHeight - innerHeight) <= 1; + setState(prevState => { + if (updatedHeight > 0 && Math.abs((prevState.height || 0) - updatedHeight) > 1 || prevState.overflow !== overflow) { + return { + overflow, + height: updatedHeight + }; + } + return prevState; + }); + }, [maxRows, minRows, textAreaRef, isAutoResizable]); + const onChangeHandler = reactExports.useCallback(e => { + if (!isControlled) { + calculateHeight(); + } + if (onChange) { + onChange(e); + } + }, [calculateHeight, isControlled, onChange]); + reactExports.useLayoutEffect(() => { + calculateHeight(); }); - if (props.onStateChange && Object.keys(changes).length) { - props.onStateChange(_extends$U({ - type: type - }, changes)); + const computedStyle = {}; + if (isAutoResizable) { + computedStyle.height = state.height; + computedStyle.overflow = state.overflow ? 'hidden' : undefined; } -} -function invokeOnChangeHandler(key, action, state, newState) { - var props = action.props, - type = action.type; - var handler = "on" + capitalizeString(key) + "Change"; - if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) { - props[handler](_extends$U({ - type: type - }, newState)); + const onSelectHandler = props.readOnly ? composeEventHandlers$5(onSelect, event => { + event.currentTarget.select(); + }) : onSelect; + let combinedProps = { + ref: mergeRefs([textAreaRef, ref]), + rows: minRows, + onChange: onChangeHandler, + onSelect: onSelectHandler, + style: { + ...computedStyle, + ...style + }, + ...props + }; + if (fieldContext) { + combinedProps = fieldContext.getInputProps(combinedProps); } -} + return React__default.createElement(React__default.Fragment, null, React__default.createElement(StyledTextarea, combinedProps), isAutoResizable && React__default.createElement(StyledTextarea, { + "aria-hidden": true, + readOnly: true, + isHidden: true, + className: props.className, + ref: shadowTextAreaRef, + tabIndex: -1, + isBare: props.isBare, + isCompact: props.isCompact, + style: style + })); +}); +Textarea.propTypes = { + isCompact: PropTypes.bool, + isBare: PropTypes.bool, + focusInset: PropTypes.bool, + isResizable: PropTypes.bool, + minRows: PropTypes.number, + maxRows: PropTypes.number, + validation: PropTypes.oneOf(VALIDATION) +}; +Textarea.displayName = 'Textarea'; /** - * Default state reducer that returns the changes. - * - * @param {Object} s state. - * @param {Object} a action with changes. - * @returns {Object} changes. - */ -function stateReducer(s, a) { - return a.changes; -} +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -/** - * Returns a message to be added to aria-live region when item is selected. - * - * @param {Object} selectionParameters Parameters required to build the message. - * @returns {string} The a11y message. - */ -function getA11ySelectionMessage(selectionParameters) { - var selectedItem = selectionParameters.selectedItem, - itemToStringLocal = selectionParameters.itemToString; - return selectedItem ? itemToStringLocal(selectedItem) + " has been selected." : ''; -} +const StartIconComponent$1 = props => React__default.createElement(StyledTextMediaFigure, Object.assign({ + position: "start" +}, props)); +StartIconComponent$1.displayName = 'FauxInput.StartIcon'; +const StartIcon$1 = StartIconComponent$1; /** - * Debounced call for updating the a11y message. - */ -var updateA11yStatus = debounce$1(function (getA11yMessage, document) { - setStatus(getA11yMessage(), document); -}, 200); +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -// istanbul ignore next -var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? reactExports.useLayoutEffect : reactExports.useEffect; +const EndIconComponent = props => React__default.createElement(StyledTextMediaFigure, Object.assign({ + position: "end" +}, props)); +EndIconComponent.displayName = 'FauxInput.EndIcon'; +const EndIcon = EndIconComponent; -// istanbul ignore next -var useElementIds = 'useId' in React__default // Avoid conditional useId call -? function useElementIds(_ref) { - var id = _ref.id, - labelId = _ref.labelId, - menuId = _ref.menuId, - getItemId = _ref.getItemId, - toggleButtonId = _ref.toggleButtonId, - inputId = _ref.inputId; - // Avoid conditional useId call - var reactId = "downshift-" + React__default.useId(); - if (!id) { - id = reactId; - } - var elementIdsRef = reactExports.useRef({ - labelId: labelId || id + "-label", - menuId: menuId || id + "-menu", - getItemId: getItemId || function (index) { - return id + "-item-" + index; - }, - toggleButtonId: toggleButtonId || id + "-toggle-button", - inputId: inputId || id + "-input" - }); - return elementIdsRef.current; -} : function useElementIds(_ref2) { - var _ref2$id = _ref2.id, - id = _ref2$id === void 0 ? "downshift-" + generateId() : _ref2$id, - labelId = _ref2.labelId, - menuId = _ref2.menuId, - getItemId = _ref2.getItemId, - toggleButtonId = _ref2.toggleButtonId, - inputId = _ref2.inputId; - var elementIdsRef = reactExports.useRef({ - labelId: labelId || id + "-label", - menuId: menuId || id + "-menu", - getItemId: getItemId || function (index) { - return id + "-item-" + index; - }, - toggleButtonId: toggleButtonId || id + "-toggle-button", - inputId: inputId || id + "-input" +/** +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ + +const FauxInputComponent = reactExports.forwardRef((_ref, ref) => { + let { + onFocus, + onBlur, + disabled, + readOnly, + isFocused: controlledIsFocused, + ...props + } = _ref; + const [isFocused, setIsFocused] = reactExports.useState(false); + const onFocusHandler = composeEventHandlers$5(onFocus, () => { + setIsFocused(true); }); - return elementIdsRef.current; + const onBlurHandler = composeEventHandlers$5(onBlur, () => { + setIsFocused(false); + }); + return React__default.createElement(StyledTextFauxInput, Object.assign({ + onFocus: onFocusHandler, + onBlur: onBlurHandler, + isFocused: controlledIsFocused === undefined ? isFocused : controlledIsFocused, + isReadOnly: readOnly, + isDisabled: disabled, + tabIndex: disabled ? undefined : 0 + }, props, { + ref: ref + })); +}); +FauxInputComponent.displayName = 'FauxInput'; +FauxInputComponent.propTypes = { + isCompact: PropTypes.bool, + isBare: PropTypes.bool, + focusInset: PropTypes.bool, + disabled: PropTypes.bool, + readOnly: PropTypes.bool, + validation: PropTypes.oneOf(VALIDATION), + isFocused: PropTypes.bool, + isHovered: PropTypes.bool }; -function getItemAndIndex(itemProp, indexProp, items, errorMessage) { - var item, index; - if (itemProp === undefined) { - if (indexProp === undefined) { - throw new Error(errorMessage); - } - item = items[indexProp]; - index = indexProp; - } else { - index = indexProp === undefined ? items.indexOf(itemProp) : indexProp; - item = itemProp; - } - return [item, index]; -} -function itemToString(item) { - return item ? String(item) : ''; -} -function capitalizeString(string) { - return "" + string.slice(0, 1).toUpperCase() + string.slice(1); -} -function useLatestRef$1(val) { - var ref = reactExports.useRef(val); - // technically this is not "concurrent mode safe" because we're manipulating - // the value during render (so it's not idempotent). However, the places this - // hook is used is to support memoizing callbacks which will be called - // *during* render, so we need the latest values *during* render. - // If not for this, then we'd probably want to use useLayoutEffect instead. - ref.current = val; - return ref; -} +const FauxInput = FauxInputComponent; +FauxInput.EndIcon = EndIcon; +FauxInput.StartIcon = StartIcon$1; /** - * Computes the controlled state using a the previous state, props, - * two reducers, one from downshift and an optional one from the user. - * Also calls the onChange handlers for state values that have changed. - * - * @param {Function} reducer Reducer function from downshift. - * @param {Object} initialState Initial state of the hook. - * @param {Object} props The hook props. - * @returns {Array} An array with the state and an action dispatcher. + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ -function useEnhancedReducer(reducer, initialState, props) { - var prevStateRef = reactExports.useRef(); - var actionRef = reactExports.useRef(); - var enhancedReducer = reactExports.useCallback(function (state, action) { - actionRef.current = action; - state = getState(state, action.props); - var changes = reducer(state, action); - var newState = action.props.stateReducer(state, _extends$U({}, action, { - changes: changes - })); - return newState; - }, [reducer]); - var _useReducer = reactExports.useReducer(enhancedReducer, initialState), - state = _useReducer[0], - dispatch = _useReducer[1]; - var propsRef = useLatestRef$1(props); - var dispatchWithProps = reactExports.useCallback(function (action) { - return dispatch(_extends$U({ - props: propsRef.current - }, action)); - }, [propsRef]); - var action = actionRef.current; - reactExports.useEffect(function () { - if (action && prevStateRef.current && prevStateRef.current !== state) { - callOnChangeProps(action, getState(prevStateRef.current, action.props), state); - } - prevStateRef.current = state; - }, [state, props, action]); - return [state, dispatchWithProps]; -} -var defaultProps$3 = { - itemToString: itemToString, - stateReducer: stateReducer, - getA11ySelectionMessage: getA11ySelectionMessage, - scrollIntoView: scrollIntoView, - environment: /* istanbul ignore next (ssr) */ - typeof window === 'undefined' ? {} : window -}; -function getDefaultValue$1(props, propKey, defaultStateValues) { - if (defaultStateValues === void 0) { - defaultStateValues = dropdownDefaultStateValues; - } - var defaultValue = props["default" + capitalizeString(propKey)]; - if (defaultValue !== undefined) { - return defaultValue; - } - return defaultStateValues[propKey]; -} -function getInitialValue$1(props, propKey, defaultStateValues) { - if (defaultStateValues === void 0) { - defaultStateValues = dropdownDefaultStateValues; - } - var value = props[propKey]; - if (value !== undefined) { - return value; - } - var initialValue = props["initial" + capitalizeString(propKey)]; - if (initialValue !== undefined) { - return initialValue; - } - return getDefaultValue$1(props, propKey, defaultStateValues); -} -function getInitialState$2(props) { - var selectedItem = getInitialValue$1(props, 'selectedItem'); - var isOpen = getInitialValue$1(props, 'isOpen'); - var highlightedIndex = getInitialValue$1(props, 'highlightedIndex'); - var inputValue = getInitialValue$1(props, 'inputValue'); - return { - highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex, - isOpen: isOpen, - selectedItem: selectedItem, - inputValue: inputValue - }; -} -function getHighlightedIndexOnOpen(props, state, offset) { - var items = props.items, - initialHighlightedIndex = props.initialHighlightedIndex, - defaultHighlightedIndex = props.defaultHighlightedIndex; - var selectedItem = state.selectedItem, - highlightedIndex = state.highlightedIndex; - if (items.length === 0) { - return -1; - } - // initialHighlightedIndex will give value to highlightedIndex on initial state only. - if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) { - return initialHighlightedIndex; - } - if (defaultHighlightedIndex !== undefined) { - return defaultHighlightedIndex; - } - if (selectedItem) { - return items.indexOf(selectedItem); - } - if (offset === 0) { - return -1; - } - return offset < 0 ? items.length - 1 : 0; -} +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; /** - * Reuse the movement tracking of mouse and touch events. - * - * @param {boolean} isOpen Whether the dropdown is open or not. - * @param {Array} downshiftElementRefs Downshift element refs to track movement (toggleButton, menu etc.) - * @param {Object} environment Environment where component/hook exists. - * @param {Function} handleBlur Handler on blur from mouse or touch. - * @returns {Object} Ref containing whether mouseDown or touchMove event is happening + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ -function useMouseAndTouchTracker(isOpen, downshiftElementRefs, environment, handleBlur) { - var mouseAndTouchTrackersRef = reactExports.useRef({ - isMouseDown: false, - isTouchMove: false - }); - reactExports.useEffect(function () { - if ((environment == null ? void 0 : environment.addEventListener) == null) { - return; - } +var objectToString = objectProto.toString; - // The same strategy for checking if a click occurred inside or outside downshift - // as in downshift.js. - var onMouseDown = function onMouseDown() { - mouseAndTouchTrackersRef.current.isMouseDown = true; - }; - var onMouseUp = function onMouseUp(event) { - mouseAndTouchTrackersRef.current.isMouseDown = false; - if (isOpen && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) { - return ref.current; - }), environment)) { - handleBlur(); - } - }; - var onTouchStart = function onTouchStart() { - mouseAndTouchTrackersRef.current.isTouchMove = false; - }; - var onTouchMove = function onTouchMove() { - mouseAndTouchTrackersRef.current.isTouchMove = true; - }; - var onTouchEnd = function onTouchEnd(event) { - if (isOpen && !mouseAndTouchTrackersRef.current.isTouchMove && !targetWithinDownshift(event.target, downshiftElementRefs.map(function (ref) { - return ref.current; - }), environment, false)) { - handleBlur(); - } - }; - environment.addEventListener('mousedown', onMouseDown); - environment.addEventListener('mouseup', onMouseUp); - environment.addEventListener('touchstart', onTouchStart); - environment.addEventListener('touchmove', onTouchMove); - environment.addEventListener('touchend', onTouchEnd); - - // eslint-disable-next-line consistent-return - return function cleanup() { - environment.removeEventListener('mousedown', onMouseDown); - environment.removeEventListener('mouseup', onMouseUp); - environment.removeEventListener('touchstart', onTouchStart); - environment.removeEventListener('touchmove', onTouchMove); - environment.removeEventListener('touchend', onTouchEnd); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isOpen, environment]); - return mouseAndTouchTrackersRef; -} +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; -/* istanbul ignore next */ -// eslint-disable-next-line import/no-mutable-exports -var useGetterPropsCalledChecker = function useGetterPropsCalledChecker() { - return noop$1; +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); }; -function useA11yMessageSetter(getA11yMessage, dependencyArray, _ref3) { - var isInitialMount = _ref3.isInitialMount, - highlightedIndex = _ref3.highlightedIndex, - items = _ref3.items, - environment = _ref3.environment, - rest = _objectWithoutPropertiesLoose$1(_ref3, _excluded$3); - // Sets a11y status message on changes in state. - reactExports.useEffect(function () { - if (isInitialMount || false) { - return; - } - updateA11yStatus(function () { - return getA11yMessage(_extends$U({ - highlightedIndex: highlightedIndex, - highlightedItem: items[highlightedIndex], - resultCount: items.length - }, rest)); - }, environment.document); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, dependencyArray); -} -function useScrollIntoView(_ref4) { - var highlightedIndex = _ref4.highlightedIndex, - isOpen = _ref4.isOpen, - itemRefs = _ref4.itemRefs, - getItemNodeFromIndex = _ref4.getItemNodeFromIndex, - menuElement = _ref4.menuElement, - scrollIntoViewProp = _ref4.scrollIntoView; - // used not to scroll on highlight by mouse. - var shouldScrollRef = reactExports.useRef(true); - // Scroll on highlighted item if change comes from keyboard. - useIsomorphicLayoutEffect(function () { - if (highlightedIndex < 0 || !isOpen || !Object.keys(itemRefs.current).length) { - return; - } - if (shouldScrollRef.current === false) { - shouldScrollRef.current = true; - } else { - scrollIntoViewProp(getItemNodeFromIndex(highlightedIndex), menuElement); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [highlightedIndex]); - return shouldScrollRef; -} - -// eslint-disable-next-line import/no-mutable-exports -var useControlPropsValidator = noop$1; /** - * Handles selection on Enter / Alt + ArrowUp. Closes the menu and resets the highlighted index, unless there is a highlighted. - * In that case, selects the item and resets to defaults for open state and highlighted idex. - * @param {Object} props The useCombobox props. - * @param {number} highlightedIndex The index from the state. - * @param {boolean} inputValue Also return the input value for state. - * @returns The changes for the state. + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); */ -function getChangesOnSelection(props, highlightedIndex, inputValue) { - var _props$items; - if (inputValue === void 0) { - inputValue = true; +function debounce$1(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject$1(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; } - var shouldSelect = ((_props$items = props.items) == null ? void 0 : _props$items.length) && highlightedIndex >= 0; - return _extends$U({ - isOpen: false, - highlightedIndex: -1 - }, shouldSelect && _extends$U({ - selectedItem: props.items[highlightedIndex], - isOpen: getDefaultValue$1(props, 'isOpen'), - highlightedIndex: getDefaultValue$1(props, 'highlightedIndex') - }, inputValue && { - inputValue: props.itemToString(props.items[highlightedIndex]) - })); -} -// Shared between all exports. -var commonPropTypes = { - environment: PropTypes.shape({ - addEventListener: PropTypes.func.isRequired, - removeEventListener: PropTypes.func.isRequired, - document: PropTypes.shape({ - createElement: PropTypes.func.isRequired, - getElementById: PropTypes.func.isRequired, - activeElement: PropTypes.any.isRequired, - body: PropTypes.any.isRequired - }).isRequired, - Node: PropTypes.func.isRequired - }), - itemToString: PropTypes.func, - stateReducer: PropTypes.func -}; + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; -// Shared between useSelect, useCombobox, Downshift. -var commonDropdownPropTypes = _extends$U({}, commonPropTypes, { - getA11yStatusMessage: PropTypes.func, - highlightedIndex: PropTypes.number, - defaultHighlightedIndex: PropTypes.number, - initialHighlightedIndex: PropTypes.number, - isOpen: PropTypes.bool, - defaultIsOpen: PropTypes.bool, - initialIsOpen: PropTypes.bool, - selectedItem: PropTypes.any, - initialSelectedItem: PropTypes.any, - defaultSelectedItem: PropTypes.any, - id: PropTypes.string, - labelId: PropTypes.string, - menuId: PropTypes.string, - getItemId: PropTypes.func, - toggleButtonId: PropTypes.string, - onSelectedItemChange: PropTypes.func, - onHighlightedIndexChange: PropTypes.func, - onStateChange: PropTypes.func, - onIsOpenChange: PropTypes.func, - scrollIntoView: PropTypes.func -}); + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } -function downshiftCommonReducer(state, action, stateChangeTypes) { - var type = action.type, - props = action.props; - var changes; - switch (type) { - case stateChangeTypes.ItemMouseMove: - changes = { - highlightedIndex: action.disabled ? -1 : action.index - }; - break; - case stateChangeTypes.MenuMouseLeave: - changes = { - highlightedIndex: -1 - }; - break; - case stateChangeTypes.ToggleButtonClick: - case stateChangeTypes.FunctionToggleMenu: - changes = { - isOpen: !state.isOpen, - highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0) - }; - break; - case stateChangeTypes.FunctionOpenMenu: - changes = { - isOpen: true, - highlightedIndex: getHighlightedIndexOnOpen(props, state, 0) - }; - break; - case stateChangeTypes.FunctionCloseMenu: - changes = { - isOpen: false - }; - break; - case stateChangeTypes.FunctionSetHighlightedIndex: - changes = { - highlightedIndex: action.highlightedIndex - }; - break; - case stateChangeTypes.FunctionSetInputValue: - changes = { - inputValue: action.inputValue - }; - break; - case stateChangeTypes.FunctionReset: - changes = { - highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), - isOpen: getDefaultValue$1(props, 'isOpen'), - selectedItem: getDefaultValue$1(props, 'selectedItem'), - inputValue: getDefaultValue$1(props, 'inputValue') - }; - break; - default: - throw new Error('Reducer called without proper action type.'); + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; } - return _extends$U({}, state, changes); -} -// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -__assign(__assign({}, commonDropdownPropTypes), { items: PropTypes.array.isRequired, isItemDisabled: PropTypes.func, getA11ySelectionMessage: PropTypes.func }); -/** - * Default implementation for status message. Only added when menu is open. - * Will specift if there are results in the list, and if so, how many, - * and what keys are relevant. - * - * @param {Object} param the downshift state and other relevant properties - * @return {String} the a11y status message - */ -function getA11yStatusMessage(_a) { - var isOpen = _a.isOpen, resultCount = _a.resultCount, previousResultCount = _a.previousResultCount; - if (!isOpen) { - return ''; + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); } - if (!resultCount) { - return 'No results are available.'; + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); } - if (resultCount !== previousResultCount) { - return "".concat(resultCount, " result").concat(resultCount === 1 ? ' is' : 's are', " available, use up and down arrow keys to navigate. Press Enter or Space Bar keys to select."); + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); } - return ''; -} -__assign(__assign({}, defaultProps$3), { getA11yStatusMessage: getA11yStatusMessage, isItemDisabled: function () { - return false; - } }); + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } -var InputKeyDownArrowDown = 0; -var InputKeyDownArrowUp = 1; -var InputKeyDownEscape = 2; -var InputKeyDownHome = 3; -var InputKeyDownEnd = 4; -var InputKeyDownPageUp = 5; -var InputKeyDownPageDown = 6; -var InputKeyDownEnter = 7; -var InputChange = 8; -var InputBlur = 9; -var InputClick = 10; -var MenuMouseLeave = 11; -var ItemMouseMove = 12; -var ItemClick = 13; -var ToggleButtonClick = 14; -var FunctionToggleMenu = 15; -var FunctionOpenMenu = 16; -var FunctionCloseMenu = 17; -var FunctionSetHighlightedIndex = 18; -var FunctionSelectItem = 19; -var FunctionSetInputValue = 20; -var FunctionReset$1 = 21; -var ControlledPropUpdatedSelectedItem = 22; + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } -var stateChangeTypes$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - InputKeyDownArrowDown: InputKeyDownArrowDown, - InputKeyDownArrowUp: InputKeyDownArrowUp, - InputKeyDownEscape: InputKeyDownEscape, - InputKeyDownHome: InputKeyDownHome, - InputKeyDownEnd: InputKeyDownEnd, - InputKeyDownPageUp: InputKeyDownPageUp, - InputKeyDownPageDown: InputKeyDownPageDown, - InputKeyDownEnter: InputKeyDownEnter, - InputChange: InputChange, - InputBlur: InputBlur, - InputClick: InputClick, - MenuMouseLeave: MenuMouseLeave, - ItemMouseMove: ItemMouseMove, - ItemClick: ItemClick, - ToggleButtonClick: ToggleButtonClick, - FunctionToggleMenu: FunctionToggleMenu, - FunctionOpenMenu: FunctionOpenMenu, - FunctionCloseMenu: FunctionCloseMenu, - FunctionSetHighlightedIndex: FunctionSetHighlightedIndex, - FunctionSelectItem: FunctionSelectItem, - FunctionSetInputValue: FunctionSetInputValue, - FunctionReset: FunctionReset$1, - ControlledPropUpdatedSelectedItem: ControlledPropUpdatedSelectedItem -}); + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); -function getInitialState$1(props) { - var initialState = getInitialState$2(props); - var selectedItem = initialState.selectedItem; - var inputValue = initialState.inputValue; - if (inputValue === '' && selectedItem && props.defaultInputValue === undefined && props.initialInputValue === undefined && props.inputValue === undefined) { - inputValue = props.itemToString(selectedItem); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; } - return _extends$U({}, initialState, { - inputValue: inputValue - }); + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; } -_extends$U({}, commonDropdownPropTypes, { - items: PropTypes.array.isRequired, - isItemDisabled: PropTypes.func, - selectedItemChanged: PropTypes.func, - getA11ySelectionMessage: PropTypes.func, - inputValue: PropTypes.string, - defaultInputValue: PropTypes.string, - initialInputValue: PropTypes.string, - inputId: PropTypes.string, - onInputValueChange: PropTypes.func -}); /** - * The useCombobox version of useControlledReducer, which also - * checks if the controlled prop selectedItem changed between - * renders. If so, it will also update inputValue with its - * string equivalent. It uses the common useEnhancedReducer to - * compute the rest of the state. + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * - * @param {Function} reducer Reducer function from downshift. - * @param {Object} initialState Initial state of the hook. - * @param {Object} props The hook props. - * @returns {Array} An array with the state and an action dispatcher. + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false */ -function useControlledReducer(reducer, initialState, props) { - var previousSelectedItemRef = reactExports.useRef(); - var _useEnhancedReducer = useEnhancedReducer(reducer, initialState, props), - state = _useEnhancedReducer[0], - dispatch = _useEnhancedReducer[1]; +function isObject$1(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - // ToDo: if needed, make same approach as selectedItemChanged from Downshift. - reactExports.useEffect(function () { - if (!isControlledProp(props, 'selectedItem')) { - return; - } - if (props.selectedItemChanged(previousSelectedItemRef.current, props.selectedItem)) { - dispatch({ - type: ControlledPropUpdatedSelectedItem, - inputValue: props.itemToString(props.selectedItem) - }); - } - previousSelectedItemRef.current = state.selectedItem === previousSelectedItemRef.current ? props.selectedItem : state.selectedItem; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [state.selectedItem, props.selectedItem]); - return [getState(state, props), dispatch]; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -var defaultProps$1 = _extends$U({}, defaultProps$3, { - selectedItemChanged: function selectedItemChanged(prevItem, item) { - return prevItem !== item; - }, - getA11yStatusMessage: getA11yStatusMessage$1, - isItemDisabled: function isItemDisabled() { - return false; - } -}); -/* eslint-disable complexity */ -function downshiftUseComboboxReducer(state, action) { - var _props$items; - var type = action.type, - props = action.props, - altKey = action.altKey; - var changes; - switch (type) { - case ItemClick: - changes = { - isOpen: getDefaultValue$1(props, 'isOpen'), - highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), - selectedItem: props.items[action.index], - inputValue: props.itemToString(props.items[action.index]) - }; - break; - case InputKeyDownArrowDown: - if (state.isOpen) { - changes = { - highlightedIndex: getHighlightedIndex(state.highlightedIndex, 1, props.items, props.isItemDisabled, true) - }; - } else { - changes = { - highlightedIndex: altKey && state.selectedItem == null ? -1 : getHighlightedIndexOnOpen(props, state, 1), - isOpen: props.items.length >= 0 - }; - } - break; - case InputKeyDownArrowUp: - if (state.isOpen) { - if (altKey) { - changes = getChangesOnSelection(props, state.highlightedIndex); - } else { - changes = { - highlightedIndex: getHighlightedIndex(state.highlightedIndex, -1, props.items, props.isItemDisabled, true) - }; - } - } else { - changes = { - highlightedIndex: getHighlightedIndexOnOpen(props, state, -1), - isOpen: props.items.length >= 0 - }; - } - break; - case InputKeyDownEnter: - changes = getChangesOnSelection(props, state.highlightedIndex); - break; - case InputKeyDownEscape: - changes = _extends$U({ - isOpen: false, - highlightedIndex: -1 - }, !state.isOpen && { - selectedItem: null, - inputValue: '' - }); - break; - case InputKeyDownPageUp: - changes = { - highlightedIndex: getHighlightedIndex(state.highlightedIndex, -10, props.items, props.isItemDisabled, true) - }; - break; - case InputKeyDownPageDown: - changes = { - highlightedIndex: getHighlightedIndex(state.highlightedIndex, 10, props.items, props.isItemDisabled, true) - }; - break; - case InputKeyDownHome: - changes = { - highlightedIndex: getNonDisabledIndex(0, false, props.items, props.isItemDisabled) - }; - break; - case InputKeyDownEnd: - changes = { - highlightedIndex: getNonDisabledIndex(props.items.length - 1, true, props.items, props.isItemDisabled) - }; - break; - case InputBlur: - changes = _extends$U({ - isOpen: false, - highlightedIndex: -1 - }, state.highlightedIndex >= 0 && ((_props$items = props.items) == null ? void 0 : _props$items.length) && action.selectItem && { - selectedItem: props.items[state.highlightedIndex], - inputValue: props.itemToString(props.items[state.highlightedIndex]) - }); - break; - case InputChange: - changes = { - isOpen: true, - highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'), - inputValue: action.inputValue - }; - break; - case InputClick: - changes = { - isOpen: !state.isOpen, - highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0) - }; - break; - case FunctionSelectItem: - changes = { - selectedItem: action.selectedItem, - inputValue: props.itemToString(action.selectedItem) - }; - break; - case ControlledPropUpdatedSelectedItem: - changes = { - inputValue: action.inputValue - }; - break; - default: - return downshiftCommonReducer(state, action, stateChangeTypes$1); - } - return _extends$U({}, state, changes); +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); } -/* eslint-enable complexity */ -var _excluded$1 = ["onMouseLeave", "refKey", "ref"], - _excluded2$1 = ["item", "index", "refKey", "ref", "onMouseMove", "onMouseDown", "onClick", "onPress", "disabled"], - _excluded3$1 = ["onClick", "onPress", "refKey", "ref"], - _excluded4$1 = ["onKeyDown", "onChange", "onInput", "onBlur", "onChangeText", "onClick", "refKey", "ref"]; -useCombobox$1.stateChangeTypes = stateChangeTypes$1; -function useCombobox$1(userProps) { - if (userProps === void 0) { - userProps = {}; +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; } - // Props defaults and destructuring. - var props = _extends$U({}, defaultProps$1, userProps); - var items = props.items, - scrollIntoView = props.scrollIntoView, - environment = props.environment, - getA11yStatusMessage = props.getA11yStatusMessage, - getA11ySelectionMessage = props.getA11ySelectionMessage, - itemToString = props.itemToString; - // Initial state depending on controlled props. - var initialState = getInitialState$1(props); - var _useControlledReducer = useControlledReducer(downshiftUseComboboxReducer, initialState, props), - state = _useControlledReducer[0], - dispatch = _useControlledReducer[1]; - var isOpen = state.isOpen, - highlightedIndex = state.highlightedIndex, - selectedItem = state.selectedItem, - inputValue = state.inputValue; + if (isSymbol(value)) { + return NAN; + } + if (isObject$1(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject$1(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - // Element refs. - var menuRef = reactExports.useRef(null); - var itemRefs = reactExports.useRef({}); - var inputRef = reactExports.useRef(null); - var toggleButtonRef = reactExports.useRef(null); - var isInitialMountRef = reactExports.useRef(true); - // prevent id re-generation between renders. - var elementIds = useElementIds(props); - // used to keep track of how many items we had on previous cycle. - var previousResultCountRef = reactExports.useRef(); - // utility callback to get item element. - var latest = useLatestRef$1({ - state: state, - props: props - }); - var getItemNodeFromIndex = reactExports.useCallback(function (index) { - return itemRefs.current[elementIds.getItemId(index)]; - }, [elementIds]); +var lodash_debounce = debounce$1; - // Effects. - // Sets a11y status message on changes in state. - useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], _extends$U({ - isInitialMount: isInitialMountRef.current, - previousResultCount: previousResultCountRef.current, - items: items, - environment: environment, - itemToString: itemToString - }, state)); - // Sets a11y status message on changes in selectedItem. - useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], _extends$U({ - isInitialMount: isInitialMountRef.current, - previousResultCount: previousResultCountRef.current, - items: items, - environment: environment, - itemToString: itemToString - }, state)); - // Scroll on highlighted item if change comes from keyboard. - var shouldScrollRef = useScrollIntoView({ - menuElement: menuRef.current, - highlightedIndex: highlightedIndex, - isOpen: isOpen, - itemRefs: itemRefs, - scrollIntoView: scrollIntoView, - getItemNodeFromIndex: getItemNodeFromIndex - }); - useControlPropsValidator({ - isInitialMount: isInitialMountRef.current, - props: props, - state: state - }); - // Focus the input on first render if required. - reactExports.useEffect(function () { - var focusOnOpen = getInitialValue$1(props, 'isOpen'); - if (focusOnOpen && inputRef.current) { - inputRef.current.focus(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - reactExports.useEffect(function () { - if (isInitialMountRef.current) { - return; - } - previousResultCountRef.current = items.length; - }); - // Add mouse/touch events to document. - var mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [inputRef, menuRef, toggleButtonRef], environment, function () { - dispatch({ - type: InputBlur, - selectItem: false - }); - }); - var setGetterPropCallInfo = useGetterPropsCalledChecker(); - // Make initial ref false. - reactExports.useEffect(function () { - isInitialMountRef.current = false; - return function () { - isInitialMountRef.current = true; - }; - }, []); - // Reset itemRefs on close. - reactExports.useEffect(function () { - var _environment$document; - if (!isOpen) { - itemRefs.current = {}; - } else if (((_environment$document = environment.document) == null ? void 0 : _environment$document.activeElement) !== inputRef.current) { - var _inputRef$current; - inputRef == null || (_inputRef$current = inputRef.current) == null ? void 0 : _inputRef$current.focus(); - } - }, [isOpen, environment]); +var debounce$2 = /*@__PURE__*/getDefaultExportFromCjs(lodash_debounce); - /* Event handler functions */ - var inputKeyDownHandlers = reactExports.useMemo(function () { - return { - ArrowDown: function ArrowDown(event) { - event.preventDefault(); - dispatch({ - type: InputKeyDownArrowDown, - altKey: event.altKey - }); - }, - ArrowUp: function ArrowUp(event) { - event.preventDefault(); - dispatch({ - type: InputKeyDownArrowUp, - altKey: event.altKey - }); - }, - Home: function Home(event) { - if (!latest.current.state.isOpen) { - return; - } - event.preventDefault(); - dispatch({ - type: InputKeyDownHome - }); - }, - End: function End(event) { - if (!latest.current.state.isOpen) { - return; - } - event.preventDefault(); - dispatch({ - type: InputKeyDownEnd - }); - }, - Escape: function Escape(event) { - var latestState = latest.current.state; - if (latestState.isOpen || latestState.inputValue || latestState.selectedItem || latestState.highlightedIndex > -1) { - event.preventDefault(); - dispatch({ - type: InputKeyDownEscape - }); - } - }, - Enter: function Enter(event) { - var latestState = latest.current.state; - // if closed or no highlighted index, do nothing. - if (!latestState.isOpen || event.which === 229 // if IME composing, wait for next Enter keydown event. - ) { - return; - } - event.preventDefault(); - dispatch({ - type: InputKeyDownEnter - }); - }, - PageUp: function PageUp(event) { - if (latest.current.state.isOpen) { - event.preventDefault(); - dispatch({ - type: InputKeyDownPageUp - }); - } - }, - PageDown: function PageDown(event) { - if (latest.current.state.isOpen) { - event.preventDefault(); - dispatch({ - type: InputKeyDownPageDown - }); - } - } - }; - }, [dispatch, latest]); +/** +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ - // Getter props. - var getLabelProps = reactExports.useCallback(function (labelProps) { - return _extends$U({ - id: elementIds.labelId, - htmlFor: elementIds.inputId - }, labelProps); - }, [elementIds]); - var getMenuProps = reactExports.useCallback(function (_temp, _temp2) { - var _extends2; - var _ref = _temp === void 0 ? {} : _temp, - onMouseLeave = _ref.onMouseLeave, - _ref$refKey = _ref.refKey, - refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey, - ref = _ref.ref, - rest = _objectWithoutPropertiesLoose$1(_ref, _excluded$1); - var _ref2 = _temp2 === void 0 ? {} : _temp2; - _ref2.suppressRefError; - return _extends$U((_extends2 = {}, _extends2[refKey] = handleRefs(ref, function (menuNode) { - menuRef.current = menuNode; - }), _extends2.id = elementIds.menuId, _extends2.role = 'listbox', _extends2['aria-labelledby'] = rest && rest['aria-label'] ? undefined : "" + elementIds.labelId, _extends2.onMouseLeave = callAllEventHandlers(onMouseLeave, function () { - dispatch({ - type: MenuMouseLeave - }); - }), _extends2), rest); - }, [dispatch, setGetterPropCallInfo, elementIds]); - var getItemProps = reactExports.useCallback(function (_temp3) { - var _extends3, _ref4; - var _ref3 = _temp3 === void 0 ? {} : _temp3, - itemProp = _ref3.item, - indexProp = _ref3.index, - _ref3$refKey = _ref3.refKey, - refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey, - ref = _ref3.ref, - onMouseMove = _ref3.onMouseMove, - onMouseDown = _ref3.onMouseDown, - onClick = _ref3.onClick; - _ref3.onPress; - var disabledProp = _ref3.disabled, - rest = _objectWithoutPropertiesLoose$1(_ref3, _excluded2$1); - if (disabledProp !== undefined) { - console.warn('Passing "disabled" as an argument to getItemProps is not supported anymore. Please use the isItemDisabled prop from useCombobox.'); - } - var _latest$current = latest.current, - latestProps = _latest$current.props, - latestState = _latest$current.state; - var _getItemAndIndex = getItemAndIndex(itemProp, indexProp, latestProps.items, 'Pass either item or index to getItemProps!'), - item = _getItemAndIndex[0], - index = _getItemAndIndex[1]; - var disabled = latestProps.isItemDisabled(item, index); - var onSelectKey = 'onClick'; - var customClickHandler = onClick; - var itemHandleMouseMove = function itemHandleMouseMove() { - if (index === latestState.highlightedIndex) { - return; - } - shouldScrollRef.current = false; - dispatch({ - type: ItemMouseMove, - index: index, - disabled: disabled - }); - }; - var itemHandleClick = function itemHandleClick() { - dispatch({ - type: ItemClick, - index: index - }); - }; - var itemHandleMouseDown = function itemHandleMouseDown(e) { - return e.preventDefault(); - }; - return _extends$U((_extends3 = {}, _extends3[refKey] = handleRefs(ref, function (itemNode) { - if (itemNode) { - itemRefs.current[elementIds.getItemId(index)] = itemNode; - } - }), _extends3['aria-disabled'] = disabled, _extends3['aria-selected'] = "" + (index === latestState.highlightedIndex), _extends3.id = elementIds.getItemId(index), _extends3.role = 'option', _extends3), !disabled && (_ref4 = {}, _ref4[onSelectKey] = callAllEventHandlers(customClickHandler, itemHandleClick), _ref4), { - onMouseMove: callAllEventHandlers(onMouseMove, itemHandleMouseMove), - onMouseDown: callAllEventHandlers(onMouseDown, itemHandleMouseDown) - }, rest); - }, [dispatch, latest, shouldScrollRef, elementIds]); - var getToggleButtonProps = reactExports.useCallback(function (_temp4) { - var _extends4; - var _ref5 = _temp4 === void 0 ? {} : _temp4, - onClick = _ref5.onClick; - _ref5.onPress; - var _ref5$refKey = _ref5.refKey, - refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey, - ref = _ref5.ref, - rest = _objectWithoutPropertiesLoose$1(_ref5, _excluded3$1); - var latestState = latest.current.state; - var toggleButtonHandleClick = function toggleButtonHandleClick() { - dispatch({ - type: ToggleButtonClick - }); - }; - return _extends$U((_extends4 = {}, _extends4[refKey] = handleRefs(ref, function (toggleButtonNode) { - toggleButtonRef.current = toggleButtonNode; - }), _extends4['aria-controls'] = elementIds.menuId, _extends4['aria-expanded'] = latestState.isOpen, _extends4.id = elementIds.toggleButtonId, _extends4.tabIndex = -1, _extends4), !rest.disabled && _extends$U({}, { - onClick: callAllEventHandlers(onClick, toggleButtonHandleClick) - }), rest); - }, [dispatch, latest, elementIds]); - var getInputProps = reactExports.useCallback(function (_temp5, _temp6) { - var _extends5; - var _ref6 = _temp5 === void 0 ? {} : _temp5, - onKeyDown = _ref6.onKeyDown, - onChange = _ref6.onChange, - onInput = _ref6.onInput, - onBlur = _ref6.onBlur; - _ref6.onChangeText; - var onClick = _ref6.onClick, - _ref6$refKey = _ref6.refKey, - refKey = _ref6$refKey === void 0 ? 'ref' : _ref6$refKey, - ref = _ref6.ref, - rest = _objectWithoutPropertiesLoose$1(_ref6, _excluded4$1); - var _ref7 = _temp6 === void 0 ? {} : _temp6; - _ref7.suppressRefError; - var latestState = latest.current.state; - var inputHandleKeyDown = function inputHandleKeyDown(event) { - var key = normalizeArrowKey(event); - if (key && inputKeyDownHandlers[key]) { - inputKeyDownHandlers[key](event); - } - }; - var inputHandleChange = function inputHandleChange(event) { - dispatch({ - type: InputChange, - inputValue: event.target.value - }); - }; - var inputHandleBlur = function inputHandleBlur(event) { - /* istanbul ignore else */ - if (latestState.isOpen && !mouseAndTouchTrackersRef.current.isMouseDown) { - var isBlurByTabChange = event.relatedTarget === null && environment.document.activeElement !== environment.document.body; - dispatch({ - type: InputBlur, - selectItem: !isBlurByTabChange - }); - } - }; - var inputHandleClick = function inputHandleClick() { - dispatch({ - type: InputClick - }); - }; +const FileUpload = React__default.forwardRef((_ref, ref) => { + let { + disabled, + ...props + } = _ref; + return ( + React__default.createElement(StyledFileUpload, Object.assign({ + ref: ref, + "aria-disabled": disabled + }, props, { + role: "button" + })) + ); +}); +FileUpload.propTypes = { + isDragging: PropTypes.bool, + isCompact: PropTypes.bool, + disabled: PropTypes.bool +}; +FileUpload.displayName = 'FileUpload'; - /* istanbul ignore next (preact) */ - var onChangeKey = 'onChange'; - var eventHandlers = {}; - if (!rest.disabled) { - var _eventHandlers; - eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, inputHandleBlur), _eventHandlers.onClick = callAllEventHandlers(onClick, inputHandleClick), _eventHandlers); - } - return _extends$U((_extends5 = {}, _extends5[refKey] = handleRefs(ref, function (inputNode) { - inputRef.current = inputNode; - }), _extends5['aria-activedescendant'] = latestState.isOpen && latestState.highlightedIndex > -1 ? elementIds.getItemId(latestState.highlightedIndex) : '', _extends5['aria-autocomplete'] = 'list', _extends5['aria-controls'] = elementIds.menuId, _extends5['aria-expanded'] = latestState.isOpen, _extends5['aria-labelledby'] = rest && rest['aria-label'] ? undefined : elementIds.labelId, _extends5.autoComplete = 'off', _extends5.id = elementIds.inputId, _extends5.role = 'combobox', _extends5.value = latestState.inputValue, _extends5), eventHandlers, rest); - }, [setGetterPropCallInfo, latest, elementIds, inputKeyDownHandlers, dispatch, mouseAndTouchTrackersRef, environment]); +/** +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ - // returns - var toggleMenu = reactExports.useCallback(function () { - dispatch({ - type: FunctionToggleMenu - }); - }, [dispatch]); - var closeMenu = reactExports.useCallback(function () { - dispatch({ - type: FunctionCloseMenu - }); - }, [dispatch]); - var openMenu = reactExports.useCallback(function () { - dispatch({ - type: FunctionOpenMenu - }); - }, [dispatch]); - var setHighlightedIndex = reactExports.useCallback(function (newHighlightedIndex) { - dispatch({ - type: FunctionSetHighlightedIndex, - highlightedIndex: newHighlightedIndex - }); - }, [dispatch]); - var selectItem = reactExports.useCallback(function (newSelectedItem) { - dispatch({ - type: FunctionSelectItem, - selectedItem: newSelectedItem - }); - }, [dispatch]); - var setInputValue = reactExports.useCallback(function (newInputValue) { - dispatch({ - type: FunctionSetInputValue, - inputValue: newInputValue - }); - }, [dispatch]); - var reset = reactExports.useCallback(function () { - dispatch({ - type: FunctionReset$1 - }); - }, [dispatch]); - return { - // prop getters. - getItemProps: getItemProps, - getLabelProps: getLabelProps, - getMenuProps: getMenuProps, - getInputProps: getInputProps, - getToggleButtonProps: getToggleButtonProps, - // actions. - toggleMenu: toggleMenu, - openMenu: openMenu, - closeMenu: closeMenu, - setHighlightedIndex: setHighlightedIndex, - setInputValue: setInputValue, - selectItem: selectItem, - reset: reset, - // state. - highlightedIndex: highlightedIndex, - isOpen: isOpen, - selectedItem: selectedItem, - inputValue: inputValue - }; -} +const ItemComponent = reactExports.forwardRef((_ref, ref) => { + let { + ...props + } = _ref; + return React__default.createElement(StyledFileListItem, Object.assign({}, props, { + ref: ref + })); +}); +ItemComponent.displayName = 'FileList.Item'; +const Item = ItemComponent; /** - * Returns a message to be added to aria-live region when item is removed. - * - * @param {Object} selectionParameters Parameters required to build the message. - * @returns {string} The a11y message. - */ -function getA11yRemovalMessage(selectionParameters) { - var removedSelectedItem = selectionParameters.removedSelectedItem, - itemToStringLocal = selectionParameters.itemToString; - return itemToStringLocal(removedSelectedItem) + " has been removed."; -} -_extends$U({}, commonPropTypes, { - selectedItems: PropTypes.array, - initialSelectedItems: PropTypes.array, - defaultSelectedItems: PropTypes.array, - getA11yRemovalMessage: PropTypes.func, - activeIndex: PropTypes.number, - initialActiveIndex: PropTypes.number, - defaultActiveIndex: PropTypes.number, - onActiveIndexChange: PropTypes.func, - onSelectedItemsChange: PropTypes.func, - keyNavigationNext: PropTypes.string, - keyNavigationPrevious: PropTypes.string -}); -({ - itemToString: defaultProps$3.itemToString, - stateReducer: defaultProps$3.stateReducer, - environment: defaultProps$3.environment, - getA11yRemovalMessage: getA11yRemovalMessage, - keyNavigationNext: 'ArrowRight', - keyNavigationPrevious: 'ArrowLeft' +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ + +const FileListComponent = reactExports.forwardRef((_ref, ref) => { + let { + ...props + } = _ref; + return React__default.createElement(StyledFileList, Object.assign({}, props, { + ref: ref + })); }); +FileListComponent.displayName = 'FileList'; +const FileList = FileListComponent; +FileList.Item = Item; /** - * Copyright Zendesk, Inc. - * - * Use of this source code is governed under the Apache License, Version 2.0 - * found at http://www.apache.org/licenses/LICENSE-2.0. - */ - -const typeMap = { - [useCombobox$1.stateChangeTypes.FunctionCloseMenu]: 'fn:setExpansion', - [useCombobox$1.stateChangeTypes.FunctionOpenMenu]: 'fn:setExpansion', - [useCombobox$1.stateChangeTypes.FunctionToggleMenu]: 'fn:setExpansion', - [useCombobox$1.stateChangeTypes.FunctionReset]: 'fn:reset', - [useCombobox$1.stateChangeTypes.FunctionSelectItem]: 'fn:setSelectionValue', - [useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex]: 'fn:setActiveIndex', - [useCombobox$1.stateChangeTypes.FunctionSetInputValue]: 'fn:setInputValue', - [useCombobox$1.stateChangeTypes.InputBlur]: 'input:blur', - [useCombobox$1.stateChangeTypes.InputChange]: 'input:change', - [useCombobox$1.stateChangeTypes.InputClick]: 'input:click', - [useCombobox$1.stateChangeTypes.InputKeyDownArrowDown]: `input:keyDown:${KEYS$2.DOWN}`, - [useCombobox$1.stateChangeTypes.InputKeyDownArrowUp]: `input:keyDown:${KEYS$2.UP}`, - [useCombobox$1.stateChangeTypes.InputKeyDownEnd]: `input:keyDown:${KEYS$2.END}`, - [useCombobox$1.stateChangeTypes.InputKeyDownEnter]: `input:keyDown:${KEYS$2.ENTER}`, - [useCombobox$1.stateChangeTypes.InputKeyDownEscape]: `input:keyDown:${KEYS$2.ESCAPE}`, - [useCombobox$1.stateChangeTypes.InputKeyDownHome]: `input:keyDown:${KEYS$2.HOME}`, - [useCombobox$1.stateChangeTypes.InputKeyDownPageDown]: `input:keyDown:${KEYS$2.PAGE_DOWN}`, - [useCombobox$1.stateChangeTypes.InputKeyDownPageUp]: `input:keyDown:${KEYS$2.PAGE_UP}`, - [useCombobox$1.stateChangeTypes.ItemClick]: 'option:click', - [useCombobox$1.stateChangeTypes.ItemMouseMove]: 'option:mouseMove', - [useCombobox$1.stateChangeTypes.MenuMouseLeave]: 'listbox:mouseLeave', - [useCombobox$1.stateChangeTypes.ToggleButtonClick]: 'toggle:click' -}; -const toType = downshiftType => { - return typeMap[downshiftType] || downshiftType; -}; -const toLabel = (labels, value) => { - if (value === undefined) { - return ''; - } - const key = typeof value === 'string' ? value : JSON.stringify(value); - return labels[key]; -}; +* Copyright Zendesk, Inc. +* +* Use of this source code is governed under the Apache License, Version 2.0 +* found at http://www.apache.org/licenses/LICENSE-2.0. +*/ -const useCombobox = _ref => { - let { - idPrefix, - triggerRef, - inputRef, - listboxRef, - isAutocomplete, - isMultiselectable, - isEditable = true, - disabled, - hasHint, - hasMessage, - options = [], - inputValue, - selectionValue, - isExpanded, - defaultExpanded, - initialExpanded, - activeIndex, - defaultActiveIndex, - initialActiveIndex, - onChange = () => undefined, - environment - } = _ref; - const win = environment || window; - const [triggerContainsInput, setTriggerContainsInput] = reactExports.useState(); - const [downshiftInputValue, setDownshiftInputValue] = reactExports.useState(inputValue); - const [matchValue, setMatchValue] = reactExports.useState(''); - const useInputValueRef = reactExports.useRef(true); - const matchTimeoutRef = reactExports.useRef(); - const previousStateRef = reactExports.useRef(); - const prefix = useId$2(idPrefix); - const idRef = reactExports.useRef({ - label: `${prefix}--label`, - hint: `${prefix}--hint`, - trigger: `${prefix}--trigger`, - input: `${prefix}--input`, - listbox: `${prefix}--listbox`, - message: `${prefix}--message`, - getOptionId: (index, isDisabled, isHidden) => `${prefix}--option${isDisabled ? '-disabled' : ''}${isHidden ? '-hidden' : ''}-${index}` - }); - const labels = reactExports.useMemo(() => ({}), []); - const selectedValues = reactExports.useMemo(() => [], []); - const disabledValues = reactExports.useMemo(() => [], []); - const hiddenValues = reactExports.useMemo(() => [], []); - const values = reactExports.useMemo(() => { - const retVal = []; - const setValues = option => { - if (option.disabled || option.hidden) { - if (option.disabled && !disabledValues.includes(option.value)) { - disabledValues.push(option.value); - } - if (option.hidden && !hiddenValues.includes(option.value)) { - hiddenValues.push(option.value); - } - } else { - retVal.push(option.value); - const disabledIndex = disabledValues.indexOf(option.value); - if (disabledIndex !== -1) { - disabledValues.splice(disabledIndex, 1); - } - const hiddenIndex = hiddenValues.indexOf(option.value); - if (hiddenIndex !== -1) { - hiddenValues.splice(hiddenIndex, 1); - } - } - if (option.selected && !selectedValues.includes(option.value)) { - selectedValues.push(option.value); - } - const key = typeof option.value === 'string' ? option.value : JSON.stringify(option.value); - labels[key] = option.label || key; - }; - options.forEach(option => { - if ('options' in option) { - option.options.forEach(setValues); - } else { - setValues(option); - } - }); - return retVal; - }, [options, disabledValues, hiddenValues, selectedValues, labels]); - const initialSelectionValue = isMultiselectable ? selectedValues : selectedValues[0]; - const initialInputValue = isMultiselectable ? '' : toLabel(labels, initialSelectionValue); - const _defaultActiveIndex = reactExports.useMemo(() => { - if (defaultActiveIndex === undefined) { - return isAutocomplete && isEditable ? 0 : undefined; - } - return defaultActiveIndex; - }, [defaultActiveIndex, isAutocomplete, isEditable]); - if (useInputValueRef.current && inputValue !== downshiftInputValue) { - setDownshiftInputValue(inputValue); - } else { - useInputValueRef.current = true; - } - if (selectionValue === undefined || selectionValue === null) { - if (!isMultiselectable && selectedValues.length > 1) { - throw new Error('Error: expected useCombobox `options` to have no more than one selected.'); - } - } - if (selectionValue !== undefined && selectionValue !== null) { - if (isMultiselectable && !Array.isArray(selectionValue)) { - throw new Error('Error: expected multiselectable useCombobox `selectionValue` to be an array.'); - } else if (!isMultiselectable && Array.isArray(selectionValue)) { - throw new Error('Error: expected useCombobox `selectionValue` not to be an array.'); - } - } - const handleDownshiftStateChange = reactExports.useCallback(_ref2 => { - let { - type, - isOpen, - selectedItem, - inputValue: _inputValue, - highlightedIndex - } = _ref2; - return onChange({ - type: toType(type), - ...(isOpen !== undefined && { - isExpanded: isOpen - }), - ...(selectedItem !== undefined && { - selectionValue: selectedItem - }), - ...(_inputValue !== undefined && { - inputValue: _inputValue - }), - ...(highlightedIndex !== undefined && { - activeIndex: highlightedIndex - }) - }); - }, [onChange]); - const stateReducer = (state, _ref3) => { - let { - type, - changes, - altKey - } = _ref3; - switch (type) { - case useCombobox$1.stateChangeTypes.ControlledPropUpdatedSelectedItem: - return state; - case useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex: - if (previousStateRef.current?.altKey) { - changes.highlightedIndex = -1; - } - break; - case useCombobox$1.stateChangeTypes.FunctionCloseMenu: - case useCombobox$1.stateChangeTypes.InputBlur: - return { - ...state, - isOpen: type === useCombobox$1.stateChangeTypes.InputBlur && triggerContainsInput && isMultiselectable && state.isOpen || false - }; - case useCombobox$1.stateChangeTypes.InputClick: - if (!isAutocomplete) { - changes.isOpen = state.isOpen; - } - break; - case useCombobox$1.stateChangeTypes.InputKeyDownArrowDown: - case useCombobox$1.stateChangeTypes.FunctionOpenMenu: - if (state.isOpen !== changes.isOpen && !altKey) { - changes.highlightedIndex = 0; - } - break; - case useCombobox$1.stateChangeTypes.InputKeyDownArrowUp: - if (state.isOpen !== changes.isOpen) { - changes.highlightedIndex = values.length - 1; - } - break; - case useCombobox$1.stateChangeTypes.InputKeyDownEnter: - case useCombobox$1.stateChangeTypes.FunctionSelectItem: - case useCombobox$1.stateChangeTypes.ItemClick: - changes.highlightedIndex = state.highlightedIndex; - if (isMultiselectable) { - changes.isOpen = state.isOpen; - changes.inputValue = ''; - } - break; - case useCombobox$1.stateChangeTypes.InputKeyDownEscape: - return { - ...state, - isOpen: false - }; - case useCombobox$1.stateChangeTypes.InputKeyDownPageDown: - case useCombobox$1.stateChangeTypes.InputKeyDownPageUp: - return state; - } - if (isMultiselectable && state.selectedItem !== changes.selectedItem) { - if (state.selectedItem !== undefined && state.selectedItem !== null && changes.selectedItem !== undefined && changes.selectedItem !== null) { - if (state.selectedItem.includes(changes.selectedItem)) { - changes.selectedItem = state.selectedItem.filter(value => value !== changes.selectedItem); - } else { - changes.selectedItem = [...state.selectedItem, changes.selectedItem]; - } - } else if (changes.selectedItem !== undefined && changes.selectedItem !== null) { - changes.selectedItem = [changes.selectedItem]; - } else { - changes.selectedItem = []; - } - } - previousStateRef.current = { - type, - altKey, - ...state - }; - return changes; - }; - const transformValue = value => value ? toLabel(labels, value) : ''; - const { - selectedItem: _selectionValue, - isOpen: _isExpanded, - highlightedIndex: _activeIndex, - inputValue: _inputValue, - getToggleButtonProps: getDownshiftTriggerProps, - getInputProps: getDownshiftInputProps, - getMenuProps: getDownshiftListboxProps, - getItemProps: getDownshiftOptionProps, - closeMenu, - openMenu, - setHighlightedIndex, - selectItem - } = useCombobox$1({ - toggleButtonId: idRef.current.trigger, - menuId: idRef.current.listbox, - getItemId: idRef.current.getOptionId, - items: values, - inputValue: downshiftInputValue, - initialInputValue, - itemToString: transformValue , - selectedItem: selectionValue, - initialSelectedItem: initialSelectionValue, - isOpen: isExpanded, - defaultIsOpen: defaultExpanded, - initialIsOpen: initialExpanded, - highlightedIndex: activeIndex, - defaultHighlightedIndex: _defaultActiveIndex, - initialHighlightedIndex: initialActiveIndex, - onStateChange: handleDownshiftStateChange, - stateReducer, - environment: win - }); - const closeListbox = reactExports.useCallback(() => { - closeMenu(); - onChange({ - type: toType(useCombobox$1.stateChangeTypes.FunctionCloseMenu), - isExpanded: false - }); - }, [closeMenu, onChange]); - const openListbox = reactExports.useCallback(() => { - openMenu(); - onChange({ - type: toType(useCombobox$1.stateChangeTypes.FunctionOpenMenu), - isExpanded: true - }); - }, [openMenu, onChange]); - const setActiveIndex = reactExports.useCallback(index => { - setHighlightedIndex(index); - onChange({ - type: toType(useCombobox$1.stateChangeTypes.FunctionSetHighlightedIndex), - activeIndex: index - }); - }, [onChange, setHighlightedIndex]); - const setDownshiftSelection = reactExports.useCallback(value => { - selectItem(value); - onChange({ - type: toType(useCombobox$1.stateChangeTypes.FunctionSelectItem), - selectionValue: value - }); - }, [onChange, selectItem]); - const { - getLabelProps: getFieldLabelProps, - getHintProps: getFieldHintProps, - getInputProps: getFieldInputProps, - getMessageProps: getFieldMessageProps - } = useField({ - hasHint, - hasMessage - }); - reactExports.useLayoutEffect(() => { - if ((isAutocomplete || !isEditable) && _isExpanded && !previousStateRef.current?.isOpen && _selectionValue && !matchValue) { - const value = Array.isArray(_selectionValue) ? _selectionValue[_selectionValue.length - 1 - ] : _selectionValue; - const index = values.findIndex(current => current === value); - if (index !== -1) { - setActiveIndex(index); - } else if (_defaultActiveIndex !== undefined) { - setActiveIndex(_defaultActiveIndex); - } - } - }, [ - isAutocomplete, isEditable, _isExpanded, _selectionValue, _inputValue, values, _defaultActiveIndex, setActiveIndex]); - reactExports.useEffect( - () => setTriggerContainsInput(triggerRef.current?.contains(inputRef.current)), [triggerRef, inputRef]); - reactExports.useEffect(() => { - clearTimeout(matchTimeoutRef.current); - matchTimeoutRef.current = window.setTimeout(() => setMatchValue(''), 500); - return () => clearTimeout(matchTimeoutRef.current); - }, [matchValue]); - reactExports.useEffect(() => { - if (previousStateRef.current?.type === useCombobox$1.stateChangeTypes.FunctionSelectItem) { - if (isEditable) { - inputRef.current?.focus(); - } else { - triggerRef.current?.focus(); - } - previousStateRef.current = { - ...previousStateRef.current, - type: useCombobox$1.stateChangeTypes.InputClick - }; - } - }); - reactExports.useEffect(() => { - if (isEditable && inputRef.current === win.document.activeElement) { - inputRef.current?.scrollIntoView && inputRef.current?.scrollIntoView({ - block: 'nearest' - }); - } - }, [inputRef, isEditable, win.document.activeElement]); - const getTriggerProps = reactExports.useCallback(function (_temp) { - let { - onBlur, - onClick, - onKeyDown, - ...other - } = _temp === void 0 ? {} : _temp; - const triggerProps = getDownshiftTriggerProps({ - 'data-garden-container-id': 'containers.combobox', - 'data-garden-container-version': '1.1.4', - onBlur, - onClick, - onKeyDown, - ref: triggerRef, - disabled, - ...other - }); - const handleBlur = event => { - if (event.relatedTarget === null || !event.currentTarget?.contains(event.relatedTarget)) { - closeListbox(); - } - }; - if (isEditable && triggerContainsInput) { - const handleClick = event => { - if (disabled) { - event.preventDefault(); - } else if (isAutocomplete) { - triggerProps.onClick && triggerProps.onClick(event); - } else { - inputRef.current?.focus(); - } - }; - return { - ...triggerProps, - onBlur: composeEventHandlers$5(onBlur, handleBlur), - onClick: composeEventHandlers$5(onClick, handleClick), - 'aria-controls': isAutocomplete ? triggerProps['aria-controls'] : undefined, - 'aria-expanded': undefined, - 'aria-disabled': disabled || undefined, - disabled: undefined - }; - } else if (!isEditable) { - const { - 'aria-activedescendant': ariaActiveDescendant, - onKeyDown: onDownshiftKeyDown - } = getDownshiftInputProps({}, { - suppressRefError: true - }); - const handleKeyDown = event => { - event.stopPropagation(); - if (!_isExpanded && (event.key === KEYS$2.SPACE || event.key === KEYS$2.ENTER)) { - event.preventDefault(); - openListbox(); - } else if (_isExpanded && !matchValue && (event.key === KEYS$2.SPACE || event.key === KEYS$2.ENTER)) { - event.preventDefault(); - if (_activeIndex !== -1) { - setDownshiftSelection(values[_activeIndex]); - } - if (!isMultiselectable) { - closeListbox(); - } - } else if (/^(?:\S| ){1}$/u.test(event.key)) { - const _matchValue = `${matchValue}${event.key}`; - setMatchValue(_matchValue); - let offset = 0; - if (_isExpanded) { - if (_activeIndex !== -1) { - offset = _matchValue.length === 1 ? _activeIndex + 1 : _activeIndex; - } - } else { - openListbox(); - const offsetValue = Array.isArray(_selectionValue) ? _selectionValue[_selectionValue.length - 1 - ] : _selectionValue; - if (offsetValue !== null) { - offset = values.findIndex(current => current === offsetValue); - } - } - for (let index = 0; index < values.length; index++) { - const valueIndex = (index + offset) % values.length; - const value = values[valueIndex]; - if (toLabel(labels, value).toLowerCase().startsWith(_matchValue.toLowerCase())) { - setActiveIndex(valueIndex); - break; - } - } - } - }; - return { - ...triggerProps, - 'aria-activedescendant': ariaActiveDescendant, - 'aria-haspopup': 'listbox', - 'aria-labelledby': idRef.current.label, - 'aria-disabled': disabled || undefined, - disabled: undefined, - role: 'combobox', - onBlur: composeEventHandlers$5(onBlur, handleBlur), - onKeyDown: composeEventHandlers$5(onKeyDown, onDownshiftKeyDown, handleKeyDown), - tabIndex: disabled ? -1 : 0 - }; - } - return triggerProps; - }, [getDownshiftTriggerProps, getDownshiftInputProps, triggerRef, disabled, _selectionValue, _isExpanded, _activeIndex, closeListbox, openListbox, setActiveIndex, setDownshiftSelection, matchValue, values, labels, triggerContainsInput, isAutocomplete, isEditable, isMultiselectable, inputRef]); - const getLabelProps = reactExports.useCallback(function (_temp2) { - let { - onClick, - ...other - } = _temp2 === void 0 ? {} : _temp2; - const { - htmlFor, - ...labelProps - } = getFieldLabelProps({ - id: idRef.current.label, - htmlFor: idRef.current.input, - ...other - }); - const handleClick = () => !isEditable && triggerRef.current?.focus(); - return { - ...labelProps, - onClick: composeEventHandlers$5(onClick, handleClick), - htmlFor: isEditable ? htmlFor : undefined - }; - }, [getFieldLabelProps, isEditable, triggerRef]); - const getHintProps = reactExports.useCallback(props => getFieldHintProps({ - id: idRef.current.hint, - ...props - }), [getFieldHintProps]); - const getInputProps = reactExports.useCallback(function (_temp3) { - let { - role = isEditable ? 'combobox' : null, - onChange: _onChange, - onClick, - onFocus, - ...other - } = _temp3 === void 0 ? {} : _temp3; - const inputProps = { - 'data-garden-container-id': 'containers.combobox.input', - 'data-garden-container-version': '1.1.4', - ref: inputRef, - role: role === null ? undefined : role, - onChange: _onChange, - onClick, - onFocus - }; - if (isEditable) { - const handleChange = event => { - if (inputValue !== undefined) { - setDownshiftInputValue(event.target.value); - useInputValueRef.current = false; - if (event.nativeEvent.isComposing) { - handleDownshiftStateChange({ - type: useCombobox$1.stateChangeTypes.InputChange, - inputValue: event.target.value - }); - } - } - }; - const handleClick = event => event.target instanceof Element && triggerRef.current?.contains(event.target) && event.stopPropagation(); - const describedBy = []; - if (hasHint) { - describedBy.push(idRef.current.hint); - } - if (hasMessage) { - describedBy.push(idRef.current.message); - } - return getDownshiftInputProps({ - ...inputProps, - disabled, - role, - 'aria-autocomplete': isAutocomplete ? 'list' : undefined, - onChange: composeEventHandlers$5(_onChange, handleChange), - onClick: composeEventHandlers$5(onClick, handleClick), - ...getFieldInputProps({ - id: idRef.current.input, - 'aria-labelledby': idRef.current.label, - 'aria-describedby': describedBy.length > 0 ? describedBy.join(' ') : undefined - }), - ...other - }); - } - const downshiftInputProps = getDownshiftInputProps({ - ...inputProps, - disabled: true, - 'aria-autocomplete': undefined, - 'aria-activedescendant': undefined, - 'aria-controls': undefined, - 'aria-expanded': undefined, - 'aria-hidden': true, - 'aria-labelledby': undefined - }); - const handleFocus = () => { - if (!isEditable) { - triggerRef.current?.focus(); - } - }; - return { - ...downshiftInputProps, - disabled, - readOnly: true, - tabIndex: -1, - onFocus: composeEventHandlers$5(onFocus, handleFocus), - ...other - }; - }, [getDownshiftInputProps, getFieldInputProps, handleDownshiftStateChange, hasHint, hasMessage, inputValue, inputRef, triggerRef, disabled, isAutocomplete, isEditable]); - const getTagProps = reactExports.useCallback(_ref4 => { - let { - option, - onClick, - onKeyDown, - ...other - } = _ref4; - const handleClick = event => event.target instanceof Element && triggerRef.current?.contains(event.target) && event.stopPropagation(); - const handleKeyDown = event => { - if (event.key === KEYS$2.BACKSPACE || event.key === KEYS$2.DELETE) { - setDownshiftSelection(option.value); - } else { - const triggerContainsTag = event.target instanceof Element && triggerRef.current?.contains(event.target); - if (triggerContainsTag && !isEditable) { - event.stopPropagation(); - } - if (triggerContainsTag && (event.key === KEYS$2.DOWN || event.key === KEYS$2.UP || event.key === KEYS$2.ESCAPE || !isEditable && (event.key === KEYS$2.ENTER || event.key === KEYS$2.SPACE))) { - const inputProps = getDownshiftInputProps(); - if (isEditable) { - inputRef.current?.focus(); - } else { - event.preventDefault(); - triggerRef.current?.focus(); - } - inputProps.onKeyDown && inputProps.onKeyDown(event); - } - } - }; - return { - 'data-garden-container-id': 'containers.combobox.tag', - 'data-garden-container-version': '1.1.4', - onClick: composeEventHandlers$5(onClick, handleClick), - onKeyDown: composeEventHandlers$5(onKeyDown, handleKeyDown), - ...other - }; - }, [triggerRef, setDownshiftSelection, getDownshiftInputProps, isEditable, inputRef]); - const getListboxProps = reactExports.useCallback(_ref5 => { - let { - role = 'listbox', - ...other - } = _ref5; - return getDownshiftListboxProps({ - 'data-garden-container-id': 'containers.combobox.listbox', - 'data-garden-container-version': '1.1.4', - ref: listboxRef, - role, - 'aria-multiselectable': isMultiselectable ? true : undefined, - ...other - }); - }, [getDownshiftListboxProps, listboxRef, isMultiselectable]); - const getOptGroupProps = reactExports.useCallback(_ref6 => { - let { - role = 'group', - ...other - } = _ref6; - return { - 'data-garden-container-id': 'containers.combobox.optgroup', - 'data-garden-container-version': '1.1.4', - role: role === null ? undefined : role, - ...other - }; - }, []); - const getOptionProps = reactExports.useCallback(function (_temp4) { - let { - role = 'option', - option, - onMouseDown, - ...other - } = _temp4 === void 0 ? {} : _temp4; - const optionProps = { - 'data-garden-container-id': 'containers.combobox.option', - 'data-garden-container-version': '1.1.4', - role, - onMouseDown, - ...other - }; - let ariaSelected = false; - if (option?.value !== undefined) { - ariaSelected = Array.isArray(_selectionValue) ? _selectionValue?.includes(option?.value) : _selectionValue === option?.value; - } - if (option?.hidden) { - return { - 'aria-disabled': option.disabled ? true : undefined, - 'aria-hidden': true, - 'aria-selected': ariaSelected, - id: option ? idRef.current.getOptionId(hiddenValues.indexOf(option.value), option.disabled, option.hidden) : undefined, - ...optionProps - }; - } - if (option === undefined || option.disabled) { - const handleMouseDown = event => event.preventDefault(); - return { - 'aria-disabled': true, - 'aria-selected': ariaSelected, - id: option ? idRef.current.getOptionId(disabledValues.indexOf(option.value), option.disabled, option.hidden) : undefined, - ...optionProps, - onMouseDown: composeEventHandlers$5(onMouseDown, handleMouseDown) - }; - } - return getDownshiftOptionProps({ - item: option.value, - index: values.indexOf(option.value), - 'aria-disabled': undefined, - 'aria-hidden': undefined, - 'aria-selected': ariaSelected, - ...optionProps - }); - }, [getDownshiftOptionProps, disabledValues, hiddenValues, values, _selectionValue]); - const getMessageProps = reactExports.useCallback(props => getFieldMessageProps({ - id: idRef.current.message, - ...props - }), [getFieldMessageProps]); - const removeSelection = reactExports.useCallback(value => { - if (value === undefined) { - setDownshiftSelection(null); - } else { - const removeValue = typeof value === 'object' && 'value' in value ? value.value : value; - if (Array.isArray(_selectionValue) && _selectionValue.includes(removeValue)) { - setDownshiftSelection(removeValue); - } else if (_selectionValue === removeValue) { - setDownshiftSelection(null); - } else ; - } - }, [_selectionValue, setDownshiftSelection]); - const selection = reactExports.useMemo(() => { - if (Array.isArray(_selectionValue)) { - return _selectionValue.map(value => ({ - value, - label: labels[value], - disabled: disabledValues.includes(value), - hidden: hiddenValues.includes(value) - })); - } else if (_selectionValue) { - return { - value: _selectionValue, - label: toLabel(labels, _selectionValue), - disabled: disabledValues.includes(_selectionValue), - hidden: hiddenValues.includes(_selectionValue) - }; - } - return null; - }, [_selectionValue, disabledValues, hiddenValues, labels]); - return reactExports.useMemo(() => ({ - getLabelProps, - getHintProps, - getTriggerProps, - getInputProps, - getTagProps, - getListboxProps, - getOptGroupProps, - getOptionProps, - getMessageProps, - selection, - isExpanded: _isExpanded, - activeValue: values[_activeIndex], - inputValue: _inputValue, - removeSelection - }), [values, selection, _isExpanded, _activeIndex, _inputValue, getLabelProps, getHintProps, getTriggerProps, getInputProps, getTagProps, getListboxProps, getOptGroupProps, getOptionProps, getMessageProps, removeSelection]); -}; -({ - children: PropTypes.func, - render: PropTypes.func, - idPrefix: PropTypes.string, - triggerRef: PropTypes.any.isRequired, - inputRef: PropTypes.any.isRequired, - listboxRef: PropTypes.any.isRequired, - isAutocomplete: PropTypes.bool, - isMultiselectable: PropTypes.bool, - isEditable: PropTypes.bool, - disabled: PropTypes.bool, - hasHint: PropTypes.bool, - hasMessage: PropTypes.bool, - options: PropTypes.arrayOf(PropTypes.any).isRequired, - inputValue: PropTypes.string, - selectionValue: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), - isExpanded: PropTypes.bool, - defaultExpanded: PropTypes.bool, - initialExpanded: PropTypes.bool, - activeIndex: PropTypes.number, - defaultActiveIndex: PropTypes.number, - initialActiveIndex: PropTypes.number, - onChange: PropTypes.func, - environment: PropTypes.any -}); - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _path$i; -function _extends$l() { _extends$l = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$l.apply(this, arguments); } -var SvgChevronDownStroke$1 = function SvgChevronDownStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$l({ - xmlns: "http://www.w3.org/2000/svg", - width: 16, - height: 16, - focusable: "false", - viewBox: "0 0 16 16", - "aria-hidden": "true" - }, props), _path$i || (_path$i = /*#__PURE__*/reactExports.createElement("path", { - fill: "currentColor", - d: "M12.688 5.61a.5.5 0 01.69.718l-.066.062-5 4a.5.5 0 01-.542.054l-.082-.054-5-4a.5.5 0 01.55-.83l.074.05L8 9.359l4.688-3.75z" - }))); -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const ComboboxContext = reactExports.createContext(undefined); -const useComboboxContext = () => { - const context = reactExports.useContext(ComboboxContext); - if (!context) { - throw new Error('Error: this component must be rendered within a .'); - } - return context; -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const FieldContext = reactExports.createContext(undefined); -const useFieldContext = () => { - const context = reactExports.useContext(FieldContext); - if (!context) { - throw new Error('Error: this component must be rendered within a .'); - } - return context; -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$X = 'dropdowns.combobox.label'; -const StyledLabel = styled(Label$2).attrs({ - 'data-garden-id': COMPONENT_ID$X, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledLabel", - componentId: "sc-1889zee-0" -})(["vertical-align:revert;", ";"], props => retrieveComponentStyles(COMPONENT_ID$X, props)); -StyledLabel.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$W = 'dropdowns.combobox.hint'; -const StyledHint = styled(Hint$1).attrs({ - 'data-garden-id': COMPONENT_ID$W, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledHint", - componentId: "sc-9kt30-0" -})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$W, props)); -StyledHint.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$V = 'dropdowns.combobox.message'; -const StyledMessage = styled(Message$1).attrs({ - 'data-garden-id': COMPONENT_ID$V, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledMessage", - componentId: "sc-15eqzu4-0" -})(["", ";"], props => retrieveComponentStyles(COMPONENT_ID$V, props)); -StyledMessage.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$U = 'dropdowns.combobox'; -const sizeStyles$i = props => { - const minWidth = `${props.isCompact ? 100 : 144}px`; - const marginTop = `${props.theme.space.base * (props.isCompact ? 1 : 2)}px`; - return Ne(["min-width:", ";", ":not([hidden]) + &&,", " + &&,", " + &&,&& + ", ",&& + ", "{margin-top:", ";}"], minWidth, StyledLabel, StyledHint, StyledMessage, StyledHint, StyledMessage, marginTop); -}; -const StyledCombobox = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$U, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledCombobox", - componentId: "sc-1hs98ew-0" -})(["", ";", ";"], sizeStyles$i, props => retrieveComponentStyles(COMPONENT_ID$U, props)); -StyledCombobox.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$T = 'dropdowns.combobox.container'; -const StyledContainer = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$T, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledContainer", - componentId: "sc-18gcb1g-0" -})(["display:flex;", ";"], props => retrieveComponentStyles(COMPONENT_ID$T, props)); -StyledContainer.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$S = 'dropdowns.combobox.field'; -const StyledField = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$S, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledField", - componentId: "sc-k7y10k-0" -})(["direction:", ";", ";"], props => props.theme.rtl ? 'rtl' : 'ltr', props => retrieveComponentStyles(COMPONENT_ID$S, props)); -StyledField.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$R = 'dropdowns.combobox.floating'; -const StyledFloatingListbox = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$R, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledFloatingListbox", - componentId: "sc-xsp548-0" -})(["top:0;left:0;", ";", ";"], props => menuStyles(props.position, { - theme: props.theme, - hidden: props.isHidden, - animationModifier: '[data-garden-animate="true"]', - zIndex: props.zIndex -}), props => retrieveComponentStyles(COMPONENT_ID$R, props)); -StyledFloatingListbox.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$Q = 'dropdowns.combobox.input'; -const colorStyles$i = props => { - const placeholderColor = getColorV8('neutralHue', 400, props.theme); - return Ne(["background-color:inherit;color:inherit;&::placeholder{opacity:1;color:", ";}"], placeholderColor); -}; -const getHeight = props => { - if (props.isBare && !props.isMultiselectable) { - return props.theme.space.base * 5; - } - return props.theme.space.base * (props.isCompact ? 5 : 8); -}; -const sizeStyles$h = props => { - const height = props.theme.space.base * 5; - const fontSize = props.theme.fontSizes.md; - const lineHeight = getLineHeight(height, fontSize); - const margin = math$1(`${props.theme.shadowWidths.sm} + ${(getHeight(props) - height) / 2}`); - const minWidth = `${props.theme.space.base * 8}px`; - return Ne(["min-width:", ";height:", "px;line-height:", ";font-size:", ";&&{margin-top:", ";margin-bottom:", ";}"], minWidth, height, lineHeight, fontSize, margin, margin); -}; -const StyledInput = styled.input.attrs({ - 'data-garden-id': COMPONENT_ID$Q, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledInput", - componentId: "sc-m2m56e-0" -})(["flex-basis:0;flex-grow:1;border:none;padding:0;font-family:inherit;&:focus{outline:none;}", ";", ";&[hidden]{display:revert;", "}&[aria-hidden='true']{display:none;}", ";"], sizeStyles$h, colorStyles$i, props => props.isEditable && hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$Q, props)); -StyledInput.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$P = 'dropdowns.combobox.input_group'; -const sizeStyles$g = props => { - const margin = props.theme.shadowWidths.sm; - return Ne(["margin:-", ";min-width:0;& > *{margin:", ";}"], margin, margin); -}; -const StyledInputGroup = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$P, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledInputGroup", - componentId: "sc-2agt8f-0" -})(["display:flex;flex-grow:1;flex-wrap:wrap;", ";", ";"], sizeStyles$g, props => retrieveComponentStyles(COMPONENT_ID$P, props)); -StyledInputGroup.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$O = 'dropdowns.combobox.trigger'; -const colorStyles$h = props => { - const SHADE = 600; - let hue = 'neutralHue'; - if (props.validation === 'success') { - hue = 'successHue'; - } else if (props.validation === 'warning') { - hue = 'warningHue'; - } else if (props.validation === 'error') { - hue = 'dangerHue'; - } - const backgroundColor = props.isBare ? 'transparent' : getColorV8('background', 600 , props.theme); - let borderColor; - let hoverBorderColor; - let focusBorderColor; - let focusShade; - if (props.validation) { - borderColor = getColorV8(hue, SHADE, props.theme); - hoverBorderColor = borderColor; - if (props.validation === 'warning') { - focusBorderColor = getColorV8(hue, SHADE + 100, props.theme); - focusShade = SHADE + 100; - } else { - focusBorderColor = borderColor; - } - } else { - borderColor = getColorV8('neutralHue', SHADE - 300, props.theme); - hoverBorderColor = getColorV8('primaryHue', SHADE, props.theme); - focusBorderColor = hoverBorderColor; - } - const disabledBackgroundColor = props.isBare ? undefined : getColorV8('neutralHue', SHADE - 500, props.theme); - const disabledBorderColor = getColorV8('neutralHue', SHADE - 400, props.theme); - const disabledForegroundColor = getColorV8('neutralHue', SHADE - 200, props.theme); - const focusSelector = ` - &:focus-within:not([aria-disabled='true']), - &:focus-visible - `; - return Ne(["border-color:", ";background-color:", ";color:", ";&:hover{border-color:", ";}", " &[aria-disabled='true']{border-color:", ";background-color:", ";color:", ";}"], props.isLabelHovered ? hoverBorderColor : borderColor, backgroundColor, getColorV8('foreground', 600 , props.theme), hoverBorderColor, focusStyles({ - theme: props.theme, - inset: props.focusInset, - hue: focusBorderColor, - shade: focusShade, - selector: focusSelector, - styles: { - borderColor: focusBorderColor - }, - condition: !props.isBare - }), disabledBorderColor, disabledBackgroundColor, disabledForegroundColor); -}; -const sizeStyles$f = props => { - const inputHeight = getHeight(props); - let minHeight; - let horizontalPadding; - if (props.isBare) { - if (props.isMultiselectable) { - minHeight = math$1(`${props.theme.shadowWidths.sm} * 2 + ${inputHeight}`); - horizontalPadding = props.theme.shadowWidths.sm; - } else { - minHeight = `${inputHeight}px`; - horizontalPadding = '0'; - } - } else { - minHeight = `${props.theme.space.base * (props.isCompact ? 3 : 2) + inputHeight}px`; - horizontalPadding = `${props.theme.space.base * 3}px`; - } - const maxHeight = props.maxHeight || minHeight; - const verticalPadding = math$1(`(${minHeight} - ${inputHeight} - (${props.isBare ? 0 : props.theme.borderWidths.sm} * 2)) / 2`); - return Ne(["padding:", " ", ";min-height:", ";max-height:", ";font-size:", ";"], verticalPadding, horizontalPadding, minHeight, maxHeight, props.theme.fontSizes.md); -}; -const StyledTrigger = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$O, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTrigger", - componentId: "sc-14t9k4c-0" -})(["overflow-y:auto;transition:border-color 0.25s ease-in-out,box-shadow 0.1s ease-in-out,background-color 0.25s ease-in-out,color 0.25s ease-in-out;border:", ";border-radius:", ";cursor:", ";box-sizing:border-box;", ";&:focus{outline:none;}", ";&[aria-disabled='true']{cursor:default;}", ";"], props => props.isBare ? 'none' : props.theme.borders.sm, props => props.isBare ? '0' : props.theme.borderRadii.md, props => !props.isAutocomplete && props.isEditable ? 'text' : 'pointer', sizeStyles$f, colorStyles$h, props => retrieveComponentStyles(COMPONENT_ID$O, props)); -StyledTrigger.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$N = 'dropdowns.combobox.input_icon'; -const colorStyles$g = props => { - const color = getColorV8('neutralHue', 600, props.theme); - const focusColor = getColorV8('neutralHue', 700, props.theme); - const disabledColor = getColorV8('neutralHue', 400, props.theme); - return Ne(["color:", ";", ":hover &,", ":focus-within &,", ":focus &,", "[data-garden-focus-visible='true'] &{color:", ";}", "[aria-disabled='true'] &{color:", ";}"], props.isLabelHovered ? focusColor : color, StyledTrigger, StyledTrigger, StyledTrigger, StyledTrigger, focusColor, StyledTrigger, disabledColor); -}; -const sizeStyles$e = props => { - const size = props.theme.iconSizes.md; - const position = math$1(`(${getHeight(props)} - ${size}) / 2`); - const margin = `${props.theme.space.base * 2}px`; - let side; - if (props.isEnd) { - side = props.theme.rtl ? 'right' : 'left'; - } else { - side = props.theme.rtl ? 'left' : 'right'; - } - return Ne(["top:", ";margin-", ":", ";width:", ";height:", ";"], position, side, margin, size, size); -}; -const StyledInputIcon = styled(_ref => { - let { - children, - isCompact, - isDisabled, - isEnd, - isLabelHovered, - isRotated, - theme, - ...props - } = _ref; - return reactExports.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$N, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledInputIcon", - componentId: "sc-15ewmjl-0" -})(["position:sticky;flex-shrink:0;transform:", ";transition:transform 0.25s ease-in-out,color 0.25s ease-in-out;", ";", ";", ";"], props => props.isRotated && `rotate(${props.theme.rtl ? '-' : '+'}180deg)`, sizeStyles$e, colorStyles$g, props => retrieveComponentStyles(COMPONENT_ID$N, props)); -StyledInputIcon.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$M = 'dropdowns.combobox.option'; -const colorStyles$f = props => { - let backgroundColor; - let boxShadow; - if (props.isActive && props.$type !== 'group' && props.$type !== 'header') { - const hue = props.$type === 'danger' ? 'dangerHue' : 'primaryHue'; - backgroundColor = getColorV8(hue, 600, props.theme, 0.08); - boxShadow = `inset ${props.theme.rtl ? `-${props.theme.shadowWidths.md}` : props.theme.shadowWidths.md} 0 ${getColorV8(hue, 600, props.theme)}`; - } - const disabledForegroundColor = getColorV8('neutralHue', 400, props.theme); - let foregroundColor = getColorV8('foreground', 600 , props.theme); - if (props.$type === 'add') { - foregroundColor = getColorV8('primaryHue', 600, props.theme); - } else if (props.$type === 'danger') { - foregroundColor = getColorV8('dangerHue', 600, props.theme); - } - return Ne(["box-shadow:", ";background-color:", ";color:", ";&[aria-disabled='true']{background-color:transparent;color:", ";}"], boxShadow, backgroundColor, foregroundColor, disabledForegroundColor); -}; -const getMinHeight = props => props.theme.space.base * (props.isCompact ? 7 : 9); -const sizeStyles$d = props => { - const lineHeight = props.theme.lineHeights.md; - const minHeight = getMinHeight(props); - const paddingHorizontal = props.$type === 'group' ? 0 : `${props.theme.space.base * 9}px`; - const paddingVertical = props.$type === 'group' ? 0 : math$1(`(${minHeight} - ${lineHeight}) / 2`); - return Ne(["box-sizing:border-box;padding:", " ", ";min-height:", "px;line-height:", ";"], paddingVertical, paddingHorizontal, minHeight, lineHeight); -}; -const StyledOption = styled.li.attrs({ - 'data-garden-id': COMPONENT_ID$M, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOption", - componentId: "sc-1b5e09t-0" -})(["display:flex;position:relative;transition:color 0.25s ease-in-out;cursor:", ";overflow-wrap:anywhere;font-weight:", ";user-select:none;&:focus{outline:none;}", ";", ";&[aria-disabled='true']{cursor:default;}&[aria-hidden='true']{", ";}", ";"], props => props.$type === 'group' || props.$type === 'header' ? 'default' : 'pointer', props => props.$type === 'header' || props.$type === 'previous' ? props.theme.fontWeights.semibold : props.theme.fontWeights.regular, sizeStyles$d, colorStyles$f, hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$M, props)); -StyledOption.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$L = 'dropdowns.combobox.option.content'; -const StyledOptionContent = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$L, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOptionContent", - componentId: "sc-536085-0" -})(["display:flex;flex-direction:column;flex-grow:1;", ";"], props => retrieveComponentStyles(COMPONENT_ID$L, props)); -StyledOptionContent.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$K = 'dropdowns.combobox.optgroup'; -const StyledOptGroup = styled.ul.attrs({ - 'data-garden-id': COMPONENT_ID$K, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOptGroup", - componentId: "sc-12dbq5s-0" -})(["margin:0;padding:0;list-style-type:none;", ";"], props => retrieveComponentStyles(COMPONENT_ID$K, props)); -StyledOptGroup.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$J = 'dropdowns.combobox.separator'; -const colorStyles$e = props => { - const backgroundColor = getColorV8('neutralHue', 200, props.theme); - return Ne(["background-color:", ";"], backgroundColor); -}; -const sizeStyles$c = props => { - const margin = `${props.theme.space.base}px`; - const height = props.theme.borderWidths.sm; - return Ne(["margin:", " 0;height:", ";"], margin, height); -}; -const StyledListboxSeparator = styled.li.attrs({ - 'data-garden-id': COMPONENT_ID$J, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledListboxSeparator", - componentId: "sc-19umtmg-0" -})(["cursor:default;", ";", ";", ";"], sizeStyles$c, colorStyles$e, props => retrieveComponentStyles(COMPONENT_ID$J, props)); -StyledListboxSeparator.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$I = 'dropdowns.combobox.listbox'; -const sizeStyles$b = props => { - const padding = props.theme.space.base; - const minHeight = props.minHeight === undefined ? `${getMinHeight(props) + padding * 2}px` : props.minHeight; - return Ne(["min-height:", ";max-height:", ";&&&{padding-top:", "px;padding-bottom:", "px;}"], minHeight, props.maxHeight, padding, padding); -}; -const StyledListbox = styled.ul.attrs({ - 'data-garden-id': COMPONENT_ID$I, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledListbox", - componentId: "sc-4uxeym-0" -})(["overflow-y:auto;list-style-type:none;", ";&&&{display:block;}", ":first-child ", " ", ":first-child ", "[role='none']:first-child{display:none;}"], sizeStyles$b, StyledOption, StyledOptionContent, StyledOptGroup, StyledListboxSeparator); -StyledListbox.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$H = 'dropdowns.combobox.option.icon'; -const sizeStyles$a = props => { - const size = props.theme.iconSizes.md; - const marginTop = math$1(`(${props.theme.lineHeights.md} - ${size}) / 2`); - const marginHorizontal = `${props.theme.space.base * 2}px`; - return Ne(["margin-top:", ";margin-", ":", ";width:", ";height:", ";"], marginTop, props.theme.rtl ? 'left' : 'right', marginHorizontal, size, size); -}; -const StyledOptionIcon = styled(_ref => { - let { - children, - theme, - ...props - } = _ref; - return reactExports.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$H, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOptionIcon", - componentId: "sc-3vecfi-0" -})(["flex-shrink:0;", ";", ";"], sizeStyles$a, props => retrieveComponentStyles(COMPONENT_ID$H, props)); -StyledOptionIcon.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$G = 'dropdowns.combobox.option.meta'; -const colorStyles$d = props => { - const color = getColorV8('neutralHue', props.isDisabled ? 400 : 600, props.theme); - return Ne(["color:", ";"], color); -}; -const sizeStyles$9 = props => { - const lineHeight = props.theme.lineHeights.sm; - const fontSize = props.theme.fontSizes.sm; - return Ne(["line-height:", ";font-size:", ";"], lineHeight, fontSize); -}; -const StyledOptionMeta = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$G, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOptionMeta", - componentId: "sc-1nizjb3-0" -})(["transition:color 0.25s ease-in-out;font-weight:", ";", ";", ";", ";"], props => props.theme.fontWeights.regular, sizeStyles$9, colorStyles$d, props => retrieveComponentStyles(COMPONENT_ID$G, props)); -StyledOptionMeta.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$F = 'dropdowns.combobox.option.type_icon'; -const colorStyles$c = props => { - const opacity = props.type && props.type !== 'danger' ? 1 : 0; - let color; - if (props.type === 'add' || props.type === 'danger') { - color = 'inherit'; - } else if (props.type === 'header' || props.type === 'next' || props.type === 'previous') { - color = getColorV8('neutralHue', 600, props.theme); - } else { - color = getColorV8('primaryHue', 600, props.theme); - } - return Ne(["opacity:", ";color:", ";", "[aria-selected='true'] > &{opacity:1;}", "[aria-disabled='true'] > &{color:inherit;}"], opacity, color, StyledOption, StyledOption); -}; -const sizeStyles$8 = props => { - const size = props.theme.iconSizes.md; - const position = `${props.theme.space.base * 3}px`; - const top = math$1(`(${getMinHeight(props)} - ${size}) / 2`); - let side; - if (props.type === 'next') { - side = props.theme.rtl ? 'left' : 'right'; - } else { - side = props.theme.rtl ? 'right' : 'left'; - } - return Ne(["top:", ";", ":", ";width:", ";height:", ";"], top, side, position, size, size); -}; -const StyledOptionTypeIcon = styled(_ref => { - let { - children, - isCompact, - theme, - type, - ...props - } = _ref; - return reactExports.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$F, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledOptionTypeIcon", - componentId: "sc-vlhimu-0" -})(["position:absolute;transform:", ";transition:opacity 0.1s ease-in-out;", ";", ";", ";"], props => props.theme.rtl && (props.type === 'next' || props.type === 'previous') && 'rotate(180deg)', sizeStyles$8, colorStyles$c, props => retrieveComponentStyles(COMPONENT_ID$F, props)); -StyledOptionTypeIcon.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ -const SIZE$2 = ['small', 'medium', 'large']; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$E = 'tags.avatar'; -const StyledAvatar = styled(_ref => { - let { - children, - ...props - } = _ref; - return React__default.cloneElement(reactExports.Children.only(children), props); -}).attrs({ - 'data-garden-id': COMPONENT_ID$E, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledAvatar", - componentId: "sc-3kdmgt-0" -})(["flex-shrink:0;font-size:0;", ";"], props => retrieveComponentStyles(COMPONENT_ID$E, props)); -StyledAvatar.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$D = 'tags.close'; -const StyledClose$1 = styled.button.attrs({ - 'data-garden-id': COMPONENT_ID$D, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledClose", - componentId: "sc-d6lrpn-0" -})(["display:flex;flex-shrink:0;align-items:center;justify-content:center;transition:opacity 0.25s ease-in-out;opacity:0.8;border:0;background:transparent;cursor:pointer;padding:0;color:inherit;font-size:0;appearance:none;&:hover{opacity:0.9;}&:focus{outline:none;}", ";"], props => retrieveComponentStyles(COMPONENT_ID$D, props)); -StyledClose$1.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$C = 'tags.tag_view'; -const colorStyles$b = props => { - let backgroundColor; - let foregroundColor; - let closeColor; - if (props.hue) { - const shade = props.hue === 'yellow' ? 400 : 600; - backgroundColor = getColorV8(props.hue, shade, props.theme); - if (props.hue === 'yellow' || props.hue === 'lemon') { - foregroundColor = getColorV8('yellow', 800, props.theme); - } else { - foregroundColor = readableColor(backgroundColor, props.theme.palette.grey[800], props.theme.palette.white); - } - } else { - backgroundColor = getColorV8('neutralHue', 200, props.theme); - foregroundColor = getColorV8('neutralHue', 700, props.theme); - closeColor = getColorV8('neutralHue', 600, props.theme); - } - return Ne(["background-color:", ";color:", ";&:hover{color:", ";}", " & ", "{color:", ";}"], backgroundColor, foregroundColor, foregroundColor, focusStyles({ - theme: props.theme, - shadowWidth: 'sm', - selector: '&:focus' - }), StyledClose$1, closeColor); -}; -const sizeStyles$7 = props => { - let borderRadius; - let padding; - let height; - let fontSize; - let minWidth; - let avatarSize; - if (props.size === 'small') { - borderRadius = props.theme.borderRadii.sm; - padding = props.theme.space.base; - height = props.theme.space.base * 4; - fontSize = props.theme.fontSizes.xs; - avatarSize = 0; - } else if (props.size === 'large') { - borderRadius = props.theme.borderRadii.md; - padding = props.theme.space.base * 3; - height = props.theme.space.base * 8; - fontSize = props.theme.fontSizes.sm; - avatarSize = props.theme.space.base * 6; - } else { - borderRadius = props.theme.borderRadii.sm; - padding = props.theme.space.base * 2; - height = props.theme.space.base * 5; - fontSize = props.theme.fontSizes.sm; - avatarSize = props.theme.space.base * 4; - } - let avatarBorderRadius = props.size === 'large' ? math$1(`${borderRadius} - 1`) : borderRadius; - const avatarMargin = (height - avatarSize) / 2; - const avatarTextMargin = props.isRound ? avatarMargin : avatarMargin * 2; - if (props.isRound) { - borderRadius = '50%'; - padding = 0; - minWidth = height; - avatarBorderRadius = '50%'; - } else if (props.isPill) { - borderRadius = '100px'; - avatarBorderRadius = '50%'; - if (props.size === 'small') { - padding = props.theme.space.base * 1.5; - minWidth = props.theme.space.base * 6; - } else if (props.size === 'large') { - minWidth = props.theme.space.base * 12; - } else { - minWidth = props.theme.space.base * 7.5; - } - } - return Ne(["border-radius:", ";padding:0 ", "px;min-width:", ";height:", "px;line-height:", ";font-size:", ";& > *{width:100%;min-width:", ";}& ", "{margin-", ":-", "px;margin-", ":", "px;border-radius:", ";width:", "px;min-width:", "px;height:", "px;}& ", "{margin-", ":-", "px;border-radius:", ";width:", "px;height:", "px;}"], borderRadius, padding, minWidth ? `${minWidth}px` : `calc(${padding * 2}px + 1ch)`, height, getLineHeight(height, fontSize), fontSize, minWidth ? `${minWidth - padding * 2}px` : '1ch', StyledAvatar, props.theme.rtl ? 'right' : 'left', padding - avatarMargin, props.theme.rtl ? 'left' : 'right', avatarTextMargin, avatarBorderRadius, avatarSize, avatarSize, avatarSize, StyledClose$1, props.theme.rtl ? 'left' : 'right', padding, borderRadius, height, height); -}; -const StyledTag$1 = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$C, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTag", - componentId: "sc-1jvbe03-0" -})(["display:inline-flex;flex-wrap:nowrap;align-items:center;justify-content:", ";transition:box-shadow 0.1s ease-in-out;box-sizing:border-box;border:0;max-width:100%;overflow:hidden;vertical-align:middle;text-decoration:none;white-space:nowrap;font-weight:", ";direction:", ";", ";&:hover{cursor:default;text-decoration:none;}&:link:hover,&:visited:hover{cursor:pointer;}&:any-link:hover{cursor:pointer;}", "{text-decoration:none;}", ";& > *{overflow:hidden;text-align:center;text-overflow:ellipsis;white-space:nowrap;}& b{font-weight:", ";}& ", "{display:", ";}& ", "{display:", ";}", ";"], props => props.isRound && 'center', props => !props.isRegular && props.theme.fontWeights.semibold, props => props.theme.rtl ? 'rtl' : 'ltr', props => sizeStyles$7(props), SELECTOR_FOCUS_VISIBLE, props => colorStyles$b(props), props => props.theme.fontWeights.semibold, StyledAvatar, props => (props.isRound || props.size === 'small') && 'none', StyledClose$1, props => props.isRound && 'none', props => retrieveComponentStyles(COMPONENT_ID$C, props)); -StyledTag$1.defaultProps = { - size: 'medium', - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -var _path$h; -function _extends$k() { _extends$k = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$k.apply(this, arguments); } -var SvgXStroke$1 = function SvgXStroke(props) { - return /*#__PURE__*/reactExports.createElement("svg", _extends$k({ - xmlns: "http://www.w3.org/2000/svg", - width: 12, - height: 12, - focusable: "false", - viewBox: "0 0 12 12", - "aria-hidden": "true" - }, props), _path$h || (_path$h = /*#__PURE__*/reactExports.createElement("path", { - stroke: "currentColor", - strokeLinecap: "round", - d: "M3 9l6-6m0 6L3 3" - }))); -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const CloseComponent = reactExports.forwardRef((props, ref) => { - const ariaLabel = useText(CloseComponent, props, 'aria-label', 'Remove'); - return React__default.createElement(StyledClose$1, Object.assign({ - ref: ref, - "aria-label": ariaLabel - }, props, { - type: "button", - tabIndex: -1 - }), React__default.createElement(SvgXStroke$1, null)); -}); -CloseComponent.displayName = 'Tag.Close'; -const Close$1 = CloseComponent; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const AvatarComponent = props => React__default.createElement(StyledAvatar, props); -AvatarComponent.displayName = 'Tag.Avatar'; -const Avatar = AvatarComponent; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const TagComponent$1 = reactExports.forwardRef((_ref, ref) => { - let { - size, - hue, - ...otherProps - } = _ref; - return React__default.createElement(StyledTag$1, Object.assign({ - ref: ref, - size: size, - hue: hue - }, otherProps)); -}); -TagComponent$1.displayName = 'Tag'; -TagComponent$1.propTypes = { - size: PropTypes.oneOf(SIZE$2), - hue: PropTypes.string, - isPill: PropTypes.bool, - isRound: PropTypes.bool, - isRegular: PropTypes.bool -}; -TagComponent$1.defaultProps = { - size: 'medium' -}; -const Tag$1 = TagComponent$1; -Tag$1.Avatar = Avatar; -Tag$1.Close = Close$1; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$B = 'dropdowns.combobox.tag'; -const StyledTag = styled(Tag$1).attrs({ - 'data-garden-id': COMPONENT_ID$B, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTag", - componentId: "sc-1mrab0f-0" -})(["&[aria-disabled='true']{color:", ";}&[hidden]{display:revert;", "}", ";"], props => props.hue ? undefined : getColorV8('neutralHue', 400, props.theme), hideVisually(), props => retrieveComponentStyles(COMPONENT_ID$B, props)); -StyledTag.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$A = 'dropdowns.combobox.value'; -const colorStyles$a = props => { - const foregroundColor = props.isPlaceholder && getColorV8('neutralHue', 400, props.theme); - return Ne(["color:", ";"], foregroundColor); -}; -const StyledValue = styled.div.attrs({ - 'data-garden-id': COMPONENT_ID$A, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledValue", - componentId: "sc-16gp0f-0" -})(["flex-basis:0;flex-grow:1;cursor:", ";overflow:hidden;text-overflow:ellipsis;white-space:pre;user-select:none;", ";", ";&[hidden]{display:none;}", ";"], props => { - if (props.isDisabled) { - return 'default'; - } - return props.isEditable && !props.isAutocomplete ? 'text' : 'pointer'; -}, sizeStyles$h, colorStyles$a, props => retrieveComponentStyles(COMPONENT_ID$A, props)); -StyledValue.defaultProps = { - theme: DEFAULT_THEME -}; - -/** -* Copyright Zendesk, Inc. -* -* Use of this source code is governed under the Apache License, Version 2.0 -* found at http://www.apache.org/licenses/LICENSE-2.0. -*/ - -const COMPONENT_ID$z = 'dropdowns.combobox.tags_button'; -const colorStyles$9 = props => { - const color = getColorV8('primaryHue', 600, props.theme); - return Ne(["color:", ";&:disabled{color:inherit;}"], color); -}; -const StyledTagsButton = styled(StyledValue).attrs({ - as: 'button', - 'data-garden-id': COMPONENT_ID$z, - 'data-garden-version': '8.76.2' -}).withConfig({ - displayName: "StyledTagsButton", - componentId: "sc-ewyffo-0" -})(["display:inline-flex;flex:0 1 auto;align-items:center;border:none;background-color:transparent;cursor:pointer;min-width:auto;font-family:inherit;&:hover{text-decoration:underline;}", ";&:disabled{cursor:default;text-decoration:none;}", ";"], colorStyles$9, props => retrieveComponentStyles(COMPONENT_ID$z, props)); -StyledTagsButton.defaultProps = { - theme: DEFAULT_THEME -}; - -const min$1 = Math.min; -const max$1 = Math.max; -const round = Math.round; -const floor = Math.floor; -const createCoords = v => ({ - x: v, - y: v -}); -const oppositeSideMap = { - left: 'right', - right: 'left', - bottom: 'top', - top: 'bottom' -}; -const oppositeAlignmentMap = { - start: 'end', - end: 'start' -}; -function evaluate(value, param) { - return typeof value === 'function' ? value(param) : value; -} -function getSide(placement) { - return placement.split('-')[0]; -} -function getAlignment(placement) { - return placement.split('-')[1]; -} -function getOppositeAxis(axis) { - return axis === 'x' ? 'y' : 'x'; -} -function getAxisLength(axis) { - return axis === 'y' ? 'height' : 'width'; -} -function getSideAxis(placement) { - return ['top', 'bottom'].includes(getSide(placement)) ? 'y' : 'x'; -} -function getAlignmentAxis(placement) { - return getOppositeAxis(getSideAxis(placement)); -} -function getAlignmentSides(placement, rects, rtl) { - if (rtl === void 0) { - rtl = false; - } - const alignment = getAlignment(placement); - const alignmentAxis = getAlignmentAxis(placement); - const length = getAxisLength(alignmentAxis); - let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; - if (rects.reference[length] > rects.floating[length]) { - mainAlignmentSide = getOppositePlacement$1(mainAlignmentSide); - } - return [mainAlignmentSide, getOppositePlacement$1(mainAlignmentSide)]; -} -function getExpandedPlacements(placement) { - const oppositePlacement = getOppositePlacement$1(placement); - return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; -} -function getOppositeAlignmentPlacement(placement) { - return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); -} -function getSideList(side, isStart, rtl) { - const lr = ['left', 'right']; - const rl = ['right', 'left']; - const tb = ['top', 'bottom']; - const bt = ['bottom', 'top']; - switch (side) { - case 'top': - case 'bottom': - if (rtl) return isStart ? rl : lr; - return isStart ? lr : rl; - case 'left': - case 'right': - return isStart ? tb : bt; - default: - return []; - } -} -function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { - const alignment = getAlignment(placement); - let list = getSideList(getSide(placement), direction === 'start', rtl); - if (alignment) { - list = list.map(side => side + "-" + alignment); - if (flipAlignment) { - list = list.concat(list.map(getOppositeAlignmentPlacement)); - } - } - return list; -} -function getOppositePlacement$1(placement) { - return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); -} -function expandPaddingObject(padding) { - return { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...padding - }; -} -function getPaddingObject(padding) { - return typeof padding !== 'number' ? expandPaddingObject(padding) : { - top: padding, - right: padding, - bottom: padding, - left: padding - }; -} -function rectToClientRect(rect) { - return { - ...rect, - top: rect.y, - left: rect.x, - right: rect.x + rect.width, - bottom: rect.y + rect.height - }; -} - -function computeCoordsFromPlacement(_ref, placement, rtl) { - let { - reference, - floating - } = _ref; - const sideAxis = getSideAxis(placement); - const alignmentAxis = getAlignmentAxis(placement); - const alignLength = getAxisLength(alignmentAxis); - const side = getSide(placement); - const isVertical = sideAxis === 'y'; - const commonX = reference.x + reference.width / 2 - floating.width / 2; - const commonY = reference.y + reference.height / 2 - floating.height / 2; - const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; - let coords; - switch (side) { - case 'top': - coords = { - x: commonX, - y: reference.y - floating.height - }; - break; - case 'bottom': - coords = { - x: commonX, - y: reference.y + reference.height - }; - break; - case 'right': - coords = { - x: reference.x + reference.width, - y: commonY - }; - break; - case 'left': - coords = { - x: reference.x - floating.width, - y: commonY - }; - break; - default: - coords = { - x: reference.x, - y: reference.y - }; - } - switch (getAlignment(placement)) { - case 'start': - coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); - break; - case 'end': - coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); - break; - } - return coords; -} - -/** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain positioning strategy. - * - * This export does not have any `platform` interface logic. You will need to - * write one for the platform you are using Floating UI with. - */ -const computePosition$1 = async (reference, floating, config) => { - const { - placement = 'bottom', - strategy = 'absolute', - middleware = [], - platform - } = config; - const validMiddleware = middleware.filter(Boolean); - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); - let rects = await platform.getElementRects({ - reference, - floating, - strategy - }); - let { - x, - y - } = computeCoordsFromPlacement(rects, placement, rtl); - let statefulPlacement = placement; - let middlewareData = {}; - let resetCount = 0; - for (let i = 0; i < validMiddleware.length; i++) { - const { - name, - fn - } = validMiddleware[i]; - const { - x: nextX, - y: nextY, - data, - reset - } = await fn({ - x, - y, - initialPlacement: placement, - placement: statefulPlacement, - strategy, - middlewareData, - rects, - platform, - elements: { - reference, - floating - } - }); - x = nextX != null ? nextX : x; - y = nextY != null ? nextY : y; - middlewareData = { - ...middlewareData, - [name]: { - ...middlewareData[name], - ...data - } - }; - if (reset && resetCount <= 50) { - resetCount++; - if (typeof reset === 'object') { - if (reset.placement) { - statefulPlacement = reset.placement; - } - if (reset.rects) { - rects = reset.rects === true ? await platform.getElementRects({ - reference, - floating, - strategy - }) : reset.rects; - } - ({ - x, - y - } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); - } - i = -1; - continue; - } - } - return { - x, - y, - placement: statefulPlacement, - strategy, - middlewareData - }; -}; - -/** - * Resolves with an object of overflow side offsets that determine how much the - * element is overflowing a given clipping boundary on each side. - * - positive = overflowing the boundary by that number of pixels - * - negative = how many pixels left before it will overflow - * - 0 = lies flush with the boundary - * @see https://floating-ui.com/docs/detectOverflow - */ -async function detectOverflow(state, options) { - var _await$platform$isEle; - if (options === void 0) { - options = {}; - } - const { - x, - y, - platform, - rects, - elements, - strategy - } = state; - const { - boundary = 'clippingAncestors', - rootBoundary = 'viewport', - elementContext = 'floating', - altBoundary = false, - padding = 0 - } = evaluate(options, state); - const paddingObject = getPaddingObject(padding); - const altContext = elementContext === 'floating' ? 'reference' : 'floating'; - const element = elements[altBoundary ? altContext : elementContext]; - const clippingClientRect = rectToClientRect(await platform.getClippingRect({ - element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), - boundary, - rootBoundary, - strategy - })); - const rect = elementContext === 'floating' ? { - ...rects.floating, - x, - y - } : rects.reference; - const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); - const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { - x: 1, - y: 1 - } : { - x: 1, - y: 1 - }; - const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ - rect, - offsetParent, - strategy - }) : rect); - return { - top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, - bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, - left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, - right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x - }; -} - -/** - * Optimizes the visibility of the floating element by flipping the `placement` - * in order to keep it in view when the preferred placement(s) will overflow the - * clipping boundary. Alternative to `autoPlacement`. - * @see https://floating-ui.com/docs/flip - */ -const flip$1 = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'flip', - options, - async fn(state) { - var _middlewareData$flip; - const { - placement, - middlewareData, - rects, - initialPlacement, - platform, - elements - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true, - fallbackPlacements: specifiedFallbackPlacements, - fallbackStrategy = 'bestFit', - fallbackAxisSideDirection = 'none', - flipAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const side = getSide(placement); - const isBasePlacement = getSide(initialPlacement) === initialPlacement; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement$1(initialPlacement)] : getExpandedPlacements(initialPlacement)); - if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') { - fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); - } - const placements = [initialPlacement, ...fallbackPlacements]; - const overflow = await detectOverflow(state, detectOverflowOptions); - const overflows = []; - let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; - if (checkMainAxis) { - overflows.push(overflow[side]); - } - if (checkCrossAxis) { - const sides = getAlignmentSides(placement, rects, rtl); - overflows.push(overflow[sides[0]], overflow[sides[1]]); - } - overflowsData = [...overflowsData, { - placement, - overflows - }]; - - // One or more sides is overflowing. - if (!overflows.every(side => side <= 0)) { - var _middlewareData$flip2, _overflowsData$filter; - const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; - const nextPlacement = placements[nextIndex]; - if (nextPlacement) { - // Try next placement and re-run the lifecycle. - return { - data: { - index: nextIndex, - overflows: overflowsData - }, - reset: { - placement: nextPlacement - } - }; - } - - // First, find the candidates that fit on the mainAxis side of overflow, - // then find the placement that fits the best on the main crossAxis side. - let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; - - // Otherwise fallback. - if (!resetPlacement) { - switch (fallbackStrategy) { - case 'bestFit': - { - var _overflowsData$map$so; - const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0]; - if (placement) { - resetPlacement = placement; - } - break; - } - case 'initialPlacement': - resetPlacement = initialPlacement; - break; - } - } - if (placement !== resetPlacement) { - return { - reset: { - placement: resetPlacement - } - }; - } - } - return {}; - } - }; -}; - -// For type backwards-compatibility, the `OffsetOptions` type was also -// Derivable. -async function convertValueToCoords(state, options) { - const { - placement, - platform, - elements - } = state; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const side = getSide(placement); - const alignment = getAlignment(placement); - const isVertical = getSideAxis(placement) === 'y'; - const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; - const crossAxisMulti = rtl && isVertical ? -1 : 1; - const rawValue = evaluate(options, state); - - // eslint-disable-next-line prefer-const - let { - mainAxis, - crossAxis, - alignmentAxis - } = typeof rawValue === 'number' ? { - mainAxis: rawValue, - crossAxis: 0, - alignmentAxis: null - } : { - mainAxis: 0, - crossAxis: 0, - alignmentAxis: null, - ...rawValue - }; - if (alignment && typeof alignmentAxis === 'number') { - crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; - } - return isVertical ? { - x: crossAxis * crossAxisMulti, - y: mainAxis * mainAxisMulti - } : { - x: mainAxis * mainAxisMulti, - y: crossAxis * crossAxisMulti - }; -} - -/** - * Modifies the placement by translating the floating element along the - * specified axes. - * A number (shorthand for `mainAxis` or distance), or an axes configuration - * object may be passed. - * @see https://floating-ui.com/docs/offset - */ -const offset$1 = function (options) { - if (options === void 0) { - options = 0; - } - return { - name: 'offset', - options, - async fn(state) { - const { - x, - y - } = state; - const diffCoords = await convertValueToCoords(state, options); - return { - x: x + diffCoords.x, - y: y + diffCoords.y, - data: diffCoords - }; - } - }; -}; - -/** - * Provides data that allows you to change the size of the floating element — - * for instance, prevent it from overflowing the clipping boundary or match the - * width of the reference element. - * @see https://floating-ui.com/docs/size - */ -const size$1 = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'size', - options, - async fn(state) { - const { - placement, - rects, - platform, - elements - } = state; - const { - apply = () => {}, - ...detectOverflowOptions - } = evaluate(options, state); - const overflow = await detectOverflow(state, detectOverflowOptions); - const side = getSide(placement); - const alignment = getAlignment(placement); - const isYAxis = getSideAxis(placement) === 'y'; - const { - width, - height - } = rects.floating; - let heightSide; - let widthSide; - if (side === 'top' || side === 'bottom') { - heightSide = side; - widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; - } else { - widthSide = side; - heightSide = alignment === 'end' ? 'top' : 'bottom'; - } - const overflowAvailableHeight = height - overflow[heightSide]; - const overflowAvailableWidth = width - overflow[widthSide]; - const noShift = !state.middlewareData.shift; - let availableHeight = overflowAvailableHeight; - let availableWidth = overflowAvailableWidth; - if (isYAxis) { - const maximumClippingWidth = width - overflow.left - overflow.right; - availableWidth = alignment || noShift ? min$1(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth; - } else { - const maximumClippingHeight = height - overflow.top - overflow.bottom; - availableHeight = alignment || noShift ? min$1(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight; - } - if (noShift && !alignment) { - const xMin = max$1(overflow.left, 0); - const xMax = max$1(overflow.right, 0); - const yMin = max$1(overflow.top, 0); - const yMax = max$1(overflow.bottom, 0); - if (isYAxis) { - availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max$1(overflow.left, overflow.right)); - } else { - availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max$1(overflow.top, overflow.bottom)); - } - } - await apply({ - ...state, - availableWidth, - availableHeight - }); - const nextDimensions = await platform.getDimensions(elements.floating); - if (width !== nextDimensions.width || height !== nextDimensions.height) { - return { - reset: { - rects: true - } - }; - } - return {}; - } - }; -}; - -function getNodeName(node) { - if (isNode(node)) { - return (node.nodeName || '').toLowerCase(); - } - // Mocked nodes in testing environments may not be instances of Node. By - // returning `#document` an infinite loop won't occur. - // https://github.com/floating-ui/floating-ui/issues/2317 - return '#document'; -} -function getWindow$1(node) { - var _node$ownerDocument; - return (node == null ? void 0 : (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; -} -function getDocumentElement(node) { - var _ref; - return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement; -} -function isNode(value) { - return value instanceof Node || value instanceof getWindow$1(value).Node; -} -function isElement(value) { - return value instanceof Element || value instanceof getWindow$1(value).Element; -} -function isHTMLElement(value) { - return value instanceof HTMLElement || value instanceof getWindow$1(value).HTMLElement; -} -function isShadowRoot(value) { - // Browsers without `ShadowRoot` support. - if (typeof ShadowRoot === 'undefined') { - return false; - } - return value instanceof ShadowRoot || value instanceof getWindow$1(value).ShadowRoot; -} -function isOverflowElement(element) { - const { - overflow, - overflowX, - overflowY, - display - } = getComputedStyle$2(element); - return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display); -} -function isTableElement(element) { - return ['table', 'td', 'th'].includes(getNodeName(element)); -} -function isContainingBlock(element) { - const webkit = isWebKit(); - const css = getComputedStyle$2(element); - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)); -} -function getContainingBlock(element) { - let currentNode = getParentNode$1(element); - while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { - if (isContainingBlock(currentNode)) { - return currentNode; - } else { - currentNode = getParentNode$1(currentNode); - } - } - return null; -} -function isWebKit() { - if (typeof CSS === 'undefined' || !CSS.supports) return false; - return CSS.supports('-webkit-backdrop-filter', 'none'); -} -function isLastTraversableNode(node) { - return ['html', 'body', '#document'].includes(getNodeName(node)); -} -function getComputedStyle$2(element) { - return getWindow$1(element).getComputedStyle(element); -} -function getNodeScroll(element) { - if (isElement(element)) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop - }; - } - return { - scrollLeft: element.pageXOffset, - scrollTop: element.pageYOffset - }; -} -function getParentNode$1(node) { - if (getNodeName(node) === 'html') { - return node; - } - const result = - // Step into the shadow DOM of the parent of a slotted node. - node.assignedSlot || - // DOM Element detected. - node.parentNode || - // ShadowRoot detected. - isShadowRoot(node) && node.host || - // Fallback. - getDocumentElement(node); - return isShadowRoot(result) ? result.host : result; -} -function getNearestOverflowAncestor(node) { - const parentNode = getParentNode$1(node); - if (isLastTraversableNode(parentNode)) { - return node.ownerDocument ? node.ownerDocument.body : node.body; - } - if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { - return parentNode; - } - return getNearestOverflowAncestor(parentNode); -} -function getOverflowAncestors(node, list) { - var _node$ownerDocument2; - if (list === void 0) { - list = []; - } - const scrollableAncestor = getNearestOverflowAncestor(node); - const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body); - const win = getWindow$1(scrollableAncestor); - if (isBody) { - return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : []); - } - return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor)); -} - -function getCssDimensions(element) { - const css = getComputedStyle$2(element); - // In testing environments, the `width` and `height` properties are empty - // strings for SVG elements, returning NaN. Fallback to `0` in this case. - let width = parseFloat(css.width) || 0; - let height = parseFloat(css.height) || 0; - const hasOffset = isHTMLElement(element); - const offsetWidth = hasOffset ? element.offsetWidth : width; - const offsetHeight = hasOffset ? element.offsetHeight : height; - const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; - if (shouldFallback) { - width = offsetWidth; - height = offsetHeight; - } - return { - width, - height, - $: shouldFallback - }; -} - -function unwrapElement(element) { - return !isElement(element) ? element.contextElement : element; -} - -function getScale(element) { - const domElement = unwrapElement(element); - if (!isHTMLElement(domElement)) { - return createCoords(1); - } - const rect = domElement.getBoundingClientRect(); - const { - width, - height, - $ - } = getCssDimensions(domElement); - let x = ($ ? round(rect.width) : rect.width) / width; - let y = ($ ? round(rect.height) : rect.height) / height; - - // 0, NaN, or Infinity should always fallback to 1. - - if (!x || !Number.isFinite(x)) { - x = 1; - } - if (!y || !Number.isFinite(y)) { - y = 1; - } - return { - x, - y - }; -} - -const noOffsets = /*#__PURE__*/createCoords(0); -function getVisualOffsets(element) { - const win = getWindow$1(element); - if (!isWebKit() || !win.visualViewport) { - return noOffsets; - } - return { - x: win.visualViewport.offsetLeft, - y: win.visualViewport.offsetTop - }; -} -function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { - if (isFixed === void 0) { - isFixed = false; - } - if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow$1(element)) { - return false; - } - return isFixed; -} - -function getBoundingClientRect$1(element, includeScale, isFixedStrategy, offsetParent) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - const clientRect = element.getBoundingClientRect(); - const domElement = unwrapElement(element); - let scale = createCoords(1); - if (includeScale) { - if (offsetParent) { - if (isElement(offsetParent)) { - scale = getScale(offsetParent); - } - } else { - scale = getScale(element); - } - } - const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0); - let x = (clientRect.left + visualOffsets.x) / scale.x; - let y = (clientRect.top + visualOffsets.y) / scale.y; - let width = clientRect.width / scale.x; - let height = clientRect.height / scale.y; - if (domElement) { - const win = getWindow$1(domElement); - const offsetWin = offsetParent && isElement(offsetParent) ? getWindow$1(offsetParent) : offsetParent; - let currentIFrame = win.frameElement; - while (currentIFrame && offsetParent && offsetWin !== win) { - const iframeScale = getScale(currentIFrame); - const iframeRect = currentIFrame.getBoundingClientRect(); - const css = getComputedStyle$2(currentIFrame); - const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; - const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; - x *= iframeScale.x; - y *= iframeScale.y; - width *= iframeScale.x; - height *= iframeScale.y; - x += left; - y += top; - currentIFrame = getWindow$1(currentIFrame).frameElement; - } - } - return rectToClientRect({ - width, - height, - x, - y - }); -} - -function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { - let { - rect, - offsetParent, - strategy - } = _ref; - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - if (offsetParent === documentElement) { - return rect; - } - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - let scale = createCoords(1); - const offsets = createCoords(0); - if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect$1(offsetParent); - scale = getScale(offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } - } - return { - width: rect.width * scale.x, - height: rect.height * scale.y, - x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, - y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y - }; -} - -function getClientRects(element) { - return Array.from(element.getClientRects()); -} - -function getWindowScrollBarX(element) { - // If has a CSS width greater than the viewport, then this will be - // incorrect for RTL. - return getBoundingClientRect$1(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft; -} - -// Gets the entire size of the scrollable document area, even extending outside -// of the `` and `` rect bounds if horizontally scrollable. -function getDocumentRect(element) { - const html = getDocumentElement(element); - const scroll = getNodeScroll(element); - const body = element.ownerDocument.body; - const width = max$1(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); - const height = max$1(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); - let x = -scroll.scrollLeft + getWindowScrollBarX(element); - const y = -scroll.scrollTop; - if (getComputedStyle$2(body).direction === 'rtl') { - x += max$1(html.clientWidth, body.clientWidth) - width; - } - return { - width, - height, - x, - y - }; -} - -function getViewportRect(element, strategy) { - const win = getWindow$1(element); - const html = getDocumentElement(element); - const visualViewport = win.visualViewport; - let width = html.clientWidth; - let height = html.clientHeight; - let x = 0; - let y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - const visualViewportBased = isWebKit(); - if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width, - height, - x, - y - }; -} - -// Returns the inner client rect, subtracting scrollbars if present. -function getInnerBoundingClientRect(element, strategy) { - const clientRect = getBoundingClientRect$1(element, true, strategy === 'fixed'); - const top = clientRect.top + element.clientTop; - const left = clientRect.left + element.clientLeft; - const scale = isHTMLElement(element) ? getScale(element) : createCoords(1); - const width = element.clientWidth * scale.x; - const height = element.clientHeight * scale.y; - const x = left * scale.x; - const y = top * scale.y; - return { - width, - height, - x, - y - }; -} -function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { - let rect; - if (clippingAncestor === 'viewport') { - rect = getViewportRect(element, strategy); - } else if (clippingAncestor === 'document') { - rect = getDocumentRect(getDocumentElement(element)); - } else if (isElement(clippingAncestor)) { - rect = getInnerBoundingClientRect(clippingAncestor, strategy); - } else { - const visualOffsets = getVisualOffsets(element); - rect = { - ...clippingAncestor, - x: clippingAncestor.x - visualOffsets.x, - y: clippingAncestor.y - visualOffsets.y - }; - } - return rectToClientRect(rect); -} -function hasFixedPositionAncestor(element, stopNode) { - const parentNode = getParentNode$1(element); - if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { - return false; - } - return getComputedStyle$2(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); -} - -// A "clipping ancestor" is an `overflow` element with the characteristic of -// clipping (or hiding) child elements. This returns all clipping ancestors -// of the given element up the tree. -function getClippingElementAncestors(element, cache) { - const cachedResult = cache.get(element); - if (cachedResult) { - return cachedResult; - } - let result = getOverflowAncestors(element).filter(el => isElement(el) && getNodeName(el) !== 'body'); - let currentContainingBlockComputedStyle = null; - const elementIsFixed = getComputedStyle$2(element).position === 'fixed'; - let currentNode = elementIsFixed ? getParentNode$1(element) : element; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { - const computedStyle = getComputedStyle$2(currentNode); - const currentNodeIsContaining = isContainingBlock(currentNode); - if (!currentNodeIsContaining && computedStyle.position === 'fixed') { - currentContainingBlockComputedStyle = null; - } - const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); - if (shouldDropCurrentNode) { - // Drop non-containing blocks. - result = result.filter(ancestor => ancestor !== currentNode); - } else { - // Record last containing block for next iteration. - currentContainingBlockComputedStyle = computedStyle; - } - currentNode = getParentNode$1(currentNode); - } - cache.set(element, result); - return result; -} - -// Gets the maximum area that the element is visible in due to any number of -// clipping ancestors. -function getClippingRect(_ref) { - let { - element, - boundary, - rootBoundary, - strategy - } = _ref; - const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary); - const clippingAncestors = [...elementClippingAncestors, rootBoundary]; - const firstClippingAncestor = clippingAncestors[0]; - const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { - const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); - accRect.top = max$1(rect.top, accRect.top); - accRect.right = min$1(rect.right, accRect.right); - accRect.bottom = min$1(rect.bottom, accRect.bottom); - accRect.left = max$1(rect.left, accRect.left); - return accRect; - }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); - return { - width: clippingRect.right - clippingRect.left, - height: clippingRect.bottom - clippingRect.top, - x: clippingRect.left, - y: clippingRect.top - }; -} - -function getDimensions(element) { - return getCssDimensions(element); -} - -function getRectRelativeToOffsetParent(element, offsetParent, strategy) { - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - const isFixed = strategy === 'fixed'; - const rect = getBoundingClientRect$1(element, true, isFixed, offsetParent); - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - const offsets = createCoords(0); - if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isOffsetParentAnElement) { - const offsetRect = getBoundingClientRect$1(offsetParent, true, isFixed, offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height - }; -} - -function getTrueOffsetParent(element, polyfill) { - if (!isHTMLElement(element) || getComputedStyle$2(element).position === 'fixed') { - return null; - } - if (polyfill) { - return polyfill(element); - } - return element.offsetParent; -} - -// Gets the closest ancestor positioned element. Handles some edge cases, -// such as table ancestors and cross browser bugs. -function getOffsetParent$1(element, polyfill) { - const window = getWindow$1(element); - if (!isHTMLElement(element)) { - return window; - } - let offsetParent = getTrueOffsetParent(element, polyfill); - while (offsetParent && isTableElement(offsetParent) && getComputedStyle$2(offsetParent).position === 'static') { - offsetParent = getTrueOffsetParent(offsetParent, polyfill); - } - if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$2(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) { - return window; - } - return offsetParent || getContainingBlock(element) || window; -} - -const getElementRects = async function (_ref) { - let { - reference, - floating, - strategy - } = _ref; - const getOffsetParentFn = this.getOffsetParent || getOffsetParent$1; - const getDimensionsFn = this.getDimensions; - return { - reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy), - floating: { - x: 0, - y: 0, - ...(await getDimensionsFn(floating)) - } - }; -}; - -function isRTL(element) { - return getComputedStyle$2(element).direction === 'rtl'; -} - -const platform = { - convertOffsetParentRelativeRectToViewportRelativeRect, - getDocumentElement, - getClippingRect, - getOffsetParent: getOffsetParent$1, - getElementRects, - getClientRects, - getDimensions, - getScale, - isElement, - isRTL -}; - -// https://samthor.au/2021/observing-dom/ -function observeMove(element, onMove) { - let io = null; - let timeoutId; - const root = getDocumentElement(element); - function cleanup() { - clearTimeout(timeoutId); - io && io.disconnect(); - io = null; - } - function refresh(skip, threshold) { - if (skip === void 0) { - skip = false; - } - if (threshold === void 0) { - threshold = 1; - } - cleanup(); - const { - left, - top, - width, - height - } = element.getBoundingClientRect(); - if (!skip) { - onMove(); - } - if (!width || !height) { - return; - } - const insetTop = floor(top); - const insetRight = floor(root.clientWidth - (left + width)); - const insetBottom = floor(root.clientHeight - (top + height)); - const insetLeft = floor(left); - const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px"; - const options = { - rootMargin, - threshold: max$1(0, min$1(1, threshold)) || 1 - }; - let isFirstUpdate = true; - function handleObserve(entries) { - const ratio = entries[0].intersectionRatio; - if (ratio !== threshold) { - if (!isFirstUpdate) { - return refresh(); - } - if (!ratio) { - timeoutId = setTimeout(() => { - refresh(false, 1e-7); - }, 100); - } else { - refresh(false, ratio); - } - } - isFirstUpdate = false; - } - - // Older browsers don't support a `document` as the root and will throw an - // error. - try { - io = new IntersectionObserver(handleObserve, { - ...options, - // Handle