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.

feat(soup): restyle filter chips and add pop down filter chip bar (#3580)

Seamuse63755446bf3
diff --git a/.agents/skills/create-ai-tool/SKILL.md b/.agents/skills/create-ai-tool/SKILL.md
new file mode 100644
index 0000000000..7e427e95c1
--- /dev/null
+++ b/.agents/skills/create-ai-tool/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: create-ai-tool
+description: Build a new AI tool end-to-end — Rust implementation, toolset wiring, infra, schema generation, and frontend UI.
+---
+
+# Create AI Tool
+
+This skill walks through building a new AI tool from scratch. Before writing any code, read the design guide at `rust/cloud-storage/ai_toolset/TOOL_DESIGN.md` and the framework docs/examples in `rust/cloud-storage/ai_toolset/src/lib.rs`.
+
+**IMPORTANT:** Never modify the `rust/cloud-storage/ai_toolset/` crate. It is the framework — you build tools that use it.
+
+## Step 1: Write the tool
+
+Decide which domain crate the tool belongs in. Tools live at `rust/cloud-storage/<crate>/src/inbound/toolset/`.
+
+Study an existing tool for patterns:
+- `rust/cloud-storage/documents/src/inbound/toolset/` — tools: `read_content.rs`, `read_metadata.rs`, `create_document.rs`
+- `rust/cloud-storage/email/src/inbound/toolset/` — tools: `send_email.rs`, `get_thread.rs`, `update_thread_labels.rs`
+- `rust/cloud-storage/soup/src/inbound/toolset/` — tool: `list_entities.rs`
+- `rust/cloud-storage/call/src/inbound/toolset/` — call-related tools
+
+Each tool is a struct that derives `JsonSchema` and `Deserialize`, with `#[schemars(title = "...", description = "...")]` on the struct and `#[schemars(description = "...")]` on each field. The struct implements `AsyncTool<Context>` from the `ai_toolset` crate.
+
+Create a new file for your tool (e.g. `my_tool.rs`), add it as a `mod` in the toolset's `mod.rs`, and wire it into the toolset's `AsyncToolSet::new().add_tool::<...>()` chain.
+
+## Step 2: Create the tool context
+
+If your tool needs dependencies (DB connections, service clients) that aren't already in an existing context, define a new context struct in the toolset's `mod.rs`. See `rust/cloud-storage/documents/src/inbound/toolset/mod.rs` for the `DocumentToolContext` pattern.
+
+The context must be `Clone` and derivable from the parent `ToolServiceContext` via `FromRef`.
+
+If the tool's dependencies are already available in an existing context (e.g. it only needs `Arc<ToolScribe>`), you can use that context directly — no new struct needed.
+
+## Step 3: Add the toolset to `all_tools` in the ai_tools crate
+
+Edit `rust/cloud-storage/ai_tools/src/lib.rs`:
+- Import your toolset function and context type
+- Add `.add_tool::<YourTool, YourContext>()` or `.add_subtoolset::<YourToolContext>(your_toolset())` to the `all_tools()` function
+
+## Step 4: Add the context to ToolServiceContext
+
+Edit `rust/cloud-storage/ai_tools/src/tool_context.rs`:
+- Add any new type aliases for your service implementations (follow the `Tool*` naming pattern)
+- Add your tool context field to the `ToolServiceContext` struct
+- Implement `FromRef<ToolServiceContext>` for your context if needed (or derive it — the struct uses `#[derive(FromRef)]`)
+
+## Step 5: Wire up env vars and service construction
+
+Edit `rust/cloud-storage/ai_tools/src/build_context.rs`:
+- Add any new env vars to the `env_var!` or `maybe_env_var!` blocks
+- Construct your service/context in `build_tool_service_context_from_env`
+- Add it to the returned `ToolServiceContext`
+
+## Step 6: Update infra (if new env vars or AWS resources are needed)
+
+Edit `infra/packages/shared/src/ai_tools.ts`:
+- Add new env vars to the `envVars` array in `getAiToolsInfra()`
+- Add any new secret ARNs, queue ARNs, or bucket ARNs to the respective arrays
+- Add any new Pulumi stack references needed to resolve the values
+
+## Step 7: Rust checks
+
+Run from `rust/cloud-storage/`:
+```bash
+cargo fmt
+cargo clippy -p ai_tools
+cargo test -p <your_domain_crate>
+```
+
+Fix any warnings or errors before proceeding.
+
+## Step 8: Generate frontend types
+
+Run from `js/app/`:
+```bash
+bun gen-tools
+```
+
+This builds `rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs`, generates `rust/cloud-storage/ai_tools/schemas/tools.json`, and transpiles the schemas into TypeScript at `js/app/packages/service-clients/service-cognition/generated/tools/`.
+
+## Step 9: Check what frontend UI is needed
+
+Run from `js/app/`:
+```bash
+bun check
+```
+
+This runs `tsc --noEmit` and will report type errors — specifically, the `toolHandlers` map in `js/app/packages/core/component/AI/component/tool/handler.tsx` will be missing your new tool name. The errors tell you exactly what to implement.
+
+## Step 10: Read existing tool UI for patterns
+
+The tool UI components live at `js/app/packages/core/component/AI/component/tool/`. Study existing renderers:
+- `Search.tsx` — search results rendering
+- `ReadContent.tsx` / `ReadMetadata.tsx` — document tool UI
+- `SendEmail.tsx` — email tool UI
+- `ListEntities.tsx` — list display
+- `Properties.tsx` — property get/set tools
+- `ListCallRecords.tsx` / `ReadCallRecord.tsx` — call tools
+- `BaseTool.tsx` — shared base component
+
+Each tool needs a handler object implementing `ToolHandler` (from `ToolRenderer.tsx`) with at minimum a `render` component. Use `createToolRenderer` to create it.
+
+## Step 11: Write the tool UI
+
+1. Create a new component file at `js/app/packages/core/component/AI/component/tool/YourTool.tsx`
+2. Export a handler using `createToolRenderer`
+3. Register it in `js/app/packages/core/component/AI/component/tool/handler.tsx`:
+ - Import your handler
+ - Add it to the `toolHandlers` map with the key matching your tool's schema title
+
+Every tool renderer must show results. Use the expandable dropdown pattern from `Search.tsx` / `ListEntities.tsx`:
+
+- Use `BaseTool` (from `BaseTool.tsx`) as the wrapper. It accepts a `response` prop for expandable content.
+- Create `const [isExpanded, setIsExpanded] = createSignal(false)` to track open/closed state.
+- Access the response via `ctx.response?.data` (typed from the generated schema).
+- Show a status summary (e.g. hit count, "No Results") on the right side of the tool row.
+- Render a `CaretRight` toggle button (`@icon/regular/caret-right.svg?component-solid`) that rotates 90deg when expanded.
+- Pass the expanded content into `BaseTool`'s `response` prop, gated on `isExpanded()`.
+
+For tools that return text/string results (not entity lists), render the response string in a `<pre>` or similar block inside the `response` prop. The key point: the response data must always be surfaced in the UI via the dropdown — never silently swallowed.
+
+## Step 12: Frontend checks
+
+Run from `js/app/`:
+```bash
+bun format
+bun check
+```
+
+Fix any remaining type or formatting errors.
diff --git a/.agents/skills/debug-service/SKILL.md b/.agents/skills/debug-service/SKILL.md
new file mode 100644
index 0000000000..c22213386e
--- /dev/null
+++ b/.agents/skills/debug-service/SKILL.md
@@ -0,0 +1,10 @@
+You are going to help me interactively debug the rust binary
+that's in this crate.
+
+Use this command to start the service with debug logging
+
+RUST_LOG=<name_of_bin>=debug,info
+ just run > /tmp/<name_of_bin>.log 2>&1 & tail -f /tmp/<name_of_bin>.log
+
+Use the log tail to answer questions as appropriate
+
diff --git a/.agents/skills/dependabot/skill.md b/.agents/skills/dependabot/skill.md
new file mode 100644
index 0000000000..e49dd677a4
--- /dev/null
+++ b/.agents/skills/dependabot/skill.md
@@ -0,0 +1,78 @@
+---
+name: dependabot
+description: Find all open Dependabot alerts for this repo and create a plan to resolve them using the appropriate package manager overrides (pnpm, bun, npm, cargo).
+allowed-tools: Bash, Read, Edit, Glob, Grep, Agent
+---
+
+# Dependabot Alert Resolution
+
+## Step 1: Fetch all open alerts
+
+```bash
+REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
+gh api "repos/${REPO}/dependabot/alerts" \
+ --jq '.[] | select(.state == "open") | {
+ number,
+ dependency: .dependency.package.name,
+ ecosystem: .dependency.package.ecosystem,
+ manifest: .dependency.manifest_path,
+ vulnerable_range: .security_vulnerability.vulnerable_version_range,
+ patched_version: .security_vulnerability.first_patched_version.identifier,
+ severity: .security_vulnerability.severity,
+ summary: .security_advisory.summary
+ }'
+```
+
+## Step 2: Group alerts by manifest/lockfile
+
+Group the alerts by their `manifest` field (e.g. `js/app/bun.lock`, `rust/cloud-storage/Cargo.lock`, `js/app/packages/loro-mirror/pnpm-lock.yaml`). This determines which override mechanism to use.
+
+## Step 3: Determine override strategy per manifest
+
+For each manifest/lockfile, determine the correct override mechanism:
+
+| Lockfile | Override mechanism |
+|----------|-------------------|
+| `bun.lock` / `bun.lockb` | `"overrides"` in the nearest `package.json` |
+| `pnpm-lock.yaml` | `"pnpm": { "overrides": { ... } }` in the workspace root `package.json` |
+| `package-lock.json` | `"overrides"` in the nearest `package.json` |
+| `yarn.lock` | `"resolutions"` in the nearest `package.json` |
+| `Cargo.lock` | `cargo update -p <package>` or workspace `[patch.crates-io]` in `Cargo.toml` |
+
+Read each target `package.json` or `Cargo.toml` to check for existing overrides before adding new ones.
+
+## Step 4: Present the plan
+
+Present a table of all alerts grouped by manifest, showing:
+- Alert numbers
+- Package name
+- Current version (from lockfile)
+- Patched version
+- Severity
+- Override mechanism to use
+
+Ask the user to confirm before making changes.
+
+## Step 5: Apply fixes
+
+For each group:
+
+### npm/bun/pnpm overrides
+- Add override entries to the appropriate `package.json`
+- Reinstall: `bun install` / `pnpm install` / `npm install`
+- Verify: check the lockfile or `<pm> ls` for the patched version
+
+### Cargo
+- Try `cargo update -p <package>` first
+- If that doesn't reach the patched version, also try `cargo update -p <parent-package>` (the package that depends on the vulnerable one, found via `cargo tree -i <package>`)
+- Verify with `cargo tree -i <package>` and checking `Cargo.lock`
+
+## Step 6: Verify
+
+After all changes, confirm patched versions are in place and no new audit issues were introduced.
+
+## Notes
+
+- Some alerts may be false positives (e.g. `undici-types` triggering `undici` alerts). Flag these to the user.
+- Prefer minimal version bumps (e.g. `>=6.14.0` not `^8.0.0`) to reduce breakage risk.
+- If a `cargo update` only bumps to a version below the patch, escalate the parent dependency.
diff --git a/.agents/skills/dump-schema/SKILL.md b/.agents/skills/dump-schema/SKILL.md
new file mode 100644
index 0000000000..0527826955
--- /dev/null
+++ b/.agents/skills/dump-schema/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: dump-schema
+description: Dump clean Postgres schema to a file and copy path to clipboard.
+allowed-tools: Bash
+---
+
+# Dump Schema
+
+Dump a clean PostgreSQL schema (no comments, no ownership, no privileges) from the local dev database.
+
+## Parameters
+
+Ask the user (if not provided):
+- **output_file** – absolute path for the `.sql` file (default: prompt user)
+
+Use this database URL unless the user specifies otherwise:
+```
+postgres://user:password@localhost:5432/macrodb
+```
+
+## Steps
+
+1. Run `pg_dump` with schema-only flags, pipe through cleanup, write to file:
+
+```bash
+pg_dump --schema-only --no-owner --no-privileges --no-comments --no-publications --no-subscriptions --no-security-labels --no-tablespaces "$DB_URL" | sed '/^--/d' | sed '/^SET /d' | sed '/^SELECT pg_catalog/d' | sed '/^$/N;/^\n$/d' > "$OUTPUT_FILE"
+```
+
+2. Copy the output path to the clipboard:
+
+```bash
+echo -n "$OUTPUT_FILE" | pbcopy
+```
+
+3. Report: `Schema dumped to <path> (path copied to clipboard)`
diff --git a/.agents/skills/qc/SKILL.md b/.agents/skills/qc/SKILL.md
new file mode 100644
index 0000000000..f0a3dcb14d
--- /dev/null
+++ b/.agents/skills/qc/SKILL.md
@@ -0,0 +1,110 @@
+---
+name: qc
+description: Quality gate. 5 parallel agents review changes. All must pass.
+allowed-tools: Task, Bash, Read, Grep, Glob
+---
+
+# QC Gate
+
+## Setup
+```bash
+DIFF=$(git diff main)
+FILES=$(git diff main --name-only)
+TASK="{task description or 'general changes'}"
+```
+
+Read 1-2 unmodified files from same directories for pattern context.
+
+## Agents
+
+Spawn all 5 in parallel. All output raw JSON only, no markdown.
+
+### 1: Code Review (sonnet)
+```
+DIFF: ${DIFF}
+
+- Descriptive naming?
+- Errors caught with useful messages?
+- No hardcoded values, commented code, debug statements?
+- No TODO without ticket ref?
+- No obvious bugs?
+- No useless comments?
+
+{"pass": bool, "issues": [...]}
+```
+
+### 2: Simplification (sonnet)
+```
+DIFF: ${DIFF}
+
+- Is this overcomplicated? Can I solve the same problem in a simpler manner?
+- Can I reduce indirection?
+- Can I reduce surface area?
+- Premature abstraction? Premature Optimization? YAGNI violations?
+- Dead code?
+- Three similar lines > one abstraction
+
+{"pass": bool, "issues": [...]}
+```
+
+### 3: Consistency (sonnet)
+```
+DIFF: ${DIFF}
+PATTERNS: ${PATTERN_FILES}
+
+- Matches existing codebase patterns?
+- Proper types, no any, no unsafe casts?
+- Idiomatic error handling?
+- Changes internally consistent?
+- Is logic isolated and composable?
+- Are there existing tests if neccesary?
+
+{"pass": bool, "issues": [...]}
+```
+
+### 4: Robustness (sonnet)
+```
+TASK: ${TASK}
+DIFF: ${DIFF}
+
+- Actually solves the problem?
+- Edge cases: empty, null, zero, negative, boundaries, concurrency?
+- Regression risk: changed signatures, shared state, removed exports?
+- Maintains API contracts?
+
+{"pass": bool, "issues": [...]}
+```
+
+### 5: Scope (haiku)
+```
+TASK: ${TASK}
+FILES: ${FILES}
+DIFF: ${DIFF}
+
+- Solved the problem or just the symptom?
+- Changes unrelated to task?
+- Unnecessary refactoring?
+
+{"pass": bool, "issues": [...]}
+```
+
+## Results
+
+| Check | Verdict | Issues |
+|-------|---------|--------|
+| Code Review | ✓/✗ | ... |
+| Simplification | ✓/✗ | ... |
+| Consistency | ✓/✗ | ... |
+| Robustness | ✓/✗ | ... |
+| Scope | ✓/✗ | ... |
+
+**ALL PASS:** Ready to commit.
+
+**ANY FAIL:** List issues, fix them, run `/qc` again.
+
+**Same issue 3x:** Escalate to user.
+
+## Notes
+
+- Invalid JSON? Retry once. Still broken? Mark fail.
+- Large diffs (>500 lines): run simplification file-by-file.
diff --git a/.agents/skills/upgrade-model/SKILL.md b/.agents/skills/upgrade-model/SKILL.md
new file mode 100644
index 0000000000..5385a44b64
--- /dev/null
+++ b/.agents/skills/upgrade-model/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: upgrade-model
+description: Upgrade an AI chat model (fast or good) across backend and frontend.
+allowed-tools: Bash, Read, Write, Edit, Grep, Glob
+---
+
+# Upgrade Chat Model
+
+Upgrades the AI model used in the chat app. There are two model slots:
+- **fast** (Enter): default/fallback model (first entry in `CHAT_MODELS`)
+- **good** (Cmd+Enter): smart mode model (second entry in `CHAT_MODELS`)
+
+The user must specify which slot to upgrade and the new model name (e.g. `Codex-opus-4-6`).
+
+## Steps
+
+### 1. Determine the change
+
+Ask the user (if not already provided):
+- Which slot: `fast` or `good`?
+- What is the new model name? (e.g. `Codex-opus-4-6`)
+
+Derive from the model name:
+- `SERDE_NAME`: the kebab-case model ID sent over the wire (e.g. `Codex-opus-4-6`)
+- `ENUM_VARIANT`: PascalCase variant name (e.g. `Claude46Opus`)
+- `CONST_NAME`: SCREAMING_SNAKE constant name (e.g. `CLAUDE_46_OPUS`)
+- `CONST_VALUE`: display string used by the frontend/provider (e.g. `Codex-4.6-opus`)
+- `PRETTY_NAME`: human-readable name (e.g. `Codex Opus 4.6`)
+
+### 2. Add model to AI crate (if it doesn't already exist)
+
+File: `rust/cloud-storage/ai/src/types/model/mod.rs`
+
+Check if the enum variant already exists. If not, add all of the following:
+
+1. **Enum variant** in `pub enum Model` (under the Anthropic section):
+ ```rust
+ #[serde(rename = "{SERDE_NAME}")]
+ #[strum(serialize = "{SERDE_NAME}")]
+ {ENUM_VARIANT},
+ ```
+
+2. **String constant** in `pub mod constants::models`:
+ ```rust
+ pub const {CONST_NAME}: &str = "{CONST_VALUE}";
+ ```
+
+3. **Match arm** in `to_provider_model_string()`:
+ ```rust
+ Model::{ENUM_VARIANT} => (ANTHROPIC, {CONST_NAME}),
+ ```
+
+4. **Match arm** in `from_model_str()`:
+ ```rust
+ {CONST_NAME} => Model::{ENUM_VARIANT},
+ ```
+
+File: `rust/cloud-storage/ai/src/types/model/metadata.rs`
+
+5. **Metadata** in `fn metadata()`:
+ ```rust
+ Model::{ENUM_VARIANT} => ModelMetadata {
+ context_window: 200_000,
+ },
+ ```
+ Use the correct context window for the model. Anthropic models are typically 200,000.
+
+6. **Provider** in `fn provider()`:
+ ```rust
+ Model::{ENUM_VARIANT} => Provider::Anthropic,
+ ```
+
+### 3. Update DCS constants
+
+File: `rust/cloud-storage/document_cognition_service/src/core/model.rs`
+
+- If upgrading the **fast** slot: change the first entry in `CHAT_MODELS` and update `FALLBACK_MODEL`.
+- If upgrading the **good** slot: change the second entry in `CHAT_MODELS`.
+
+### 4. Update DCS chat message handler
+
+File: `rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs`
+
+Search for the old model variant being used in the model selection logic (e.g. `Model::Claude45Opus`). Update it to the new variant.
+
+### 5. Verify Rust compiles
+
+```bash
+cd rust/cloud-storage && cargo check -p ai -p document_cognition_service
+```
+
+Fix any compilation errors before proceeding.
+
+### 6. Generate frontend types
+
+Run from `js/app/`:
+```bash
+cd js/app && bun install && bun run gen-api
+```
+
+This builds all Rust OpenAPI and models binaries from local code, generates `openapi.json`, runs orval for TypeScript types, and generates `model.ts` from the local models binary. All generated files will reflect your local Rust changes.
+
+### 7. Run `bun check` to find frontend usages
+
+```bash
+cd js/app && bun check
+```
+
+This will report TypeScript errors everywhere the old model string is used. Fix each one. Common locations:
+
+- `packages/core/component/AI/constant/model.ts` — `MODEL_PRETTYNAME`, `MODEL_PROVIDER_ICON`, `SMART_MODE_MODEL` / `DEFAULT_MODEL`
+- `packages/core/component/AI/component/input/useChatInput.tsx` — hardcoded model references
+- `packages/core/component/AI/signal/pendingSend.test.ts` — test data
+
+Replace old model strings and update display names.
+
+### 8. Format and verify
+
+```bash
+cd js/app && bun format && bun check
+```
+
+The only errors remaining should be **pre-existing** ones unrelated to models (e.g. `three`, `@aws-crypto/sha256-js` type issues). All model-related errors must be resolved.
+
+Finally, run the CI check:
+```bash
+cd js/app && bun run gen-api -- --check
+```
+
+This must pass.
+
+## Notes
+
+- We only support Anthropic models for chat. Other providers exist in the AI crate but are not used for the chat feature.
+- The `ExhaustiveMap` type in `constant/model.ts` requires an entry for every model in the `Model` type, so missing entries will cause type errors.
+- The `SMART_MODE_MODEL` constant is the "good" model, `DEFAULT_MODEL` is the "fast" model.
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
deleted file mode 100644
index 960a281af5..0000000000
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/active-filter-chips.tsx
+++ /dev/null
@@ -1,362 +0,0 @@
-import { truncateLabel } from '@core/util/string';
-import { Combobox } from '@kobalte/core/combobox';
-import CheckIcon from '@phosphor/check.svg';
-import XIcon from '@phosphor/x.svg';
-import { Button, cn, Dropdown, Layer } from '@ui';
-import { type Accessor, createSignal, For, type JSX, Show } from 'solid-js';
-import type { SearchableOption } from './search-filter-controls';
-import { SearchableMultiSelect } from './searchable-multi-select';
-import type { FilterOption } from './unified-filter-dropdown';
-
-export type ActiveFilter = {
- categoryLabel: 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[];
- /** When false, the chip dropdown renders radio-style indicators instead of checkboxes. */
- multiple?: boolean;
- /**
- * Per-chip remove handler. When present, takes precedence over the shared
- * `onRemove` prop on `ActiveFilterChips`. Use this for filters that live
- * outside `soup.filters` (e.g. assigneeFilter).
- */
- onRemove?: () => void;
- /**
- * Per-chip replace handler. When present, takes precedence over the shared
- * `onReplace` prop on `ActiveFilterChips`. Use this for filters that need
- * side effects beyond toggling `soup.filters` (e.g. updating queryFilters).
- */
- onReplace?: (newOptionId: string) => void;
- /**
- * Per-chip active-state predicate. When set, takes precedence over the shared
- * `isOptionActive` for this chip's dropdown. Use when the filter state lives
- * outside `soup.filters` (e.g. email importance in queryFilters).
- */
- isOptionActive?: (optionId: string) => boolean;
- /**
- * When set, the chip opens a searchable multi-select combobox instead of the
- * simple replace dropdown. Use for list-valued filters like In/From.
- */
- searchableOptions?: Accessor<SearchableOption[]>;
- /** Currently-active ids for the searchable chip, used to render selection state. */
- activeSearchableIds?: Accessor<string[]>;
- /** Called with the new full id list when the searchable selection changes. */
- 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;
- /** Per-chip override for the container-level `hideCategoryLabel`. */
- hideCategoryLabel?: boolean;
-};
-
-interface ActiveFilterChipsProps {
- filters: ActiveFilter[];
- onRemove: (optionId: string) => void;
- onReplace: (oldOptionId: string, newOptionId: string) => void;
- onClearAll: () => void;
- /** Check if a filter option is currently active */
- isOptionActive: (optionId: string) => boolean;
- /** Extra class applied to each chip wrapper */
- chipClass?: string;
- /** Hide the "Category: " prefix in each chip label */
- hideCategoryLabel?: boolean;
-}
-
-const ChipContent = (props: {
- filter: ActiveFilter;
- hideCategoryLabel?: boolean;
-}) => {
- const showCategory = () =>
- !(props.filter.hideCategoryLabel ?? props.hideCategoryLabel);
- return (
- <>
- <Show when={props.filter.icon}>
- {(icon) => (
- <span class="size-3 flex items-center justify-center shrink-0">
- {icon()()}
- </span>
- )}
- </Show>
- <span class="font-medium" title={props.filter.optionLabel()}>
- <Show when={showCategory()}>{props.filter.categoryLabel}: </Show>
- {truncateLabel(props.filter.optionLabel())}
- </span>
- </>
- );
-};
-
-const ChipRemoveButton = (props: { onRemove: () => void }) => (
- <button
- type="button"
- class={cn(
- 'inline-flex items-center justify-center px-1',
- 'not-disabled:hover:bg-ink/10 not-disabled:active:bg-ink/12'
- )}
- onClick={(e) => {
- e.stopPropagation();
- props.onRemove();
- }}
- >
- <XIcon class="size-3" />
- </button>
-);
-
-const SearchableFilterChip = (props: {
- filter: ActiveFilter;
- onRemove: () => void;
- chipClass?: string;
- hideCategoryLabel?: boolean;
-}) => {
- const options: Accessor<SearchableOption[]> = () =>
- props.filter.searchableOptions?.() ?? [];
- const activeIds: Accessor<string[]> = () =>
- props.filter.activeSearchableIds?.() ?? [];
-
- const handleChange = (ids: string[]) => {
- props.filter.onSearchableChange?.(ids);
- };
-
- const placeholder =
- props.filter.searchPlaceholder ??
- `Search ${props.filter.categoryLabel.toLowerCase()}...`;
-
- return (
- <Layer depth={0}>
- <div
- class={cn(
- 'h-6 inline-flex items-stretch overflow-hidden text-xs font-medium leading-none whitespace-nowrap rounded-sm',
- 'bg-transparent text-ink border border-edge-muted',
- props.chipClass
- )}
- >
- <SearchableMultiSelect
- options={options}
- activeIds={activeIds}
- onChange={handleChange}
- placeholder={placeholder}
- placement="bottom-start"
- open={props.filter.isPopupOpen}
- onOpenChange={(v) => props.filter.setPopupOpen?.(v)}
- >
- <Combobox.Trigger class="inline-flex h-full items-center gap-1.5 px-2 leading-none not-disabled:hover:bg-ink/10 not-disabled:active:bg-ink/12">
- <ChipContent
- filter={props.filter}
- hideCategoryLabel={props.hideCategoryLabel}
- />
- </Combobox.Trigger>
- </SearchableMultiSelect>
-
- <ChipRemoveButton onRemove={props.onRemove} />
- </div>
- </Layer>
- );
-};
-
-const FilterChip = (props: {
- filter: ActiveFilter;
- onRemove: () => void;
- onReplace: (newOptionId: string) => void;
- isOptionActive: (optionId: string) => boolean;
- chipClass?: string;
- hideCategoryLabel?: boolean;
-}) => {
- const [open, setOpen] = createSignal(false);
-
- const hasOptions = () =>
- props.filter.categoryOptions && props.filter.categoryOptions.length > 0;
-
- return (
- <Layer depth={0}>
- <div
- class={cn(
- 'h-6 inline-flex items-stretch overflow-hidden text-xs font-medium leading-none whitespace-nowrap rounded-sm',
- 'bg-transparent text-ink border border-edge-muted',
- props.chipClass
- )}
- >
- <Show
- when={hasOptions()}
- fallback={
- <span class="inline-flex items-center gap-1.5 pxl-2 pr-1 py-1">
- <ChipContent
- filter={props.filter}
- hideCategoryLabel={props.hideCategoryLabel}
- />
- </span>
- }
- >
- <Dropdown open={open()} onOpenChange={setOpen}>
- <Dropdown.Trigger
- variant="ghost"
- class="inline-flex items-center gap-1.5 px-2 leading-none not-disabled:hover:bg-ink/10 not-disabled:active:bg-ink/12"
- >
- <ChipContent
- filter={props.filter}
- hideCategoryLabel={props.hideCategoryLabel}
- />
- </Dropdown.Trigger>
- <Dropdown.Content>
- <Dropdown.Group>
- <For each={props.filter.categoryOptions}>
- {(option) => {
- const active = () =>
- props.filter.isOptionActive
- ? props.filter.isOptionActive(option.id)
- : props.isOptionActive(option.id);
- const isSingleSelect = () =>
- props.filter.multiple === false;
- return (
- <Dropdown.Item
- onSelect={() => {
- if (active()) return;
- if (props.filter.onReplace) {
- props.filter.onReplace(option.id);
- } else {
- props.onReplace(option.id);
- }
- }}
- >
- <Show
- when={isSingleSelect()}
- fallback={
- <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-surface" />
- </Show>
- </span>
- }
- >
- <span
- class={cn(
- 'size-4 flex items-center justify-center shrink-0 rounded-full border transition-colors',
- active()
- ? 'bg-accent border-accent'
- : 'border-edge'
- )}
- >
- <Show when={active()}>
- <CheckIcon class="size-2.5 text-surface" />
- </Show>
- </span>
- </Show>
-
- <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>
- </Dropdown.Item>
- );
- }}
- </For>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- </Show>
-
- <ChipRemoveButton onRemove={props.onRemove} />
- </div>
- </Layer>
- );
-};
-
-export const ActiveFilterChips = (props: ActiveFilterChipsProps) => {
- const lastIndex = () => props.filters.length - 1;
-
- const renderChip = (filter: ActiveFilter) => {
- const onRemove = () => {
- if (filter.onRemove) {
- filter.onRemove();
- } else {
- props.onRemove(filter.optionId());
- }
- };
-
- return (
- <Show
- when={filter.searchableOptions}
- fallback={
- <FilterChip
- filter={filter}
- onRemove={onRemove}
- onReplace={(newOptionId) =>
- props.onReplace(filter.optionId(), newOptionId)
- }
- isOptionActive={props.isOptionActive}
- chipClass={props.chipClass}
- hideCategoryLabel={props.hideCategoryLabel}
- />
- }
- >
- <SearchableFilterChip
- filter={filter}
- onRemove={onRemove}
- chipClass={props.chipClass}
- hideCategoryLabel={props.hideCategoryLabel}
- />
- </Show>
- );
- };
-
- return (
- <Show when={props.filters.length > 0}>
- <div class="flex items-center gap-2 flex-wrap">
- <For each={props.filters}>
- {(filter, index) => (
- // To make sure that the Clear all button never wraps to a new line on its own, we wrap it with the last FilterChip
- <Show
- when={props.filters.length > 1 && index() === lastIndex()}
- fallback={renderChip(filter)}
- >
- <span class="inline-flex items-center gap-1.5">
- {renderChip(filter)}
- <Button
- onClick={() => props.onClearAll()}
- variant="base"
- size="sm"
- >
- <XIcon class="size-3!" />
- Clear
- </Button>
- </span>
- </Show>
- )}
- </For>
- </div>
- </Show>
- );
-};
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/consolidated-filter-chip.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/consolidated-filter-chip.tsx
new file mode 100644
index 0000000000..081a2b25ea
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/consolidated-filter-chip.tsx
@@ -0,0 +1,388 @@
+import { Combobox } from '@kobalte/core/combobox';
+import CheckIcon from '@phosphor/check.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button, cn, Dropdown, Layer } from '@ui';
+import {
+ type Accessor,
+ createSignal,
+ For,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import type { SearchableOption } from './search-filter-controls';
+import { SearchableMultiSelect } from './searchable-multi-select';
+
+export type FilterValue = {
+ id: string;
+ label: string;
+ icon?: () => JSX.Element;
+};
+
+export type ConsolidatedFilter = {
+ /** Unique key for this filter group (e.g., 'status', 'type', 'in-channel') */
+ key: string;
+ /** Display label for the category (e.g., 'Status', 'Type', 'In') */
+ categoryLabel: string;
+ /** Plural form for multi-value display (e.g., 'Statuses', 'Types'). Falls back to categoryLabel + 's' */
+ categoryLabelPlural?: string;
+ /** Icon for the category */
+ categoryIcon?: () => JSX.Element;
+ /** Currently active values - accessor for reactivity */
+ values: Accessor<FilterValue[]>;
+ /** Available options for the value dropdown */
+ availableOptions?: FilterValue[];
+ /** Whether multiple values can be selected */
+ multiple?: boolean;
+ /** Remove a single value */
+ onRemoveValue?: (valueId: string) => void;
+ /** Remove all values (clear entire filter) */
+ onRemoveAll: () => void;
+ /** Toggle a value on/off */
+ onToggleValue?: (valueId: string) => void;
+ /** Check if a value is active */
+ isValueActive?: (valueId: string) => boolean;
+
+ // Searchable filter props (for In/From style filters)
+ searchableOptions?: Accessor<SearchableOption[]>;
+ activeSearchableIds?: Accessor<string[]>;
+ onSearchableChange?: (ids: string[]) => void;
+ searchPlaceholder?: string;
+ isPopupOpen?: Accessor<boolean>;
+ setPopupOpen?: (v: boolean) => void;
+};
+
+interface ConsolidatedFilterChipProps {
+ filter: ConsolidatedFilter;
+ class?: string;
+ hideCategoryLabel?: boolean;
+ mobile?: boolean;
+}
+
+const ChipDivider = (props: { mobile?: boolean }) => (
+ <Show when={!props.mobile}>
+ <div class="w-px self-stretch bg-edge-muted shrink-0" />
+ </Show>
+);
+
+const SingleValueDisplay = (props: { value: FilterValue }) => (
+ <span class="inline-flex h-full items-center gap-1.5">
+ <Show when={props.value.icon}>
+ {(icon) => (
+ <span class="size-4 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
+ )}
+ </Show>
+ <span class="truncate max-w-32">{props.value.label}</span>
+ </span>
+);
+
+const MultiValueDisplay = (props: { values: FilterValue[] }) => {
+ const first = () => props.values[0];
+ const overflowCount = () => props.values.length - 1;
+
+ return (
+ <span
+ class="inline-flex h-full items-center gap-1.5"
+ title={props.values.map((v) => v.label).join(', ')}
+ >
+ <Show when={first()?.icon}>
+ {(icon) => (
+ <span class="size-4 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
+ )}
+ </Show>
+ <span class="truncate max-w-32">{first()?.label}</span>
+ <Show when={overflowCount() > 0}>
+ <span class="inline-flex items-center justify-center px-1 min-w-4 h-4 rounded-full bg-ink/10 text-xxs">
+ +{overflowCount()}
+ </span>
+ </Show>
+ </span>
+ );
+};
+
+/** People filter keys that should show avatar stacks */
+const PEOPLE_FILTER_KEYS = new Set(['assignee', 'channel-from', 'call-from']);
+
+const PeopleMultiValueDisplay = (props: { values: FilterValue[] }) => {
+ const first = () => props.values[0];
+ const overflowCount = () => props.values.length - 1;
+
+ return (
+ <span
+ class="inline-flex items-center gap-1.5"
+ title={props.values.map((v) => v.label).join(', ')}
+ >
+ <Show when={first()?.icon}>
+ {(icon) => (
+ <span class="size-4 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
+ )}
+ </Show>
+ <span class="truncate max-w-32">{first()?.label}</span>
+ <Show when={overflowCount() > 0}>
+ <span class="inline-flex items-center justify-center px-1 min-w-4 h-4 rounded-full bg-ink/10 text-xxs">
+ +{overflowCount()}
+ </span>
+ </Show>
+ </span>
+ );
+};
+
+const ValueDisplay = (props: {
+ values: Accessor<FilterValue[]>;
+ isPeopleFilter?: boolean;
+}) => {
+ const vals = () => props.values();
+ const isSingle = () => vals().length === 1;
+
+ return (
+ <Switch>
+ <Match when={isSingle()}>
+ <SingleValueDisplay value={vals()[0]} />
+ </Match>
+ <Match when={props.isPeopleFilter}>
+ <PeopleMultiValueDisplay values={vals()} />
+ </Match>
+ <Match when={!props.isPeopleFilter}>
+ <MultiValueDisplay values={vals()} />
+ </Match>
+ </Switch>
+ );
+};
+
+const ValueDropdownContent = (props: { filter: ConsolidatedFilter }) => {
+ const isActive = (id: string) =>
+ props.filter.isValueActive?.(id) ??
+ props.filter.values().some((v) => v.id === id);
+
+ return (
+ <Dropdown.Content>
+ <Dropdown.Group>
+ <For each={props.filter.availableOptions}>
+ {(option) => {
+ const active = () => isActive(option.id);
+ return (
+ <Dropdown.Item
+ closeOnSelect={!props.filter.multiple}
+ onSelect={() => {
+ props.filter.onToggleValue?.(option.id);
+ }}
+ >
+ <Show
+ when={props.filter.multiple}
+ fallback={
+ <span
+ class={cn(
+ 'size-4 flex items-center justify-center shrink-0 rounded-full border',
+ active() ? 'bg-accent border-accent' : 'border-edge'
+ )}
+ >
+ <Show when={active()}>
+ <CheckIcon class="size-2.5 text-surface" />
+ </Show>
+ </span>
+ }
+ >
+ <span
+ class={cn(
+ 'size-4 flex items-center justify-center shrink-0 rounded border',
+ active() ? 'bg-accent border-accent' : 'border-edge'
+ )}
+ >
+ <Show when={active()}>
+ <CheckIcon class="size-2.5 text-surface" />
+ </Show>
+ </span>
+ </Show>
+
+ <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>
+ </Dropdown.Item>
+ );
+ }}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ );
+};
+
+const SearchableValueSegment = (props: {
+ filter: ConsolidatedFilter;
+ class?: string;
+ mobile?: boolean;
+}) => {
+ const options: Accessor<SearchableOption[]> = () =>
+ props.filter.searchableOptions?.() ?? [];
+ const activeIds: Accessor<string[]> = () =>
+ props.filter.activeSearchableIds?.() ?? [];
+
+ const handleChange = (ids: string[]) => {
+ props.filter.onSearchableChange?.(ids);
+ };
+
+ const placeholder =
+ props.filter.searchPlaceholder ??
+ `Search ${props.filter.categoryLabel.toLowerCase()}...`;
+
+ const isPeopleFilter = () => PEOPLE_FILTER_KEYS.has(props.filter.key);
+
+ return (
+ <SearchableMultiSelect
+ options={options}
+ activeIds={activeIds}
+ onChange={handleChange}
+ placeholder={placeholder}
+ placement="bottom-start"
+ open={props.filter.isPopupOpen}
+ onOpenChange={(v) => props.filter.setPopupOpen?.(v)}
+ >
+ <Combobox.Trigger
+ class={cn(
+ 'inline-flex h-full items-center gap-1.5 px-2',
+ props.mobile
+ ? 'bg-active hover:bg-active active:bg-active px-3'
+ : 'hover:bg-hover active:bg-active',
+ props.class
+ )}
+ >
+ <ValueDisplay
+ values={props.filter.values}
+ isPeopleFilter={isPeopleFilter()}
+ />
+ </Combobox.Trigger>
+ </SearchableMultiSelect>
+ );
+};
+
+const StandardValueSegment = (props: {
+ filter: ConsolidatedFilter;
+ class?: string;
+ mobile?: boolean;
+}) => {
+ const [open, setOpen] = createSignal(false);
+ const hasOptions = () =>
+ props.filter.availableOptions && props.filter.availableOptions.length > 0;
+
+ const isPeopleFilter = () => PEOPLE_FILTER_KEYS.has(props.filter.key);
+
+ return (
+ <Show
+ when={hasOptions()}
+ fallback={
+ <span
+ class={cn(
+ 'inline-flex items-center gap-1.5 px-2.5',
+ props.mobile && 'bg-active px-3',
+ props.class
+ )}
+ >
+ <ValueDisplay
+ values={props.filter.values}
+ isPeopleFilter={isPeopleFilter()}
+ />
+ </span>
+ }
+ >
+ <Dropdown open={open()} onOpenChange={setOpen}>
+ <Dropdown.Trigger
+ variant="ghost"
+ class={cn(
+ 'inline-flex items-center gap-1.5 px-2.5 h-auto!',
+ props.mobile
+ ? 'bg-active hover:bg-active active:bg-active rounded-none px-3'
+ : 'hover:bg-ink/5 active:bg-ink/8 rounded-none',
+ props.class
+ )}
+ >
+ <ValueDisplay
+ values={props.filter.values}
+ isPeopleFilter={isPeopleFilter()}
+ />
+ </Dropdown.Trigger>
+ <ValueDropdownContent filter={props.filter} />
+ </Dropdown>
+ </Show>
+ );
+};
+
+export const ConsolidatedFilterChip = (props: ConsolidatedFilterChipProps) => {
+ const isSearchable = () => Boolean(props.filter.searchableOptions);
+
+ return (
+ <Layer depth={2}>
+ <div
+ class={cn(
+ props.mobile ? 'h-10' : 'h-7',
+ 'flex items-stretch text-xs whitespace-nowrap rounded-md',
+ 'bg-surface text-ink border border-edge-muted overflow-clip',
+ props.mobile && 'bg-active border-none rounded-lg',
+ props.class
+ )}
+ >
+ <Show when={!props.hideCategoryLabel}>
+ <span class="inline-flex items-center gap-1.5 px-2 text-ink-muted">
+ <Show when={props.filter.categoryIcon}>
+ {(icon) => (
+ <span class="size-3 flex items-center justify-center shrink-0">
+ {icon()()}
+ </span>
+ )}
+ </Show>
+ <span>{props.filter.categoryLabel}</span>
+ </span>
+
+ <ChipDivider mobile={props.mobile} />
+ </Show>
+
+ {/* Value segment */}
+ <Switch>
+ <Match when={isSearchable()}>
+ <SearchableValueSegment
+ filter={props.filter}
+ mobile={props.mobile}
+ />
+ </Match>
+ <Match when={!isSearchable()}>
+ <StandardValueSegment filter={props.filter} mobile={props.mobile} />
+ </Match>
+ </Switch>
+
+ <ChipDivider mobile={props.mobile} />
+
+ <Button
+ class={cn(
+ 'rounded-none h-full not-disabled:hover:text-failure',
+ props.mobile && 'bg-active border-none'
+ )}
+ size="icon-sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ props.filter.onRemoveAll();
+ }}
+ >
+ <XIcon class="size-3.5!" />
+ </Button>
+ </div>
+ </Layer>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
index 752023ad9e..d2e9efd3fc 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/mobile-filter-drawer.tsx
@@ -27,11 +27,12 @@ import ChevronDownIcon from '@phosphor/caret-down.svg';
import CheckIcon from '@phosphor/check.svg';
import CircleDashedIcon from '@phosphor/circle-dashed.svg';
import SearchIcon from '@phosphor/magnifying-glass.svg';
+import XIcon from '@phosphor/x.svg';
import SlidersHorizontalIcon from '@phosphor-icons/core/regular/sliders-horizontal.svg?component-solid';
import { useContacts } from '@queries/contacts/contacts';
import { Button, cn } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
-import { ActiveFilterChips } from './active-filter-chips';
+import { ConsolidatedFilterChip } from './consolidated-filter-chip';
import {
buildContactLabel,
type FilterOption,
@@ -60,13 +61,8 @@ function scrollAccordionItemToTop(
}
export const MobileFilterDrawer = () => {
- const {
- activeFiltersList,
- removeFilter,
- replaceFilter,
- resetToTabDefaults,
- isOptionActive,
- } = useFilterRefinements();
+ const { consolidatedFiltersList, resetToTabDefaults } =
+ useFilterRefinements();
const { soup, queryFilters, assigneeFilter, setAssigneeFilter } =
useSoupView();
@@ -188,7 +184,7 @@ export const MobileFilterDrawer = () => {
);
});
- const activeCount = () => activeFiltersList().length;
+ const activeCount = () => consolidatedFiltersList().length;
const [scrollRef, setScrollRef] = createSignal<HTMLElement>();
@@ -464,16 +460,27 @@ export const MobileFilterDrawer = () => {
{/* Active filter chips footer */}
<Show when={activeCount() > 0}>
- <div class="shrink-0 border-t border-edge-muted py-2">
- <ActiveFilterChips
- filters={activeFiltersList()}
- onRemove={removeFilter}
- onReplace={replaceFilter}
- onClearAll={resetToTabDefaults}
- isOptionActive={isOptionActive}
- chipClass="min-h-11 bg-surface border-none rounded-lg"
- hideCategoryLabel
- />
+ <div class="shrink-0 border-t border-edge-muted p-2">
+ <div class="flex items-center gap-2 flex-wrap">
+ <For each={consolidatedFiltersList()}>
+ {(filter) => (
+ <ConsolidatedFilterChip
+ filter={filter}
+ hideCategoryLabel
+ mobile
+ />
+ )}
+ </For>
+ <Button
+ onClick={() => resetToTabDefaults()}
+ variant="base"
+ size="sm"
+ class="min-h-10 rounded-lg bg-active!"
+ >
+ <XIcon class="size-3!" />
+ Clear all
+ </Button>
+ </div>
</div>
</Show>
</MobileDrawer.Content>
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
index 8a0766508d..074ca489c9 100644
--- 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
@@ -3,7 +3,7 @@ import type { CollectionNode } from '@kobalte/core';
import { Combobox } from '@kobalte/core/combobox';
import CheckIcon from '@phosphor/check.svg';
import SearchIcon from '@phosphor/magnifying-glass.svg';
-import { cn } from '@ui';
+import { cn, Layer } from '@ui';
import {
type Accessor,
createMemo,
@@ -176,37 +176,39 @@ export const SearchableMultiSelect = (props: SearchableMultiSelectProps) => {
</Combobox.Control>
<Combobox.Portal>
- <Combobox.Content
- class={cn(
- 'z-action-menu bg-surface ring-1 ring-edge-muted rounded-sm shadow-md w-65 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={sortedOptions()}
- class={props.listboxClass}
+ <Layer depth={2}>
+ <Combobox.Content
+ class={cn(
+ 'z-action-menu bg-surface ring-1 ring-edge-muted rounded-xl shadow-md w-65 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...'}
/>
- </Show>
- </div>
- </Combobox.Content>
+ </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={sortedOptions()}
+ class={props.listboxClass}
+ />
+ </Show>
+ </div>
+ </Combobox.Content>
+ </Layer>
</Combobox.Portal>
</Combobox>
);
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-active-filters-bar.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-active-filters-bar.tsx
new file mode 100644
index 0000000000..020a8b2188
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-active-filters-bar.tsx
@@ -0,0 +1,69 @@
+import Plus from '@phosphor/plus.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button, cn, Dropdown, Layer } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import {
+ type ConsolidatedFilter,
+ ConsolidatedFilterChip,
+} from './consolidated-filter-chip';
+import { UnifiedFilterDropdown } from './unified-filter-dropdown';
+
+interface SoupActiveFiltersBarProps {
+ filters: ConsolidatedFilter[];
+ onClearAll: () => void;
+ class?: string;
+}
+
+/**
+ * A dedicated filter bar that appears at the top of the soup view when there are active filters.
+ * Contains filter chips on the left, and add/clear buttons on the right.
+ */
+const AddFilterButton = () => (
+ <Dropdown.Trigger
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Add filters"
+ class="p-1 rounded-full"
+ >
+ <Plus class="size-3" />
+ </Dropdown.Trigger>
+);
+
+export function SoupActiveFiltersBar(props: SoupActiveFiltersBarProps) {
+ const [addFilterOpen, setAddFilterOpen] = createSignal(false);
+
+ return (
+ <Show when={props.filters.length > 0}>
+ <Layer depth={0}>
+ <div class={cn('w-full p-2', props.class)}>
+ <div class="flex items-start p-2 border border-edge-muted bg-surface rounded-lg font-medium">
+ {/* Filter chips and add button - flex left */}
+ <div class="flex items-center gap-2 flex-wrap flex-1 min-w-0">
+ <For each={props.filters}>
+ {(filter) => <ConsolidatedFilterChip filter={filter} />}
+ </For>
+ <UnifiedFilterDropdown
+ open={() => addFilterOpen()}
+ onOpenChange={setAddFilterOpen}
+ customTrigger={<AddFilterButton />}
+ />
+ </div>
+
+ <div class="flex items-center shrink-0">
+ <Button
+ onClick={() => props.onClearAll()}
+ variant="base"
+ size="sm"
+ class="h-7 rounded-md"
+ tooltip="Clear active filters"
+ >
+ <XIcon />
+ <span class="hidden @min-[300px]/split:inline">Clear all</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </Layer>
+ </Show>
+ );
+}
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
index b83544f877..dadbe3dab5 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
@@ -1,5 +1,5 @@
import { useAnalytics } from '@app/component/analytics-context';
-import { ActiveFilterChips } from '@app/component/next-soup/soup-view/filters-bar/active-filter-chips';
+import { SoupActiveFiltersBar } from '@app/component/next-soup/soup-view/filters-bar/soup-active-filters-bar';
import { SoupViewContextGroup } from '@app/component/next-soup/soup-view/filters-bar/soup-view-context-group';
import { SoupViewContextSort } from '@app/component/next-soup/soup-view/filters-bar/soup-view-context-sort';
import { UnifiedFilterDropdown } from '@app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown';
@@ -15,17 +15,13 @@ import { isMobile } from '@core/mobile/isMobile';
import EyeIcon from '@phosphor-icons/core/regular/eye.svg?component-solid';
import EyeSlashIcon from '@phosphor-icons/core/regular/eye-slash.svg?component-solid';
import { Button, Tooltip } from '@ui';
-import { createMemo, Show } from 'solid-js';
+import { createMemo, createSignal, Show } from 'solid-js';
import { useSoup } from '../../soup-context';
export function SoupFiltersBar() {
- const {
- resetToTabDefaults,
- activeFiltersList,
- isOptionActive,
- replaceFilter,
- removeFilter,
- } = useFilterRefinements();
+ const { resetToTabDefaults, consolidatedFiltersList } =
+ useFilterRefinements();
+ const [filterDropdownOpen, setFilterDropdownOpen] = createSignal(false);
const panel = useSplitPanelOrThrow();
const analytics = useAnalytics();
@@ -69,13 +65,9 @@ export function SoupFiltersBar() {
<SoupViewContextSort />
<SoupViewContextGroup />
</Show>
- <UnifiedFilterDropdown />
- <ActiveFilterChips
- isOptionActive={isOptionActive}
- onClearAll={resetToTabDefaults}
- filters={activeFiltersList()}
- onReplace={replaceFilter}
- onRemove={removeFilter}
+ <UnifiedFilterDropdown
+ open={filterDropdownOpen}
+ onOpenChange={setFilterDropdownOpen}
/>
</div>
</SplitToolbarLeft>
@@ -93,6 +85,11 @@ export function SoupFiltersBar() {
</Button>
</Tooltip>
</SplitToolbarRight>
+ {/* Active filters bar - shown below the toolbar when there are filters */}
+ <SoupActiveFiltersBar
+ filters={consolidatedFiltersList()}
+ onClearAll={resetToTabDefaults}
+ />
</Show>
);
}
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 f252b9fd0f..9dc4fa7794 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
@@ -77,6 +77,8 @@ export type FilterOption = {
type FilterCategory = {
id: string;
label: string;
+ /** Plural form for multi-value chip display (e.g., 'Types', 'Statuses') */
+ labelPlural?: string;
options: FilterOption[];
multiple?: boolean;
};
@@ -86,6 +88,7 @@ const INBOX_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'type',
label: 'Type',
+ labelPlural: 'Types',
options: [
{
id: 'document',
@@ -139,6 +142,7 @@ const MAIL_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'status',
label: 'Status',
+ labelPlural: 'Statuses',
options: [
{ id: 'unread', label: 'Unread' },
{ id: 'read', label: 'Read' },
@@ -150,6 +154,7 @@ const MAIL_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'attachment',
label: 'Attachments',
+ labelPlural: 'Attachments',
options: [
{
id: 'attachment-pdf',
@@ -172,6 +177,7 @@ const MAIL_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'calendar',
label: 'Calendar',
+ labelPlural: 'Calendar',
options: [{ id: 'has-calendar-invite', label: 'Has Calendar Invite' }],
multiple: false,
},
@@ -181,6 +187,7 @@ const TASKS_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'status',
label: 'Status',
+ labelPlural: 'Statuses',
options: [
{
id: 'task-not-started',
@@ -238,6 +245,7 @@ const TASKS_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'priority',
label: 'Priority',
+ labelPlural: 'Priorities',
options: [
{
id: 'task-urgent',
@@ -289,6 +297,7 @@ const DOCUMENTS_FILTER_CATEGORIES: FilterCategory[] = [
{
id: 'type',
label: 'Type',
+ labelPlural: 'Types',
options: [
{
id: 'doc-markdown',
@@ -657,8 +666,25 @@ const SearchIndexSubRow = (props: {
</Dropdown.Sub>
);
-export const UnifiedFilterDropdown = () => {
- const [open, setOpen] = createSignal(false);
+interface UnifiedFilterDropdownProps {
+ /** Optional controlled open state */
+ open?: Accessor<boolean>;
+ onOpenChange?: (open: boolean) => void;
+ /** Optional custom trigger element. If not provided, uses default Filter button. */
+ customTrigger?: JSX.Element;
+ /** Hide the default trigger entirely (useful when controlling open state externally) */
+ hideTrigger?: boolean;
+}
+
+export const UnifiedFilterDropdown = (
+ props: UnifiedFilterDropdownProps = {}
+) => {
+ const [internalOpen, setInternalOpen] = createSignal(false);
+ const open = () => props.open?.() ?? internalOpen();
+ const setOpen = (v: boolean) => {
+ setInternalOpen(v);
+ props.onOpenChange?.(v);
+ };
const panel = useSplitPanelOrThrow();
const { soup, queryFilters, assigneeFilter, setAssigneeFilter, activeTab } =
useSoupView();
@@ -819,15 +845,51 @@ export const UnifiedFilterDropdown = () => {
},
});
+ // Capture anchor position when menu opens to prevent jumping when chips are added
+ const [anchorRect, setAnchorRect] = createSignal<DOMRect | null>(null);
+
+ const handleOpenChange = (isOpen: boolean) => {
+ if (isOpen) {
+ // Clear any stale anchor rect so it gets recaptured from trigger
+ setAnchorRect(null);
+ }
+ setOpen(isOpen);
+ };
+
+ const getAnchorRect = (anchor?: HTMLElement) => {
+ // If we have a captured rect, use it (prevents jumping)
+ const captured = anchorRect();
+ if (captured) return captured;
+
+ // Otherwise capture the current position
+ if (anchor) {
+ const rect = anchor.getBoundingClientRect();
+ setAnchorRect(rect);
+ return rect;
+ }
+ return undefined;
+ };
+
return (
<Show when={categories().length > 0 || isTasksView() || isSearchView()}>
- <Dropdown open={open()} onOpenChange={setOpen}>
- <Tooltip label="Filter" hotkey={TOKENS.soup.filter}>
- <Dropdown.Trigger depth={2} class="bg-surface">
- <SlidersHorizontalIcon />
- <span>Filter</span>
- </Dropdown.Trigger>
- </Tooltip>
+ <Dropdown
+ open={open()}
+ onOpenChange={handleOpenChange}
+ getAnchorRect={getAnchorRect}
+ >
+ <Show when={!props.hideTrigger}>
+ <Switch>
+ <Match when={props.customTrigger}>{props.customTrigger}</Match>
+ <Match when={true}>
+ <Tooltip label="Filter" hotkey={TOKENS.soup.filter}>
+ <Dropdown.Trigger depth={2} class="bg-surface">
+ <SlidersHorizontalIcon />
+ <span>Filter</span>
+ </Dropdown.Trigger>
+ </Tooltip>
+ </Match>
+ </Switch>
+ </Show>
<Dropdown.Content>
<Dropdown.Group>
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 de2984d99e..5c14c5650c 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
@@ -13,12 +13,23 @@ 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 { UserIcon } from '@core/component/UserIcon';
import { useUserContext, useUserId } from '@core/context/user';
import { deepEqual } from '@core/util/compareUtils';
+import CircleDashedIcon from '@phosphor/circle-dashed.svg';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import { useContacts } from '@queries/contacts/contacts';
-import { type Accessor, batch, createMemo, createSignal } from 'solid-js';
-import type { ActiveFilter } from './active-filter-chips';
+import {
+ type Accessor,
+ batch,
+ createMemo,
+ createSignal,
+ type JSX,
+} from 'solid-js';
+import type {
+ ConsolidatedFilter,
+ FilterValue,
+} from './consolidated-filter-chip';
import {
cacheCallSubFilters,
cacheChannelSubFilters,
@@ -117,16 +128,108 @@ export function useFilterRefinements() {
* Human-readable options for the assignee sub-filter, keyed by assignee ID.
* Mirrors the same logic used in UnifiedFilterDropdown's assigneeOptions.
*/
- const assigneeOptionsMap = createMemo((): Map<string, { label: string }> => {
+ const assigneeOptionsMap = createMemo(
+ (): Map<string, { label: string; icon?: () => JSX.Element }> => {
+ const uid = currentUserId();
+ const map = new Map<
+ string,
+ { label: string; icon?: () => JSX.Element }
+ >();
+ map.set(NO_ASSIGNEE, {
+ label: 'Unassigned',
+ icon: () => <CircleDashedIcon class="size-3 text-ink-muted" />,
+ });
+ for (const contact of contacts()) {
+ map.set(contact.id, {
+ label: buildContactLabel(contact, uid),
+ icon: () => (
+ <UserIcon
+ id={contact.id}
+ size="sm"
+ suppressClick
+ showTooltip={false}
+ />
+ ),
+ });
+ }
+ return map;
+ }
+ );
+
+ /**
+ * Searchable options for the assignee filter (for use in searchable multi-select).
+ */
+ const assigneeSearchableOptions = createMemo((): SearchableOption[] => {
const uid = currentUserId();
- const map = new Map<string, { label: string }>();
- map.set(NO_ASSIGNEE, { label: 'Unassigned' });
+ const noAssigneeOption: SearchableOption = {
+ id: NO_ASSIGNEE,
+ label: 'Unassigned',
+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,
+ };
+ let meOption: SearchableOption | undefined;
+ const otherContactOptions: SearchableOption[] = [];
for (const contact of contacts()) {
- map.set(contact.id, { label: buildContactLabel(contact, uid) });
+ const opt: SearchableOption = {
+ id: contact.id,
+ label: buildContactLabel(contact, uid),
+ icon: () => (
+ <UserIcon
+ id={contact.id}
+ size="sm"
+ suppressClick
+ showTooltip={false}
+ />
+ ),
+ };
+ if (contact.id === uid) {
+ meOption = opt;
+ } else {
+ otherContactOptions.push(opt);
+ }
}
- return map;
+ return [
+ ...(meOption ? [meOption] : []),
+ noAssigneeOption,
+ ...otherContactOptions,
+ ];
});
+ /**
+ * Handler for assignee filter changes.
+ */
+ const handleAssigneeChange = (ids: string[]) => {
+ const current = assigneeFilter();
+ const toAdd = ids.filter((id) => !current.includes(id));
+ const toRemove = current.filter((id) => !ids.includes(id));
+
+ // Exclude NO_ASSIGNEE from backend queries - it's handled client-side only
+ const toProps = (list: string[]) =>
+ list
+ .filter((id) => id !== NO_ASSIGNEE)
+ .map((id) => ({
+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ type: 'entity' as const,
+ value: id,
+ }));
+
+ batch(() => {
+ setAssigneeFilter(ids);
+
+ // Activate/deactivate the assignee predicate based on selection
+ const shouldBeActive = ids.length > 0;
+ if (shouldBeActive !== soup.predicates.isActive('assignee')) {
+ soup.predicates.toggle({ and: ['assignee'] });
+ }
+
+ const removeProps = toProps(toRemove);
+ const addProps = toProps(toAdd);
+ if (removeProps.length)
+ queryFilters.remove({ include: { properties: removeProps } });
+ if (addProps.length)
+ queryFilters.add({ include: { properties: addProps } });
+ });
+ };
+
/**
* Get filter categories for the current view
*/
@@ -136,17 +239,6 @@ export function useFilterRefinements() {
return VIEW_FILTER_CATEGORIES[view as ListView] ?? [];
});
- 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 setFilterIds =
(
field: 'callChannelId' | 'callSpeakerId' | 'channelId' | 'channelSenderId'
@@ -159,114 +251,298 @@ export function useFilterRefinements() {
});
/**
- * 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.
+ * Cache for consolidated filter chips, similar to chipCache but for the new format.
+ * We track the view and tab to invalidate when they change, since cached chips
+ * may close over stale values (e.g. group.allOptions, coveredByView, presetFilterIds).
*/
- const chipCache = new Map<string, ActiveFilter>();
- const getOrCreateChip = (
+ const consolidatedChipCache = new Map<string, ConsolidatedFilter>();
+ let lastCacheViewId: ListView | undefined;
+ let lastCacheTab: string | undefined;
+
+ const getOrCreateConsolidatedChip = (
key: string,
- build: () => ActiveFilter
- ): ActiveFilter => {
- let chip = chipCache.get(key);
+ build: () => ConsolidatedFilter
+ ): ConsolidatedFilter => {
+ let chip = consolidatedChipCache.get(key);
if (!chip) {
chip = build();
- chipCache.set(key, chip);
+ consolidatedChipCache.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).
+ * Returns consolidated filters grouped by category.
+ * Multiple values in the same category are shown in a single chip.
*/
- const activeFiltersList = createMemo((): ActiveFilter[] => {
+ const consolidatedFiltersList = createMemo((): ConsolidatedFilter[] => {
+ const view = currentView();
const preset = currentPreset();
+ const tab = activeTab();
+
+ // Invalidate cache when view or tab changes, since cached chips
+ // close over render-local values like group.allOptions, coveredByView, presetFilterIds
+ if (view !== lastCacheViewId || tab !== lastCacheTab) {
+ consolidatedChipCache.clear();
+ lastCacheViewId = view;
+ lastCacheTab = tab;
+ }
+
const presetFilterIds = new Set([
...(preset?.clientFilters.and ?? []),
...(preset?.clientFilters.or ?? []),
]);
- const filters: ActiveFilter[] = [];
+ const filters: ConsolidatedFilter[] = [];
const seenKeys = new Set<string>();
+ // Group view category filters by category
+ const categoryGroups = new Map<
+ string,
+ {
+ label: string;
+ labelPlural?: string;
+ allOptions: FilterValue[];
+ multiple: boolean;
+ }
+ >();
+
for (const category of viewCategories()) {
+ const activeValues: FilterValue[] = [];
+ const allOptions: FilterValue[] = [];
+
for (const option of category.options) {
+ allOptions.push({
+ id: option.id,
+ label: option.label,
+ icon: option.icon,
+ });
+
if (
- !soup.predicates.isActive(option.id) ||
- TAB_ONLY_FILTERS.has(option.id) ||
- presetFilterIds.has(option.id as FilterID)
+ soup.predicates.isActive(option.id) &&
+ !TAB_ONLY_FILTERS.has(option.id) &&
+ !presetFilterIds.has(option.id as FilterID)
) {
- continue;
- }
- const key = `${category.label}|${option.id}`;
- seenKeys.add(key);
- filters.push(
- getOrCreateChip(key, () => ({
- categoryLabel: category.label,
- optionId: () => option.id,
- optionLabel: () => option.label,
+ activeValues.push({
+ id: option.id,
+ label: option.label,
icon: option.icon,
- categoryOptions: category.options,
- }))
- );
+ });
+ }
}
+
+ if (activeValues.length > 0) {
+ categoryGroups.set(category.id, {
+ label: category.label,
+ labelPlural: category.labelPlural,
+ allOptions,
+ multiple: category.multiple ?? true,
+ });
+ }
+ }
+
+ // Build consolidated chips for each category group
+ for (const [categoryId, group] of categoryGroups) {
+ const key = `category:${categoryId}`;
+ seenKeys.add(key);
+
+ // Helper to get current active values for this category (computed fresh)
+ const getActiveValues = (): FilterValue[] => {
+ const result: FilterValue[] = [];
+ for (const opt of group.allOptions) {
+ if (
+ soup.predicates.isActive(opt.id) &&
+ !TAB_ONLY_FILTERS.has(opt.id) &&
+ !presetFilterIds.has(opt.id as FilterID)
+ ) {
+ result.push(opt);
+ }
+ }
+ return result;
+ };
+
+ filters.push(
+ getOrCreateConsolidatedChip(key, () => ({
+ key,
+ categoryLabel: group.label,
+ categoryLabelPlural: group.labelPlural,
+ values: getActiveValues, // Accessor - computed fresh each render
+ availableOptions: group.allOptions,
+ multiple: group.multiple,
+ isValueActive: (id) => soup.predicates.isActive(id),
+ onToggleValue: (id) => {
+ const query = getFilterQuery(id);
+ batch(() => {
+ soup.predicates.toggle({ or: [id as FilterID] });
+ if (query) {
+ if (soup.predicates.isActive(id)) {
+ queryFilters.add(query);
+ } else {
+ queryFilters.remove(query);
+ }
+ }
+ });
+ },
+ onRemoveAll: () => {
+ // Compute current active values at removal time
+ const currentValues = getActiveValues();
+ batch(() => {
+ for (const value of currentValues) {
+ const query = getFilterQuery(value.id);
+ soup.predicates.toggle({ or: [value.id as FilterID] });
+ if (query) queryFilters.remove(query);
+ }
+ });
+ },
+ }))
+ );
}
- // Search operator filters: index: (entity type toggles)
+ // Search index type filters (single-select, replaces)
const coveredByView = new Set<string>(
viewCategories().flatMap((c) => c.options.map((o) => o.id))
);
+ const activeIndexOptions: FilterValue[] = [];
for (const option of INDEX_OPTIONS) {
const optionId = option.value as FilterID;
if (
- !soup.predicates.isActive(optionId) ||
- coveredByView.has(optionId) ||
- presetFilterIds.has(optionId)
+ soup.predicates.isActive(optionId) &&
+ !coveredByView.has(optionId) &&
+ !presetFilterIds.has(optionId)
) {
- continue;
+ activeIndexOptions.push({
+ id: option.value,
+ label: option.label,
+ icon: option.icon,
+ });
}
- const key = `Type|${option.value}`;
+ }
+
+ if (activeIndexOptions.length > 0) {
+ const key = 'type:index';
seenKeys.add(key);
+
+ const getActiveIndexValues = (): FilterValue[] => {
+ const result: FilterValue[] = [];
+ for (const option of INDEX_OPTIONS) {
+ const optionId = option.value as FilterID;
+ if (
+ soup.predicates.isActive(optionId) &&
+ !coveredByView.has(optionId) &&
+ !presetFilterIds.has(optionId)
+ ) {
+ result.push({
+ id: option.value,
+ label: option.label,
+ icon: option.icon,
+ });
+ }
+ }
+ return result;
+ };
+
filters.push(
- getOrCreateChip(key, () => ({
+ getOrCreateConsolidatedChip(key, () => ({
+ key,
categoryLabel: 'Type',
- optionId: () => option.value,
- optionLabel: () => option.label,
- icon: option.icon,
- categoryOptions: INDEX_OPTIONS.map((o) => ({
+ categoryLabelPlural: 'Types',
+ values: getActiveIndexValues,
+ availableOptions: INDEX_OPTIONS.map((o) => ({
id: o.value,
label: o.label,
icon: o.icon,
- })) as ActiveFilter['categoryOptions'],
+ })),
multiple: false,
- onRemove: () => changeIndex('all'),
- onReplace: (newOptionId) => changeIndex(newOptionId),
+ isValueActive: (id) => soup.predicates.isActive(id),
+ onToggleValue: (id) => changeIndex(id),
+ onRemoveAll: () => changeIndex('all'),
}))
);
}
- // Keep a chip alive while its popup is still open, even if the user
- // toggled every option off — closing the menu mid-swap is jarring.
- const pushSearchableChip = (args: {
+ // Assignee filter (consolidated) - using searchable approach
+ const pushAssigneeConsolidatedChip = () => {
+ const key = 'assignee';
+ const popupOpen =
+ consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;
+ const ids = assigneeFilter();
+ if (ids.length === 0 && !popupOpen) return;
+
+ seenKeys.add(key);
+
+ // Compute values as accessor for reactivity, including icons
+ const getValues = (): FilterValue[] =>
+ assigneeFilter().map((id) => {
+ const opt = assigneeOptionsMap().get(id);
+ return {
+ id,
+ label: opt?.label ?? id,
+ icon: opt?.icon,
+ };
+ });
+
+ filters.push(
+ getOrCreateConsolidatedChip(key, () => {
+ const [isPopupOpen, _setPopupOpen] = createSignal(false);
+ const setPopupOpen = (v: boolean) => {
+ if (!v) {
+ queueMicrotask(() =>
+ panel.panelRef()?.focus({ preventScroll: true })
+ );
+ }
+ _setPopupOpen(v);
+ };
+ return {
+ key,
+ categoryLabel: 'Assignee',
+ values: getValues,
+ searchableOptions: assigneeSearchableOptions,
+ activeSearchableIds: assigneeFilter,
+ onSearchableChange: handleAssigneeChange,
+ searchPlaceholder: 'Search assignees...',
+ isPopupOpen,
+ setPopupOpen,
+ onRemoveAll: () => handleAssigneeChange([]),
+ };
+ })
+ );
+ };
+
+ pushAssigneeConsolidatedChip();
+
+ // Searchable filters helper for consolidated chips
+ const pushSearchableConsolidatedChip = (args: {
key: string;
- categoryLabel: 'In' | 'From';
- optionIdPrefix: string;
+ categoryLabel: string;
getIds: () => string[];
searchableOptions: Accessor<SearchableOption[]>;
labelMap: Accessor<Map<string, string>>;
onChange: (ids: string[]) => void;
searchPlaceholder: string;
}) => {
- const popupOpen = chipCache.get(args.key)?.isPopupOpen?.() ?? false;
- if (args.getIds().length === 0 && !popupOpen) return;
+ const popupOpen =
+ consolidatedChipCache.get(args.key)?.isPopupOpen?.() ?? false;
+ const ids = args.getIds();
+ if (ids.length === 0 && !popupOpen) return;
+
seenKeys.add(args.key);
+
+ // Compute values as accessor for reactivity
+ const getValues = (): FilterValue[] => {
+ const options = args.searchableOptions();
+ return args.getIds().map((id) => {
+ const opt = options.find((o) => o.id === id);
+ return {
+ id,
+ label: args.labelMap().get(id) ?? id,
+ icon: opt?.icon,
+ };
+ });
+ };
+
filters.push(
- getOrCreateChip(args.key, () => {
+ getOrCreateConsolidatedChip(args.key, () => {
const [isPopupOpen, _setPopupOpen] = createSignal(false);
- // restores focus to the split panel on close
const setPopupOpen = (v: boolean) => {
if (!v) {
queueMicrotask(() =>
@@ -276,53 +552,25 @@ export function useFilterRefinements() {
_setPopupOpen(v);
};
return {
+ key: args.key,
categoryLabel: args.categoryLabel,
- optionId: () => `${args.optionIdPrefix}:${args.getIds().join(',')}`,
- optionLabel: () => labelForIds(args.getIds(), args.labelMap()),
+ values: getValues,
searchableOptions: args.searchableOptions,
activeSearchableIds: args.getIds,
onSearchableChange: args.onChange,
searchPlaceholder: args.searchPlaceholder,
- onRemove: () => args.onChange([]),
isPopupOpen,
setPopupOpen,
+ onRemoveAll: () => args.onChange([]),
};
})
);
};
- for (const id of assigneeFilter()) {
- const key = `Assignee|${id}`;
- seenKeys.add(key);
- filters.push(
- getOrCreateChip(key, () => ({
- categoryLabel: 'Assignee',
- optionId: () => id,
- optionLabel: () => assigneeOptionsMap().get(id)?.label ?? id,
- onRemove: () => {
- batch(() => {
- setAssigneeFilter(assigneeFilter().filter((a) => a !== id));
- queryFilters.remove({
- include: {
- properties: [
- {
- propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
- type: 'entity',
- value: id,
- },
- ],
- },
- });
- });
- },
- }))
- );
- }
-
- pushSearchableChip({
- key: 'ChannelIn',
+ // Channel In/From filters
+ pushSearchableConsolidatedChip({
+ key: 'channel-in',
categoryLabel: 'In',
- optionIdPrefix: 'channel-in',
getIds: () =>
(queryFilters.state.include.channelId ?? []).filter(
(id) => id !== NIL_UUID
@@ -333,10 +581,9 @@ export function useFilterRefinements() {
searchPlaceholder: 'Search channels...',
});
- pushSearchableChip({
- key: 'ChannelFrom',
+ pushSearchableConsolidatedChip({
+ key: 'channel-from',
categoryLabel: 'From',
- optionIdPrefix: 'channel-from',
getIds: () => queryFilters.state.include.channelSenderId ?? [],
searchableOptions: senderOptions,
labelMap: senderLabelMap,
@@ -344,12 +591,12 @@ export function useFilterRefinements() {
searchPlaceholder: 'Search senders...',
});
+ // Search view specific filters
if (currentView() === 'search') {
if (soup.predicates.isActive('calls')) {
- pushSearchableChip({
- key: 'CallIn',
+ pushSearchableConsolidatedChip({
+ key: 'call-in',
categoryLabel: 'In',
- optionIdPrefix: 'call-in',
getIds: () =>
(queryFilters.state.include.callChannelId ?? []).filter(
(id) => id !== NIL_UUID
@@ -360,10 +607,9 @@ export function useFilterRefinements() {
searchPlaceholder: 'Search channels...',
});
- pushSearchableChip({
- key: 'CallFrom',
+ pushSearchableConsolidatedChip({
+ key: 'call-from',
categoryLabel: 'From',
- optionIdPrefix: 'call-from',
getIds: () => queryFilters.state.include.callSpeakerId ?? [],
searchableOptions: senderOptions,
labelMap: senderLabelMap,
@@ -371,107 +617,103 @@ export function useFilterRefinements() {
searchPlaceholder: 'Search speakers...',
});
+ // Call attended filter
const callAttended = queryFilters.state.include.callAttended;
if (callAttended !== undefined && callAttended !== null) {
- const ATTENDED_YES = 'attended:yes';
- const ATTENDED_NO = 'attended:no';
- const key = 'CallAttended';
+ const key = 'call-attended';
seenKeys.add(key);
+
+ const getAttendedValues = (): FilterValue[] => {
+ const attended = queryFilters.state.include.callAttended;
+ if (attended === undefined || attended === null) return [];
+ return [
+ {
+ id: attended ? 'yes' : 'no',
+ label: attended ? 'Attended' : 'Unattended',
+ },
+ ];
+ };
+
filters.push(
- getOrCreateChip(key, () => ({
+ getOrCreateConsolidatedChip(key, () => ({
+ key,
categoryLabel: 'Attended',
- hideCategoryLabel: true,
- optionId: () =>
- queryFilters.state.include.callAttended
- ? ATTENDED_YES
- : ATTENDED_NO,
- optionLabel: () =>
- queryFilters.state.include.callAttended
- ? 'Attended'
- : 'Unattended',
- categoryOptions: [
- { id: ATTENDED_YES, label: 'Attended' },
- { id: ATTENDED_NO, label: 'Unattended' },
- ] as unknown as ActiveFilter['categoryOptions'],
+ values: getAttendedValues,
+ availableOptions: [
+ { id: 'yes', label: 'Attended' },
+ { id: 'no', label: 'Unattended' },
+ ],
multiple: false,
- isOptionActive: (optionId) =>
- optionId ===
- (queryFilters.state.include.callAttended
- ? ATTENDED_YES
- : ATTENDED_NO),
- onRemove: () =>
+ isValueActive: (id) =>
+ id === (queryFilters.state.include.callAttended ? 'yes' : 'no'),
+ onToggleValue: (id) =>
+ queryFilters.add({ include: { callAttended: id === 'yes' } }),
+ onRemoveAll: () =>
queryFilters.remove({
include: {
callAttended: queryFilters.state.include.callAttended,
},
}),
- onReplace: (newOptionId) =>
- queryFilters.add({
- include: {
- callAttended: newOptionId === ATTENDED_YES,
- },
- }),
}))
);
}
}
- // undefined importance means "All" — no chip.
+ // Email importance filter
if (
soup.predicates.isActive('email') &&
queryFilters.state.include.emailImportance !== undefined
) {
- const IMPORTANCE_SIGNAL = 'importance:signal';
- const IMPORTANCE_NOISE = 'importance:noise';
- const key = 'Importance';
+ const key = 'email-importance';
seenKeys.add(key);
+
+ const getImportanceValues = (): FilterValue[] => {
+ const importance = filterData().include.emailImportance;
+ if (importance === undefined) return [];
+ return [
+ {
+ id: importance ? 'signal' : 'noise',
+ label: importance ? 'Signal' : 'Noise',
+ },
+ ];
+ };
+
filters.push(
- getOrCreateChip(key, () => ({
+ getOrCreateConsolidatedChip(key, () => ({
+ key,
categoryLabel: 'Importance',
- optionId: () =>
- filterData().include.emailImportance
- ? IMPORTANCE_SIGNAL
- : IMPORTANCE_NOISE,
- optionLabel: () =>
- filterData().include.emailImportance ? 'Signal' : 'Noise',
- categoryOptions: [
- { id: IMPORTANCE_SIGNAL, label: 'Signal' },
- { id: IMPORTANCE_NOISE, label: 'Noise' },
- ] as unknown as ActiveFilter['categoryOptions'],
+ values: getImportanceValues,
+ availableOptions: [
+ { id: 'signal', label: 'Signal' },
+ { id: 'noise', label: 'Noise' },
+ ],
multiple: false,
- isOptionActive: (optionId) =>
- optionId ===
- (filterData().include.emailImportance
- ? IMPORTANCE_SIGNAL
- : IMPORTANCE_NOISE),
- onRemove: () =>
+ isValueActive: (id) =>
+ id ===
+ (filterData().include.emailImportance ? 'signal' : 'noise'),
+ onToggleValue: (id) =>
+ queryFilters.add({
+ include: { emailImportance: id === 'signal' },
+ }),
+ onRemoveAll: () =>
queryFilters.remove({
include: {
emailImportance: queryFilters.state.include.emailImportance,
},
}),
- onReplace: (newOptionId) =>
- queryFilters.add({
- include: { emailImportance: 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);
+ // Evict stale chips
+ for (const key of consolidatedChipCache.keys()) {
+ if (!seenKeys.has(key)) consolidatedChipCache.delete(key);
}
return filters;
});
- const isOptionActive = (optionId: string) => {
- return soup.predicates.isActive(optionId);
- };
-
const getFilterContext = (): FilterContext => ({
userId: currentUserId(),
assignees: assigneeFilter(),
@@ -485,33 +727,6 @@ export function useFilterRefinements() {
: filter.query;
};
- const removeFilter = (optionId: string) => {
- const query = getFilterQuery(optionId);
- batch(() => {
- soup.predicates.toggle({ or: [optionId as FilterID] });
- if (query) {
- queryFilters.remove(query);
- }
- });
- };
-
- const replaceFilter = (oldOptionId: string, newOptionId: string) => {
- const oldQuery = getFilterQuery(oldOptionId);
- const newQuery = getFilterQuery(newOptionId);
- batch(() => {
- if (soup.predicates.isActive(oldOptionId)) {
- soup.predicates.toggle({ or: [oldOptionId as FilterID] });
- }
-
- if (!soup.predicates.isActive(newOptionId)) {
- soup.predicates.toggle({ or: [newOptionId as FilterID] });
- }
-
- if (oldQuery) queryFilters.remove(oldQuery);
- if (newQuery) queryFilters.add(newQuery);
- });
- };
-
const resetToTabDefaults = () => {
const preset = currentPreset();
if (!preset) return;
@@ -532,9 +747,6 @@ export function useFilterRefinements() {
hasActiveRefinements,
resetToTabDefaults,
currentView,
- activeFiltersList,
- removeFilter,
- replaceFilter,
- isOptionActive,
+ consolidatedFiltersList,
};
}
diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsx
index bf484f130e..3416c971c5 100644
--- a/js/app/packages/core/component/EntityIcon.tsx
+++ b/js/app/packages/core/component/EntityIcon.tsx
@@ -322,12 +322,12 @@ const ICON_SIZES = {
} as const;
export const ICON_SIZE_CLASSES = {
- xs: `${ICON_SIZES.xs} flex justify-center overflow-hidden shrink-0`,
- sm: `${ICON_SIZES.sm} flex justify-center overflow-hidden shrink-0`,
- md: `${ICON_SIZES.md} flex justify-center overflow-hidden shrink-0`,
- lg: `${ICON_SIZES.lg} flex justify-center overflow-hidden shrink-0`,
- fill: `${ICON_SIZES.fill} flex justify-center overflow-hidden shrink-0`,
- shrinkFill: `${ICON_SIZES.fill} flex justify-center overflow-hidden`,
+ xs: `${ICON_SIZES.xs} flex items-center justify-center overflow-hidden shrink-0`,
+ sm: `${ICON_SIZES.sm} flex items-center justify-center overflow-hidden shrink-0`,
+ md: `${ICON_SIZES.md} flex items-center justify-center overflow-hidden shrink-0`,
+ lg: `${ICON_SIZES.lg} flex items-center justify-center overflow-hidden shrink-0`,
+ fill: `${ICON_SIZES.fill} flex items-center justify-center overflow-hidden shrink-0`,
+ shrinkFill: `${ICON_SIZES.fill} flex items-center justify-center overflow-hidden`,
} as const;
export type EntityIconProps = {
diff --git a/js/app/packages/ui/components/Dropdown.tsx b/js/app/packages/ui/components/Dropdown.tsx
index 602e4bf285..56ed693d1c 100644
--- a/js/app/packages/ui/components/Dropdown.tsx
+++ b/js/app/packages/ui/components/Dropdown.tsx
@@ -143,6 +143,7 @@ function DropdownItem(props: DropdownItemProps) {
return (
<KobalteDropdownMenu.Item
class={cn(ROW_CLASS, local.class)}
+ closeOnSelect={props.closeOnSelect}
{...rest}
/>
);