Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(search): snappier, keyboard-navigable In/From filter submenu (#2643)

gbirmanc1b381ce50c1
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx
index d3af666710..55b7435126 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx
@@ -1,26 +1,25 @@
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import { Combobox } from '@kobalte/core/combobox';
-import type { CollectionNode } from '@kobalte/core';
import { cn } from '@ui/utils/classname';
-import {
- type Accessor,
- createMemo,
- createSignal,
- For,
- type JSX,
- Show,
-} from 'solid-js';
+import { type Accessor, createSignal, For, type JSX, Show } from 'solid-js';
import XIcon from '@icon/regular/x.svg';
import CheckIcon from '@icon/regular/check.svg';
-import SearchIcon from '@icon/regular/magnifying-glass.svg';
import type { FilterOption } from './unified-filter-dropdown';
import type { SearchableOption } from './search-filter-controls';
+import { SearchableMultiSelect } from './searchable-multi-select';
import { Button } from '@ui/components/Button';
export type ActiveFilter = {
categoryLabel: string;
- optionId: string;
- optionLabel: string;
+ /**
+ * Accessor returning the current filter id. Wrapped as an accessor so that
+ * multi-select chips (In/From) can keep stable object identity across
+ * selection toggles — the id string changes but the chip component doesn't
+ * remount, preserving its internal state (open, search text).
+ */
+ optionId: Accessor<string>;
+ /** Accessor returning the current display label. See `optionId` for rationale. */
+ optionLabel: Accessor<string>;
icon?: () => JSX.Element;
/** Available options in this category for replacement */
categoryOptions?: FilterOption[];
@@ -55,6 +54,14 @@ export type ActiveFilter = {
onSearchableChange?: (ids: string[]) => void;
/** Placeholder for the searchable chip's search input. */
searchPlaceholder?: string;
+ /**
+ * Optional controlled popup open state. When provided, the upstream can
+ * keep the chip mounted while the popup is still open even if the chip's
+ * active selections drop to zero (so toggling A off then B on in the same
+ * session doesn't close the menu).
+ */
+ isPopupOpen?: Accessor<boolean>;
+ setPopupOpen?: (v: boolean) => void;
};
interface ActiveFilterChipsProps {
@@ -70,93 +77,24 @@ interface ActiveFilterChipsProps {
hideCategoryLabel?: boolean;
}
-const SearchableChipItem = (itemProps: {
- item: CollectionNode<SearchableOption>;
-}) => (
- <Combobox.Item
- item={itemProps.item}
- class="w-full flex items-center gap-2.5 px-3 py-2 rounded-xs text-left text-xs data-[highlighted]:bg-ink/5 group"
- >
- <span class="size-4 flex items-center justify-center shrink-0 rounded-xs border border-edge group-data-[selected]:bg-accent group-data-[selected]:border-accent">
- <Combobox.ItemIndicator>
- <CheckIcon class="size-2.5 text-page" />
- </Combobox.ItemIndicator>
- </span>
- <Show when={itemProps.item.rawValue.icon}>
- {(icon) => (
- <span class="size-4 flex items-center justify-center shrink-0">
- {icon()()}
- </span>
- )}
- </Show>
- <Combobox.ItemLabel class="flex-1 truncate text-ink-muted group-data-[selected]:text-ink">
- {itemProps.item.rawValue.label}
- </Combobox.ItemLabel>
- </Combobox.Item>
-);
-
-// Persist open/search state across chip remounts — the active-filters array
-// recomputes with new object references on every selection toggle, which makes
-// <For> destroy and re-mount the chip, losing its internal open state.
-const chipPersistentState = new Map<
- string,
- {
- isOpen: Accessor<boolean>;
- setIsOpen: (v: boolean) => void;
- searchQuery: Accessor<string>;
- setSearchQuery: (v: string) => void;
- }
->();
-
-const getChipState = (key: string) => {
- let entry = chipPersistentState.get(key);
- if (!entry) {
- const [isOpen, setIsOpen] = createSignal(false);
- const [searchQuery, setSearchQuery] = createSignal('');
- entry = { isOpen, setIsOpen, searchQuery, setSearchQuery };
- chipPersistentState.set(key, entry);
- }
- return entry;
-};
-
const SearchableFilterChip = (props: {
filter: ActiveFilter;
onRemove: () => void;
chipClass?: string;
hideCategoryLabel?: boolean;
}) => {
- const state = () => getChipState(props.filter.categoryLabel);
- const searchQuery = () => state().searchQuery();
- const setSearchQuery = (v: string) => state().setSearchQuery(v);
- const isOpen = () => state().isOpen();
- const setIsOpen = (v: boolean) => state().setIsOpen(v);
-
- const allOptions = () => props.filter.searchableOptions?.() ?? [];
- const activeIds = () => props.filter.activeSearchableIds?.() ?? [];
-
- const activeOptions = createMemo(() => {
- const set = new Set(activeIds());
- return allOptions().filter((opt) => set.has(opt.id));
- });
+ const options: Accessor<SearchableOption[]> = () =>
+ props.filter.searchableOptions?.() ?? [];
+ const activeIds: Accessor<string[]> = () =>
+ props.filter.activeSearchableIds?.() ?? [];
- const filteredOptions = createMemo(() => {
- const q = searchQuery().toLowerCase().trim();
- if (!q) return allOptions();
- return allOptions().filter((opt) => opt.label.toLowerCase().includes(q));
- });
-
- const handleChange = (selected: SearchableOption[]) => {
- props.filter.onSearchableChange?.(selected.map((o) => o.id));
+ const handleChange = (ids: string[]) => {
+ props.filter.onSearchableChange?.(ids);
};
- const onInputChange = (value: string) => {
- setSearchQuery(value);
- };
-
- const onOpenChange = (open: boolean) => {
- setIsOpen(open);
- if (!open) setSearchQuery('');
- };
+ const placeholder =
+ props.filter.searchPlaceholder ??
+ `Search ${props.filter.categoryLabel.toLowerCase()}...`;
return (
<div
@@ -167,75 +105,36 @@ const SearchableFilterChip = (props: {
props.chipClass
)}
>
- <Combobox<SearchableOption>
- multiple
- selectionBehavior="toggle"
- closeOnSelection={false}
- open={isOpen()}
- options={filteredOptions()}
- value={activeOptions()}
+ <SearchableMultiSelect
+ options={options}
+ activeIds={activeIds}
onChange={handleChange}
- onInputChange={onInputChange}
- onOpenChange={onOpenChange}
- optionValue="id"
- optionTextValue="label"
- optionLabel="label"
- allowsEmptyCollection
+ placeholder={placeholder}
placement="bottom-start"
- gutter={4}
- itemComponent={SearchableChipItem}
+ open={props.filter.isPopupOpen}
+ onOpenChange={(v) => props.filter.setPopupOpen?.(v)}
>
- <Combobox.Control class="flex">
- <Combobox.Trigger
- class={cn(
- 'inline-flex items-center gap-1.5 pl-2 pr-1 py-1',
- 'hover:text-ink hover:bg-edge-muted'
+ <Combobox.Trigger
+ class={cn(
+ 'inline-flex items-center gap-1.5 pl-2 pr-1 py-1',
+ 'hover:text-ink hover:bg-edge-muted'
+ )}
+ >
+ <Show when={props.filter.icon}>
+ {(icon) => (
+ <span class="size-3 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
)}
- >
- <Show when={props.filter.icon}>
- {(icon) => (
- <span class="size-3 flex items-center justify-center shrink-0">
- {icon()()}
- </span>
- )}
+ </Show>
+ <span class="font-medium">
+ <Show when={!props.hideCategoryLabel}>
+ {props.filter.categoryLabel}:{' '}
</Show>
- <span class="font-medium">
- <Show when={!props.hideCategoryLabel}>
- {props.filter.categoryLabel}:{' '}
- </Show>
- {props.filter.optionLabel}
- </span>
- </Combobox.Trigger>
- <Combobox.Input class="sr-only" />
- </Combobox.Control>
-
- <Combobox.Portal>
- <Combobox.Content class="z-action-menu bg-surface-0 border border-edge-muted rounded-sm shadow-md w-[260px] max-w-[90vw] overflow-hidden">
- <div class="flex items-center gap-2 px-3 py-2 border-b border-edge-muted">
- <SearchIcon class="size-3.5 text-ink-muted shrink-0" />
- <Combobox.Input
- class="flex-1 min-w-0 text-xs bg-transparent outline-none caret-accent placeholder:text-ink-faint"
- placeholder={
- props.filter.searchPlaceholder ??
- `Search ${props.filter.categoryLabel.toLowerCase()}...`
- }
- />
- </div>
- <div class="p-1">
- <Show
- when={filteredOptions().length > 0}
- fallback={
- <div class="py-3 px-2 text-center text-xs text-ink-muted">
- No options match "{searchQuery()}"
- </div>
- }
- >
- <Combobox.Listbox class="max-h-[240px] overflow-y-auto" />
- </Show>
- </div>
- </Combobox.Content>
- </Combobox.Portal>
- </Combobox>
+ {props.filter.optionLabel()}
+ </span>
+ </Combobox.Trigger>
+ </SearchableMultiSelect>
<button
type="button"
@@ -292,7 +191,7 @@ const FilterChip = (props: {
<Show when={!props.hideCategoryLabel}>
{props.filter.categoryLabel}:{' '}
</Show>
- {props.filter.optionLabel}
+ {props.filter.optionLabel()}
</span>
</span>
}
@@ -315,7 +214,7 @@ const FilterChip = (props: {
<Show when={!props.hideCategoryLabel}>
{props.filter.categoryLabel}:{' '}
</Show>
- {props.filter.optionLabel}
+ {props.filter.optionLabel()}
</span>
</DropdownMenu.Trigger>
@@ -433,9 +332,9 @@ export const ActiveFilterChips = (props: ActiveFilterChipsProps) => {
fallback={
<FilterChip
filter={filter}
- onRemove={() => props.onRemove(filter.optionId)}
+ onRemove={() => props.onRemove(filter.optionId())}
onReplace={(newOptionId) =>
- props.onReplace(filter.optionId, newOptionId)
+ props.onReplace(filter.optionId(), newOptionId)
}
isOptionActive={props.isOptionActive}
chipClass={props.chipClass}
@@ -449,7 +348,7 @@ export const ActiveFilterChips = (props: ActiveFilterChipsProps) => {
if (filter.onRemove) {
filter.onRemove();
} else {
- props.onRemove(filter.optionId);
+ props.onRemove(filter.optionId());
}
}}
chipClass={props.chipClass}
@@ -464,9 +363,9 @@ export const ActiveFilterChips = (props: ActiveFilterChipsProps) => {
fallback={
<FilterChip
filter={filter}
- onRemove={() => props.onRemove(filter.optionId)}
+ onRemove={() => props.onRemove(filter.optionId())}
onReplace={(newOptionId) =>
- props.onReplace(filter.optionId, newOptionId)
+ props.onReplace(filter.optionId(), newOptionId)
}
isOptionActive={props.isOptionActive}
chipClass={props.chipClass}
@@ -480,7 +379,7 @@ export const ActiveFilterChips = (props: ActiveFilterChipsProps) => {
if (filter.onRemove) {
filter.onRemove();
} else {
- props.onRemove(filter.optionId);
+ props.onRemove(filter.optionId());
}
}}
chipClass={props.chipClass}
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/searchable-multi-select.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/searchable-multi-select.tsx
new file mode 100644
index 0000000000..ab2ce00754
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/searchable-multi-select.tsx
@@ -0,0 +1,307 @@
+import { Combobox } from '@kobalte/core/combobox';
+import type { CollectionNode } from '@kobalte/core';
+import { cn } from '@ui/utils/classname';
+import {
+ type Accessor,
+ createMemo,
+ createSignal,
+ type JSX,
+ Show,
+} from 'solid-js';
+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
+import CheckIcon from '@icon/regular/check.svg';
+import SearchIcon from '@icon/regular/magnifying-glass.svg';
+import type { SearchableOption } from './search-filter-controls';
+
+const ITEM_HEIGHT = 36;
+const LISTBOX_CLASS = 'max-h-[240px] overflow-y-auto';
+
+export type SearchableMultiSelectProps = {
+ options: Accessor<SearchableOption[]>;
+ activeIds: Accessor<string[]>;
+ onChange: (ids: string[]) => void;
+ placeholder?: string;
+ placement?:
+ | 'bottom-start'
+ | 'bottom-end'
+ | 'top-start'
+ | 'top-end'
+ | 'right-start'
+ | 'left-start';
+ gutter?: number;
+ contentClass?: string;
+ listboxClass?: string;
+ open?: Accessor<boolean>;
+ onOpenChange?: (open: boolean) => void;
+ children: JSX.Element;
+};
+
+const SearchableMultiSelectItem = (itemProps: {
+ item: CollectionNode<SearchableOption>;
+}) => (
+ <Combobox.Item
+ item={itemProps.item}
+ class="w-full flex items-center gap-2.5 px-3 py-2 rounded-xs text-left text-xs data-[highlighted]:bg-ink/5 group"
+ >
+ <span class="size-4 flex items-center justify-center shrink-0 rounded-xs border border-edge group-data-[selected]:bg-accent group-data-[selected]:border-accent">
+ <Combobox.ItemIndicator>
+ <CheckIcon class="size-2.5 text-page" />
+ </Combobox.ItemIndicator>
+ </span>
+ <Show when={itemProps.item.rawValue.icon}>
+ {(icon) => (
+ <span class="size-4 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
+ )}
+ </Show>
+ <Combobox.ItemLabel class="flex-1 truncate text-ink-muted group-data-[selected]:text-ink">
+ {itemProps.item.rawValue.label}
+ </Combobox.ItemLabel>
+ </Combobox.Item>
+);
+
+const VirtualizedListbox = (props: {
+ options: SearchableOption[];
+ class?: string;
+}) => {
+ let handle: VirtualizerHandle | undefined;
+ return (
+ <Combobox.Listbox<SearchableOption>
+ scrollToItem={(key) => {
+ const idx = props.options.findIndex((o) => o.id === key);
+ if (idx !== -1) handle?.scrollToIndex(idx, { align: 'nearest' });
+ }}
+ class={cn(LISTBOX_CLASS, props.class)}
+ >
+ {(items) => (
+ <Virtualizer
+ ref={(h) => {
+ handle = h;
+ }}
+ data={[...items()]}
+ itemSize={ITEM_HEIGHT}
+ >
+ {(item) => <SearchableMultiSelectItem item={item} />}
+ </Virtualizer>
+ )}
+ </Combobox.Listbox>
+ );
+};
+
+/**
+ * Tracks whether any option matches the search query. Used to toggle the
+ * "no results" message. Precomputes lowercased labels so substring matching
+ * on each keystroke isn't O(n) toLowerCase calls.
+ */
+const useHasMatches = (
+ options: Accessor<SearchableOption[]>,
+ searchQuery: Accessor<string>
+) => {
+ const lowered = createMemo(() =>
+ options().map((opt) => opt.label.toLowerCase())
+ );
+ return createMemo(() => {
+ const q = searchQuery().trim().toLowerCase();
+ if (!q) return options().length > 0;
+ return lowered().some((label) => label.includes(q));
+ });
+};
+
+const useActiveOptions = (
+ options: Accessor<SearchableOption[]>,
+ activeIds: Accessor<string[]>
+) =>
+ createMemo(() => {
+ const ids = activeIds();
+ if (ids.length === 0) return [];
+ const set = new Set(ids);
+ return options().filter((opt) => set.has(opt.id));
+ });
+
+export const SearchableMultiSelect = (props: SearchableMultiSelectProps) => {
+ const [internalOpen, setInternalOpen] = createSignal(false);
+ const [searchQuery, setSearchQuery] = createSignal('');
+
+ const isOpen = () => props.open?.() ?? internalOpen();
+ const setIsOpen = (v: boolean) => {
+ if (props.onOpenChange) props.onOpenChange(v);
+ else setInternalOpen(v);
+ };
+
+ const activeOptions = useActiveOptions(props.options, props.activeIds);
+ const hasMatches = useHasMatches(props.options, searchQuery);
+
+ const handleChange = (selected: SearchableOption[]) => {
+ props.onChange(selected.map((o) => o.id));
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ setIsOpen(open);
+ if (!open) setSearchQuery('');
+ };
+
+ return (
+ <Combobox<SearchableOption>
+ multiple
+ selectionBehavior="toggle"
+ closeOnSelection={false}
+ open={isOpen()}
+ options={props.options()}
+ value={activeOptions()}
+ onChange={handleChange}
+ onInputChange={setSearchQuery}
+ onOpenChange={handleOpenChange}
+ optionValue="id"
+ optionTextValue="label"
+ optionLabel="label"
+ allowsEmptyCollection
+ virtualized
+ placement={props.placement ?? 'bottom-start'}
+ gutter={props.gutter ?? 4}
+ >
+ <Combobox.Control class="flex">
+ {props.children}
+ <Combobox.Input class="sr-only" />
+ </Combobox.Control>
+
+ <Combobox.Portal>
+ <Combobox.Content
+ class={cn(
+ 'z-action-menu bg-surface-0 border border-edge-muted rounded-sm shadow-md w-[260px] max-w-[90vw] overflow-hidden',
+ props.contentClass
+ )}
+ >
+ <div class="flex items-center gap-2 px-3 py-2 border-b border-edge-muted">
+ <SearchIcon class="size-3.5 text-ink-muted shrink-0" />
+ <Combobox.Input
+ class="flex-1 min-w-0 text-xs bg-transparent outline-none caret-accent placeholder:text-ink-faint"
+ placeholder={props.placeholder ?? 'Search...'}
+ />
+ </div>
+ <div class="p-1">
+ <Show
+ when={hasMatches()}
+ fallback={
+ <div class="py-3 px-2 text-center text-xs text-ink-muted">
+ {searchQuery().trim()
+ ? `No options match "${searchQuery()}"`
+ : 'No options available'}
+ </div>
+ }
+ >
+ <VirtualizedListbox
+ options={props.options()}
+ class={props.listboxClass}
+ />
+ </Show>
+ </div>
+ </Combobox.Content>
+ </Combobox.Portal>
+ </Combobox>
+ );
+};
+
+export type SearchableMultiSelectInlineProps = {
+ options: Accessor<SearchableOption[]>;
+ activeIds: Accessor<string[]>;
+ onChange: (ids: string[]) => void;
+ placeholder?: string;
+ inputRef?: (el: HTMLInputElement) => void;
+ onRequestClose?: () => void;
+ listboxClass?: string;
+};
+
+/**
+ * Inline variant — renders Combobox Input + Listbox without a Trigger/Portal.
+ * Designed to live inside another popover (e.g. DropdownMenu.SubContent).
+ * Stops arrow/enter/character keys from bubbling so the outer menu's
+ * keyboard handler doesn't fight Kobalte's built-in combobox navigation.
+ */
+export const SearchableMultiSelectInline = (
+ props: SearchableMultiSelectInlineProps
+) => {
+ const [searchQuery, setSearchQuery] = createSignal('');
+
+ const activeOptions = useActiveOptions(props.options, props.activeIds);
+ const hasMatches = useHasMatches(props.options, searchQuery);
+
+ const handleChange = (selected: SearchableOption[]) => {
+ props.onChange(selected.map((o) => o.id));
+ };
+
+ const handleInputKeyDown = (e: KeyboardEvent) => {
+ switch (e.key) {
+ case 'ArrowLeft': {
+ const input = e.currentTarget as HTMLInputElement;
+ // At the start of the input (no caret movement possible), collapse
+ // back to the parent menu. Otherwise let the input move the caret.
+ if (input.selectionStart === 0 && input.selectionEnd === 0) {
+ props.onRequestClose?.();
+ return;
+ }
+ e.stopPropagation();
+ return;
+ }
+ case 'Escape':
+ // Let parent close
+ return;
+ case 'ArrowDown':
+ case 'ArrowUp':
+ case 'Enter':
+ case 'Home':
+ case 'End':
+ case 'PageUp':
+ case 'PageDown':
+ e.stopPropagation();
+ return;
+ default:
+ // Character keys, backspace, etc. — Combobox.Input handles them;
+ // stop bubbling so the outer menu doesn't run typeahead.
+ e.stopPropagation();
+ }
+ };
+
+ return (
+ <Combobox<SearchableOption>
+ multiple
+ selectionBehavior="toggle"
+ closeOnSelection={false}
+ open
+ options={props.options()}
+ value={activeOptions()}
+ onChange={handleChange}
+ onInputChange={setSearchQuery}
+ optionValue="id"
+ optionTextValue="label"
+ optionLabel="label"
+ allowsEmptyCollection
+ virtualized
+ >
+ <div class="flex items-center gap-2 px-3 py-2 border-b border-edge-muted">
+ <SearchIcon class="size-3.5 text-ink-muted shrink-0" />
+ <Combobox.Input
+ ref={props.inputRef}
+ onKeyDown={handleInputKeyDown}
+ class="flex-1 min-w-0 text-xs bg-transparent outline-none caret-accent placeholder:text-ink-faint"
+ placeholder={props.placeholder ?? 'Search...'}
+ />
+ </div>
+ <div class="p-1">
+ <Show
+ when={hasMatches()}
+ fallback={
+ <div class="py-3 px-2 text-center text-xs text-ink-muted">
+ No options match "{searchQuery()}"
+ </div>
+ }
+ >
+ <VirtualizedListbox
+ options={props.options()}
+ class={props.listboxClass}
+ />
+ </Show>
+ </div>
+ </Combobox>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
index 9700b8a1c6..46926898d2 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx
@@ -18,8 +18,8 @@ import {
import SlidersHorizontalIcon from '@macro-icons/wide/sliders-horizontal.svg';
import CaretRightIcon from '@icon/regular/caret-right.svg';
import CheckIcon from '@icon/regular/check.svg';
-import SearchIcon from '@icon/regular/magnifying-glass.svg';
import CircleDashedIcon from '@icon/regular/circle-dashed.svg';
+import { SearchableMultiSelectInline } from './searchable-multi-select';
import { EntityIcon } from '@core/component/EntityIcon';
import { PropertyValueIcon } from '@core/component/Properties/component/propertyValue/PropertyValueIcon';
import { PROPERTY_OPTION_IDS } from '@core/component/Properties/constants';
@@ -335,165 +335,60 @@ const SearchableFilterSubmenu = (props: {
label: string;
options: Accessor<SearchableOption[]>;
activeIds: Accessor<string[]>;
- onToggle: (id: string) => void;
+ onChange: (ids: string[]) => void;
placeholder?: string;
- multiple?: boolean;
+ open?: Accessor<boolean>;
+ onOpenChange?: (v: boolean) => void;
}) => {
- const [search, setSearch] = createSignal('');
- const [highlightedIndex, setHighlightedIndex] = createSignal(0);
- let inputRef: HTMLInputElement | undefined;
-
- const filteredOptions = createMemo(() => {
- const query = search().toLowerCase();
- if (!query) return props.options();
- return props.options().filter((o) => o.label.toLowerCase().includes(query));
- });
-
- const isActive = (id: string) => props.activeIds().includes(id);
-
- const [isOpen, setIsOpen] = createSignal(false);
-
- const handleOpenChange = (open: boolean) => {
- setIsOpen(open);
- if (!open) return;
- setSearch('');
- setHighlightedIndex(0);
- // Double rAF to run after Kobalte finishes its own focus management
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- inputRef?.focus();
- });
- });
- };
-
- const handleSubContentFocusOut = (e: FocusEvent) => {
- const subContentEl = e.currentTarget as HTMLElement;
- // If focus leaves SubContent while sub is still open (e.g. Kobalte focusing
- // the SubTrigger on hover), refocus the input
- if (isOpen() && !subContentEl.contains(e.relatedTarget as Node)) {
- requestAnimationFrame(() => {
- if (isOpen()) inputRef?.focus();
- });
- }
- };
-
- const handleKeyDown = (e: KeyboardEvent) => {
- const options = filteredOptions();
- const maxIndex = options.length - 1;
-
- switch (e.key) {
- case 'ArrowDown':
- e.preventDefault();
- setHighlightedIndex((i) => Math.min(i + 1, maxIndex));
- break;
- case 'ArrowUp':
- e.preventDefault();
- setHighlightedIndex((i) => Math.max(i - 1, 0));
- break;
- case 'Enter':
- e.preventDefault();
- const option = options[highlightedIndex()];
- if (option) {
- props.onToggle(option.id);
- }
- break;
- case 'ArrowLeft':
- if (search() === '') {
- e.preventDefault();
- setIsOpen(false);
- }
- break;
- default:
- // Stop propagation for other keys to prevent Kobalte typeahead
- e.stopPropagation();
- }
+ const [internalOpen, setInternalOpen] = createSignal(false);
+ const isOpen = () => props.open?.() ?? internalOpen();
+ const setIsOpen = (v: boolean) => {
+ if (props.onOpenChange) props.onOpenChange(v);
+ else setInternalOpen(v);
};
+ let inputRef: HTMLInputElement | undefined;
return (
- <DropdownMenu.Sub
- gutter={4}
- open={isOpen()}
- onOpenChange={handleOpenChange}
- >
- <DropdownMenu.SubTrigger class="w-full flex items-center justify-between gap-2 px-3 py-2 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-[highlighted]:bg-hover">
+ <DropdownMenu.Sub gutter={4} open={isOpen()} onOpenChange={setIsOpen}>
+ <DropdownMenu.SubTrigger
+ class="w-full flex items-center justify-between gap-2 px-3 py-2 rounded-xs text-left text-xs transition-colors hover:bg-hover outline-none data-[highlighted]:bg-hover"
+ onPointerEnter={(e) => {
+ // Kobalte's "grace polygon" keeps an open sub alive when the
+ // pointer crosses toward its content. For sibling In/From triggers,
+ // that means moving between them leaves the prior sub stuck open
+ // and the prior trigger stuck with data-highlighted. Force focus
+ // + open so Kobalte's parent selection manager updates to this
+ // trigger and the shared signal closes the sibling.
+ if (e.pointerType !== 'mouse') return;
+ e.currentTarget.focus({ preventScroll: true });
+ if (!isOpen()) setIsOpen(true);
+ }}
+ >
<span class="text-ink">{props.label}</span>
<CaretRightIcon class="size-3 text-ink-muted" />
</DropdownMenu.SubTrigger>
<DropdownMenu.Portal>
<DropdownMenu.SubContent
- class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl min-w-[200px] max-w-[500px] p-1"
- onFocusOut={handleSubContentFocusOut}
+ class="z-action-menu bg-menu border border-edge-muted rounded-sm shadow-xl w-[260px] max-w-[90vw] overflow-hidden"
+ onFocusIn={(e) => {
+ // Kobalte focuses SubContent itself on open; redirect to the
+ // search input so it gets focus deterministically.
+ if (e.target === e.currentTarget && inputRef) {
+ inputRef.focus();
+ }
+ }}
>
- {/* Search input */}
- <div class="flex items-center gap-2 px-2 py-2 border-b border-edge-muted mb-2">
- <SearchIcon class="size-3.5 text-ink-muted shrink-0" />
- <input
- ref={inputRef}
- type="text"
- value={search()}
- onInput={(e) => {
- setSearch(e.currentTarget.value);
- setHighlightedIndex(0);
- }}
- onKeyDown={handleKeyDown}
- placeholder={props.placeholder ?? 'Search...'}
- class="flex-1 bg-transparent text-xs outline-none placeholder:text-ink-muted"
- />
- </div>
-
- {/* Options list */}
- <div class="max-h-48 overflow-y-auto">
- <For each={filteredOptions()}>
- {(option, index) => {
- const active = () => isActive(option.id);
- const highlighted = () => highlightedIndex() === index();
- return (
- <button
- type="button"
- class={cn(
- 'w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xs text-left text-xs transition-colors',
- highlighted() ? 'bg-hover' : 'hover:bg-hover'
- )}
- onClick={() => props.onToggle(option.id)}
- onMouseEnter={() => setHighlightedIndex(index())}
- >
- <span
- class={cn(
- 'size-4 flex items-center justify-center shrink-0 rounded border transition-colors',
- active() ? 'bg-accent border-accent' : 'border-edge'
- )}
- >
- <Show when={active()}>
- <CheckIcon class="size-2.5 text-page" />
- </Show>
- </span>
-
- <Show when={option.icon}>
- {(icon) => (
- <span class="size-4 flex items-center justify-center shrink-0">
- {icon()()}
- </span>
- )}
- </Show>
-
- <span
- class={cn(
- 'flex-1 truncate',
- active() ? 'text-ink' : 'text-ink-muted'
- )}
- >
- {option.label}
- </span>
- </button>
- );
- }}
- </For>
-
- <Show when={filteredOptions().length === 0}>
- <div class="px-3 py-2 text-xs text-ink-muted">No results</div>
- </Show>
- </div>
+ <SearchableMultiSelectInline
+ options={props.options}
+ activeIds={props.activeIds}
+ onChange={props.onChange}
+ placeholder={props.placeholder}
+ inputRef={(el) => {
+ inputRef = el;
+ }}
+ onRequestClose={() => setIsOpen(false)}
+ />
</DropdownMenu.SubContent>
</DropdownMenu.Portal>
</DropdownMenu.Sub>
@@ -571,15 +466,6 @@ export const UnifiedFilterDropdown = () => {
];
});
- const toggleAssignee = (id: string) => {
- const current = assigneeFilter();
- if (current.includes(id)) {
- setAssigneeFilter(current.filter((a) => a !== id));
- } else {
- setAssigneeFilter([...current, id]);
- }
- };
-
const isTasksView = () => currentView() === 'tasks';
const isSearchView = () => currentView() === 'search';
const isChannelsIndexActive = () => soup.filters.isActive('channels');
@@ -611,18 +497,14 @@ export const UnifiedFilterDropdown = () => {
() => queryFilters().channel_filters?.channel_ids ?? []
);
- const toggleChannelId = (id: string) => {
+ const setChannelIds = (ids: string[]) => {
batch(() => {
if (!isChannelsIndexActive()) handleIndexChange('channels');
- const current = queryFilters().channel_filters?.channel_ids ?? [];
- const nextIds = current.includes(id)
- ? current.filter((cid) => cid !== id)
- : [...current, id];
setQueryFilters((prev) => ({
...prev,
channel_filters: {
...prev.channel_filters,
- channel_ids: nextIds.length > 0 ? nextIds : undefined,
+ channel_ids: ids.length > 0 ? ids : undefined,
},
}));
});
@@ -632,18 +514,14 @@ export const UnifiedFilterDropdown = () => {
() => queryFilters().channel_filters?.sender_ids ?? []
);
- const toggleSenderId = (id: string) => {
+ const setSenderIds = (ids: string[]) => {
batch(() => {
if (!isChannelsIndexActive()) handleIndexChange('channels');
- const current = queryFilters().channel_filters?.sender_ids ?? [];
- const nextIds = current.includes(id)
- ? current.filter((sid) => sid !== id)
- : [...current, id];
setQueryFilters((prev) => ({
...prev,
channel_filters: {
...prev.channel_filters,
- sender_ids: nextIds.length > 0 ? nextIds : undefined,
+ sender_ids: ids.length > 0 ? ids : undefined,
},
}));
});
@@ -661,6 +539,10 @@ export const UnifiedFilterDropdown = () => {
const importance = createMemo(() => queryFilters().email_filters?.importance);
+ const [openChannelSub, setOpenChannelSub] = createSignal<
+ 'in' | 'from' | null
+ >(null);
+
registerHotkey({
hotkey: 'f',
scopeId: panel.splitHotkeyScope,
@@ -758,9 +640,8 @@ export const UnifiedFilterDropdown = () => {
label="Assignee"
options={assigneeOptions}
activeIds={assigneeFilter}
- onToggle={toggleAssignee}
+ onChange={setAssigneeFilter}
placeholder="Search assignees..."
- multiple
/>
</Show>
@@ -833,17 +714,23 @@ export const UnifiedFilterDropdown = () => {
label="In"
options={inChannelOptions}
activeIds={activeChannelIds}
- onToggle={toggleChannelId}
+ onChange={setChannelIds}
placeholder="Search channels..."
- multiple
+ open={() => openChannelSub() === 'in'}
+ onOpenChange={(v) =>
+ setOpenChannelSub(v ? 'in' : null)
+ }
/>
<SearchableFilterSubmenu
label="From"
options={fromSenderOptions}
activeIds={activeSenderIds}
- onToggle={toggleSenderId}
+ onChange={setSenderIds}
placeholder="Search senders..."
- multiple
+ open={() => openChannelSub() === 'from'}
+ onOpenChange={(v) =>
+ setOpenChannelSub(v ? 'from' : null)
+ }
/>
</Show>
<Show when={option.value === 'email'}>
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
index 5dc892ef48..12a3969457 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx
@@ -9,11 +9,10 @@ import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-contex
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import type { ListView } from '@app/constants/list-views';
import { isListViewID } from '@app/constants/list-views';
-import { useQuickAccess } from '@core/context/quickAccess';
import { useUserContext, useUserId } from '@core/context/user';
import { deepEqual } from '@core/util/compareUtils';
import { useContacts } from '@queries/contacts/contacts';
-import { batch, createMemo } from 'solid-js';
+import { batch, createMemo, createSignal } from 'solid-js';
import type { ActiveFilter } from './active-filter-chips';
import { INDEX_OPTIONS } from './search-operator-autocomplete';
import {
@@ -57,7 +56,6 @@ export function useFilterRefinements() {
const user = useUserContext();
const contacts = useContacts();
const currentUserId = useUserId();
- const quickAccess = useQuickAccess();
const { channelOptions, senderOptions } = useSearchFilterOptions();
const { changeIndex } = useSearchIndexController();
@@ -133,6 +131,70 @@ export function useFilterRefinements() {
return VIEW_FILTER_CATEGORIES[view as ListView] ?? [];
});
+ // Reactive id → label maps derived from the chip's option sources.
+ // Using quickAccess.getById here would read a plain Map that isn't a signal,
+ // so on page reload the chip label shows the raw uuid until the first
+ // rerender that happens to read live data.
+ const channelLabelMap = createMemo(() => {
+ const map = new Map<string, string>();
+ for (const opt of channelOptions()) map.set(opt.id, opt.label);
+ return map;
+ });
+ const senderLabelMap = createMemo(() => {
+ const map = new Map<string, string>();
+ for (const opt of senderOptions()) map.set(opt.id, opt.label);
+ return map;
+ });
+
+ const labelForIds = (
+ ids: string[],
+ labelMap: Map<string, string>
+ ): string => {
+ if (ids.length === 0) return '';
+ const [first, ...rest] = ids;
+ const firstLabel = labelMap.get(first) ?? first;
+ if (rest.length === 0) return firstLabel;
+ return `${firstLabel} and ${rest.length} ${rest.length === 1 ? 'other' : 'others'}`;
+ };
+
+ const setChannelIds = (ids: string[]) =>
+ setQueryFilters((prev) => ({
+ ...prev,
+ channel_filters: {
+ ...prev.channel_filters,
+ channel_ids: ids.length > 0 ? ids : undefined,
+ },
+ }));
+
+ const setSenderIds = (ids: string[]) =>
+ setQueryFilters((prev) => ({
+ ...prev,
+ channel_filters: {
+ ...prev.channel_filters,
+ sender_ids: ids.length > 0 ? ids : undefined,
+ },
+ }));
+
+ /**
+ * Cache of chip objects keyed by a stable id derived from the chip's category
+ * and static identity (e.g. "In", "Type|channels", "Assignee|<uuid>"). Reusing
+ * the same `ActiveFilter` object across memo runs keeps `<For>` from
+ * remounting the chip — its internal combobox state (open, search) survives
+ * selection toggles. Mutable state lives inside the accessor fields.
+ */
+ const chipCache = new Map<string, ActiveFilter>();
+ const getOrCreateChip = (
+ key: string,
+ build: () => ActiveFilter
+ ): ActiveFilter => {
+ let chip = chipCache.get(key);
+ if (!chip) {
+ chip = build();
+ chipCache.set(key, chip);
+ }
+ return chip;
+ };
+
/**
* Returns a list of active filters that can be displayed as removable chips.
* Excludes filters that are set by tabs (like signal/noise).
@@ -145,6 +207,8 @@ export function useFilterRefinements() {
]);
const filters: ActiveFilter[] = [];
+ const seenKeys = new Set<string>();
+
for (const category of viewCategories()) {
for (const option of category.options) {
if (
@@ -154,13 +218,17 @@ export function useFilterRefinements() {
) {
continue;
}
- filters.push({
- categoryLabel: category.label,
- optionId: option.id,
- optionLabel: option.label,
- icon: option.icon,
- categoryOptions: category.options,
- });
+ const key = `${category.label}|${option.id}`;
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => ({
+ categoryLabel: category.label,
+ optionId: () => option.id,
+ optionLabel: () => option.label,
+ icon: option.icon,
+ categoryOptions: category.options,
+ }))
+ );
}
}
@@ -177,92 +245,111 @@ export function useFilterRefinements() {
) {
continue;
}
- filters.push({
- categoryLabel: 'Type',
- optionId: option.id,
- optionLabel: option.label,
- icon: option.icon,
- categoryOptions: INDEX_OPTIONS as ActiveFilter['categoryOptions'],
- multiple: false,
- onRemove: () => changeIndex('all'),
- onReplace: (newOptionId) => changeIndex(newOptionId),
- });
+ const key = `Type|${option.id}`;
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => ({
+ categoryLabel: 'Type',
+ optionId: () => option.id,
+ optionLabel: () => option.label,
+ icon: option.icon,
+ categoryOptions: INDEX_OPTIONS as ActiveFilter['categoryOptions'],
+ multiple: false,
+ onRemove: () => changeIndex('all'),
+ onReplace: (newOptionId) => changeIndex(newOptionId),
+ }))
+ );
}
// Sub-filters: assignee
- const optionsMap = assigneeOptionsMap();
+ const _optionsMap = assigneeOptionsMap();
for (const id of assigneeFilter()) {
- const option = optionsMap.get(id);
- filters.push({
- categoryLabel: 'Assignee',
- optionId: id,
- optionLabel: option?.label ?? id,
- onRemove: () =>
- setAssigneeFilter(assigneeFilter().filter((a) => a !== id)),
- });
+ const key = `Assignee|${id}`;
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => ({
+ categoryLabel: 'Assignee',
+ optionId: () => id,
+ optionLabel: () => assigneeOptionsMap().get(id)?.label ?? id,
+ onRemove: () =>
+ setAssigneeFilter(assigneeFilter().filter((a) => a !== id)),
+ }))
+ );
}
- const labelForIds = (ids: string[]): string => {
- const [first, ...rest] = ids;
- const firstItem = quickAccess.getById(first);
- const firstLabel =
- firstItem && 'data' in firstItem && firstItem.data?.name
- ? firstItem.data.name
- : first;
- if (rest.length === 0) return firstLabel;
- return `${firstLabel} and ${rest.length} ${rest.length === 1 ? 'other' : 'others'}`;
- };
-
// Search operator filters: in: (channel_ids)
const channelIds = (
queryFilters().channel_filters?.channel_ids ?? []
).filter((id) => id !== NIL_UUID);
- const setChannelIds = (ids: string[]) =>
- setQueryFilters((prev) => ({
- ...prev,
- channel_filters: {
- ...prev.channel_filters,
- channel_ids: ids.length > 0 ? ids : undefined,
- },
- }));
- if (channelIds.length > 0) {
- filters.push({
- categoryLabel: 'In',
- optionId: `in:${channelIds.join(',')}`,
- optionLabel: labelForIds(channelIds),
- searchableOptions: channelOptions,
- activeSearchableIds: () =>
- (queryFilters().channel_filters?.channel_ids ?? []).filter(
- (id) => id !== NIL_UUID
- ),
- onSearchableChange: setChannelIds,
- searchPlaceholder: 'Search channels...',
- onRemove: () => setChannelIds([]),
- });
+ // Keep the chip alive while its popup is still open, even if the user
+ // toggled every option off — they may be mid-way through swapping A→B
+ // and closing the menu on them would be jarring.
+ const inChipOpen = chipCache.get('In')?.isPopupOpen?.() ?? false;
+ if (channelIds.length > 0 || inChipOpen) {
+ const key = 'In';
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => {
+ const [isPopupOpen, setPopupOpen] = createSignal(false);
+ return {
+ categoryLabel: 'In',
+ optionId: () => {
+ const ids = (
+ queryFilters().channel_filters?.channel_ids ?? []
+ ).filter((id) => id !== NIL_UUID);
+ return `in:${ids.join(',')}`;
+ },
+ optionLabel: () => {
+ const ids = (
+ queryFilters().channel_filters?.channel_ids ?? []
+ ).filter((id) => id !== NIL_UUID);
+ return labelForIds(ids, channelLabelMap());
+ },
+ searchableOptions: channelOptions,
+ activeSearchableIds: () =>
+ (queryFilters().channel_filters?.channel_ids ?? []).filter(
+ (id) => id !== NIL_UUID
+ ),
+ onSearchableChange: setChannelIds,
+ searchPlaceholder: 'Search channels...',
+ onRemove: () => setChannelIds([]),
+ isPopupOpen,
+ setPopupOpen,
+ };
+ })
+ );
}
// Search operator filters: from: (sender_ids)
const senderIds = queryFilters().channel_filters?.sender_ids ?? [];
- const setSenderIds = (ids: string[]) =>
- setQueryFilters((prev) => ({
- ...prev,
- channel_filters: {
- ...prev.channel_filters,
- sender_ids: ids.length > 0 ? ids : undefined,
- },
- }));
- if (senderIds.length > 0) {
- filters.push({
- categoryLabel: 'From',
- optionId: `from:${senderIds.join(',')}`,
- optionLabel: labelForIds(senderIds),
- searchableOptions: senderOptions,
- activeSearchableIds: () =>
- queryFilters().channel_filters?.sender_ids ?? [],
- onSearchableChange: setSenderIds,
- searchPlaceholder: 'Search senders...',
- onRemove: () => setSenderIds([]),
- });
+ const fromChipOpen = chipCache.get('From')?.isPopupOpen?.() ?? false;
+ if (senderIds.length > 0 || fromChipOpen) {
+ const key = 'From';
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => {
+ const [isPopupOpen, setPopupOpen] = createSignal(false);
+ return {
+ categoryLabel: 'From',
+ optionId: () => {
+ const ids = queryFilters().channel_filters?.sender_ids ?? [];
+ return `from:${ids.join(',')}`;
+ },
+ optionLabel: () => {
+ const ids = queryFilters().channel_filters?.sender_ids ?? [];
+ return labelForIds(ids, senderLabelMap());
+ },
+ searchableOptions: senderOptions,
+ activeSearchableIds: () =>
+ queryFilters().channel_filters?.sender_ids ?? [],
+ onSearchableChange: setSenderIds,
+ searchPlaceholder: 'Search senders...',
+ onRemove: () => setSenderIds([]),
+ isPopupOpen,
+ setPopupOpen,
+ };
+ })
+ );
}
// Email importance (only when the email index is active in the search view
@@ -272,36 +359,54 @@ export function useFilterRefinements() {
if (importance !== undefined) {
const IMPORTANCE_SIGNAL = 'importance:signal';
const IMPORTANCE_NOISE = 'importance:noise';
- const currentOptionId = importance
- ? IMPORTANCE_SIGNAL
- : IMPORTANCE_NOISE;
- filters.push({
- categoryLabel: 'Importance',
- optionId: currentOptionId,
- optionLabel: importance ? 'Signal' : 'Noise',
- categoryOptions: [
- { id: IMPORTANCE_SIGNAL, label: 'Signal' },
- { id: IMPORTANCE_NOISE, label: 'Noise' },
- ] as unknown as ActiveFilter['categoryOptions'],
- multiple: false,
- isOptionActive: (optionId) => optionId === currentOptionId,
- onRemove: () =>
- setQueryFilters((prev) => ({
- ...prev,
- email_filters: { ...prev.email_filters, importance: undefined },
- })),
- onReplace: (newOptionId) =>
- setQueryFilters((prev) => ({
- ...prev,
- email_filters: {
- ...prev.email_filters,
- importance: newOptionId === IMPORTANCE_SIGNAL,
- },
- })),
- });
+ const key = 'Importance';
+ seenKeys.add(key);
+ filters.push(
+ getOrCreateChip(key, () => ({
+ categoryLabel: 'Importance',
+ optionId: () =>
+ queryFilters().email_filters?.importance
+ ? IMPORTANCE_SIGNAL
+ : IMPORTANCE_NOISE,
+ optionLabel: () =>
+ queryFilters().email_filters?.importance ? 'Signal' : 'Noise',
+ categoryOptions: [
+ { id: IMPORTANCE_SIGNAL, label: 'Signal' },
+ { id: IMPORTANCE_NOISE, label: 'Noise' },
+ ] as unknown as ActiveFilter['categoryOptions'],
+ multiple: false,
+ isOptionActive: (optionId) =>
+ optionId ===
+ (queryFilters().email_filters?.importance
+ ? IMPORTANCE_SIGNAL
+ : IMPORTANCE_NOISE),
+ onRemove: () =>
+ setQueryFilters((prev) => ({
+ ...prev,
+ email_filters: {
+ ...prev.email_filters,
+ importance: undefined,
+ },
+ })),
+ onReplace: (newOptionId) =>
+ setQueryFilters((prev) => ({
+ ...prev,
+ email_filters: {
+ ...prev.email_filters,
+ importance: newOptionId === IMPORTANCE_SIGNAL,
+ },
+ })),
+ }))
+ );
}
}
+ // Evict chips whose keys are no longer present so a fresh chip (with
+ // reset internal state) gets built next time that filter reappears.
+ for (const key of chipCache.keys()) {
+ if (!seenKeys.has(key)) chipCache.delete(key);
+ }
+
return filters;
});