diff --git a/r/combobox.json b/r/combobox.json index fa0f9cb9..411354f6 100644 --- a/r/combobox.json +++ b/r/combobox.json @@ -20,7 +20,7 @@ "path": "src/components/cipher/ui/combobox.tsx", "type": "registry:file", "target": "src/components/cipher/ui/combobox.tsx", - "content": "import * as React from \"react\";\n\nimport { useDiscardChangesGuard } from \"../hooks/use-discard-changes-guard\";\nimport { useDescendantFlags } from \"../lib/descendant-flags\";\nimport { useFieldControlAttributes } from \"../lib/field-context\";\nimport { type OptionCreateHandler, useOptionCreation } from \"../lib/use-option-creation\";\nimport { cn, titleIfClamped } from \"../lib/utils\";\nimport { DiscardChangesAlertDialog } from \"./alert-dialog\";\nimport { Button } from \"./button\";\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator\n} from \"./command\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle\n} from \"./dialog\";\nimport { Icon, type IconSource } from \"./icon\";\nimport { type FieldWidth, fieldBoxFlags, fieldBoxWatch } from \"./input\";\nimport { MultiSelect } from \"./multi-select\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"./popover\";\nimport { Spinner } from \"./spinner\";\nimport { Highlight } from \"./text\";\n\nimport controlStyles from \"./controls.module.css\";\nimport menu from \"./menu.module.css\";\nimport styles from \"./picker.module.css\";\n\nexport type ComboboxOption = {\n value: string;\n label: string;\n /** A glyph at the row's start, also shown in the trigger while this option is selected. Single selection only. */\n icon?: IconSource;\n /** A muted line under the label. Search matches it as well as the label. */\n description?: string;\n meta?: string;\n /** Options that share a group sit under its heading, in the order each group first appears. */\n group?: string;\n disabled?: boolean;\n};\nexport type ComboboxCreationFormProps = {\n /** The trimmed search text when the row was chosen, for prefilling a name. */\n query: string;\n /** Give the form element this id; the dialog's submit button targets it. */\n formId: string;\n /** Select the created option and close the dialog. Ignored once the dialog was dismissed. */\n complete: (option: ComboboxOption) => void;\n /** Close the dialog, asking first when the form reported unsaved changes. */\n dismiss: () => void;\n onDirtyChange: (dirty: boolean) => void;\n onPendingChange: (pending: boolean) => void;\n /** Relabel the submit button while this form is open; undefined goes back to submitLabel. */\n onSubmitLabelChange: (label: string | undefined) => void;\n};\nexport type ComboboxCreation =\n | {\n mode: \"inline\";\n onCreate: OptionCreateHandler;\n /** Keeps the Create row visible but disabled, with this reason beside it. */\n disabledReason?: string;\n }\n | {\n mode: \"dialog\";\n /** The row label, for example Create connection. */\n label: string;\n title: string;\n description?: string;\n submitLabel?: string;\n renderForm: (props: ComboboxCreationFormProps) => React.ReactNode;\n /** Keeps the Create row visible but disabled, with this reason beside it. */\n disabledReason?: string;\n discardTitle?: string;\n discardDescription?: string;\n }\n | {\n /** Shows the Create row and hands over to your own flow, such as a MultiStep dialog. */\n mode: \"action\";\n label: string;\n /** query is the trimmed search text; complete selects the created option. */\n onSelect: (props: { query: string; complete: (option: ComboboxOption) => void }) => void;\n disabledReason?: string;\n };\ntype SharedComboboxProps = {\n options: readonly ComboboxOption[];\n placeholder?: string;\n label: string;\n id?: string;\n \"aria-describedby\"?: string;\n emptyText?: string;\n disabled?: boolean;\n invalid?: boolean;\n mono?: boolean;\n defaultOpen?: boolean;\n closeOnFocusOutside?: boolean;\n onCreate?: OptionCreateHandler;\n /** The inline Create row's text for the trimmed search, for example (query) => `Create category \"${query}\"`. */\n createLabel?: (query: string) => string;\n /** Shows a clear X in place of the chevron while the value holds something the person can remove. Locked (disabled) options stay selected. */\n clearable?: boolean;\n /** The clear X's accessible name, for example Remove usage cap. Defaults to Clear selection, or Clear all selections with multiple. */\n clearLabel?: string;\n /** A fixed token width that doesn't shrink. Unset fills the row. */\n width?: FieldWidth;\n className?: string;\n};\nexport type ComboboxProps = SharedComboboxProps &\n (\n | {\n multiple?: false;\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n onValueChange?: (value: string) => void;\n onSearch?: (query: string) => void;\n loading?: boolean;\n creation?: ComboboxCreation;\n }\n | {\n multiple: true;\n value?: string[];\n defaultValue?: string[];\n onChange?: (value: string[]) => void;\n onValueChange?: (value: string[]) => void;\n onSearch?: never;\n loading?: never;\n creation?: never;\n }\n );\nexport function Combobox({\n ref,\n ...props\n}: ComboboxProps & { ref?: React.Ref }) {\n const {\n options,\n placeholder = \"Select an option\",\n label,\n emptyText = \"No options found\",\n disabled,\n invalid,\n mono,\n onCreate,\n width,\n className\n } = props;\n const onSearch = props.multiple ? undefined : props.onSearch;\n const loading = !props.multiple && Boolean(props.loading);\n const creationConfig = props.multiple ? undefined : props.creation;\n const dialogCreation = creationConfig?.mode === \"dialog\" ? creationConfig : undefined;\n const rowCreation = creationConfig?.mode === \"inline\" ? undefined : creationConfig;\n const inlineCreate = creationConfig?.mode === \"inline\" ? creationConfig.onCreate : onCreate;\n const creationBlocked = creationConfig?.disabledReason || undefined;\n const field = useFieldControlAttributes(props);\n const [internal, setInternal] = React.useState(\n props.defaultValue ?? (props.multiple ? [] : \"\")\n );\n const current = props.value === undefined ? internal : props.value;\n const selected = Array.isArray(current) ? current : current ? [current] : [];\n const apply = (next: string[]) => {\n if (props.multiple) {\n if (props.value === undefined) setInternal(next);\n props.onChange?.(next);\n props.onValueChange?.(next);\n } else {\n const value = next[0] ?? \"\";\n if (props.value === undefined) setInternal(value);\n props.onChange?.(value);\n props.onValueChange?.(value);\n }\n };\n const [open, setOpen] = React.useState(props.defaultOpen ?? false);\n const closeOnFocusOutside = props.closeOnFocusOutside ?? !props.defaultOpen;\n const fieldRef = React.useRef(null);\n const fieldBoxRef = useDescendantFlags(fieldBoxFlags, fieldBoxWatch, fieldRef);\n const refocus = React.useRef(undefined);\n React.useLayoutEffect(() => {\n if (refocus.current === undefined) return;\n const target = refocus.current;\n refocus.current = undefined;\n const chip = Array.from(\n fieldRef.current?.querySelectorAll(\"[data-slot=combobox-chip-remove]\") ??\n []\n ).find((button) => button.dataset.value === target);\n (\n chip ?? fieldRef.current?.querySelector(\"[data-slot=multi-select]\")\n )?.focus();\n });\n const isLocked = (value: string) =>\n disabled || Boolean(options.find((option) => option.value === value)?.disabled);\n const remove = (value: string) => {\n const index = selected.indexOf(value);\n refocus.current =\n selected.slice(index + 1).find((item) => !isLocked(item)) ??\n selected\n .slice(0, index)\n .reverse()\n .find((item) => !isLocked(item)) ??\n null;\n apply(selected.filter((item) => item !== value));\n };\n const contentId = React.useId();\n const [query, setQuery] = React.useState(\"\");\n const creation = useOptionCreation(inlineCreate, () => changeOpen(false));\n const { creating, error } = creation;\n const changeQuery = (next: string) => {\n creation.cancel();\n setQuery(next);\n onSearch?.(next);\n };\n const changeOpen = (next: boolean) => {\n creation.cancel();\n setOpen(next);\n if (next || !query) return;\n setQuery(\"\");\n onSearch?.(\"\");\n };\n const [picked, setPicked] = React.useState();\n const selectedOption =\n options.find((option) => option.value === selected[0]) ??\n (picked?.value === selected[0] ? picked : undefined);\n const filtered = onSearch\n ? options\n : options.filter((option) =>\n `${option.label} ${option.description ?? \"\"} ${option.meta ?? \"\"}`\n .toLowerCase()\n .includes(query.toLowerCase())\n );\n const groups = [...new Set(filtered.map((option) => option.group ?? \"\"))];\n const canCreate =\n inlineCreate &&\n query.trim() &&\n !options.some((option) => option.label.toLowerCase() === query.trim().toLowerCase());\n const triggerRef = React.useRef(null);\n const formId = React.useId();\n const sessionRef = React.useRef(0);\n const [session, setSession] = React.useState<{ id: number; query: string; open: boolean }>();\n const [formDirty, setFormDirty] = React.useState(false);\n const [formPending, setFormPending] = React.useState(false);\n const [formSubmitLabel, setFormSubmitLabel] = React.useState();\n const closeDialog = () => {\n sessionRef.current += 1;\n setSession((current) => current && { ...current, open: false });\n setFormDirty(false);\n setFormPending(false);\n };\n const guard = useDiscardChangesGuard({ isDirty: formDirty, onDiscard: closeDialog });\n const openDialog = () => {\n sessionRef.current += 1;\n setSession({ id: sessionRef.current, query: query.trim(), open: true });\n setFormDirty(false);\n setFormPending(false);\n setFormSubmitLabel(undefined);\n changeOpen(false);\n };\n const complete = (id: number, option: ComboboxOption) => {\n if (id !== sessionRef.current) return;\n setPicked(option);\n apply([option.value]);\n closeDialog();\n };\n const latestApply = React.useRef(apply);\n React.useLayoutEffect(() => {\n latestApply.current = apply;\n });\n const canClear = Boolean(props.clearable) && selected.some((value) => !isLocked(value));\n if (props.multiple)\n return (\n \n {selected.map((value) => {\n const chipLabel = options.find((option) => option.value === value)?.label ?? value;\n return (\n \n {chipLabel}\n remove(value)}\n onKeyDown={(event) => {\n if (event.key !== \"Backspace\" && event.key !== \"Delete\") return;\n event.preventDefault();\n remove(value);\n }}\n >\n \n \n \n );\n })}\n null : undefined}\n onCreate={onCreate}\n createLabel={props.createLabel}\n className={className}\n onEmptyBackspace={() => {\n const last = selected[selected.length - 1];\n if (last && !options.find((option) => option.value === last)?.disabled)\n apply(selected.slice(0, -1));\n }}\n />\n {canClear && (\n event.preventDefault()}\n onClick={() => {\n refocus.current = open ? undefined : null;\n apply(selected.filter(isLocked));\n }}\n >\n \n \n )}\n \n );\n const trigger = (\n \n {\n triggerRef.current = node;\n if (typeof ref === \"function\") return ref(node);\n if (ref) ref.current = node;\n return undefined;\n }}\n {...field}\n type=\"button\"\n role=\"combobox\"\n data-size=\"sm\"\n data-width={width}\n data-placeholder={selected.length ? undefined : \"\"}\n aria-label={label}\n aria-expanded={open}\n aria-controls={open ? contentId : undefined}\n aria-invalid={invalid || field[\"aria-invalid\"] || undefined}\n disabled={disabled}\n onKeyDown={(event) => {\n if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n event.preventDefault();\n changeOpen(true);\n }}\n className={cn(controlStyles.field, controlStyles.trigger, mono && styles.mono, className)}\n >\n {selectedOption?.icon && (\n \n \n \n )}\n {selectedOption?.label ?? (selected[0] || placeholder)}\n \n \n \n );\n const control = props.clearable ? (\n \n {trigger}\n {canClear && (\n event.preventDefault()}\n onClick={() => {\n apply([]);\n if (!open) triggerRef.current?.focus();\n }}\n >\n \n \n )}\n \n ) : (\n trigger\n );\n return (\n {\n if (!disabled) changeOpen(next);\n }}\n >\n {control}\n {\n if (!closeOnFocusOutside) event.preventDefault();\n }}\n onInteractOutside={(event) => {\n const clear =\n event.target instanceof Element && event.target.closest('[data-slot=\"combobox-clear\"]');\n if (clear && (!clear.isConnected || triggerRef.current?.parentElement?.contains(clear)))\n event.preventDefault();\n }}\n >\n \n {\n if (event.nativeEvent.isComposing || event.keyCode === 229) event.stopPropagation();\n }}\n trailing={loading ? : undefined}\n />\n \n {!onSearch && !rowCreation && {emptyText}}\n {(onSearch || rowCreation) && !filtered.length && (\n

\n {loading ? \"Searching…\" : emptyText}\n

\n )}\n {groups.map((group) => (\n \n {filtered\n .filter((option) => (option.group ?? \"\") === group)\n .map((option) => (\n {\n setPicked(option);\n apply([option.value]);\n changeOpen(false);\n }}\n >\n {option.icon && }\n {option.description ? (\n \n \n \n \n titleIfClamped(event.currentTarget)}\n >\n \n \n \n ) : (\n \n \n \n )}\n {option.meta && {option.meta}}\n \n ))}\n \n ))}\n {canCreate && (\n \n {\n creation.create(query.trim());\n }}\n >\n \n {creating\n ? \"Creating…\"\n : (props.createLabel?.(query.trim()) ?? `Create \"${query.trim()}\"`)}\n \n {creationBlocked && {creationBlocked}}\n \n \n )}\n {rowCreation && (\n <>\n {filtered.length > 0 && }\n \n {\n if (rowCreation.mode === \"dialog\") {\n openDialog();\n return;\n }\n changeOpen(false);\n rowCreation.onSelect({\n query: query.trim(),\n complete: (option) => {\n setPicked(option);\n latestApply.current([option.value]);\n }\n });\n }}\n >\n \n {rowCreation.label}\n {creationBlocked && {creationBlocked}}\n \n \n \n )}\n
\n
\n {error && (\n

\n {error}\n

\n )}\n \n {dialogCreation && session && (\n <>\n {\n if (!next) guard.requestDiscard();\n }}\n >\n event.stopPropagation()}\n onCloseAutoFocus={(event) => {\n event.preventDefault();\n triggerRef.current?.focus();\n }}\n >\n \n {dialogCreation.title}\n {dialogCreation.description && (\n {dialogCreation.description}\n )}\n \n \n {dialogCreation.renderForm({\n query: session.query,\n formId,\n complete: (option) => complete(session.id, option),\n dismiss: guard.requestDiscard,\n onDirtyChange: setFormDirty,\n onPendingChange: setFormPending,\n onSubmitLabelChange: setFormSubmitLabel\n })}\n \n \n \n \n \n \n \n \n \n )}\n \n );\n}\nCombobox.displayName = \"Combobox\";\n\nexport const ComboboxInput = CommandInput;\nexport const ComboboxContent = PopoverContent;\nexport const ComboboxTrigger = PopoverTrigger;\nexport const ComboboxList = CommandList;\nexport const ComboboxItem = CommandItem;\nexport const ComboboxEmpty = CommandEmpty;\nexport const ComboboxGroup = CommandGroup;\nexport const ComboboxSeparator = CommandSeparator;\nexport function ComboboxLabel({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"span\"> & { ref?: React.Ref }) {\n return ;\n}\nComboboxLabel.displayName = \"ComboboxLabel\";\nexport const ComboboxValue = ComboboxLabel;\nexport const ComboboxCollection = React.Fragment;\nexport function ComboboxChips({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"div\"> & { ref?: React.Ref }) {\n return
;\n}\nComboboxChips.displayName = \"ComboboxChips\";\nexport function ComboboxChip({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"span\"> & { ref?: React.Ref }) {\n return ;\n}\nComboboxChip.displayName = \"ComboboxChip\";\nexport const ComboboxChipsInput = CommandInput;\nexport const useComboboxAnchor = () => React.useRef(null);\n" + "content": "import * as React from \"react\";\n\nimport { useDiscardChangesGuard } from \"../hooks/use-discard-changes-guard\";\nimport { useDescendantFlags } from \"../lib/descendant-flags\";\nimport { useFieldControlAttributes } from \"../lib/field-context\";\nimport { type OptionCreateHandler, useOptionCreation } from \"../lib/use-option-creation\";\nimport { cn, titleIfClamped } from \"../lib/utils\";\nimport { DiscardChangesAlertDialog } from \"./alert-dialog\";\nimport { Button } from \"./button\";\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator\n} from \"./command\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle\n} from \"./dialog\";\nimport { Icon, type IconSource } from \"./icon\";\nimport { type FieldWidth, fieldBoxFlags, fieldBoxWatch } from \"./input\";\nimport { MultiSelect } from \"./multi-select\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"./popover\";\nimport { Spinner } from \"./spinner\";\nimport { Highlight } from \"./text\";\n\nimport controlStyles from \"./controls.module.css\";\nimport menu from \"./menu.module.css\";\nimport styles from \"./picker.module.css\";\n\nexport type ComboboxOption = {\n value: string;\n label: string;\n /** A glyph at the row's start, also shown in the trigger while this option is selected. Single selection only. */\n icon?: IconSource;\n /** A muted line under the label. Search matches it as well as the label. */\n description?: string;\n meta?: string;\n /** Options that share a group sit under its heading, in the order each group first appears. Search matches the heading too. */\n group?: string;\n /** Extra words search matches but never shows, such as a product's other names or an ID. */\n keywords?: readonly string[];\n disabled?: boolean;\n};\nexport type ComboboxCreationFormProps = {\n /** The trimmed search text when the row was chosen, for prefilling a name. */\n query: string;\n /** Give the form element this id; the dialog's submit button targets it. */\n formId: string;\n /** Select the created option and close the dialog. Ignored once the dialog was dismissed. */\n complete: (option: ComboboxOption) => void;\n /** Close the dialog, asking first when the form reported unsaved changes. */\n dismiss: () => void;\n onDirtyChange: (dirty: boolean) => void;\n onPendingChange: (pending: boolean) => void;\n /** Relabel the submit button while this form is open; undefined goes back to submitLabel. */\n onSubmitLabelChange: (label: string | undefined) => void;\n};\nexport type ComboboxCreation =\n | {\n mode: \"inline\";\n onCreate: OptionCreateHandler;\n /** Keeps the Create row visible but disabled, with this reason beside it. */\n disabledReason?: string;\n }\n | {\n mode: \"dialog\";\n /** The row label, for example Create connection. */\n label: string;\n title: string;\n description?: string;\n submitLabel?: string;\n renderForm: (props: ComboboxCreationFormProps) => React.ReactNode;\n /** Keeps the Create row visible but disabled, with this reason beside it. */\n disabledReason?: string;\n discardTitle?: string;\n discardDescription?: string;\n }\n | {\n /** Shows the Create row and hands over to your own flow, such as a MultiStep dialog. */\n mode: \"action\";\n label: string;\n /** query is the trimmed search text; complete selects the created option. */\n onSelect: (props: { query: string; complete: (option: ComboboxOption) => void }) => void;\n disabledReason?: string;\n };\ntype SharedComboboxProps = {\n options: readonly ComboboxOption[];\n placeholder?: string;\n label: string;\n id?: string;\n \"aria-describedby\"?: string;\n emptyText?: string;\n /** The search field's placeholder. Defaults to \"Search options\". */\n searchPlaceholder?: string;\n disabled?: boolean;\n invalid?: boolean;\n mono?: boolean;\n defaultOpen?: boolean;\n closeOnFocusOutside?: boolean;\n onCreate?: OptionCreateHandler;\n /** The inline Create row's text for the trimmed search, for example (query) => `Create category \"${query}\"`. */\n createLabel?: (query: string) => string;\n /** Shows a clear X in place of the chevron while the value holds something the person can remove. Locked (disabled) options stay selected. */\n clearable?: boolean;\n /** The clear X's accessible name, for example Remove usage cap. Defaults to Clear selection, or Clear all selections with multiple. */\n clearLabel?: string;\n /** A fixed token width that doesn't shrink. Unset fills the row. */\n width?: FieldWidth;\n className?: string;\n};\nexport type ComboboxProps = SharedComboboxProps &\n (\n | {\n multiple?: false;\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n onValueChange?: (value: string) => void;\n onSearch?: (query: string) => void;\n loading?: boolean;\n creation?: ComboboxCreation;\n }\n | {\n multiple: true;\n value?: string[];\n defaultValue?: string[];\n onChange?: (value: string[]) => void;\n onValueChange?: (value: string[]) => void;\n onSearch?: never;\n loading?: never;\n creation?: never;\n }\n );\nexport function Combobox({\n ref,\n ...props\n}: ComboboxProps & { ref?: React.Ref }) {\n const {\n options,\n placeholder = \"Select an option\",\n label,\n emptyText = \"No options found\",\n searchPlaceholder = \"Search options\",\n disabled,\n invalid,\n mono,\n onCreate,\n width,\n className\n } = props;\n const onSearch = props.multiple ? undefined : props.onSearch;\n const loading = !props.multiple && Boolean(props.loading);\n const creationConfig = props.multiple ? undefined : props.creation;\n const dialogCreation = creationConfig?.mode === \"dialog\" ? creationConfig : undefined;\n const rowCreation = creationConfig?.mode === \"inline\" ? undefined : creationConfig;\n const inlineCreate = creationConfig?.mode === \"inline\" ? creationConfig.onCreate : onCreate;\n const creationBlocked = creationConfig?.disabledReason || undefined;\n const field = useFieldControlAttributes(props);\n const [internal, setInternal] = React.useState(\n props.defaultValue ?? (props.multiple ? [] : \"\")\n );\n const current = props.value === undefined ? internal : props.value;\n const selected = Array.isArray(current) ? current : current ? [current] : [];\n const apply = (next: string[]) => {\n if (props.multiple) {\n if (props.value === undefined) setInternal(next);\n props.onChange?.(next);\n props.onValueChange?.(next);\n } else {\n const value = next[0] ?? \"\";\n if (props.value === undefined) setInternal(value);\n props.onChange?.(value);\n props.onValueChange?.(value);\n }\n };\n const [open, setOpen] = React.useState(props.defaultOpen ?? false);\n const closeOnFocusOutside = props.closeOnFocusOutside ?? !props.defaultOpen;\n const fieldRef = React.useRef(null);\n const fieldBoxRef = useDescendantFlags(fieldBoxFlags, fieldBoxWatch, fieldRef);\n const refocus = React.useRef(undefined);\n React.useLayoutEffect(() => {\n if (refocus.current === undefined) return;\n const target = refocus.current;\n refocus.current = undefined;\n const chip = Array.from(\n fieldRef.current?.querySelectorAll(\"[data-slot=combobox-chip-remove]\") ??\n []\n ).find((button) => button.dataset.value === target);\n (\n chip ?? fieldRef.current?.querySelector(\"[data-slot=multi-select]\")\n )?.focus();\n });\n const isLocked = (value: string) =>\n disabled || Boolean(options.find((option) => option.value === value)?.disabled);\n const remove = (value: string) => {\n const index = selected.indexOf(value);\n refocus.current =\n selected.slice(index + 1).find((item) => !isLocked(item)) ??\n selected\n .slice(0, index)\n .reverse()\n .find((item) => !isLocked(item)) ??\n null;\n apply(selected.filter((item) => item !== value));\n };\n const contentId = React.useId();\n const [query, setQuery] = React.useState(\"\");\n const creation = useOptionCreation(inlineCreate, () => changeOpen(false));\n const { creating, error } = creation;\n const changeQuery = (next: string) => {\n creation.cancel();\n setQuery(next);\n onSearch?.(next);\n };\n const changeOpen = (next: boolean) => {\n creation.cancel();\n setOpen(next);\n if (next || !query) return;\n setQuery(\"\");\n onSearch?.(\"\");\n };\n const [picked, setPicked] = React.useState();\n const selectedOption =\n options.find((option) => option.value === selected[0]) ??\n (picked?.value === selected[0] ? picked : undefined);\n const filtered = onSearch\n ? options\n : options.filter((option) =>\n [option.label, option.description, option.meta, option.group, ...(option.keywords ?? [])]\n .join(\" \")\n .toLowerCase()\n .includes(query.toLowerCase())\n );\n const groups = [...new Set(filtered.map((option) => option.group ?? \"\"))];\n const canCreate =\n inlineCreate &&\n query.trim() &&\n !options.some((option) => option.label.toLowerCase() === query.trim().toLowerCase());\n const triggerRef = React.useRef(null);\n const formId = React.useId();\n const sessionRef = React.useRef(0);\n const [session, setSession] = React.useState<{ id: number; query: string; open: boolean }>();\n const [formDirty, setFormDirty] = React.useState(false);\n const [formPending, setFormPending] = React.useState(false);\n const [formSubmitLabel, setFormSubmitLabel] = React.useState();\n const closeDialog = () => {\n sessionRef.current += 1;\n setSession((current) => current && { ...current, open: false });\n setFormDirty(false);\n setFormPending(false);\n };\n const guard = useDiscardChangesGuard({ isDirty: formDirty, onDiscard: closeDialog });\n const openDialog = () => {\n sessionRef.current += 1;\n setSession({ id: sessionRef.current, query: query.trim(), open: true });\n setFormDirty(false);\n setFormPending(false);\n setFormSubmitLabel(undefined);\n changeOpen(false);\n };\n const complete = (id: number, option: ComboboxOption) => {\n if (id !== sessionRef.current) return;\n setPicked(option);\n apply([option.value]);\n closeDialog();\n };\n const latestApply = React.useRef(apply);\n React.useLayoutEffect(() => {\n latestApply.current = apply;\n });\n const canClear = Boolean(props.clearable) && selected.some((value) => !isLocked(value));\n if (props.multiple)\n return (\n \n {selected.map((value) => {\n const chipLabel = options.find((option) => option.value === value)?.label ?? value;\n return (\n \n {chipLabel}\n remove(value)}\n onKeyDown={(event) => {\n if (event.key !== \"Backspace\" && event.key !== \"Delete\") return;\n event.preventDefault();\n remove(value);\n }}\n >\n \n \n \n );\n })}\n null : undefined}\n onCreate={onCreate}\n createLabel={props.createLabel}\n className={className}\n onEmptyBackspace={() => {\n const last = selected[selected.length - 1];\n if (last && !options.find((option) => option.value === last)?.disabled)\n apply(selected.slice(0, -1));\n }}\n />\n {canClear && (\n event.preventDefault()}\n onClick={() => {\n refocus.current = open ? undefined : null;\n apply(selected.filter(isLocked));\n }}\n >\n \n \n )}\n
\n );\n const trigger = (\n \n {\n triggerRef.current = node;\n if (typeof ref === \"function\") return ref(node);\n if (ref) ref.current = node;\n return undefined;\n }}\n {...field}\n type=\"button\"\n role=\"combobox\"\n data-size=\"sm\"\n data-width={width}\n data-placeholder={selected.length ? undefined : \"\"}\n aria-label={label}\n aria-expanded={open}\n aria-controls={open ? contentId : undefined}\n aria-invalid={invalid || field[\"aria-invalid\"] || undefined}\n disabled={disabled}\n onKeyDown={(event) => {\n if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n event.preventDefault();\n changeOpen(true);\n }}\n className={cn(controlStyles.field, controlStyles.trigger, mono && styles.mono, className)}\n >\n {selectedOption?.icon && (\n \n \n \n )}\n {selectedOption?.label ?? (selected[0] || placeholder)}\n \n \n \n );\n const control = props.clearable ? (\n \n {trigger}\n {canClear && (\n event.preventDefault()}\n onClick={() => {\n apply([]);\n if (!open) triggerRef.current?.focus();\n }}\n >\n \n \n )}\n \n ) : (\n trigger\n );\n return (\n {\n if (!disabled) changeOpen(next);\n }}\n >\n {control}\n {\n if (!closeOnFocusOutside) event.preventDefault();\n }}\n onInteractOutside={(event) => {\n const clear =\n event.target instanceof Element && event.target.closest('[data-slot=\"combobox-clear\"]');\n if (clear && (!clear.isConnected || triggerRef.current?.parentElement?.contains(clear)))\n event.preventDefault();\n }}\n >\n \n {\n if (event.nativeEvent.isComposing || event.keyCode === 229) event.stopPropagation();\n }}\n trailing={loading ? : undefined}\n />\n \n {!onSearch && !rowCreation && {emptyText}}\n {(onSearch || rowCreation) && !filtered.length && (\n

\n {loading ? \"Searching…\" : emptyText}\n

\n )}\n {groups.map((group) => (\n \n {filtered\n .filter((option) => (option.group ?? \"\") === group)\n .map((option) => (\n {\n setPicked(option);\n apply([option.value]);\n changeOpen(false);\n }}\n >\n {option.icon && }\n {option.description ? (\n \n \n \n \n titleIfClamped(event.currentTarget)}\n >\n \n \n
\n ) : (\n \n \n \n )}\n {option.meta && {option.meta}}\n \n ))}\n \n ))}\n {canCreate && (\n \n {\n creation.create(query.trim());\n }}\n >\n \n {creating\n ? \"Creating…\"\n : (props.createLabel?.(query.trim()) ?? `Create \"${query.trim()}\"`)}\n \n {creationBlocked && {creationBlocked}}\n \n \n )}\n {rowCreation && (\n <>\n {filtered.length > 0 && }\n \n {\n if (rowCreation.mode === \"dialog\") {\n openDialog();\n return;\n }\n changeOpen(false);\n rowCreation.onSelect({\n query: query.trim(),\n complete: (option) => {\n setPicked(option);\n latestApply.current([option.value]);\n }\n });\n }}\n >\n \n {rowCreation.label}\n {creationBlocked && {creationBlocked}}\n \n \n \n )}\n \n \n {error && (\n

\n {error}\n

\n )}\n \n {dialogCreation && session && (\n <>\n {\n if (!next) guard.requestDiscard();\n }}\n >\n event.stopPropagation()}\n onCloseAutoFocus={(event) => {\n event.preventDefault();\n triggerRef.current?.focus();\n }}\n >\n \n {dialogCreation.title}\n {dialogCreation.description && (\n {dialogCreation.description}\n )}\n \n \n {dialogCreation.renderForm({\n query: session.query,\n formId,\n complete: (option) => complete(session.id, option),\n dismiss: guard.requestDiscard,\n onDirtyChange: setFormDirty,\n onPendingChange: setFormPending,\n onSubmitLabelChange: setFormSubmitLabel\n })}\n \n \n \n \n \n \n \n \n \n )}\n \n );\n}\nCombobox.displayName = \"Combobox\";\n\nexport const ComboboxInput = CommandInput;\nexport const ComboboxContent = PopoverContent;\nexport const ComboboxTrigger = PopoverTrigger;\nexport const ComboboxList = CommandList;\nexport const ComboboxItem = CommandItem;\nexport const ComboboxEmpty = CommandEmpty;\nexport const ComboboxGroup = CommandGroup;\nexport const ComboboxSeparator = CommandSeparator;\nexport function ComboboxLabel({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"span\"> & { ref?: React.Ref }) {\n return ;\n}\nComboboxLabel.displayName = \"ComboboxLabel\";\nexport const ComboboxValue = ComboboxLabel;\nexport const ComboboxCollection = React.Fragment;\nexport function ComboboxChips({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"div\"> & { ref?: React.Ref }) {\n return
;\n}\nComboboxChips.displayName = \"ComboboxChips\";\nexport function ComboboxChip({\n ref,\n ...props\n}: React.ComponentPropsWithoutRef<\"span\"> & { ref?: React.Ref }) {\n return ;\n}\nComboboxChip.displayName = \"ComboboxChip\";\nexport const ComboboxChipsInput = CommandInput;\nexport const useComboboxAnchor = () => React.useRef(null);\n" }, { "path": "src/components/cipher/ui/controls.module.css", diff --git a/r/filter-bar.json b/r/filter-bar.json index cb17222b..ab162b59 100644 --- a/r/filter-bar.json +++ b/r/filter-bar.json @@ -22,7 +22,7 @@ "path": "src/components/cipher/patterns/filter-bar.tsx", "type": "registry:file", "target": "src/components/cipher/patterns/filter-bar.tsx", - "content": "import * as React from \"react\";\nimport type { DateRange } from \"react-day-picker\";\n\nimport { Button } from \"../ui/button\";\nimport { ButtonGroup } from \"../ui/button-group\";\nimport { Calendar } from \"../ui/calendar\";\nimport { pickRange } from \"../ui/date-range-picker\";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuTrigger\n} from \"../ui/dropdown-menu\";\nimport { Input } from \"../ui/input\";\nimport { MultiSelect } from \"../ui/multi-select\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"../ui/popover\";\nimport { ToggleGroup, ToggleGroupItem } from \"../ui/toggle-group\";\n\nimport styles from \"./filter-bar.module.css\";\n\nexport type FilterBarOption = { value: string; label: string; group?: string };\ntype FilterBarChoiceField = {\n key: string;\n label: string;\n options: readonly FilterBarOption[];\n searchable?: boolean;\n};\nexport type FilterBarField =\n | (FilterBarChoiceField & { type: \"select\" })\n | (FilterBarChoiceField & { type: \"multi-select\" })\n | { key: string; label: string; type: \"date\"; defaultMonth?: Date }\n | { key: string; label: string; type: \"date-range\"; defaultMonth?: Date }\n | { key: string; label: string; type: \"text\"; placeholder?: string };\nexport type FilterBarFilter = {\n field: string;\n operator?: \"before\" | \"after\";\n /** ISO dates for date fields: one for date, [from, to] for date-range. */\n values: string[];\n};\nexport type FilterBarProps = {\n label: string;\n /** Leave out for a bar that is only a search box. */\n fields?: readonly FilterBarField[];\n /** Applied filters. Only filters with values arrive here: one just added stays in the bar until its picker closes, and leaves without a change if none was picked. */\n value?: readonly FilterBarFilter[];\n onChange?: (value: FilterBarFilter[]) => void;\n /** Your own search control. Leave out and pass searchValue and onSearchChange for the built-in one. */\n search?: React.ReactNode;\n searchValue?: string;\n onSearchChange?: (value: string) => void;\n /** The built-in search's accessible name, and its placeholder unless searchPlaceholder is set. */\n searchLabel?: string;\n searchPlaceholder?: string;\n /** \"/\" focuses the built-in search from anywhere on the page. Turn it off on a second FilterBar so only the main search answers \"/\". */\n slashShortcut?: boolean;\n /** The search stops at size-search-max; fill stretches it across the row up to the filters and actions. */\n width?: \"fill\";\n actions?: React.ReactNode;\n};\n\nconst isoDate = (date: Date) =>\n `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}-${String(date.getDate()).padStart(2, \"0\")}`;\nconst parseDate = (value: string | undefined) => {\n if (!value) return undefined;\n const [year, month, day] = value.split(\"-\").map(Number);\n return new Date(year, month - 1, day);\n};\n\nconst shortRange = (from: Date, to: Date) => {\n const withYear =\n from.getFullYear() !== to.getFullYear() || from.getFullYear() !== new Date().getFullYear();\n const format = (date: Date) =>\n date.toLocaleDateString(undefined, {\n month: \"short\",\n day: \"numeric\",\n year: withYear ? \"numeric\" : undefined\n });\n return from.getTime() === to.getTime() ? format(from) : `${format(from)} to ${format(to)}`;\n};\n\nexport const describeFilter = (field: FilterBarField, filter: FilterBarFilter) => {\n if (field.type === \"date\")\n return { verb: filter.operator ?? \"before\", value: filter.values[0] ?? \"any date\" };\n if (field.type === \"date-range\") {\n const from = parseDate(filter.values[0]);\n const to = parseDate(filter.values[1]);\n if (!from || !to) return { verb: \"is\", value: \"any date\" };\n return { verb: from.getTime() === to.getTime() ? \"on\" : \"from\", value: shortRange(from, to) };\n }\n if (field.type === \"text\") return { verb: \"contains\", value: filter.values[0] ?? \"anything\" };\n const labels = filter.values.map(\n (value) => field.options.find((option) => option.value === value)?.label ?? value\n );\n let value = \"any\";\n if (labels.length === 1) [value] = labels;\n else if (labels.length === 2) value = `${labels[0]} or ${labels[1]}`;\n else if (labels.length > 2) value = `${labels[0]} or ${labels.length - 1} more`;\n return { verb: \"is\", value };\n};\n\nconst DateRangeFilter = ({\n label,\n defaultMonth,\n values,\n onPick\n}: {\n label: string;\n defaultMonth?: Date;\n values: readonly string[];\n onPick: (values: [string, string]) => void;\n}) => {\n const [draft, setDraft] = React.useState(() => {\n const from = parseDate(values[0]);\n const to = parseDate(values[1]);\n return from && to ? { from, to } : undefined;\n });\n return (\n {\n const next = pickRange(draft, day);\n setDraft(next);\n if (next.from && next.to) onPick([isoDate(next.from), isoDate(next.to)]);\n }}\n />\n );\n};\n\ntype Draft = { filter: FilterBarFilter; index: number };\nconst withDraft = (list: readonly FilterBarFilter[], draft: Draft | null) => {\n if (!draft) return list;\n if (list.some((filter) => filter.field === draft.filter.field))\n return list.map((filter) => (filter.field === draft.filter.field ? draft.filter : filter));\n const next = [...list];\n next.splice(Math.min(draft.index, next.length), 0, draft.filter);\n return next;\n};\n\nexport const FilterBar = ({\n label,\n fields = [],\n value: valueProp,\n onChange,\n search,\n searchValue,\n onSearchChange,\n searchLabel = \"Search\",\n searchPlaceholder,\n slashShortcut = true,\n width,\n actions\n}: FilterBarProps) => {\n const [uncontrolled, setUncontrolled] = React.useState([]);\n const value = valueProp ?? uncontrolled;\n const [draft, setDraftState] = React.useState(null);\n const draftRef = React.useRef(draft);\n const setDraft = (next: Draft | null) => {\n draftRef.current = next;\n setDraftState(next);\n };\n const shown = withDraft(value, draft);\n const [open, setOpen] = React.useState(null);\n const [focusTarget, setFocusTarget] = React.useState(null);\n const picked = React.useRef(null);\n const addButton = React.useRef(null);\n const triggers = React.useRef(new Map());\n\n React.useEffect(() => {\n if (!focusTarget) return;\n (focusTarget === \"add\" ? addButton.current : triggers.current.get(focusTarget))?.focus();\n setFocusTarget(null);\n }, [focusTarget]);\n\n const latest = React.useRef(value);\n React.useLayoutEffect(() => {\n latest.current = value;\n }, [value]);\n const commit = (next: FilterBarFilter[]) => {\n latest.current = next;\n if (valueProp === undefined) setUncontrolled(next);\n onChange?.(next);\n };\n const update = (key: string, patch: Partial) => {\n const current = latest.current;\n const pending = draftRef.current?.filter.field === key ? draftRef.current : null;\n const index = current.findIndex((filter) => filter.field === key);\n const base = index >= 0 ? current[index] : pending?.filter;\n if (!base) return;\n const next = { ...base, ...patch };\n const at = index >= 0 ? index : (pending?.index ?? current.length);\n if (pending || !next.values.length) setDraft({ filter: next, index: at });\n if (next.values.length)\n commit(\n index >= 0\n ? current.map((filter) => (filter.field === key ? next : filter))\n : [...current.slice(0, at), next, ...current.slice(at)]\n );\n else if (index >= 0) commit(current.filter((filter) => filter.field !== key));\n };\n const remove = (key: string) => {\n const before = withDraft(latest.current, draftRef.current);\n const index = before.findIndex((filter) => filter.field === key);\n const next = before.filter((filter) => filter.field !== key);\n if (draftRef.current?.filter.field === key) setDraft(null);\n if (latest.current.some((filter) => filter.field === key))\n commit(latest.current.filter((filter) => filter.field !== key));\n setFocusTarget((next[index] ?? next[index - 1])?.field ?? \"add\");\n };\n const add = (field: FilterBarField) => {\n picked.current = field.key;\n setDraft({\n filter: {\n field: field.key,\n operator: field.type === \"date\" ? \"before\" : undefined,\n values: []\n },\n index: latest.current.length\n });\n };\n const changeOpen = (key: string, next: boolean) => {\n setOpen(next ? key : null);\n if (next) return;\n const applied = latest.current.find((filter) => filter.field === key)?.values.length;\n if (!applied) remove(key);\n else if (draftRef.current?.filter.field === key) setDraft(null);\n };\n const searchControl =\n search ??\n (onSearchChange || searchValue !== undefined ? (\n onSearchChange?.(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Escape\" && searchValue) {\n event.preventDefault();\n onSearchChange?.(\"\");\n }\n }}\n />\n ) : null);\n\n return (\n
\n
\n {searchControl && (\n
\n {searchControl}\n
\n )}\n {fields.length > 0 && (\n \n \n \n \n {\n if (!picked.current) return;\n event.preventDefault();\n setOpen(picked.current);\n picked.current = null;\n }}\n >\n Filter by\n {fields.map((field) => {\n const applied = shown.some((filter) => filter.field === field.key);\n return (\n add(field)}\n >\n {field.label}\n \n );\n })}\n \n \n )}\n {actions &&
{actions}
}\n
\n {shown.length > 0 && (\n
\n
    \n {shown.map((filter) => {\n const field = fields.find((entry) => entry.key === filter.field);\n if (!field) return null;\n const text = describeFilter(field, filter);\n const trigger = (\n {\n if (node) triggers.current.set(field.key, node);\n else triggers.current.delete(field.key);\n }}\n variant=\"outline\"\n iconRight=\"chev-down\"\n aria-label={`${field.label} ${text.verb} ${text.value}`}\n >\n {`${field.label} ${text.verb}`}\n {text.value}\n \n );\n const isOpen = open === field.key;\n const openChange = (next: boolean) => changeOpen(field.key, next);\n let picker: React.ReactNode;\n if (field.type === \"select\")\n picker = (\n update(field.key, { values: next ? [next] : [] })}\n open={isOpen}\n onOpenChange={openChange}\n trigger={trigger}\n />\n );\n else if (field.type === \"multi-select\")\n picker = (\n update(field.key, { values: next })}\n open={isOpen}\n onOpenChange={openChange}\n trigger={trigger}\n />\n );\n else\n picker = (\n \n {trigger}\n {\n if (field.type === \"date-range\") event.preventDefault();\n }}\n >\n {field.type === \"date-range\" && (\n {\n update(field.key, { values: next });\n openChange(false);\n }}\n />\n )}\n {field.type === \"date\" && (\n
    \n {\n if (next === \"before\" || next === \"after\")\n update(field.key, { operator: next });\n }}\n >\n Before\n After\n \n \n update(field.key, { values: date ? [isoDate(date)] : [] })\n }\n />\n
    \n )}\n {field.type === \"text\" && (\n \n update(field.key, {\n values: event.target.value ? [event.target.value] : []\n })\n }\n onKeyDown={(event) => {\n if (event.key === \"Enter\") openChange(false);\n }}\n />\n )}\n \n
    \n );\n return (\n
  • \n \n {picker}\n remove(field.key)}\n >{`Remove ${field.label} filter`}\n \n
  • \n );\n })}\n
\n {\n setDraft(null);\n commit([]);\n setFocusTarget(\"add\");\n }}\n >\n Clear filters\n \n
\n )}\n
\n );\n};\n" + "content": "import * as React from \"react\";\nimport type { DateRange } from \"react-day-picker\";\n\nimport { Button } from \"../ui/button\";\nimport { ButtonGroup } from \"../ui/button-group\";\nimport { Calendar } from \"../ui/calendar\";\nimport { pickRange } from \"../ui/date-range-picker\";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuTrigger\n} from \"../ui/dropdown-menu\";\nimport { Input } from \"../ui/input\";\nimport { MultiSelect } from \"../ui/multi-select\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"../ui/popover\";\nimport { ToggleGroup, ToggleGroupItem } from \"../ui/toggle-group\";\n\nimport styles from \"./filter-bar.module.css\";\n\nexport type FilterBarOption = { value: string; label: string; group?: string };\ntype FilterBarChoiceField = {\n key: string;\n label: string;\n options: readonly FilterBarOption[];\n searchable?: boolean;\n};\nexport type FilterBarField =\n | (FilterBarChoiceField & { type: \"select\" })\n | (FilterBarChoiceField & { type: \"multi-select\" })\n | { key: string; label: string; type: \"date\"; defaultMonth?: Date }\n | { key: string; label: string; type: \"date-range\"; defaultMonth?: Date }\n | {\n key: string;\n label: string;\n type: \"text\";\n placeholder?: string;\n /** How the chip reads the value, such as \"is\" for an exact match. Defaults to \"contains\". */\n verb?: string;\n };\nexport type FilterBarFilter = {\n field: string;\n operator?: \"before\" | \"after\";\n /** ISO dates for date fields: one for date, [from, to] for date-range. */\n values: string[];\n};\nexport type FilterBarProps = {\n label: string;\n /** Leave out for a bar that is only a search box. */\n fields?: readonly FilterBarField[];\n /** Applied filters. Only filters with values arrive here: one just added stays in the bar until its picker closes, and leaves without a change if none was picked. */\n value?: readonly FilterBarFilter[];\n onChange?: (value: FilterBarFilter[]) => void;\n /** Your own search control. Leave out and pass searchValue and onSearchChange for the built-in one. */\n search?: React.ReactNode;\n searchValue?: string;\n onSearchChange?: (value: string) => void;\n /** The built-in search's accessible name, and its placeholder unless searchPlaceholder is set. */\n searchLabel?: string;\n searchPlaceholder?: string;\n /** \"/\" focuses the built-in search from anywhere on the page. Turn it off on a second FilterBar so only the main search answers \"/\". */\n slashShortcut?: boolean;\n /** The search stops at size-search-max; fill stretches it across the row up to the filters and actions. */\n width?: \"fill\";\n actions?: React.ReactNode;\n};\n\nconst isoDate = (date: Date) =>\n `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}-${String(date.getDate()).padStart(2, \"0\")}`;\nconst parseDate = (value: string | undefined) => {\n if (!value) return undefined;\n const [year, month, day] = value.split(\"-\").map(Number);\n return new Date(year, month - 1, day);\n};\n\nconst shortRange = (from: Date, to: Date) => {\n const withYear =\n from.getFullYear() !== to.getFullYear() || from.getFullYear() !== new Date().getFullYear();\n const format = (date: Date) =>\n date.toLocaleDateString(undefined, {\n month: \"short\",\n day: \"numeric\",\n year: withYear ? \"numeric\" : undefined\n });\n return from.getTime() === to.getTime() ? format(from) : `${format(from)} to ${format(to)}`;\n};\n\nexport const describeFilter = (field: FilterBarField, filter: FilterBarFilter) => {\n if (field.type === \"date\")\n return { verb: filter.operator ?? \"before\", value: filter.values[0] ?? \"any date\" };\n if (field.type === \"date-range\") {\n const from = parseDate(filter.values[0]);\n const to = parseDate(filter.values[1]);\n if (!from || !to) return { verb: \"is\", value: \"any date\" };\n return { verb: from.getTime() === to.getTime() ? \"on\" : \"from\", value: shortRange(from, to) };\n }\n if (field.type === \"text\")\n return { verb: field.verb ?? \"contains\", value: filter.values[0] ?? \"anything\" };\n const labels = filter.values.map(\n (value) => field.options.find((option) => option.value === value)?.label ?? value\n );\n let value = \"any\";\n if (labels.length === 1) [value] = labels;\n else if (labels.length === 2) value = `${labels[0]} or ${labels[1]}`;\n else if (labels.length > 2) value = `${labels[0]} or ${labels.length - 1} more`;\n return { verb: \"is\", value };\n};\n\nconst DateRangeFilter = ({\n label,\n defaultMonth,\n values,\n onPick\n}: {\n label: string;\n defaultMonth?: Date;\n values: readonly string[];\n onPick: (values: [string, string]) => void;\n}) => {\n const [draft, setDraft] = React.useState(() => {\n const from = parseDate(values[0]);\n const to = parseDate(values[1]);\n return from && to ? { from, to } : undefined;\n });\n return (\n {\n const next = pickRange(draft, day);\n setDraft(next);\n if (next.from && next.to) onPick([isoDate(next.from), isoDate(next.to)]);\n }}\n />\n );\n};\n\ntype Draft = { filter: FilterBarFilter; index: number };\nconst withDraft = (list: readonly FilterBarFilter[], draft: Draft | null) => {\n if (!draft) return list;\n if (list.some((filter) => filter.field === draft.filter.field))\n return list.map((filter) => (filter.field === draft.filter.field ? draft.filter : filter));\n const next = [...list];\n next.splice(Math.min(draft.index, next.length), 0, draft.filter);\n return next;\n};\n\nexport const FilterBar = ({\n label,\n fields = [],\n value: valueProp,\n onChange,\n search,\n searchValue,\n onSearchChange,\n searchLabel = \"Search\",\n searchPlaceholder,\n slashShortcut = true,\n width,\n actions\n}: FilterBarProps) => {\n const [uncontrolled, setUncontrolled] = React.useState([]);\n const value = valueProp ?? uncontrolled;\n const [draft, setDraftState] = React.useState(null);\n const draftRef = React.useRef(draft);\n const setDraft = (next: Draft | null) => {\n draftRef.current = next;\n setDraftState(next);\n };\n const shown = withDraft(value, draft);\n const [open, setOpen] = React.useState(null);\n const [focusTarget, setFocusTarget] = React.useState(null);\n const picked = React.useRef(null);\n const addButton = React.useRef(null);\n const triggers = React.useRef(new Map());\n\n React.useEffect(() => {\n if (!focusTarget) return;\n (focusTarget === \"add\" ? addButton.current : triggers.current.get(focusTarget))?.focus();\n setFocusTarget(null);\n }, [focusTarget]);\n\n const latest = React.useRef(value);\n React.useLayoutEffect(() => {\n latest.current = value;\n }, [value]);\n const commit = (next: FilterBarFilter[]) => {\n latest.current = next;\n if (valueProp === undefined) setUncontrolled(next);\n onChange?.(next);\n };\n const update = (key: string, patch: Partial) => {\n const current = latest.current;\n const pending = draftRef.current?.filter.field === key ? draftRef.current : null;\n const index = current.findIndex((filter) => filter.field === key);\n const base = index >= 0 ? current[index] : pending?.filter;\n if (!base) return;\n const next = { ...base, ...patch };\n const at = index >= 0 ? index : (pending?.index ?? current.length);\n if (pending || !next.values.length) setDraft({ filter: next, index: at });\n if (next.values.length)\n commit(\n index >= 0\n ? current.map((filter) => (filter.field === key ? next : filter))\n : [...current.slice(0, at), next, ...current.slice(at)]\n );\n else if (index >= 0) commit(current.filter((filter) => filter.field !== key));\n };\n const remove = (key: string) => {\n const before = withDraft(latest.current, draftRef.current);\n const index = before.findIndex((filter) => filter.field === key);\n const next = before.filter((filter) => filter.field !== key);\n if (draftRef.current?.filter.field === key) setDraft(null);\n if (latest.current.some((filter) => filter.field === key))\n commit(latest.current.filter((filter) => filter.field !== key));\n setFocusTarget((next[index] ?? next[index - 1])?.field ?? \"add\");\n };\n const add = (field: FilterBarField) => {\n picked.current = field.key;\n setDraft({\n filter: {\n field: field.key,\n operator: field.type === \"date\" ? \"before\" : undefined,\n values: []\n },\n index: latest.current.length\n });\n };\n const changeOpen = (key: string, next: boolean) => {\n setOpen(next ? key : null);\n if (next) return;\n const applied = latest.current.find((filter) => filter.field === key)?.values.length;\n if (!applied) remove(key);\n else if (draftRef.current?.filter.field === key) setDraft(null);\n };\n const searchControl =\n search ??\n (onSearchChange || searchValue !== undefined ? (\n onSearchChange?.(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Escape\" && searchValue) {\n event.preventDefault();\n onSearchChange?.(\"\");\n }\n }}\n />\n ) : null);\n\n return (\n
\n
\n {searchControl && (\n
\n {searchControl}\n
\n )}\n {fields.length > 0 && (\n \n \n \n \n {\n if (!picked.current) return;\n event.preventDefault();\n setOpen(picked.current);\n picked.current = null;\n }}\n >\n Filter by\n {fields.map((field) => {\n const applied = shown.some((filter) => filter.field === field.key);\n return (\n add(field)}\n >\n {field.label}\n \n );\n })}\n \n \n )}\n {actions &&
{actions}
}\n
\n {shown.length > 0 && (\n
\n
    \n {shown.map((filter) => {\n const field = fields.find((entry) => entry.key === filter.field);\n if (!field) return null;\n const text = describeFilter(field, filter);\n const trigger = (\n {\n if (node) triggers.current.set(field.key, node);\n else triggers.current.delete(field.key);\n }}\n variant=\"outline\"\n iconRight=\"chev-down\"\n aria-label={`${field.label} ${text.verb} ${text.value}`}\n >\n {`${field.label} ${text.verb}`}\n {text.value}\n \n );\n const isOpen = open === field.key;\n const openChange = (next: boolean) => changeOpen(field.key, next);\n let picker: React.ReactNode;\n if (field.type === \"select\")\n picker = (\n update(field.key, { values: next ? [next] : [] })}\n open={isOpen}\n onOpenChange={openChange}\n trigger={trigger}\n />\n );\n else if (field.type === \"multi-select\")\n picker = (\n update(field.key, { values: next })}\n open={isOpen}\n onOpenChange={openChange}\n trigger={trigger}\n />\n );\n else\n picker = (\n \n {trigger}\n {\n if (field.type === \"date-range\") event.preventDefault();\n }}\n >\n {field.type === \"date-range\" && (\n {\n update(field.key, { values: next });\n openChange(false);\n }}\n />\n )}\n {field.type === \"date\" && (\n
    \n {\n if (next === \"before\" || next === \"after\")\n update(field.key, { operator: next });\n }}\n >\n Before\n After\n \n \n update(field.key, { values: date ? [isoDate(date)] : [] })\n }\n />\n
    \n )}\n {field.type === \"text\" && (\n \n update(field.key, {\n values: event.target.value ? [event.target.value] : []\n })\n }\n onKeyDown={(event) => {\n if (event.key === \"Enter\") openChange(false);\n }}\n />\n )}\n \n
    \n );\n return (\n
  • \n \n {picker}\n remove(field.key)}\n >{`Remove ${field.label} filter`}\n \n
  • \n );\n })}\n
\n {\n setDraft(null);\n commit([]);\n setFocusTarget(\"add\");\n }}\n >\n Clear filters\n \n
\n )}\n
\n );\n};\n" }, { "path": "src/components/cipher/patterns/filter-bar.module.css", diff --git a/r/multi-select.json b/r/multi-select.json index c75e3b27..3f7d5de1 100644 --- a/r/multi-select.json +++ b/r/multi-select.json @@ -14,7 +14,7 @@ "path": "src/components/cipher/ui/multi-select.tsx", "type": "registry:file", "target": "src/components/cipher/ui/multi-select.tsx", - "content": "import * as React from \"react\";\n\nimport { useFieldControlAttributes } from \"../lib/field-context\";\nimport { ListHighlight } from \"../lib/list-highlight\";\nimport { useControllableState } from \"../lib/use-controllable-state\";\nimport { type OptionCreateHandler, useOptionCreation } from \"../lib/use-option-creation\";\nimport { cn, titleIfClamped } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Icon } from \"./icon\";\nimport { useMenuInset } from \"./menu-inset\";\nimport { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from \"./popover\";\nimport { Spinner } from \"./spinner\";\n\nimport controlStyles from \"./controls.module.css\";\nimport menu from \"./menu.module.css\";\nimport styles from \"./picker.module.css\";\n\nexport type MultiSelectOption = {\n value: string;\n label: string;\n /** A muted line under the label. Search matches it as well as the label. */\n description?: string;\n /** A short muted value at the row's end, such as a count. */\n meta?: string;\n disabled?: boolean;\n group?: string;\n};\ntype Shared = {\n onCreate?: OptionCreateHandler;\n /** The Create row's text for the trimmed search, for example (query) => `Create tag \"${query}\"`. */\n createLabel?: (query: string) => string;\n onEmptyBackspace?: () => void;\n options: readonly MultiSelectOption[];\n label: string;\n id?: string;\n \"aria-describedby\"?: string;\n placeholder?: string;\n allLabel?: string;\n disabled?: boolean;\n invalid?: boolean;\n searchable?: boolean;\n /** Searches on the server: called with each query (and with \"\" when the menu closes), while options holds the results as they arrive. It turns on the search field. Include the selected options in options on first render so their labels show. */\n onSearch?: (query: string) => void;\n /** While onSearch is in flight: a spinner in the search field, and Searching… in place of No options found. */\n loading?: boolean;\n anchorRef?: React.RefObject;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n renderValue?: (selected: readonly MultiSelectOption[]) => React.ReactNode;\n trigger?: React.ReactElement>;\n size?: \"sm\" | \"md\";\n align?: \"start\" | \"center\" | \"end\";\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n menuWidth?: React.CSSProperties[\"width\"];\n quickActions?: boolean;\n closeOnFocusOutside?: boolean;\n className?: string;\n};\nexport type MultiSelectProps = Shared &\n (\n | {\n multiple?: true;\n value?: string[];\n defaultValue?: string[];\n onChange?: (value: string[]) => void;\n }\n | {\n multiple: false;\n value?: string | null;\n defaultValue?: string | null;\n onChange?: (value: string | null) => void;\n }\n );\nexport function MultiSelect({\n ref,\n ...props\n}: MultiSelectProps & { ref?: React.Ref }) {\n const {\n options,\n label,\n placeholder = \"Select options\",\n allLabel,\n disabled,\n invalid,\n searchable: searchableProp = false,\n onSearch,\n loading = false,\n anchorRef,\n renderValue,\n trigger,\n size = \"sm\",\n align = \"start\",\n side = \"bottom\",\n menuWidth,\n quickActions = true,\n closeOnFocusOutside = true,\n className\n } = props;\n const optionValues = new Set();\n options.forEach((option) => {\n if (optionValues.has(option.value))\n throw new Error(\"MultiSelect option values must be unique.\");\n optionValues.add(option.value);\n });\n const searchable = searchableProp || Boolean(onSearch);\n const field = useFieldControlAttributes(props);\n const generated = React.useId();\n const listId = `${generated}-list`;\n const [internal, setInternal] = React.useState(\n props.defaultValue ?? (props.multiple === false ? null : [])\n );\n const current = props.value === undefined ? internal : props.value;\n const selected = Array.isArray(current) ? current : current ? [current] : [];\n const [open, setOpen] = useControllableState({\n value: props.open,\n defaultValue: props.defaultOpen ?? false,\n onChange: props.onOpenChange\n });\n const [query, setQuery] = React.useState(\"\");\n const creation = useOptionCreation(props.onCreate, () => {\n setQuery(\"\");\n onSearch?.(\"\");\n search.current?.focus();\n });\n const { creating, error: createError } = creation;\n const changeQuery = (next: string) => {\n creation.cancel();\n setQuery(next);\n onSearch?.(next);\n };\n const changeOpen = (next: boolean) => {\n if (disabled && next) return;\n creation.cancel();\n setOpen(next);\n if (next || !query) return;\n setQuery(\"\");\n onSearch?.(\"\");\n };\n const [remembered, setRemembered] = React.useState([]);\n React.useLayoutEffect(() => {\n creation.cancel();\n }, [open, disabled, creation.cancel]);\n const canCreate = Boolean(\n props.onCreate &&\n query.trim() &&\n !options.some((option) => option.label.toLowerCase() === query.trim().toLowerCase())\n );\n const create = () => {\n if (canCreate && !creating && !disabled) creation.create(query.trim());\n };\n const [active, setActive] = React.useState(\"\");\n const prefix = React.useRef({ value: \"\", at: 0 });\n const list = React.useRef(null);\n const listInset = useMenuInset(list);\n const search = React.useRef(null);\n const apply = (values: string[]) => {\n if (disabled) return;\n if (props.multiple === false) {\n const next = values[0] ?? null;\n if (props.value === undefined) setInternal(next);\n props.onChange?.(next);\n } else {\n const included = new Set(values);\n const ordered = onSearch\n ? [...included]\n : options.filter((option) => included.has(option.value)).map((option) => option.value);\n if (props.value === undefined) setInternal(ordered);\n props.onChange?.(ordered);\n }\n };\n const shown = options.filter((option) => selected.includes(option.value));\n if (onSearch && shown.some((option) => !remembered.includes(option)))\n setRemembered((known) => [\n ...known.filter((item) => !shown.some((option) => option.value === item.value)),\n ...shown\n ]);\n const chosen = onSearch\n ? selected.flatMap(\n (value) =>\n options.find((option) => option.value === value) ??\n remembered.find((option) => option.value === value) ??\n []\n )\n : shown;\n const firstChosen = chosen[0];\n const eligible = options.filter((option) => !option.disabled);\n const allSelected =\n eligible.length > 0 && eligible.every((option) => selected.includes(option.value));\n const noneSelected = !eligible.some((option) => selected.includes(option.value));\n const multiple = props.multiple !== false;\n let summary: React.ReactNode = placeholder;\n if (renderValue) summary = renderValue(chosen);\n else if (firstChosen) {\n summary =\n props.multiple !== false && allLabel && allSelected && !onSearch ? (\n allLabel\n ) : (\n \n {firstChosen.label}\n {chosen.length > 1 && (\n \n +{chosen.length - 1}\n \n )}\n \n );\n }\n const filtered = onSearch\n ? options\n : options.filter((option) =>\n `${option.label} ${option.description ?? \"\"} ${option.meta ?? \"\"}`\n .toLowerCase()\n .includes(query.toLowerCase())\n );\n const enabled = filtered.filter((option) => !option.disabled && !disabled);\n const currentActive = enabled.find((option) => option.value === active) ?? enabled[0];\n const optionId = (value: string) =>\n `${generated}-option-${options.findIndex((option) => option.value === value)}`;\n React.useEffect(() => {\n if (open && currentActive)\n document.getElementById(optionId(currentActive.value))?.scrollIntoView({ block: \"nearest\" });\n }, [open, currentActive?.value]);\n const groups = [...new Set(filtered.map((option) => option.group ?? \"\"))];\n const all = () => apply([...selected, ...eligible.map((option) => option.value)]);\n const none = () =>\n apply(selected.filter((value) => !eligible.some((option) => option.value === value)));\n const toggle = (option: MultiSelectOption) => {\n if (option.disabled || disabled) return;\n if (onSearch)\n setRemembered((known) => [...known.filter((item) => item.value !== option.value), option]);\n if (props.multiple === false) {\n apply([option.value]);\n changeOpen(false);\n } else\n apply(\n selected.includes(option.value)\n ? selected.filter((value) => value !== option.value)\n : [...selected, option.value]\n );\n };\n const keydown = (event: React.KeyboardEvent) => {\n if (event.nativeEvent.isComposing || event.keyCode === 229) return;\n if (\n (event.ctrlKey || event.metaKey) &&\n event.key.toLowerCase() === \"a\" &&\n props.multiple !== false\n ) {\n event.preventDefault();\n if (allSelected) none();\n else all();\n return;\n }\n if (event.target instanceof HTMLButtonElement) return;\n if (event.key === \"Backspace\" && !query && props.onEmptyBackspace) {\n event.preventDefault();\n props.onEmptyBackspace();\n return;\n }\n if (event.key === \"Enter\" && !currentActive && canCreate) {\n event.preventDefault();\n create();\n return;\n }\n const index = enabled.findIndex((option) => option.value === currentActive?.value);\n if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n event.preventDefault();\n setActive(\n enabled[(index + (event.key === \"ArrowDown\" ? 1 : -1) + enabled.length) % enabled.length]\n ?.value ?? \"\"\n );\n } else if ((event.key === \"Home\" || event.key === \"End\") && event.target !== search.current) {\n event.preventDefault();\n setActive((event.key === \"Home\" ? enabled[0] : enabled[enabled.length - 1])?.value ?? \"\");\n } else if (\n (event.key === \"Enter\" || (event.key === \" \" && event.target !== search.current)) &&\n currentActive\n ) {\n event.preventDefault();\n toggle(currentActive);\n } else if (\n !searchable &&\n event.key.length === 1 &&\n !event.ctrlKey &&\n !event.metaKey &&\n !event.altKey\n ) {\n event.preventDefault();\n const now = Date.now();\n prefix.current = {\n value:\n (now - prefix.current.at < 500 ? prefix.current.value : \"\") + event.key.toLowerCase(),\n at: now\n };\n const found = enabled.find((option) =>\n option.label.toLowerCase().startsWith(prefix.current.value)\n );\n if (found) setActive(found.value);\n }\n };\n return (\n \n {anchorRef && }\n \n {trigger ? (\n React.cloneElement(trigger, {\n ...field,\n disabled: disabled || trigger.props.disabled,\n \"aria-disabled\": disabled || trigger.props.disabled || trigger.props[\"aria-disabled\"],\n \"aria-haspopup\": \"listbox\",\n tabIndex: disabled ? -1 : trigger.props.tabIndex,\n onClickCapture: (event: React.MouseEvent) => {\n if (disabled) {\n event.preventDefault();\n event.stopPropagation();\n } else trigger.props.onClickCapture?.(event);\n },\n onKeyDownCapture: (event: React.KeyboardEvent) => {\n if (disabled && (event.key === \"Enter\" || event.key === \" \")) {\n event.preventDefault();\n event.stopPropagation();\n } else trigger.props.onKeyDownCapture?.(event);\n },\n id: field.id ?? trigger.props.id,\n \"aria-labelledby\": field[\"aria-labelledby\"] ?? trigger.props[\"aria-labelledby\"],\n \"aria-describedby\":\n [field[\"aria-describedby\"], trigger.props[\"aria-describedby\"]]\n .filter(Boolean)\n .join(\" \") || undefined,\n \"aria-invalid\": invalid || field[\"aria-invalid\"] || trigger.props[\"aria-invalid\"]\n })\n ) : (\n {\n if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n event.preventDefault();\n changeOpen(true);\n }}\n className={cn(\n controlStyles.field,\n controlStyles.trigger,\n controlStyles.triggerHover,\n className\n )}\n >\n \n {summary}\n
\n \n \n )}\n \n {\n if (!closeOnFocusOutside) event.preventDefault();\n }}\n onInteractOutside={(event) => {\n const clear =\n event.target instanceof Element &&\n event.target.closest('[data-slot=\"combobox-clear\"]');\n if (clear && (!clear.isConnected || anchorRef?.current?.contains(clear)))\n event.preventDefault();\n }}\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n (searchable ? search.current : list.current)?.focus();\n }}\n onKeyDown={keydown}\n >\n {searchable && (\n
\n \n changeQuery(event.target.value)}\n placeholder=\"Search options\"\n />\n {loading && }\n
\n )}\n {multiple && quickActions ? (\n
\n \n {onSearch\n ? `${selected.length} selected`\n : `${chosen.length} of ${options.length} selected`}\n \n {[\n { text: \"Select all\", disabled: allSelected, run: all },\n { text: \"Deselect all\", disabled: noneSelected, run: none }\n ].map((action) => (\n event.preventDefault()}\n onClick={() => {\n action.run();\n list.current?.focus();\n }}\n >\n {action.text}\n \n ))}\n
\n ) : (\n \n {selected.length} selected\n \n )}\n \n {groups.map((group) => (\n
\n {group &&
{group}
}\n {filtered\n .filter((option) => (option.group ?? \"\") === group)\n .map((option) => (\n {\n if (!option.disabled) setActive(option.value);\n }}\n onMouseDown={(event) => event.preventDefault()}\n onClick={() => toggle(option)}\n >\n {multiple && (\n \n {selected.includes(option.value) && (\n \n )}\n \n )}\n {option.description ? (\n \n {option.label}\n titleIfClamped(event.currentTarget)}\n >\n {option.description}\n \n \n ) : (\n {option.label}\n )}\n {option.meta && {option.meta}}\n {!multiple && (\n \n {selected.includes(option.value) && }\n \n )}\n
\n ))}\n
\n ))}\n \n \n {!filtered.length && (\n

\n {loading ? \"Searching…\" : \"No options found\"}\n

\n )}\n {canCreate && (\n
\n {canCreate && (\n \n {props.createLabel?.(query.trim()) ?? `Create \"${query.trim()}\"`}\n \n )}\n
\n )}\n {createError && (\n

\n {createError}\n

\n )}\n \n \n );\n}\nMultiSelect.displayName = \"MultiSelect\";\n" + "content": "import * as React from \"react\";\n\nimport { useFieldControlAttributes } from \"../lib/field-context\";\nimport { ListHighlight } from \"../lib/list-highlight\";\nimport { useControllableState } from \"../lib/use-controllable-state\";\nimport { type OptionCreateHandler, useOptionCreation } from \"../lib/use-option-creation\";\nimport { cn, titleIfClamped } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Icon } from \"./icon\";\nimport { useMenuInset } from \"./menu-inset\";\nimport { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from \"./popover\";\nimport { Spinner } from \"./spinner\";\n\nimport controlStyles from \"./controls.module.css\";\nimport menu from \"./menu.module.css\";\nimport styles from \"./picker.module.css\";\n\nexport type MultiSelectOption = {\n value: string;\n label: string;\n /** A muted line under the label. Search matches it as well as the label. */\n description?: string;\n /** A short muted value at the row's end, such as a count. */\n meta?: string;\n disabled?: boolean;\n /** Search matches the group's heading too. */\n group?: string;\n /** Extra words the search matches but never shows, such as an ID or an alias. */\n keywords?: readonly string[];\n};\ntype Shared = {\n onCreate?: OptionCreateHandler;\n /** The Create row's text for the trimmed search, for example (query) => `Create tag \"${query}\"`. */\n createLabel?: (query: string) => string;\n onEmptyBackspace?: () => void;\n options: readonly MultiSelectOption[];\n label: string;\n id?: string;\n \"aria-describedby\"?: string;\n placeholder?: string;\n allLabel?: string;\n disabled?: boolean;\n invalid?: boolean;\n searchable?: boolean;\n searchPlaceholder?: string;\n /** Searches on the server: called with each query (and with \"\" when the menu closes), while options holds the results as they arrive. It turns on the search field. Include the selected options in options on first render so their labels show. */\n onSearch?: (query: string) => void;\n /** While onSearch is in flight: a spinner in the search field, and Searching… in place of No options found. */\n loading?: boolean;\n anchorRef?: React.RefObject;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n renderValue?: (selected: readonly MultiSelectOption[]) => React.ReactNode;\n trigger?: React.ReactElement>;\n size?: \"sm\" | \"md\";\n align?: \"start\" | \"center\" | \"end\";\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n menuWidth?: React.CSSProperties[\"width\"];\n quickActions?: boolean;\n closeOnFocusOutside?: boolean;\n className?: string;\n};\nexport type MultiSelectProps = Shared &\n (\n | {\n multiple?: true;\n value?: string[];\n defaultValue?: string[];\n onChange?: (value: string[]) => void;\n }\n | {\n multiple: false;\n value?: string | null;\n defaultValue?: string | null;\n onChange?: (value: string | null) => void;\n }\n );\nexport function MultiSelect({\n ref,\n ...props\n}: MultiSelectProps & { ref?: React.Ref }) {\n const {\n options,\n label,\n placeholder = \"Select options\",\n allLabel,\n disabled,\n invalid,\n searchable: searchableProp = false,\n searchPlaceholder = \"Search options\",\n onSearch,\n loading = false,\n anchorRef,\n renderValue,\n trigger,\n size = \"sm\",\n align = \"start\",\n side = \"bottom\",\n menuWidth,\n quickActions = true,\n closeOnFocusOutside = true,\n className\n } = props;\n const optionValues = new Set();\n options.forEach((option) => {\n if (optionValues.has(option.value))\n throw new Error(\"MultiSelect option values must be unique.\");\n optionValues.add(option.value);\n });\n const searchable = searchableProp || Boolean(onSearch);\n const field = useFieldControlAttributes(props);\n const generated = React.useId();\n const listId = `${generated}-list`;\n const [internal, setInternal] = React.useState(\n props.defaultValue ?? (props.multiple === false ? null : [])\n );\n const current = props.value === undefined ? internal : props.value;\n const selected = Array.isArray(current) ? current : current ? [current] : [];\n const [open, setOpen] = useControllableState({\n value: props.open,\n defaultValue: props.defaultOpen ?? false,\n onChange: props.onOpenChange\n });\n const [query, setQuery] = React.useState(\"\");\n const creation = useOptionCreation(props.onCreate, () => {\n setQuery(\"\");\n onSearch?.(\"\");\n search.current?.focus();\n });\n const { creating, error: createError } = creation;\n const changeQuery = (next: string) => {\n creation.cancel();\n setQuery(next);\n onSearch?.(next);\n };\n const changeOpen = (next: boolean) => {\n if (disabled && next) return;\n creation.cancel();\n setOpen(next);\n if (next || !query) return;\n setQuery(\"\");\n onSearch?.(\"\");\n };\n const [remembered, setRemembered] = React.useState([]);\n React.useLayoutEffect(() => {\n creation.cancel();\n }, [open, disabled, creation.cancel]);\n const canCreate = Boolean(\n props.onCreate &&\n query.trim() &&\n !options.some((option) => option.label.toLowerCase() === query.trim().toLowerCase())\n );\n const create = () => {\n if (canCreate && !creating && !disabled) creation.create(query.trim());\n };\n const [active, setActive] = React.useState(\"\");\n const prefix = React.useRef({ value: \"\", at: 0 });\n const list = React.useRef(null);\n const listInset = useMenuInset(list);\n const search = React.useRef(null);\n const apply = (values: string[]) => {\n if (disabled) return;\n if (props.multiple === false) {\n const next = values[0] ?? null;\n if (props.value === undefined) setInternal(next);\n props.onChange?.(next);\n } else {\n const included = new Set(values);\n const ordered = onSearch\n ? [...included]\n : options.filter((option) => included.has(option.value)).map((option) => option.value);\n if (props.value === undefined) setInternal(ordered);\n props.onChange?.(ordered);\n }\n };\n const shown = options.filter((option) => selected.includes(option.value));\n if (onSearch && shown.some((option) => !remembered.includes(option)))\n setRemembered((known) => [\n ...known.filter((item) => !shown.some((option) => option.value === item.value)),\n ...shown\n ]);\n const chosen = onSearch\n ? selected.flatMap(\n (value) =>\n options.find((option) => option.value === value) ??\n remembered.find((option) => option.value === value) ??\n []\n )\n : shown;\n const firstChosen = chosen[0];\n const eligible = options.filter((option) => !option.disabled);\n const allSelected =\n eligible.length > 0 && eligible.every((option) => selected.includes(option.value));\n const noneSelected = !eligible.some((option) => selected.includes(option.value));\n const multiple = props.multiple !== false;\n let summary: React.ReactNode = placeholder;\n if (renderValue) summary = renderValue(chosen);\n else if (firstChosen) {\n summary =\n props.multiple !== false && allLabel && allSelected && !onSearch ? (\n allLabel\n ) : (\n \n {firstChosen.label}\n {chosen.length > 1 && (\n \n +{chosen.length - 1}\n \n )}\n \n );\n }\n const filtered = onSearch\n ? options\n : options.filter((option) =>\n [option.label, option.description, option.meta, option.group, ...(option.keywords ?? [])]\n .join(\" \")\n .toLowerCase()\n .includes(query.toLowerCase())\n );\n const enabled = filtered.filter((option) => !option.disabled && !disabled);\n const currentActive = enabled.find((option) => option.value === active) ?? enabled[0];\n const optionId = (value: string) =>\n `${generated}-option-${options.findIndex((option) => option.value === value)}`;\n React.useEffect(() => {\n if (open && currentActive)\n document.getElementById(optionId(currentActive.value))?.scrollIntoView({ block: \"nearest\" });\n }, [open, currentActive?.value]);\n const groups = [...new Set(filtered.map((option) => option.group ?? \"\"))];\n const all = () => apply([...selected, ...eligible.map((option) => option.value)]);\n const none = () =>\n apply(selected.filter((value) => !eligible.some((option) => option.value === value)));\n const toggle = (option: MultiSelectOption) => {\n if (option.disabled || disabled) return;\n if (onSearch)\n setRemembered((known) => [...known.filter((item) => item.value !== option.value), option]);\n if (props.multiple === false) {\n apply([option.value]);\n changeOpen(false);\n } else\n apply(\n selected.includes(option.value)\n ? selected.filter((value) => value !== option.value)\n : [...selected, option.value]\n );\n };\n const keydown = (event: React.KeyboardEvent) => {\n if (event.nativeEvent.isComposing || event.keyCode === 229) return;\n if (\n (event.ctrlKey || event.metaKey) &&\n event.key.toLowerCase() === \"a\" &&\n props.multiple !== false\n ) {\n event.preventDefault();\n if (allSelected) none();\n else all();\n return;\n }\n if (event.target instanceof HTMLButtonElement) return;\n if (event.key === \"Backspace\" && !query && props.onEmptyBackspace) {\n event.preventDefault();\n props.onEmptyBackspace();\n return;\n }\n if (event.key === \"Enter\" && !currentActive && canCreate) {\n event.preventDefault();\n create();\n return;\n }\n const index = enabled.findIndex((option) => option.value === currentActive?.value);\n if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n event.preventDefault();\n setActive(\n enabled[(index + (event.key === \"ArrowDown\" ? 1 : -1) + enabled.length) % enabled.length]\n ?.value ?? \"\"\n );\n } else if ((event.key === \"Home\" || event.key === \"End\") && event.target !== search.current) {\n event.preventDefault();\n setActive((event.key === \"Home\" ? enabled[0] : enabled[enabled.length - 1])?.value ?? \"\");\n } else if (\n (event.key === \"Enter\" || (event.key === \" \" && event.target !== search.current)) &&\n currentActive\n ) {\n event.preventDefault();\n toggle(currentActive);\n } else if (\n !searchable &&\n event.key.length === 1 &&\n !event.ctrlKey &&\n !event.metaKey &&\n !event.altKey\n ) {\n event.preventDefault();\n const now = Date.now();\n prefix.current = {\n value:\n (now - prefix.current.at < 500 ? prefix.current.value : \"\") + event.key.toLowerCase(),\n at: now\n };\n const found = enabled.find((option) =>\n option.label.toLowerCase().startsWith(prefix.current.value)\n );\n if (found) setActive(found.value);\n }\n };\n return (\n \n {anchorRef && }\n \n {trigger ? (\n React.cloneElement(trigger, {\n ...field,\n disabled: disabled || trigger.props.disabled,\n \"aria-disabled\": disabled || trigger.props.disabled || trigger.props[\"aria-disabled\"],\n \"aria-haspopup\": \"listbox\",\n tabIndex: disabled ? -1 : trigger.props.tabIndex,\n onClickCapture: (event: React.MouseEvent) => {\n if (disabled) {\n event.preventDefault();\n event.stopPropagation();\n } else trigger.props.onClickCapture?.(event);\n },\n onKeyDownCapture: (event: React.KeyboardEvent) => {\n if (disabled && (event.key === \"Enter\" || event.key === \" \")) {\n event.preventDefault();\n event.stopPropagation();\n } else trigger.props.onKeyDownCapture?.(event);\n },\n id: field.id ?? trigger.props.id,\n \"aria-labelledby\": field[\"aria-labelledby\"] ?? trigger.props[\"aria-labelledby\"],\n \"aria-describedby\":\n [field[\"aria-describedby\"], trigger.props[\"aria-describedby\"]]\n .filter(Boolean)\n .join(\" \") || undefined,\n \"aria-invalid\": invalid || field[\"aria-invalid\"] || trigger.props[\"aria-invalid\"]\n })\n ) : (\n {\n if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n event.preventDefault();\n changeOpen(true);\n }}\n className={cn(\n controlStyles.field,\n controlStyles.trigger,\n controlStyles.triggerHover,\n className\n )}\n >\n \n {summary}\n
\n \n \n )}\n \n {\n if (!closeOnFocusOutside) event.preventDefault();\n }}\n onInteractOutside={(event) => {\n const clear =\n event.target instanceof Element && event.target.closest('[data-slot=\"combobox-clear\"]');\n if (clear && (!clear.isConnected || anchorRef?.current?.contains(clear)))\n event.preventDefault();\n }}\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n (searchable ? search.current : list.current)?.focus();\n }}\n onKeyDown={keydown}\n >\n {searchable && (\n
\n \n changeQuery(event.target.value)}\n placeholder={searchPlaceholder}\n />\n {loading && }\n
\n )}\n {multiple && quickActions ? (\n
\n \n {onSearch\n ? `${selected.length} selected`\n : `${chosen.length} of ${options.length} selected`}\n \n {[\n { text: \"Select all\", disabled: allSelected, run: all },\n { text: \"Deselect all\", disabled: noneSelected, run: none }\n ].map((action) => (\n event.preventDefault()}\n onClick={() => {\n action.run();\n list.current?.focus();\n }}\n >\n {action.text}\n \n ))}\n
\n ) : (\n \n {selected.length} selected\n \n )}\n \n {groups.map((group) => (\n
\n {group &&
{group}
}\n {filtered\n .filter((option) => (option.group ?? \"\") === group)\n .map((option) => (\n {\n if (!option.disabled) setActive(option.value);\n }}\n onMouseDown={(event) => event.preventDefault()}\n onClick={() => toggle(option)}\n >\n {multiple && (\n \n {selected.includes(option.value) && (\n \n )}\n \n )}\n {option.description ? (\n \n {option.label}\n titleIfClamped(event.currentTarget)}\n >\n {option.description}\n \n \n ) : (\n {option.label}\n )}\n {option.meta && {option.meta}}\n {!multiple && (\n \n {selected.includes(option.value) && }\n \n )}\n
\n ))}\n \n ))}\n \n \n {!filtered.length && (\n

\n {loading ? \"Searching…\" : \"No options found\"}\n

\n )}\n {canCreate && (\n
\n {canCreate && (\n \n {props.createLabel?.(query.trim()) ?? `Create \"${query.trim()}\"`}\n \n )}\n
\n )}\n {createError && (\n

\n {createError}\n

\n )}\n \n \n );\n}\nMultiSelect.displayName = \"MultiSelect\";\n" }, { "path": "src/components/cipher/ui/controls.module.css", diff --git a/site/src/catalog.json b/site/src/catalog.json index bb03721e..70c265cc 100644 --- a/site/src/catalog.json +++ b/site/src/catalog.json @@ -544,6 +544,10 @@ { "title": "Option icons", "module": "combobox/icons" + }, + { + "title": "Search over keywords and group headings, with a custom search placeholder", + "module": "combobox/keywords" } ] }, @@ -932,6 +936,10 @@ { "title": "Search only", "module": "filter-bar/search-only" + }, + { + "title": "Exact-match text field: the chip reads is instead of contains", + "module": "filter-bar/exact-match" } ] }, diff --git a/site/src/examples/combobox/keywords.tsx b/site/src/examples/combobox/keywords.tsx new file mode 100644 index 00000000..94e7fc9f --- /dev/null +++ b/site/src/examples/combobox/keywords.tsx @@ -0,0 +1,64 @@ +import { useState } from "react"; + +import { Combobox, type ComboboxOption } from "@infisical/cipher/ui/combobox"; +import { Field } from "@infisical/cipher/ui/field"; + +const products: ComboboxOption[] = [ + { + value: "pro-monthly", + label: "Pro, monthly", + meta: "$18", + group: "Self-serve", + keywords: ["price_1QfPro0Monthly", "prod_SecretsPro"] + }, + { + value: "pro-yearly", + label: "Pro, yearly", + meta: "$180", + group: "Self-serve", + keywords: ["price_1QfPro0Yearly", "prod_SecretsPro"] + }, + { + value: "enterprise", + label: "Enterprise", + group: "Sales-led", + keywords: ["price_1QfEnt0Custom", "prod_SecretsEnterprise"] + }, + { + value: "enterprise-gov", + label: "Enterprise for government and regulated industries, annual commitment", + group: "Sales-led", + keywords: ["price_1QfEnt0FedRAMP", "FedRAMP", "GovCloud"] + }, + { + value: "pam-addon", + label: "Privileged access add-on", + group: "Add-ons", + keywords: ["price_1QfPam0Seat", "PAM"] + } +]; + +const Product = ({ label, initial }: { label: string; initial: string }) => { + const [value, setValue] = useState(initial); + return ( + + + + ); +}; + +export default function Example() { + return ( +
+ + + +
+ ); +} diff --git a/site/src/examples/filter-bar/exact-match.tsx b/site/src/examples/filter-bar/exact-match.tsx new file mode 100644 index 00000000..60bb8aff --- /dev/null +++ b/site/src/examples/filter-bar/exact-match.tsx @@ -0,0 +1,44 @@ +import { useState } from "react"; + +import { + FilterBar, + type FilterBarField, + type FilterBarFilter +} from "@infisical/cipher/patterns/filter-bar"; + +const fields: FilterBarField[] = [ + { key: "org", label: "Org ID", type: "text", placeholder: "Exact org ID", verb: "is" }, + { key: "customer", label: "Customer", type: "text", placeholder: "Part of a name" } +]; + +const Bar = ({ initial }: { initial: FilterBarFilter[] }) => { + const [filters, setFilters] = useState(initial); + const [query, setQuery] = useState(""); + return ( + + ); +}; + +export default function Example() { + return ( +
+ + + +
+ ); +} diff --git a/src/patterns/filter-bar.tsx b/src/patterns/filter-bar.tsx index 351c4d5d..d005a8be 100644 --- a/src/patterns/filter-bar.tsx +++ b/src/patterns/filter-bar.tsx @@ -31,7 +31,14 @@ export type FilterBarField = | (FilterBarChoiceField & { type: "multi-select" }) | { key: string; label: string; type: "date"; defaultMonth?: Date } | { key: string; label: string; type: "date-range"; defaultMonth?: Date } - | { key: string; label: string; type: "text"; placeholder?: string }; + | { + key: string; + label: string; + type: "text"; + placeholder?: string; + /** How the chip reads the value, such as "is" for an exact match. Defaults to "contains". */ + verb?: string; + }; export type FilterBarFilter = { field: string; operator?: "before" | "after"; @@ -88,7 +95,8 @@ export const describeFilter = (field: FilterBarField, filter: FilterBarFilter) = if (!from || !to) return { verb: "is", value: "any date" }; return { verb: from.getTime() === to.getTime() ? "on" : "from", value: shortRange(from, to) }; } - if (field.type === "text") return { verb: "contains", value: filter.values[0] ?? "anything" }; + if (field.type === "text") + return { verb: field.verb ?? "contains", value: filter.values[0] ?? "anything" }; const labels = filter.values.map( (value) => field.options.find((option) => option.value === value)?.label ?? value ); diff --git a/src/ui/combobox.tsx b/src/ui/combobox.tsx index 22b5edf2..4375b64f 100644 --- a/src/ui/combobox.tsx +++ b/src/ui/combobox.tsx @@ -43,8 +43,10 @@ export type ComboboxOption = { /** A muted line under the label. Search matches it as well as the label. */ description?: string; meta?: string; - /** Options that share a group sit under its heading, in the order each group first appears. */ + /** Options that share a group sit under its heading, in the order each group first appears. Search matches the heading too. */ group?: string; + /** Extra words search matches but never shows, such as a product's other names or an ID. */ + keywords?: readonly string[]; disabled?: boolean; }; export type ComboboxCreationFormProps = { @@ -96,6 +98,8 @@ type SharedComboboxProps = { id?: string; "aria-describedby"?: string; emptyText?: string; + /** The search field's placeholder. Defaults to "Search options". */ + searchPlaceholder?: string; disabled?: boolean; invalid?: boolean; mono?: boolean; @@ -144,6 +148,7 @@ export function Combobox({ placeholder = "Select an option", label, emptyText = "No options found", + searchPlaceholder = "Search options", disabled, invalid, mono, @@ -229,7 +234,8 @@ export function Combobox({ const filtered = onSearch ? options : options.filter((option) => - `${option.label} ${option.description ?? ""} ${option.meta ?? ""}` + [option.label, option.description, option.meta, option.group, ...(option.keywords ?? [])] + .join(" ") .toLowerCase() .includes(query.toLowerCase()) ); @@ -318,6 +324,7 @@ export function Combobox({ disabled={disabled} invalid={invalid} searchable + searchPlaceholder={searchPlaceholder} quickActions={false} anchorRef={fieldRef} open={open} @@ -442,7 +449,7 @@ export function Combobox({ { if (event.nativeEvent.isComposing || event.keyCode === 229) event.stopPropagation(); diff --git a/src/ui/multi-select.tsx b/src/ui/multi-select.tsx index c9b19530..4b3f3b0b 100644 --- a/src/ui/multi-select.tsx +++ b/src/ui/multi-select.tsx @@ -23,7 +23,10 @@ export type MultiSelectOption = { /** A short muted value at the row's end, such as a count. */ meta?: string; disabled?: boolean; + /** Search matches the group's heading too. */ group?: string; + /** Extra words the search matches but never shows, such as an ID or an alias. */ + keywords?: readonly string[]; }; type Shared = { onCreate?: OptionCreateHandler; @@ -39,6 +42,7 @@ type Shared = { disabled?: boolean; invalid?: boolean; searchable?: boolean; + searchPlaceholder?: string; /** Searches on the server: called with each query (and with "" when the menu closes), while options holds the results as they arrive. It turns on the search field. Include the selected options in options on first render so their labels show. */ onSearch?: (query: string) => void; /** While onSearch is in flight: a spinner in the search field, and Searching… in place of No options found. */ @@ -84,6 +88,7 @@ export function MultiSelect({ disabled, invalid, searchable: searchableProp = false, + searchPlaceholder = "Search options", onSearch, loading = false, anchorRef, @@ -209,7 +214,8 @@ export function MultiSelect({ const filtered = onSearch ? options : options.filter((option) => - `${option.label} ${option.description ?? ""} ${option.meta ?? ""}` + [option.label, option.description, option.meta, option.group, ...(option.keywords ?? [])] + .join(" ") .toLowerCase() .includes(query.toLowerCase()) ); @@ -380,8 +386,7 @@ export function MultiSelect({ }} onInteractOutside={(event) => { const clear = - event.target instanceof Element && - event.target.closest('[data-slot="combobox-clear"]'); + event.target instanceof Element && event.target.closest('[data-slot="combobox-clear"]'); if (clear && (!clear.isConnected || anchorRef?.current?.contains(clear))) event.preventDefault(); }} @@ -404,7 +409,7 @@ export function MultiSelect({ aria-activedescendant={currentActive ? optionId(currentActive.value) : undefined} value={query} onChange={(event) => changeQuery(event.target.value)} - placeholder="Search options" + placeholder={searchPlaceholder} /> {loading && }