Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(dashboard-v2): query-first DSL filter for the dashboards list (#12046)

Ashwin Bhatkal8e4d7c68b3ae
diff --git a/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.module.scss b/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.module.scss
index f96a80f35c..4a54ee381a 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.module.scss
+++ b/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.module.scss
@@ -24,6 +24,12 @@
}
.headerZone {
+ // Sticks to the top of the scroll area so the heading + filters stay put while
+ // the results scroll beneath. Its own stacking context sits above the rows; the
+ // DSL suggestion popup (z-index 1000) still layers above everything.
+ position: sticky;
+ top: 0;
+ z-index: 5;
display: flex;
flex-direction: column;
gap: 14px;
@@ -50,7 +56,6 @@
:global(.ant-table-row:last-child)
:global(.ant-table-cell)
> div {
- border-radius: 0 0 6px 6px;
}
:global(.ant-pagination-item) {
diff --git a/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.tsx b/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.tsx
index e167bce829..37d6b515de 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/DashboardsList/DashboardsList.tsx
@@ -10,7 +10,10 @@ import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useAppContext } from 'providers/App/App';
import { toAPIError } from 'utils/errorUtils';
-import { useAccumulatedTags } from '../../hooks/useAccumulatedTags';
+import {
+ type TagPair,
+ useAccumulatedTags,
+} from '../../hooks/useAccumulatedTags';
import { useActiveView } from '../../hooks/useActiveView';
import { useCreatorOptions } from '../../hooks/useCreatorOptions';
import { useDashboardFilters } from '../../hooks/useDashboardFilters';
@@ -22,7 +25,7 @@ import {
import { useDashboardViewsStore } from '../../store/useDashboardViewsStore';
import { useDashboardsListVisibleColumnsStore } from '../../store/useVisibleColumnsStore';
import { BuiltinViewId } from '../../types';
-import type { SelectedTag, UpdatedWindow } from '../../types';
+import type { SuggestionSource } from '../../utils/dslSuggestions';
import type { DashboardListItem } from '../../utils/helpers';
import { applyClientView } from '../../utils/views';
import FilterZone from '../FilterZone/FilterZone';
@@ -50,17 +53,7 @@ function DashboardsList(): JSX.Element {
);
const canEdit = !!editDashboard;
- const {
- filters,
- query,
- isEmpty: filtersEmpty,
- setSearch,
- setCreatedBy,
- setUpdated,
- setTags,
- applyFilters,
- clearAll,
- } = useDashboardFilters();
+ const { query, isEmpty: filtersEmpty, setQuery } = useDashboardFilters();
const [sortColumn, setSortColumn] = useSortColumn();
const [sortOrder, setSortOrder] = useSortOrder();
const [page, setPage] = usePage();
@@ -80,8 +73,8 @@ function DashboardsList(): JSX.Element {
removeView,
renameView,
} = useActiveView({
- filters,
- applyFilters,
+ query,
+ setQuery,
userEmail: user.email,
sortColumn,
sortOrder,
@@ -95,38 +88,13 @@ function DashboardsList(): JSX.Element {
// Any filter change resets to the first page so the user isn't stranded on a
// now-out-of-range offset.
- const handleSearchChange = useCallback(
+ const handleQueryChange = useCallback(
(value: string): void => {
- setSearch(value);
- void setPage(1);
- },
- [setSearch, setPage],
- );
- const handleCreatedByChange = useCallback(
- (emails: string[]): void => {
- setCreatedBy(emails);
- void setPage(1);
- },
- [setCreatedBy, setPage],
- );
- const handleUpdatedChange = useCallback(
- (window: UpdatedWindow): void => {
- setUpdated(window);
+ setQuery(value);
void setPage(1);
},
- [setUpdated, setPage],
+ [setQuery, setPage],
);
- const handleTagsChange = useCallback(
- (tags: SelectedTag[]): void => {
- setTags(tags);
- void setPage(1);
- },
- [setTags, setPage],
- );
- const handleClearAll = useCallback((): void => {
- clearAll();
- void setPage(1);
- }, [clearAll, setPage]);
// View actions that change the result set reset pagination too.
const handleSelectView = useCallback(
@@ -195,6 +163,16 @@ function DashboardsList(): JSX.Element {
);
const total = clientView ? dashboards.length : (response?.data?.total ?? 0);
+ // Step back a page when a delete empties the current one, instead of showing nothing.
+ useEffect(() => {
+ if (clientView || isFetching) {
+ return;
+ }
+ if (page > 1 && dashboards.length === 0) {
+ void setPage(page - 1);
+ }
+ }, [clientView, isFetching, dashboards.length, page, setPage]);
+
// Authors present on the loaded page — a fallback for the creator filter until
// the org-wide user list resolves.
const pageAuthorEmails = useMemo<string[]>(
@@ -210,15 +188,34 @@ function DashboardsList(): JSX.Element {
});
// All key:value tags the API reports for the org's dashboards, powering the
- // Tags filter chip and DSL key suggestions. Accumulated across refetches so
- // previously-seen tags stay selectable even when a filtered page omits them.
- const responseTags = useMemo<SelectedTag[]>(
+ // DSL key/value autocomplete. Accumulated across refetches so previously-seen
+ // tags stay suggestable even when a filtered page omits them.
+ const responseTags = useMemo<TagPair[]>(
() =>
(response?.data?.tags ?? []).map((t) => ({ key: t.key, value: t.value })),
[response],
);
const availableTags = useAccumulatedTags(responseTags);
+ // Autocomplete data source: reserved keys from the response, tag keys/values
+ // accumulated across pages, and creator emails for `created_by` values.
+ const source = useMemo<SuggestionSource>(() => {
+ const tagValuesByKey: Record<string, string[]> = {};
+ const tagKeys = new Set<string>();
+ availableTags.forEach((t) => {
+ tagKeys.add(t.key);
+ const lower = t.key.toLowerCase();
+ (tagValuesByKey[lower] ??= []).push(t.value);
+ });
+ return {
+ reservedKeys: response?.data?.reservedKeywords,
+ tagKeys: Array.from(tagKeys),
+ tagValuesByKey,
+ creatorEmails: creatorOptions.map((o) => o.email),
+ currentUserEmail: user.email,
+ };
+ }, [availableTags, creatorOptions, response, user.email]);
+
const [isCreateOpen, setIsCreateOpen] = useState(false);
const visibleColumns = useDashboardsListVisibleColumnsStore(
(s) => s.visibleColumns,
@@ -306,18 +303,10 @@ function DashboardsList(): JSX.Element {
onCreate={openCreate}
/>
<FilterZone
- search={filters.search}
- createdBy={filters.createdBy}
- updated={filters.updated}
- tags={filters.tags}
- availableTags={availableTags}
+ query={query}
creatorOptions={creatorOptions}
- isEmpty={filtersEmpty}
- onSearchChange={handleSearchChange}
- onCreatedByChange={handleCreatedByChange}
- onUpdatedChange={handleUpdatedChange}
- onTagsChange={handleTagsChange}
- onClearAll={handleClearAll}
+ source={source}
+ onQueryChange={handleQueryChange}
/>
</div>
<div className={styles.viewContent}>
@@ -332,7 +321,7 @@ function DashboardsList(): JSX.Element {
errorMessage={errorMessage}
dashboards={dashboards}
activeViewId={activeViewId}
- searchValue={filters.search}
+ searchValue={query}
hasFilters={!filtersEmpty}
sortColumn={sortColumn}
onSortChange={onSortChange}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterChips.tsx b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterChips.tsx
index 916a8ef57a..38d5dd94a7 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterChips.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterChips.tsx
@@ -1,7 +1,4 @@
-import { useMemo } from 'react';
-import { Button } from '@signozhq/ui/button';
-import { DropdownMenuSimple, type MenuItem } from '@signozhq/ui/dropdown-menu';
-import { CalendarClock, ChevronDown, User } from '@signozhq/icons';
+import { Checkbox, Select } from 'antd';
import cx from 'classnames';
import type { UpdatedWindow } from '../../types';
@@ -21,6 +18,10 @@ const UPDATED_LABELS: Record<UpdatedWindow, string> = {
};
const UPDATED_WINDOWS: UpdatedWindow[] = ['any', 'today', '7d', '30d'];
+const UPDATED_OPTIONS = UPDATED_WINDOWS.map((w) => ({
+ value: w,
+ label: UPDATED_LABELS[w],
+}));
interface Props {
createdBy: string[];
@@ -28,6 +29,10 @@ interface Props {
creatorOptions: CreatorOption[];
onCreatedByChange: (emails: string[]) => void;
onUpdatedChange: (window: UpdatedWindow) => void;
+ // Run the staged draft — fired when a dropdown closes.
+ onApply: () => void;
+ // Clear all Created-by selections and run immediately.
+ onClearCreatedBy: () => void;
}
function FilterChips({
@@ -36,92 +41,57 @@ function FilterChips({
creatorOptions,
onCreatedByChange,
onUpdatedChange,
+ onApply,
+ onClearCreatedBy,
}: Props): JSX.Element {
- const createdByLabel = useMemo((): string => {
- if (createdBy.length === 0) {
- return 'Anyone';
- }
- if (createdBy.length === 1) {
- const match = creatorOptions.find((o) => o.email === createdBy[0]);
- return match?.label ?? createdBy[0];
- }
- return `${createdBy.length} people`;
- }, [createdBy, creatorOptions]);
+ const creatorOptionsData = creatorOptions.map((o) => ({
+ value: o.email,
+ label: o.label,
+ }));
- const createdByItems = useMemo<MenuItem[]>(() => {
- const items: MenuItem[] = creatorOptions.map((option) => ({
- type: 'checkbox',
- key: option.email,
- label: option.label,
- checked: createdBy.includes(option.email),
- onCheckedChange: (checked: boolean): void =>
- onCreatedByChange(
- checked
- ? [...createdBy, option.email]
- : createdBy.filter((e) => e !== option.email),
- ),
- }));
- if (createdBy.length > 0) {
- items.push({ type: 'divider', key: 'sep' });
- items.push({
- key: 'clear',
- label: 'Clear selection',
- onClick: (): void => onCreatedByChange([]),
- });
+ const runOnClose = (open: boolean): void => {
+ if (!open) {
+ onApply();
}
- return items;
- }, [creatorOptions, createdBy, onCreatedByChange]);
-
- const updatedItems = useMemo<MenuItem[]>(
- () => [
- {
- type: 'radio-group',
- value: updated,
- onChange: (value: string): void => onUpdatedChange(value as UpdatedWindow),
- children: UPDATED_WINDOWS.map((window) => ({
- type: 'radio',
- key: window,
- value: window,
- label: UPDATED_LABELS[window],
- })),
- },
- ],
- [updated, onUpdatedChange],
- );
+ };
return (
<div className={styles.chips}>
- <DropdownMenuSimple menu={{ items: createdByItems }} align="start">
- <Button
- variant="outlined"
- color="secondary"
- size="sm"
- prefix={<User size={12} />}
- suffix={<ChevronDown size={12} />}
- className={cx(styles.chip, {
- [styles.chipActive]: createdBy.length > 0,
- })}
- testId="dashboards-filter-created-by"
- >
- Created by: {createdByLabel}
- </Button>
- </DropdownMenuSimple>
-
- <DropdownMenuSimple menu={{ items: updatedItems }} align="start">
- <Button
- variant="outlined"
- color="secondary"
- size="sm"
- prefix={<CalendarClock size={12} />}
- suffix={<ChevronDown size={12} />}
- className={cx(styles.chip, {
- [styles.chipActive]: updated !== 'any',
- })}
- testId="dashboards-filter-updated"
- >
- Updated: {UPDATED_LABELS[updated]}
- </Button>
- </DropdownMenuSimple>
+ <Select
+ mode="multiple"
+ showSearch
+ allowClear
+ className={cx(styles.select, styles.selectWide)}
+ placeholder="Created by"
+ value={createdBy}
+ options={creatorOptionsData}
+ optionFilterProp="label"
+ maxTagCount={1}
+ menuItemSelectedIcon={null}
+ data-testid="dashboards-filter-created-by"
+ onClear={onClearCreatedBy}
+ optionRender={(option): JSX.Element => (
+ <div className={styles.creatorOption}>
+ <Checkbox
+ checked={createdBy.includes(option.value as string)}
+ className={styles.creatorCheck}
+ />
+ <span className={styles.creatorLabel}>{option.label}</span>
+ </div>
+ )}
+ onChange={(value): void => onCreatedByChange(value as string[])}
+ onDropdownVisibleChange={runOnClose}
+ />
+ <Select
+ showSearch
+ className={cx(styles.select, styles.selectNarrow)}
+ placeholder="Updated"
+ value={updated}
+ options={UPDATED_OPTIONS}
+ optionFilterProp="label"
+ data-testid="dashboards-filter-updated"
+ onChange={(value): void => onUpdatedChange(value as UpdatedWindow)}
+ />
</div>
);
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.module.scss b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.module.scss
index 61817977e7..c88957acda 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.module.scss
+++ b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.module.scss
@@ -37,14 +37,62 @@
display: flex;
align-items: center;
gap: 8px;
- flex-wrap: wrap;
+ // Keep the two dropdowns side by side; each is fixed-width so pills can't
+ // grow the trigger and wrap them onto separate lines.
+ flex-wrap: nowrap;
+}
+
+.select {
+ flex: none;
+
+ // Match the search bar: near-black background, --l2-border border.
+ :global(.ant-select-selector) {
+ background-color: var(--l1-background) !important;
+ border-color: var(--l2-border) !important;
+ }
+}
+
+// The single-select (Updated) is compact; the multi-select (Created-by) is wider
+// to fit a truncated pill + "+N" + clear.
+.selectNarrow {
+ width: 140px;
+}
+
+.selectWide {
+ width: 240px;
+
+ // Keep the pills on one line and let the first pill shrink + ellipsis to fill
+ // the available width (antd sets `flex: none` on tags, so allow the pill to
+ // shrink; keep the "+N" count and the search area intact).
+ :global(.ant-select-selection-overflow) {
+ flex-wrap: nowrap;
+ }
+
+ :global(.ant-select-selection-overflow-item) {
+ flex-shrink: 1;
+ min-width: 0;
+ }
+
+ :global(.ant-select-selection-overflow-item-rest),
+ :global(.ant-select-selection-overflow-item-suffix) {
+ flex-shrink: 0;
+ }
+}
+
+// Created-by option: a presentational checkbox + label (antd handles the toggle).
+.creatorOption {
+ display: flex;
+ align-items: center;
+ gap: 8px;
}
-.chip {
- font-size: var(--font-size-sm);
+.creatorCheck {
+ flex-shrink: 0;
+ pointer-events: none;
}
-.chipActive {
- border-color: var(--primary-background) !important;
- color: var(--l1-foreground) !important;
+.creatorLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.tsx b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.tsx
index 44d6fcb135..eabe8b060e 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/FilterZone.tsx
@@ -9,79 +9,108 @@ import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { X } from '@signozhq/icons';
-import { buildSuggestionKeys } from '../../utils/dslSuggestions';
-import type { SelectedTag, UpdatedWindow } from '../../types';
+import type { SuggestionSource } from '../../utils/dslSuggestions';
+import {
+ createdByClause,
+ parseReflectedClauses,
+ spliceClause,
+ updatedClause,
+} from '../../utils/filterQuery';
+import type { UpdatedWindow } from '../../types';
import SearchBar from '../SearchBar/SearchBar';
import FilterChips, { type CreatorOption } from './FilterChips';
-import TagsFilterChip from './TagsFilterChip';
import styles from './FilterZone.module.scss';
interface Props {
- search: string;
- createdBy: string[];
- updated: UpdatedWindow;
- tags: SelectedTag[];
- availableTags: SelectedTag[];
+ // The last-run query (source of truth for fetching + the dirty baseline).
+ query: string;
creatorOptions: CreatorOption[];
- isEmpty: boolean;
- onSearchChange: (value: string) => void;
- onCreatedByChange: (emails: string[]) => void;
- onUpdatedChange: (window: UpdatedWindow) => void;
- onTagsChange: (tags: SelectedTag[]) => void;
- onClearAll: () => void;
+ source: SuggestionSource;
+ // Commit (run) the draft — the only path that triggers a fetch.
+ onQueryChange: (value: string) => void;
// Rendered at the end of the search row (e.g. the New Dashboard action).
rightSlot?: ReactNode;
}
-// The filter command zone: name search + structured chips (created-by, updated)
-// + clear-all. Search is committed on submit/blur (matching the prior bar);
-// chips apply immediately.
+// The filter command zone. The query box is a DRAFT: typing and the Created-by /
+// Updated dropdowns all edit the draft (dropdowns splice their clause in); nothing
+// fetches until the draft is run (Cmd/Ctrl+Enter or the Run button). A dirty dot
+// signals unrun changes. The draft re-syncs when the last-run query changes
+// externally (view select, back/forward).
function FilterZone({
- search,
- createdBy,
- updated,
- tags,
- availableTags,
+ query,
creatorOptions,
- isEmpty,
- onSearchChange,
- onCreatedByChange,
- onUpdatedChange,
- onTagsChange,
- onClearAll,
+ source,
+ onQueryChange,
rightSlot,
}: Props): JSX.Element {
- const [searchInput, setSearchInput] = useState(search);
+ const [draft, setDraft] = useState(query);
+
+ useEffect(() => {
+ setDraft(query);
+ }, [query]);
+
+ const reflected = useMemo(() => parseReflectedClauses(draft), [draft]);
+ const dirty = draft.trim() !== query.trim();
+ const isEmpty = !draft.trim();
+
+ const run = useCallback((): void => {
+ const next = draft.trim();
+ if (next !== query) {
+ onQueryChange(next);
+ }
+ }, [draft, query, onQueryChange]);
+
+ // Created-by (multi-select) only STAGES its clause into the draft; the query runs
+ // when the dropdown closes (FilterChips fires onApply), not on each pick.
+ const handleCreatedByChange = useCallback((emails: string[]): void => {
+ setDraft((d) => spliceClause(d, 'created_by', createdByClause(emails)));
+ }, []);
- const suggestionKeys = useMemo(
- () => buildSuggestionKeys(availableTags),
- [availableTags],
+ // Updated (single-select) is a definitive single choice, so it splices AND runs
+ // immediately (with the fresh value, avoiding the async draft-state lag).
+ const handleUpdatedChange = useCallback(
+ (window: UpdatedWindow): void => {
+ const next = spliceClause(draft, 'updated_at', updatedClause(window));
+ setDraft(next);
+ const trimmed = next.trim();
+ if (trimmed !== query) {
+ onQueryChange(trimmed);
+ }
+ },
+ [draft, query, onQueryChange],
);
- // Keep the local input in sync with external search changes (applying a view,
- // clear-all, back/forward). User typing only mutates the local copy.
- useEffect(() => {
- setSearchInput(search);
- }, [search]);
+ // Clear-all on the Created-by select removes its clause and runs immediately.
+ const handleClearCreatedBy = useCallback((): void => {
+ const next = spliceClause(draft, 'created_by', null);
+ setDraft(next);
+ const trimmed = next.trim();
+ if (trimmed !== query) {
+ onQueryChange(trimmed);
+ }
+ }, [draft, query, onQueryChange]);
- const handleSubmit = useCallback((): void => {
- const next = searchInput.trim();
- if (next !== search) {
- onSearchChange(next);
+ // Clear resets the draft and runs immediately (empty query).
+ const handleClear = useCallback((): void => {
+ setDraft('');
+ if (query !== '') {
+ onQueryChange('');
}
- }, [searchInput, search, onSearchChange]);
+ }, [query, onQueryChange]);
return (
<div className={styles.filterZone}>
<div className={styles.searchRow}>
<div className={styles.searchInput}>
<SearchBar
- value={searchInput}
- placeholder={`Search with DSL — e.g. name contains "prod" AND env = "staging"`}
- suggestionKeys={suggestionKeys}
- onChange={setSearchInput}
- onSubmit={handleSubmit}
+ value={draft}
+ placeholder="DSL Filter — e.g. name CONTAINS 'api' AND env IN ['prod','staging']"
+ source={source}
+ dirty={dirty}
+ onChange={setDraft}
+ onSubmit={run}
/>
</div>
{rightSlot}
@@ -89,16 +118,13 @@ function FilterZone({
<div className={styles.filtersRow}>
<Typography.Text className={styles.filtersLabel}>Filters</Typography.Text>
<FilterChips
- createdBy={createdBy}
- updated={updated}
+ createdBy={reflected.createdBy}
+ updated={reflected.updated}
creatorOptions={creatorOptions}
- onCreatedByChange={onCreatedByChange}
- onUpdatedChange={onUpdatedChange}
- />
- <TagsFilterChip
- availableTags={availableTags}
- tags={tags}
- onTagsChange={onTagsChange}
+ onCreatedByChange={handleCreatedByChange}
+ onUpdatedChange={handleUpdatedChange}
+ onApply={run}
+ onClearCreatedBy={handleClearCreatedBy}
/>
{!isEmpty && (
<Button
@@ -106,7 +132,7 @@ function FilterZone({
color="primary"
size="sm"
prefix={<X size={12} />}
- onClick={onClearAll}
+ onClick={handleClear}
testId="dashboards-filter-clear"
>
Clear
diff --git a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/TagsFilterChip.tsx b/frontend/src/pages/DashboardsListPageV2/components/FilterZone/TagsFilterChip.tsx
deleted file mode 100644
index d17eacbdf5..0000000000
--- a/frontend/src/pages/DashboardsListPageV2/components/FilterZone/TagsFilterChip.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import { useMemo } from 'react';
-import { Button } from '@signozhq/ui/button';
-import { DropdownMenuSimple, type MenuItem } from '@signozhq/ui/dropdown-menu';
-import { ChevronDown, Tag } from '@signozhq/icons';
-import cx from 'classnames';
-
-import type { SelectedTag } from '../../types';
-
-import styles from './FilterZone.module.scss';
-
-interface Props {
- // All key:value tags the list API reports across the org's dashboards.
- availableTags: SelectedTag[];
- tags: SelectedTag[];
- onTagsChange: (tags: SelectedTag[]) => void;
-}
-
-const tagId = (tag: SelectedTag): string => `${tag.key}:${tag.value}`;
-
-function TagsFilterChip({
- availableTags,
- tags,
- onTagsChange,
-}: Props): JSX.Element {
- const selectedIds = useMemo(() => new Set(tags.map(tagId)), [tags]);
-
- const label = useMemo((): string => {
- if (tags.length === 0) {
- return 'Any';
- }
- if (tags.length === 1) {
- return tagId(tags[0]);
- }
- return `${tags.length} tags`;
- }, [tags]);
-
- const items = useMemo<MenuItem[]>(() => {
- const options: MenuItem[] = availableTags.map((tag) => {
- const id = tagId(tag);
- return {
- type: 'checkbox',
- key: id,
- label: id,
- checked: selectedIds.has(id),
- onCheckedChange: (checked: boolean): void =>
- onTagsChange(
- checked ? [...tags, tag] : tags.filter((t) => tagId(t) !== id),
- ),
- };
- });
- if (tags.length > 0) {
- options.push({ type: 'divider', key: 'sep' });
- options.push({
- key: 'clear',
- label: 'Clear selection',
- onClick: (): void => onTagsChange([]),
- });
- }
- return options;
- }, [availableTags, selectedIds, tags, onTagsChange]);
-
- return (
- <DropdownMenuSimple menu={{ items }} align="start">
- <Button
- variant="outlined"
- color="secondary"
- size="sm"
- prefix={<Tag size={12} />}
- suffix={<ChevronDown size={12} />}
- className={cx(styles.chip, { [styles.chipActive]: tags.length > 0 })}
- disabled={availableTags.length === 0}
- testId="dashboards-filter-tags"
- >
- Tags: {label}
- </Button>
- </DropdownMenuSimple>
- );
-}
-
-export default TagsFilterChip;
diff --git a/frontend/src/pages/DashboardsListPageV2/components/ListHeader/ListHeader.module.scss b/frontend/src/pages/DashboardsListPageV2/components/ListHeader/ListHeader.module.scss
index ef4df9e9db..6756fe82c6 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/ListHeader/ListHeader.module.scss
+++ b/frontend/src/pages/DashboardsListPageV2/components/ListHeader/ListHeader.module.scss
@@ -5,8 +5,7 @@
padding: 16px;
height: 44px;
flex-shrink: 0;
- border-radius: 6px 6px 0px 0px;
- border: 1px solid var(--l2-border);
+ border-bottom: 1px solid var(--l2-border);
background: var(--l1-background);
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.module.scss b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.module.scss
index 0f122203e9..fe9a5f2620 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.module.scss
+++ b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.module.scss
@@ -1,70 +1,203 @@
.wrapper {
position: relative;
width: 100%;
-}
-.input::placeholder {
- color: var(--l3-foreground);
-}
+ // --- CodeMirror internals, scoped to this component ---
+ :global(.cm-editor) {
+ background: transparent;
+ // The completion popup is an absolute child; keep it from being clipped.
+ overflow: visible;
+ }
+
+ // The query wraps (EditorView.lineWrapping), so no horizontal scrolling.
+ :global(.cm-scroller) {
+ overflow-x: hidden;
+ }
+
+ // DSL token colours.
+ :global(.cm-dsl-key) {
+ color: var(--bg-robin-400);
+ }
+
+ :global(.cm-dsl-op) {
+ color: var(--bg-vanilla-400);
+ }
+
+ :global(.cm-dsl-logic) {
+ color: var(--bg-sakura-400);
+ font-weight: var(--font-weight-medium);
+ }
+
+ :global(.cm-dsl-string) {
+ color: var(--bg-forest-400);
+ }
+
+ :global(.cm-dsl-value) {
+ color: var(--bg-amber-400);
+ }
+
+ // Completion popup — pinned to the input box (absolute, left:0/right:0) like the
+ // query builder's where-clause editor, not caret-anchored. A "SUGGESTIONS"
+ // header, a scrolling option list, and a keyboard-hint footer.
+ :global(.cm-tooltip.cm-tooltip-autocomplete) {
+ position: absolute !important;
+ top: calc(100% + 6px) !important;
+ left: 0 !important;
+ width: 100% !important;
+ z-index: 1000;
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ overflow: hidden;
+ border: 1px solid var(--l2-border);
+ border-radius: 6px;
+ background: var(--l1-background);
+ /* stylelint-disable-next-line local/prefer-css-variables -- dropdown shadow */
+ box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
+
+ &::before {
+ content: 'SUGGESTIONS';
+ padding: 12px 14px 8px;
+ font-size: 11px;
+ font-weight: var(--font-weight-medium);
+ line-height: 18px;
+ letter-spacing: 0.88px;
+ text-transform: uppercase;
+ color: var(--muted-foreground);
+ }
+
+ &::after {
+ content: '↑↓ to navigate · ↵ to apply · esc to dismiss';
+ padding: 10px 14px;
+ border-top: 1px solid var(--l1-border);
+ background: var(--l2-background);
+ font-size: var(--font-size-xs);
+ color: var(--l2-foreground);
+ }
+
+ & > ul {
+ flex: 1 1 auto;
+ // min-height:0 lets the list scroll inside the flex column instead of
+ // overflowing past the footer; width 100% so the scrollbar sits at the
+ // popup's right edge (CM otherwise caps the list width, leaving a gap).
+ min-height: 0;
+ width: 100% !important;
+ max-width: 100% !important;
+ max-height: 46vh;
+ margin: 0;
+ overflow-y: auto;
+
+ &::-webkit-scrollbar {
+ width: 6px;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ border-radius: 10px;
+ background: var(--l3-background);
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+ }
+
+ & > ul > li {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 11px 14px;
+ color: var(--l2-foreground);
+ line-height: 20px;
+
+ &[aria-selected='true'] {
+ background: var(--l2-background);
+ color: var(--l1-foreground);
+ }
+ }
+ }
-// Flatten the input's bottom corners while the dropdown is attached below it.
-.inputOpen {
- border-bottom-left-radius: 0;
- border-bottom-right-radius: 0;
+ :global(.cm-tooltip-autocomplete .cm-completionLabel) {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ // Right-aligned "field" / "tag" hint, as a pill (matches the QB type tags).
+ :global(.cm-tooltip-autocomplete .cm-completionDetail) {
+ flex-shrink: 0;
+ padding: 0 8px;
+ border-radius: 50px;
+ background: color-mix(in srgb, var(--l1-foreground) 10%, transparent);
+ font-style: normal;
+ font-size: var(--font-size-xs);
+ color: var(--l2-foreground);
+ text-transform: capitalize;
+ }
+
+ :global(.cm-completionIcon) {
+ display: none;
+ }
}
-.suggestions {
- position: absolute;
- top: 100%;
- left: 0;
- right: 0;
- z-index: 1000;
- display: flex;
- flex-direction: column;
- gap: 2px;
- max-height: 260px;
- overflow-y: auto;
- padding: 4px;
+// Input-like shell. The lead icon and Run button overlay the editor (absolute) so
+// the editor — and its full-width completion popup — spans the whole box.
+.field {
+ position: relative;
border: 1px solid var(--l2-border);
- border-top: none;
- border-radius: 0 0 6px 6px;
+ border-radius: 6px;
background: var(--l1-background);
- /* stylelint-disable-next-line local/prefer-css-variables -- matches the V2 dashboard dropdown shadow */
- box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
+
+ &:focus-within {
+ border-color: var(--bg-robin-500);
+ }
}
-.suggestion {
- display: flex;
- align-items: center;
- padding: 8px 10px;
- border: none;
- border-radius: 4px;
- background: transparent;
- color: var(--l2-foreground);
- font-family: 'Space Mono', monospace;
- font-size: var(--font-size-sm);
- text-align: left;
- cursor: pointer;
- transition: background 0.1s;
+.leadIcon {
+ position: absolute;
+ top: 11px;
+ left: 10px;
+ z-index: 1;
}
-.suggestionActive {
- background: var(--l2-background);
- color: var(--l1-foreground);
+.editor {
+ width: 100%;
}
.submit {
+ position: absolute;
+ top: 5px;
+ right: 6px;
+ z-index: 1;
display: inline-flex;
align-items: center;
gap: 6px;
+ // Bordered light pill so "Run query ⌘↵" reads as an actionable button, not stray
+ // text.
+ padding: 3px 8px;
+ border-radius: 6px;
+ border: 1px solid var(--l2-border);
+ background: var(--l2-background);
color: var(--bg-vanilla-400);
}
+// Unrun-changes indicator next to "Run query".
+.dirtyDot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--bg-robin-500);
+}
+
+// Keycap-styled shortcut so ⌘↵ reads as "press this", not decoration.
.cmdHint {
display: inline-flex;
align-items: center;
- gap: 2px;
- padding: 2px 4px;
+ gap: 3px;
+ padding: 1px 5px;
border-radius: 4px;
+ border: 1px solid var(--l1-border);
background: var(--l2-background);
+ color: var(--bg-vanilla-400);
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.tsx b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.tsx
index 97d0511f9b..6655dc7595 100644
--- a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.tsx
+++ b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/SearchBar.tsx
@@ -1,22 +1,24 @@
+import { type MouseEvent, useMemo, useRef } from 'react';
import {
- ChangeEvent,
- KeyboardEvent,
- MouseEvent,
- useMemo,
- useState,
-} from 'react';
+ autocompletion,
+ closeCompletion,
+ completionKeymap,
+ startCompletion,
+} from '@codemirror/autocomplete';
import { Button } from '@signozhq/ui/button';
-import { Input } from '@signozhq/ui/input';
import { Color } from '@signozhq/design-tokens';
import { ChevronUp, Command, CornerDownLeft, Search } from '@signozhq/icons';
-import cx from 'classnames';
+import CodeMirror, {
+ EditorView,
+ keymap,
+ Prec,
+ type ReactCodeMirrorRef,
+} from '@uiw/react-codemirror';
import { getUserOperatingSystem, UserOperatingSystem } from 'utils/getUserOS';
-import {
- applyKeySuggestion,
- getActiveKeyToken,
- matchKeys,
-} from '../../utils/dslSuggestions';
+import type { SuggestionSource } from '../../utils/dslSuggestions';
+import { dslCompletionSource } from './dslCompletions';
+import { dslHighlight } from './dslHighlight';
import styles from './SearchBar.module.scss';
@@ -25,139 +27,160 @@ interface Props {
onChange: (value: string) => void;
onSubmit: () => void;
placeholder?: string;
- // Keys offered as you type (reserved DSL columns + tag keys from the API).
- suggestionKeys?: string[];
+ source?: SuggestionSource;
+ // The draft differs from the last-run query — shows a "run to apply" hint.
+ dirty?: boolean;
}
+const EMPTY_SOURCE: SuggestionSource = {
+ tagKeys: [],
+ tagValuesByKey: {},
+ creatorEmails: [],
+};
+
+// Token colours come from `.cm-dsl-*` classes (SearchBar.module.scss); this only
+// handles layout — transparent background, monospace, single line.
+const editorTheme = EditorView.theme({
+ '&': { fontSize: '13px', backgroundColor: 'transparent' },
+ '&.cm-focused': { outline: 'none' },
+ '.cm-content': {
+ // Leave room for the overlaid lead icon (left) and Run button (right).
+ padding: '8px 120px 8px 30px',
+ fontFamily: "'Space Mono', monospace",
+ color: 'var(--l1-foreground)',
+ caretColor: 'var(--l1-foreground)',
+ },
+ '.cm-line': { padding: '0' },
+ '.cm-scroller': { fontFamily: 'inherit', lineHeight: '1.5' },
+ '.cm-placeholder': { color: 'var(--l3-foreground)' },
+});
+
+const BASIC_SETUP = {
+ lineNumbers: false,
+ foldGutter: false,
+ highlightActiveLine: false,
+ highlightActiveLineGutter: false,
+ highlightSelectionMatches: false,
+ bracketMatching: false,
+ closeBrackets: false,
+ autocompletion: false,
+ // Use the browser's native caret so it blinks (a CM-drawn cursor needs extra
+ // styling and doesn't blink by default).
+ drawSelection: false,
+} as const;
+
function SearchBar({
value,
onChange,
onSubmit,
- placeholder = "Search with DSL (e.g. name CONTAINS 'foo')",
- suggestionKeys = [],
+ placeholder = "Filter with DSL (e.g. name CONTAINS 'foo')",
+ source = EMPTY_SOURCE,
+ dirty = false,
}: Props): JSX.Element {
- const [focused, setFocused] = useState(false);
- // -1 means nothing is highlighted, so Enter submits the typed query rather
- // than picking a suggestion (arrow keys engage selection).
- const [highlighted, setHighlighted] = useState(-1);
-
const isMac = getUserOperatingSystem() === UserOperatingSystem.MACOS;
+ const editorRef = useRef<ReactCodeMirrorRef>(null);
- const active = useMemo(() => getActiveKeyToken(value), [value]);
- const suggestions = useMemo(
- () => (active ? matchKeys(suggestionKeys, active.token) : []),
- [active, suggestionKeys],
- );
- const showSuggestions = focused && suggestions.length > 0;
-
- const pickSuggestion = (key: string): void => {
- if (active) {
- onChange(applyKeySuggestion(value, active, key));
- }
- setHighlighted(-1);
- };
+ // Refs so the (memoised, stable) extensions always see the latest values.
+ const sourceRef = useRef(source);
+ sourceRef.current = source;
+ const onSubmitRef = useRef(onSubmit);
+ onSubmitRef.current = onSubmit;
- const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>): void => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
- e.preventDefault();
- onSubmit();
- return;
- }
- if (showSuggestions && e.key === 'ArrowDown') {
- e.preventDefault();
- setHighlighted((h) => Math.min(h + 1, suggestions.length - 1));
- return;
- }
- if (showSuggestions && e.key === 'ArrowUp') {
- e.preventDefault();
- setHighlighted((h) => Math.max(h - 1, 0));
- return;
- }
- if (e.key === 'Enter') {
- if (showSuggestions && highlighted >= 0) {
- e.preventDefault();
- pickSuggestion(suggestions[highlighted]);
- } else {
- onSubmit();
- }
- return;
- }
- if (e.key === 'Escape') {
- setFocused(false);
- setHighlighted(-1);
- }
- };
+ const extensions = useMemo(
+ () => [
+ dslHighlight,
+ editorTheme,
+ // Wrap a long query onto the next line instead of scrolling horizontally.
+ EditorView.lineWrapping,
+ autocompletion({
+ override: [dslCompletionSource(() => sourceRef.current)],
+ closeOnBlur: true,
+ activateOnTyping: true,
+ maxRenderedOptions: 100,
+ icons: false,
+ }),
+ // Open the suggestions on focus/click (not only while typing), so a click
+ // into the box immediately shows the key list.
+ EditorView.domEventHandlers({
+ focus: (_event, view): boolean => {
+ startCompletion(view);
+ return false;
+ },
+ click: (_event, view): boolean => {
+ startCompletion(view);
+ return false;
+ },
+ }),
+ Prec.highest(
+ keymap.of([
+ ...completionKeymap,
+ { key: 'Escape', run: closeCompletion },
+ // Enter accepts an open suggestion (via completionKeymap above); with
+ // none open it is a no-op — it never runs the query or inserts a newline.
+ { key: 'Enter', preventDefault: true, run: (): boolean => true },
+ { key: 'Shift-Enter', preventDefault: true, run: (): boolean => true },
+ {
+ key: 'Mod-Enter',
+ preventDefault: true,
+ run: (): boolean => {
+ onSubmitRef.current();
+ return true;
+ },
+ },
+ ]),
+ ),
+ ],
+ [],
+ );
return (
<div className={styles.wrapper}>
- <Input
- className={cx(styles.input, { [styles.inputOpen]: showSuggestions })}
- placeholder={placeholder}
- prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
- suffix={
- <Button
- variant="ghost"
- color="secondary"
- size="sm"
- className={styles.submit}
- aria-label="Run search"
- testId="dashboards-list-search-submit"
- onMouseDown={(e: MouseEvent<HTMLButtonElement>): void => {
- // Prevent the input's blur from firing first and double-submitting.
- e.preventDefault();
- }}
- onClick={onSubmit}
- >
- Run query
- <span className={styles.cmdHint}>
- {isMac ? (
- <Command size={12} color={Color.BG_VANILLA_400} />
- ) : (
- <ChevronUp size={12} color={Color.BG_VANILLA_400} />
- )}
- <CornerDownLeft size={12} color={Color.BG_VANILLA_400} />
- </span>
- </Button>
- }
- value={value}
- testId="dashboards-list-search"
- onChange={(e: ChangeEvent<HTMLInputElement>): void => {
- onChange(e.target.value);
- setHighlighted(-1);
- }}
- onFocus={(): void => setFocused(true)}
- onBlur={(): void => {
- setFocused(false);
- setHighlighted(-1);
- onSubmit();
- }}
- onKeyDown={handleKeyDown}
- />
- {showSuggestions && (
- <div
- className={styles.suggestions}
- data-testid="dashboards-list-search-suggestions"
+ <div className={styles.field}>
+ <Search
+ size={12}
+ color={Color.BG_VANILLA_400}
+ className={styles.leadIcon}
+ />
+ <CodeMirror
+ ref={editorRef}
+ className={styles.editor}
+ value={value}
+ placeholder={placeholder}
+ extensions={extensions}
+ basicSetup={BASIC_SETUP}
+ indentWithTab={false}
+ data-testid="dashboards-list-search"
+ onChange={(next): void => onChange(next.replace(/\n/g, ' '))}
+ />
+ <Button
+ variant="ghost"
+ color="secondary"
+ size="sm"
+ className={styles.submit}
+ aria-label="Run search"
+ testId="dashboards-list-search-submit"
+ onMouseDown={(e: MouseEvent<HTMLButtonElement>): void => {
+ e.preventDefault();
+ }}
+ onClick={onSubmit}
>
- {suggestions.map((key, index) => (
- <button
- key={key}
- type="button"
- className={cx(styles.suggestion, {
- [styles.suggestionActive]: index === highlighted,
- })}
- data-testid={`dashboards-list-search-suggestion-${key}`}
- onMouseEnter={(): void => setHighlighted(index)}
- onMouseDown={(e: MouseEvent<HTMLButtonElement>): void => {
- // Keep focus on the input so blur doesn't submit before we update.
- e.preventDefault();
- }}
- onClick={(): void => pickSuggestion(key)}
- >
- {key}
- </button>
- ))}
- </div>
- )}
+ {dirty && (
+ <span
+ className={styles.dirtyDot}
+ data-testid="dashboards-list-search-dirty"
+ />
+ )}
+ Run query
+ <span className={styles.cmdHint}>
+ {isMac ? (
+ <Command size={12} color={Color.BG_VANILLA_400} />
+ ) : (
+ <ChevronUp size={12} color={Color.BG_VANILLA_400} />
+ )}
+ <CornerDownLeft size={12} color={Color.BG_VANILLA_400} />
+ </span>
+ </Button>
+ </div>
</div>
);
}
diff --git a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslCompletions.ts b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslCompletions.ts
new file mode 100644
index 0000000000..b17a28b2be
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslCompletions.ts
@@ -0,0 +1,50 @@
+// Bridges our stage-aware DSL suggestion engine into CodeMirror's autocompletion,
+// so the query box gets keyboard navigation + a scrollable popup for free.
+import {
+ type CompletionContext,
+ type CompletionResult,
+ startCompletion,
+} from '@codemirror/autocomplete';
+import type { EditorView } from '@codemirror/view';
+
+import {
+ getSuggestions,
+ type SuggestionSource,
+} from '../../utils/dslSuggestions';
+
+// `getSource` is a getter so the freshest tags/users (which load async) are read
+// on every keystroke.
+export const dslCompletionSource =
+ (getSource: () => SuggestionSource) =>
+ (context: CompletionContext): CompletionResult | null => {
+ const query = context.state.doc.toString();
+ const { items, ctx } = getSuggestions(query, context.pos, getSource());
+ if (items.length === 0) {
+ return null;
+ }
+ return {
+ from: ctx.replaceStart,
+ to: ctx.replaceEnd,
+ // We already filtered/ranked in getSuggestions; keep CodeMirror from
+ // re-filtering by the typed text.
+ filter: false,
+ options: items.map((item) => ({
+ label: item.label,
+ type: item.kind,
+ detail: item.detail,
+ // Insert the raw text (not the display label) and re-open completion so
+ // key -> operator -> value chains without extra keystrokes.
+ apply: (view: EditorView, _c, from: number, to: number): void => {
+ view.dispatch({
+ changes: { from, to, insert: item.insertText },
+ // caretOffset lands the caret inside a `[...]` list (before its
+ // closing bracket) so multi-select can continue.
+ selection: {
+ anchor: from + item.insertText.length - (item.caretOffset ?? 0),
+ },
+ });
+ startCompletion(view);
+ },
+ })),
+ };
+ };
diff --git a/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslHighlight.ts b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslHighlight.ts
new file mode 100644
index 0000000000..6e7e96f19e
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/components/SearchBar/dslHighlight.ts
@@ -0,0 +1,96 @@
+// CodeMirror syntax highlighting for the dashboards-list DSL, driven by the same
+// tokenizer used for autocomplete (dslTokenizer). Each key / operator / value /
+// AND-OR span gets a `cm-dsl-*` class coloured in SearchBar.module.scss.
+import { RangeSetBuilder } from '@codemirror/state';
+import {
+ Decoration,
+ type DecorationSet,
+ type EditorView,
+ ViewPlugin,
+ type ViewUpdate,
+} from '@codemirror/view';
+
+import { scanTerm, splitTopLevelTerms } from '../../utils/dslTokenizer';
+
+const KEY = Decoration.mark({ class: 'cm-dsl-key' });
+const OP = Decoration.mark({ class: 'cm-dsl-op' });
+const STRING = Decoration.mark({ class: 'cm-dsl-string' });
+const VALUE = Decoration.mark({ class: 'cm-dsl-value' });
+const LOGIC = Decoration.mark({ class: 'cm-dsl-logic' });
+
+interface Marked {
+ from: number;
+ to: number;
+ deco: Decoration;
+}
+
+const collectRanges = (query: string): Marked[] => {
+ const ranges: Marked[] = [];
+ const terms = splitTopLevelTerms(query);
+ terms.forEach((term, i) => {
+ // The AND/OR keyword sits in the gap before this term.
+ if (i > 0 && term.precedingJoiner) {
+ const prevEnd = terms[i - 1].end;
+ const m = /\b(?:AND|OR)\b/i.exec(query.slice(prevEnd, term.start));
+ if (m) {
+ ranges.push({
+ from: prevEnd + m.index,
+ to: prevEnd + m.index + m[0].length,
+ deco: LOGIC,
+ });
+ }
+ }
+ const scan = scanTerm(term.text);
+ const base = term.start;
+ if (scan.key) {
+ ranges.push({
+ from: base + scan.key.start,
+ to: base + scan.key.end,
+ deco: KEY,
+ });
+ }
+ if (scan.operator) {
+ ranges.push({
+ from: base + scan.operator.start,
+ to: base + scan.operator.end,
+ deco: OP,
+ });
+ }
+ if (scan.value) {
+ const isString = /^['"]/.test(scan.value.text.trim());
+ ranges.push({
+ from: base + scan.value.start,
+ to: base + scan.value.end,
+ deco: isString ? STRING : VALUE,
+ });
+ }
+ });
+ return ranges
+ .filter((r) => r.to > r.from)
+ .sort((a, b) => a.from - b.from || a.to - b.to);
+};
+
+const buildDecorations = (view: EditorView): DecorationSet => {
+ const builder = new RangeSetBuilder<Decoration>();
+ collectRanges(view.state.doc.toString()).forEach((r) => {
+ builder.add(r.from, r.to, r.deco);
+ });
+ return builder.finish();
+};
+
+export const dslHighlight = ViewPlugin.fromClass(
+ class {
+ decorations: DecorationSet;
+
+ constructor(view: EditorView) {
+ this.decorations = buildDecorations(view);
+ }
+
+ update(update: ViewUpdate): void {
+ if (update.docChanged || update.viewportChanged) {
+ this.decorations = buildDecorations(update.view);
+ }
+ }
+ },
+ { decorations: (plugin): DecorationSet => plugin.decorations },
+);
diff --git a/frontend/src/pages/DashboardsListPageV2/hooks/useAccumulatedTags.ts b/frontend/src/pages/DashboardsListPageV2/hooks/useAccumulatedTags.ts
index 53ac82c4d0..ea80271d0d 100644
--- a/frontend/src/pages/DashboardsListPageV2/hooks/useAccumulatedTags.ts
+++ b/frontend/src/pages/DashboardsListPageV2/hooks/useAccumulatedTags.ts
@@ -1,14 +1,18 @@
import { useEffect, useState } from 'react';
-import type { SelectedTag } from '../types';
+// A key:value tag pair the list API reports across the org's dashboards.
+export interface TagPair {
+ key: string;
+ value: string;
+}
-const tagId = (tag: SelectedTag): string => `${tag.key}:${tag.value}`;
+const tagId = (tag: TagPair): string => `${tag.key}:${tag.value}`;
// The list response only reports the tags present in the current (filtered) page,
-// so tags vanish from the filter options as results narrow. Accumulate every tag
-// we've ever seen so previously-surfaced tags stay selectable across refetches.
-export function useAccumulatedTags(responseTags: SelectedTag[]): SelectedTag[] {
- const [tags, setTags] = useState<SelectedTag[]>([]);
+// so tags vanish from the suggestions as results narrow. Accumulate every tag
+// we've ever seen so previously-surfaced tags stay suggestable across refetches.
+export function useAccumulatedTags(responseTags: TagPair[]): TagPair[] {
+ const [tags, setTags] = useState<TagPair[]>([]);
useEffect(() => {
if (responseTags.length === 0) {
diff --git a/frontend/src/pages/DashboardsListPageV2/hooks/useActiveView.ts b/frontend/src/pages/DashboardsListPageV2/hooks/useActiveView.ts
index 9674687604..6d43ef88ec 100644
--- a/frontend/src/pages/DashboardsListPageV2/hooks/useActiveView.ts
+++ b/frontend/src/pages/DashboardsListPageV2/hooks/useActiveView.ts
@@ -1,21 +1,17 @@
import { useCallback, useMemo } from 'react';
-import { parseAsString, useQueryState, type Options } from 'nuqs';
+import { type Options, parseAsString, useQueryState } from 'nuqs';
import type {
DashboardtypesListOrderDTO,
DashboardtypesListSortDTO,
} from 'api/generated/services/sigNoz.schemas';
-import {
- areFilterStatesEqual,
- DEFAULT_FILTER_STATE,
- filterStateToQuery,
-} from '../utils/filterQuery';
+import { areQueriesEqual } from '../utils/filterQuery';
import { BuiltinViewId } from '../types';
-import type { DashboardFilterState, SavedView } from '../types';
+import type { SavedView } from '../types';
import {
BUILTIN_VIEWS,
- builtinViewSnapshot,
type BuiltinView,
+ builtinViewQuery,
isClientView,
} from '../utils/views';
import { useSavedViews } from './useSavedViews';
@@ -23,8 +19,8 @@ import { useSavedViews } from './useSavedViews';
const opts: Options = { history: 'push' };
interface UseActiveViewArgs {
- filters: DashboardFilterState;
- applyFilters: (next: DashboardFilterState) => void;
+ query: string;
+ setQuery: (next: string) => void;
userEmail: string;
sortColumn: DashboardtypesListSortDTO;
sortOrder: DashboardtypesListOrderDTO;
@@ -38,7 +34,7 @@ export interface UseActiveViewResult {
customViews: SavedView[];
customViewsLoading: boolean;
isCustomActive: boolean;
- // Current filters diverge from the active view's canonical snapshot.
+ // The current query diverges from the active view's canonical query.
isModified: boolean;
// Whether the active view constrains the list client-side (pinned/recent).
clientView: boolean;
@@ -50,19 +46,13 @@ export interface UseActiveViewResult {
renameView: (id: string, name: string) => void;
}
-// The canonical filter snapshot a saved view "is": the backend stores a flat
-// query, so a view folds entirely into the search box with empty chips.
-const customSnapshot = (view: SavedView): DashboardFilterState => ({
- ...DEFAULT_FILTER_STATE,
- search: view.query,
-});
-
// Orchestrates the active view: which view is selected (URL `view` param),
-// merging built-in + org-shared saved views, applying a view's snapshot on
-// select, dirty detection, and save/reset/delete via the Views API.
+// merging built-in + org-shared saved views, applying a view's query on select,
+// dirty detection, and save/reset/delete via the Views API. A view now simply
+// "is" a query string, so dirty detection is a trimmed string compare.
export function useActiveView({
- filters,
- applyFilters,
+ query,
+ setQuery,
userEmail,
sortColumn,
sortOrder,
@@ -87,35 +77,34 @@ export function useActiveView({
[customViews, activeViewId],
);
- // The filter state the active view "is" — used to detect divergence.
- const canonicalSnapshot = useMemo<DashboardFilterState | null>(
+ // The query the active view "is" — used to detect divergence.
+ const canonicalQuery = useMemo<string | null>(
() =>
activeCustom
- ? customSnapshot(activeCustom)
- : builtinViewSnapshot(activeViewId, userEmail),
+ ? activeCustom.query
+ : builtinViewQuery(activeViewId, userEmail),
[activeCustom, activeViewId, userEmail],
);
- const isModified = canonicalSnapshot
- ? !areFilterStatesEqual(filters, canonicalSnapshot)
- : false;
+ const isModified =
+ canonicalQuery !== null && !areQueriesEqual(query, canonicalQuery);
const selectView = useCallback(
(id: string): void => {
void setActiveViewId(id);
const custom = customViews.find((v) => v.id === id);
if (custom) {
- applyFilters(customSnapshot(custom));
+ setQuery(custom.query);
setSortColumn(custom.sort);
setSortOrder(custom.order);
return;
}
- applyFilters(builtinViewSnapshot(id, userEmail) ?? DEFAULT_FILTER_STATE);
+ setQuery(builtinViewQuery(id, userEmail) ?? '');
},
[
setActiveViewId,
customViews,
- applyFilters,
+ setQuery,
userEmail,
setSortColumn,
setSortOrder,
@@ -124,9 +113,6 @@ export function useActiveView({
const saveView = useCallback(
(name: string): void => {
- // The active view's clause already lives in the filter state (e.g. Locked
- // seeds `locked = true` into search), so the chips fold into one query.
- const query = filterStateToQuery(filters);
void (async (): Promise<void> => {
const created = await createView({
name,
@@ -136,55 +122,44 @@ export function useActiveView({
});
if (created) {
void setActiveViewId(created.id);
- // Re-apply the folded representation so the new view isn't
- // immediately flagged as modified.
- applyFilters(customSnapshot(created));
}
})();
},
- [filters, createView, sortColumn, sortOrder, setActiveViewId, applyFilters],
+ [query, createView, sortColumn, sortOrder, setActiveViewId],
);
const saveActiveView = useCallback((): void => {
if (!activeCustom) {
return;
}
- const query = filterStateToQuery(filters);
updateView(activeCustom.id, {
name: activeCustom.name,
query,
sort: sortColumn,
order: sortOrder,
});
- applyFilters({ ...DEFAULT_FILTER_STATE, search: query });
- }, [activeCustom, filters, updateView, sortColumn, sortOrder, applyFilters]);
+ }, [activeCustom, query, updateView, sortColumn, sortOrder]);
const resetView = useCallback((): void => {
- if (!canonicalSnapshot) {
+ if (canonicalQuery === null) {
return;
}
- applyFilters(canonicalSnapshot);
+ setQuery(canonicalQuery);
if (activeCustom) {
setSortColumn(activeCustom.sort);
setSortOrder(activeCustom.order);
}
- }, [
- canonicalSnapshot,
- applyFilters,
- activeCustom,
- setSortColumn,
- setSortOrder,
- ]);
+ }, [canonicalQuery, setQuery, activeCustom, setSortColumn, setSortOrder]);
const removeView = useCallback(
(id: string): void => {
deleteView(id);
if (activeViewId === id) {
void setActiveViewId(BuiltinViewId.All);
- applyFilters(DEFAULT_FILTER_STATE);
+ setQuery('');
}
},
- [deleteView, activeViewId, setActiveViewId, applyFilters],
+ [deleteView, activeViewId, setActiveViewId, setQuery],
);
// Rename only touches the view's name; its stored query/sort/order are preserved.
diff --git a/frontend/src/pages/DashboardsListPageV2/hooks/useDashboardFilters.ts b/frontend/src/pages/DashboardsListPageV2/hooks/useDashboardFilters.ts
index 7f8ff777d0..02eab44cdb 100644
--- a/frontend/src/pages/DashboardsListPageV2/hooks/useDashboardFilters.ts
+++ b/frontend/src/pages/DashboardsListPageV2/hooks/useDashboardFilters.ts
@@ -1,138 +1,33 @@
-import { useCallback, useMemo } from 'react';
-import {
- parseAsArrayOf,
- parseAsString,
- parseAsStringLiteral,
- useQueryState,
- type Options,
-} from 'nuqs';
+import { useCallback } from 'react';
+import { type Options, parseAsString, useQueryState } from 'nuqs';
-import {
- DEFAULT_FILTER_STATE,
- filterStateToQuery,
- isFilterStateEmpty,
-} from '../utils/filterQuery';
-import type {
- DashboardFilterState,
- SelectedTag,
- UpdatedWindow,
-} from '../types';
-
-const UPDATED_WINDOWS: UpdatedWindow[] = ['any', 'today', '7d', '30d'];
+import { isQueryEmpty } from '../utils/filterQuery';
const opts: Options = { history: 'push' };
-// Tags are carried in the URL as `key:value` strings; split on the first colon.
-const parseTag = (raw: string): SelectedTag | null => {
- const idx = raw.indexOf(':');
- if (idx <= 0) {
- return null;
- }
- return { key: raw.slice(0, idx), value: raw.slice(idx + 1) };
-};
-
-const serializeTag = (tag: SelectedTag): string => `${tag.key}:${tag.value}`;
-
export interface UseDashboardFiltersResult {
- filters: DashboardFilterState;
- // The backend list-filter `query` string derived from the current filters.
+ // The last-run backend list-filter query string — the source of truth for
+ // fetching. The editable draft lives in FilterZone; this only changes when a
+ // query is actually run (or a view is applied).
query: string;
isEmpty: boolean;
- setSearch: (value: string) => void;
- setCreatedBy: (emails: string[]) => void;
- setUpdated: (window: UpdatedWindow) => void;
- setTags: (tags: SelectedTag[]) => void;
- // Replace the whole filter state at once — used when applying a saved view.
- applyFilters: (next: DashboardFilterState) => void;
- clearAll: () => void;
+ setQuery: (value: string) => void;
}
-// Owns the dashboards-list filter state, synced to the URL (shareable links,
-// back/forward) and projected into the backend `query` string. Sort/order/page
-// live in their own query-param hooks; this hook is filters-only.
+// Owns the run dashboards-list query, synced to the URL (shareable links,
+// back/forward). Sort/order/page live in their own query-param hooks.
export function useDashboardFilters(): UseDashboardFiltersResult {
- const [search, setSearchState] = useQueryState(
- 'search',
+ const [query, setQueryState] = useQueryState(
+ 'query',
parseAsString.withDefault('').withOptions(opts),
);
- const [createdBy, setCreatedByState] = useQueryState(
- 'createdBy',
- parseAsArrayOf(parseAsString).withDefault([]).withOptions(opts),
- );
- const [updated, setUpdatedState] = useQueryState(
- 'updated',
- parseAsStringLiteral(UPDATED_WINDOWS).withDefault('any').withOptions(opts),
- );
- const [tagStrings, setTagStringsState] = useQueryState(
- 'tags',
- parseAsArrayOf(parseAsString).withDefault([]).withOptions(opts),
- );
- const tags = useMemo<SelectedTag[]>(
- () => tagStrings.map(parseTag).filter((t): t is SelectedTag => t !== null),
- [tagStrings],
- );
-
- const filters = useMemo<DashboardFilterState>(
- () => ({ search, createdBy, updated, tags }),
- [search, createdBy, updated, tags],
- );
-
- const query = useMemo(() => filterStateToQuery(filters), [filters]);
-
- const setSearch = useCallback(
+ const setQuery = useCallback(
(value: string): void => {
- void setSearchState(value);
- },
- [setSearchState],
- );
-
- const setCreatedBy = useCallback(
- (emails: string[]): void => {
- void setCreatedByState(emails.length ? emails : null);
- },
- [setCreatedByState],
- );
-
- const setUpdated = useCallback(
- (window: UpdatedWindow): void => {
- void setUpdatedState(window);
- },
- [setUpdatedState],
- );
-
- const setTags = useCallback(
- (next: SelectedTag[]): void => {
- void setTagStringsState(next.length ? next.map(serializeTag) : null);
- },
- [setTagStringsState],
- );
-
- const applyFilters = useCallback(
- (next: DashboardFilterState): void => {
- void setSearchState(next.search || null);
- void setCreatedByState(next.createdBy.length ? next.createdBy : null);
- void setUpdatedState(next.updated);
- void setTagStringsState(
- next.tags.length ? next.tags.map(serializeTag) : null,
- );
+ void setQueryState(value.trim() ? value : null);
},
- [setSearchState, setCreatedByState, setUpdatedState, setTagStringsState],
+ [setQueryState],
);
- const clearAll = useCallback((): void => {
- applyFilters(DEFAULT_FILTER_STATE);
- }, [applyFilters]);
-
- return {
- filters,
- query,
- isEmpty: isFilterStateEmpty(filters),
- setSearch,
- setCreatedBy,
- setUpdated,
- setTags,
- applyFilters,
- clearAll,
- };
+ return { query, isEmpty: isQueryEmpty(query), setQuery };
}
diff --git a/frontend/src/pages/DashboardsListPageV2/types.ts b/frontend/src/pages/DashboardsListPageV2/types.ts
index de61964ba4..398fc342f1 100644
--- a/frontend/src/pages/DashboardsListPageV2/types.ts
+++ b/frontend/src/pages/DashboardsListPageV2/types.ts
@@ -3,27 +3,9 @@ import type {
DashboardtypesListSortDTO,
} from 'api/generated/services/sigNoz.schemas';
-// Relative "updated within" windows offered by the Updated filter chip.
+// Relative "updated within" windows offered by the Updated filter dropdown.
export type UpdatedWindow = 'any' | 'today' | '7d' | '30d';
-// A tag selected in the Tags filter chip — a concrete key:value pair drawn from
-// the tags the list API reports across the org's dashboards.
-export interface SelectedTag {
- key: string;
- value: string;
-}
-
-// The user-controllable filter state a view captures. `search` is a raw filter
-// DSL fragment the user types; the structured chips (created-by, updated, tags)
-// are AND-ed onto it. Sort/order are handled separately via URL query params and
-// are not part of a view snapshot.
-export interface DashboardFilterState {
- search: string;
- createdBy: string[]; // emails (created_by)
- updated: UpdatedWindow;
- tags: SelectedTag[];
-}
-
// A saved view: a named filter the org shares, persisted via the backend Views
// API. The backend stores a flat `{ query, sort, order }` (no structured chips),
// so a view captures the fully-combined DSL query plus the sort/order to apply.
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/dslGrammar.ts b/frontend/src/pages/DashboardsListPageV2/utils/dslGrammar.ts
new file mode 100644
index 0000000000..c36c45673d
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/utils/dslGrammar.ts
@@ -0,0 +1,122 @@
+// Frontend mirror of the backend dashboards-list filter DSL grammar
+// (pkg/types/dashboardtypes/list_filter.go). There is no keys/operators API, so
+// the valid keys, per-field operators, and value shapes are encoded here. Keep in
+// sync with the backend allow-lists.
+import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
+
+// Reserved keys the backend recognises as dashboard columns. Any other key is a
+// tag key. (`updated_by` and `source` are NOT queryable.)
+export const RESERVED_KEYS = [
+ 'name',
+ 'description',
+ 'created_by',
+ 'created_at',
+ 'updated_at',
+ 'locked',
+] as const;
+
+export type DslFieldType = 'string' | 'timestamp' | 'bool' | 'tag';
+
+const RESERVED_FIELD_TYPES: Record<string, DslFieldType> = {
+ name: 'string',
+ description: 'string',
+ created_by: 'string',
+ created_at: 'timestamp',
+ updated_at: 'timestamp',
+ locked: 'bool',
+};
+
+// A reserved key maps to its column type; anything else is a tag.
+export const classifyField = (key: string): DslFieldType =>
+ RESERVED_FIELD_TYPES[key.toLowerCase()] ?? 'tag';
+
+// String/tag comparison operators, reusing the shared operator constants
+// (REGEXP is allow-listed by the backend but unimplemented, so it is omitted).
+const STRING_OPS = [
+ OPERATORS['='],
+ OPERATORS['!='],
+ OPERATORS.CONTAINS,
+ negateOperator(OPERATORS.CONTAINS),
+ OPERATORS.LIKE,
+ negateOperator(OPERATORS.LIKE),
+ OPERATORS.ILIKE,
+ negateOperator(OPERATORS.ILIKE),
+ OPERATORS.IN,
+ negateOperator(OPERATORS.IN),
+];
+
+// Valid operators per field type. Tags additionally support existence checks.
+export const OPERATOR_MATRIX: Record<DslFieldType, string[]> = {
+ string: STRING_OPS,
+ tag: [...STRING_OPS, OPERATORS.EXISTS, negateOperator(OPERATORS.EXISTS)],
+ timestamp: [
+ OPERATORS['='],
+ OPERATORS['!='],
+ OPERATORS['<'],
+ OPERATORS['<='],
+ OPERATORS['>'],
+ OPERATORS['>='],
+ OPERATORS.BETWEEN,
+ negateOperator(OPERATORS.BETWEEN),
+ ],
+ bool: [OPERATORS['='], OPERATORS['!=']],
+};
+
+// Operators that take no value (the clause is complete after the operator).
+export const VALUELESS_OPERATORS = new Set([
+ OPERATORS.EXISTS,
+ negateOperator(OPERATORS.EXISTS),
+]);
+
+// Operators whose value is a bracketed list (`IN ['a', 'b']`) rather than a
+// single literal — value suggestions wrap/append inside the `[...]`.
+export const LIST_OPERATORS = new Set([
+ OPERATORS.IN,
+ negateOperator(OPERATORS.IN),
+]);
+
+// Every operator, longest spelling first, so the tokenizer matches `NOT IN`
+// before `NOT`/`IN` and `>=` before `>`. Word operators allow flexible internal
+// whitespace (`NOT IN`).
+export const OPERATOR_PATTERN = new RegExp(
+ '^(' +
+ [
+ 'NOT\\s+CONTAINS',
+ 'NOT\\s+LIKE',
+ 'NOT\\s+ILIKE',
+ 'NOT\\s+BETWEEN',
+ 'NOT\\s+EXISTS',
+ 'NOT\\s+IN',
+ 'CONTAINS',
+ 'ILIKE',
+ 'LIKE',
+ 'BETWEEN',
+ 'EXISTS',
+ 'IN',
+ '>=',
+ '<=',
+ '!=',
+ '<>',
+ '==',
+ '=',
+ '<',
+ '>',
+ ].join('|') +
+ ')',
+ 'i',
+);
+
+// Canonical (uppercase, single-spaced) form of a matched operator spelling.
+export const canonicalOperator = (raw: string): string => {
+ const collapsed = raw.replace(/\s+/g, ' ').trim().toUpperCase();
+ return collapsed === '==' ? '=' : collapsed === '<>' ? '!=' : collapsed;
+};
+
+// Characters that start an operator symbol — used to end a bare key token that
+// abuts an operator without whitespace (`name='x'`).
+export const isOperatorSymbolStart = (ch: string): boolean =>
+ ch === '=' || ch === '!' || ch === '<' || ch === '>';
+
+// A single-quoted DSL string literal with embedded single quotes escaped.
+export const literal = (value: string): string =>
+ `'${value.replace(/'/g, "\\'")}'`;
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.test.ts b/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.test.ts
index 974bac287a..a4c1307d98 100644
--- a/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.test.ts
+++ b/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.test.ts
@@ -1,57 +1,138 @@
-import {
- applyKeySuggestion,
- buildSuggestionKeys,
- getActiveKeyToken,
- matchKeys,
- RESERVED_DSL_KEYS,
-} from './dslSuggestions';
+import { getSuggestions, type SuggestionSource } from './dslSuggestions';
-describe('getActiveKeyToken', () => {
- it('returns the partial key at the start', () => {
- expect(getActiveKeyToken('nam')).toStrictEqual({ token: 'nam', start: 0 });
+const source: SuggestionSource = {
+ tagKeys: ['env', 'team'],
+ tagValuesByKey: { env: ['prod', 'dev'] },
+ creatorEmails: ['[email protected]', '[email protected]'],
+ currentUserEmail: '[email protected]',
+};
+
+const labels = (q: string, caret: number): string[] =>
+ getSuggestions(q, caret, source).items.map((i) => i.label);
+const inserts = (q: string, caret: number): string[] =>
+ getSuggestions(q, caret, source).items.map((i) => i.insertText);
+
+describe('getSuggestions — key stage', () => {
+ it('suggests reserved + tag keys matching the partial', () => {
+ expect(labels('en', 2)).toStrictEqual(['env']);
});
- it('returns the partial key after AND', () => {
- const value = 'name = "x" AND en';
- expect(getActiveKeyToken(value)).toStrictEqual({ token: 'en', start: 15 });
+ it('inserts the key with a trailing space', () => {
+ expect(inserts('en', 2)).toStrictEqual(['env ']);
});
+});
- it('is null once an operator (space) has been typed', () => {
- expect(getActiveKeyToken('name contains')).toBeNull();
+describe('getSuggestions — operator stage', () => {
+ it('offers the full tag operator set as "key op" labels', () => {
+ const out = labels('env ', 4);
+ expect(out).toContain('env =');
+ expect(out).toContain('env CONTAINS');
+ expect(out).toContain('env NOT IN');
+ expect(out).toContain('env EXISTS');
+ expect(out.some((l) => l.includes('REGEXP'))).toBe(false);
});
- it('is null for an empty trailing segment', () => {
- expect(getActiveKeyToken('name = "x" AND ')).toBeNull();
+ it('restricts locked to = and !=', () => {
+ expect(labels('locked ', 7)).toStrictEqual(['locked =', 'locked !=']);
});
-});
-describe('buildSuggestionKeys', () => {
- it('lists reserved keys plus distinct tag keys', () => {
- const keys = buildSuggestionKeys([
- { key: 'env', value: 'prod' },
- { key: 'env', value: 'dev' },
- { key: 'team', value: 'core' },
+ it('offers range operators for a timestamp key', () => {
+ const out = labels('updated_at ', 11);
+ expect(out).toContain('updated_at >=');
+ expect(out).toContain('updated_at BETWEEN');
+ expect(out).not.toContain('updated_at CONTAINS');
+ });
+
+ it('filters operators by the typed partial', () => {
+ expect(labels('env NOT ', 8)).toHaveLength(0); // "NOT " + space → past partial op, no ops
+ expect(labels('env NOT', 7)).toStrictEqual([
+ 'env NOT CONTAINS',
+ 'env NOT LIKE',
+ 'env NOT ILIKE',
+ 'env NOT IN',
+ 'env NOT EXISTS',
]);
- expect(keys).toStrictEqual([...RESERVED_DSL_KEYS, 'env', 'team']);
+ });
+
+ it('inserts just the operator with a trailing space', () => {
+ expect(inserts('env C', 5)).toStrictEqual(['CONTAINS ']);
});
});
-describe('matchKeys', () => {
- it('matches case-insensitively and excludes exact matches', () => {
- expect(matchKeys(['name', 'created_by', 'env'], 'NAM')).toStrictEqual([
- 'name',
- ]);
- expect(matchKeys(['name'], 'name')).toStrictEqual([]);
+describe('getSuggestions — value stage', () => {
+ it('suggests creator emails (current user first, labelled) for created_by', () => {
+ const out = getSuggestions('created_by = ', 13, source);
+ expect(out.items[0].label).toBe('[email protected] (me)');
+ expect(out.items.map((i) => i.insertText)).toContain("'[email protected]' ");
+ });
+
+ it('suggests true/false unquoted for locked', () => {
+ expect(inserts('locked = ', 9)).toStrictEqual(['true ', 'false ']);
+ });
+
+ it('suggests known tag values (quoted, trailing space) for a tag key', () => {
+ expect(inserts('env = ', 6)).toStrictEqual(["'prod' ", "'dev' "]);
+ });
+
+ it('filters values by the open-quote partial', () => {
+ expect(inserts("env = 'pr", 9)).toStrictEqual(["'prod' "]);
+ });
+
+ it('offers no value suggestions for free-text keys', () => {
+ expect(labels('name = ', 7)).toStrictEqual([]);
+ });
+});
+
+describe('getSuggestions — IN list values', () => {
+ it('wraps a fresh IN value in a bracketed list, caret before the close', () => {
+ const q = 'created_by IN ';
+ const out = getSuggestions(q, q.length, source);
+ const alice = out.items.find((i) => i.label === '[email protected]');
+ expect(alice?.insertText).toBe("['[email protected]']");
+ expect(alice?.caretOffset).toBe(1);
+ });
+
+ it('wraps tag IN values in a bracketed list', () => {
+ const q = 'env IN ';
+ expect(inserts(q, q.length)).toStrictEqual(["['prod']", "['dev']"]);
+ });
+
+ it('appends to an open list and excludes already-entered values', () => {
+ const q = "env IN ['prod', ]";
+ const caret = q.indexOf(']'); // inside the brackets, after "'prod', "
+ const out = getSuggestions(q, caret, source);
+ expect(out.items.map((i) => i.label)).toStrictEqual(['dev']);
+ const dev = out.items[0];
+ // No closing bracket (the existing `]` stays); caret lands at the end.
+ expect(dev.insertText).toBe("['prod', 'dev'");
+ expect(dev.caretOffset).toBe(0);
+ });
+
+ it('treats a complete last literal (no trailing comma) as entered', () => {
+ const q = "env IN ['prod'";
+ const out = getSuggestions(q, q.length, source);
+ // 'prod' is committed; only 'dev' remains and it appends after it.
+ expect(out.items.map((i) => i.label)).toStrictEqual(['dev']);
+ expect(out.items[0].insertText).toBe("['prod', 'dev'");
+ });
+
+ it('filters open-list suggestions by the fragment under the caret', () => {
+ const q = "env IN ['de";
+ expect(inserts(q, q.length)).toStrictEqual(["['dev'"]);
+ });
+
+ it('uses a plain literal for a single-value operator (=)', () => {
+ expect(inserts('env = ', 6)).toStrictEqual(["'prod' ", "'dev' "]);
});
});
-describe('applyKeySuggestion', () => {
- it('replaces the partial key with the chosen key and a trailing space', () => {
- const value = 'name = "x" AND en';
- const active = getActiveKeyToken(value);
- if (!active) {
- throw new Error('expected an active key token');
- }
- expect(applyKeySuggestion(value, active, 'env')).toBe('name = "x" AND env ');
+describe('getSuggestions — connector stage', () => {
+ it('chains AND/OR after a valueless operator', () => {
+ expect(labels('env EXISTS ', 11)).toStrictEqual(['AND', 'OR']);
+ });
+
+ it('chains AND/OR after a complete value', () => {
+ expect(labels("env = 'prod' ", 13)).toStrictEqual(['AND', 'OR']);
+ expect(inserts("env = 'prod' ", 13)).toStrictEqual(['AND ', 'OR ']);
});
});
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.ts b/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.ts
index 1383b8fa5e..ca0331a01d 100644
--- a/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.ts
+++ b/frontend/src/pages/DashboardsListPageV2/utils/dslSuggestions.ts
@@ -1,68 +1,255 @@
-// Key-name suggestions for the dashboards-list DSL search box. The reserved keys
-// mirror the backend filter DSL (pkg/.../listfilter_visitor.go); any other key is
-// treated as a tag key, so we also surface the tag keys the list API reports.
-import type { SelectedTag } from '../types';
-
-// Reserved DSL keys the backend recognises as dashboard columns.
-export const RESERVED_DSL_KEYS: string[] = [
- 'name',
- 'description',
- 'created_at',
- 'updated_at',
- 'created_by',
- 'locked',
- 'source',
-];
-
-export interface ActiveKeyToken {
- token: string;
- // Index in the value string where the partial key begins.
- start: number;
+// Stage-aware autocomplete for the dashboards-list DSL: as the caret moves, it
+// suggests keys, then operators (valid for that key's field type), then values
+// (drawn from the tags/users the API reports). Grammar lives in dslGrammar.ts;
+// caret/stage detection in dslTokenizer.ts.
+import {
+ classifyField,
+ LIST_OPERATORS,
+ literal,
+ OPERATOR_MATRIX,
+ RESERVED_KEYS,
+ VALUELESS_OPERATORS,
+} from './dslGrammar';
+import { type CaretContext, getCaretContext } from './dslTokenizer';
+
+// Show the full key set (the popup scrolls); values are capped a bit higher too.
+const KEY_LIMIT = 100;
+const VALUE_LIMIT = 50;
+
+export interface SuggestionSource {
+ // Reserved column keys (from the list response, falling back to RESERVED_KEYS).
+ reservedKeys?: string[];
+ tagKeys: string[];
+ // Known values per tag key (lower-cased key → values).
+ tagValuesByKey: Record<string, string[]>;
+ // Creator emails for `created_by` value suggestions.
+ creatorEmails: string[];
+ currentUserEmail?: string;
+}
+
+export interface Suggestion {
+ label: string;
+ insertText: string;
+ kind: 'key' | 'operator' | 'value' | 'connector';
+ // Right-aligned hint in the popup — e.g. 'field' vs 'tag' so reserved columns
+ // are distinguishable from org tag keys.
+ detail?: string;
+ // Chars to move the caret back from the end of `insertText` after applying.
+ // Used to land the caret inside a `[...]` list so multi-select can continue.
+ caretOffset?: number;
+}
+
+export interface SuggestionsResult {
+ items: Suggestion[];
+ ctx: CaretContext;
+}
+
+const includesInsensitive = (haystack: string, needle: string): boolean =>
+ haystack.toLowerCase().includes(needle.toLowerCase());
+
+const dedupe = (values: string[]): string[] => Array.from(new Set(values));
+
+const keySuggestions = (
+ partial: string,
+ source: SuggestionSource,
+): Suggestion[] => {
+ const reserved = source.reservedKeys ?? [...RESERVED_KEYS];
+ const reservedSet = new Set(reserved.map((k) => k.toLowerCase()));
+ // Show reserved keys in our defined (purpose) order — name, description, … —
+ // rather than the API's alphabetical order; any extra API keys follow, then tags.
+ const known = RESERVED_KEYS as readonly string[];
+ const orderedReserved = [
+ ...known.filter((k) => reserved.includes(k)),
+ ...reserved.filter((k) => !known.includes(k)),
+ ];
+ const keys = dedupe([...orderedReserved, ...source.tagKeys]);
+ const lower = partial.toLowerCase();
+ return keys
+ .filter((k) => includesInsensitive(k, partial) && k.toLowerCase() !== lower)
+ .slice(0, KEY_LIMIT)
+ .map((k) => ({
+ label: k,
+ insertText: `${k} `,
+ kind: 'key',
+ // Distinguish built-in columns from org tag keys in the popup.
+ detail: reservedSet.has(k.toLowerCase()) ? 'field' : 'tag',
+ }));
+};
+
+const operatorSuggestions = (
+ fieldKey: string,
+ partial: string,
+): Suggestion[] => {
+ const ops = OPERATOR_MATRIX[classifyField(fieldKey)];
+ const upper = partial.toUpperCase();
+ return ops
+ .filter((op) => op.startsWith(upper))
+ .map((op) => ({
+ // Echo the key with the operator (matches the query-builder UX) so the
+ // suggestion reads as the clause being built.
+ label: `${fieldKey} ${op}`,
+ insertText: `${op} `,
+ kind: 'operator',
+ }));
+};
+
+// Strip a leading opening quote from a partially-typed value for matching.
+const unquotePartial = (partial: string): string =>
+ partial.replace(/^['"]/, '');
+
+// A complete quoted literal (`'a'` or `"a"`, escapes allowed) — used to tell an
+// already-entered list value from the fragment the user is still typing.
+const COMPLETE_LITERAL = /^(['"])(?:\\.|(?!\1).)*\1$/;
+
+interface ListPartial {
+ // Values already entered in the list (unquoted).
+ committed: string[];
+ // The value fragment the caret is currently typing (unquoted).
+ fragment: string;
}
-// The partial key the user is currently typing: the trailing segment after the
-// last top-level AND/OR (or the start), provided it hasn't yet reached an
-// operator (no whitespace). Returns null once the key is complete.
-export const getActiveKeyToken = (value: string): ActiveKeyToken | null => {
- const boundaryRe = /\b(?:AND|OR)\b/gi;
- let lastEnd = 0;
- let match = boundaryRe.exec(value);
- while (match !== null) {
- lastEnd = match.index + match[0].length;
- match = boundaryRe.exec(value);
+// Index just past the string literal opening at `start` (mirrors the tokenizer's
+// escape handling); runs to end-of-input if unterminated.
+const skipStringLiteral = (text: string, start: number): number => {
+ const quote = text[start];
+ for (let i = start + 1; i < text.length; i += 1) {
+ if (text[i] === '\\') {
+ i += 1;
+ } else if (text[i] === quote) {
+ return i;
+ }
}
- const segment = value.slice(lastEnd);
- const leading = segment.length - segment.trimStart().length;
- const partial = segment.slice(leading);
- if (partial.length === 0 || /[\s(]/.test(partial)) {
- return null;
+ return text.length - 1;
+};
+
+// Split a top-level, comma-separated `[...]` partial (quote-aware) into its
+// already-entered values and the fragment under the caret. A trailing comma or a
+// complete quoted last piece means the caret starts a fresh value (fragment '').
+const parseListPartial = (partial: string): ListPartial => {
+ const inner = partial.trim().replace(/^[[(]/, '');
+ const pieces: string[] = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < inner.length; i += 1) {
+ const c = inner[i];
+ if (c === "'" || c === '"') {
+ i = skipStringLiteral(inner, i);
+ } else if (c === '[' || c === '(') {
+ depth += 1;
+ } else if (c === ']' || c === ')') {
+ depth = Math.max(0, depth - 1);
+ } else if (c === ',' && depth === 0) {
+ pieces.push(inner.slice(start, i));
+ start = i + 1;
+ }
}
- return { token: partial, start: lastEnd + leading };
+ pieces.push(inner.slice(start));
+ const last = pieces[pieces.length - 1].trim();
+ const lastIsComplete = last !== '' && COMPLETE_LITERAL.test(last);
+ const committedPieces = lastIsComplete ? pieces : pieces.slice(0, -1);
+ return {
+ committed: committedPieces
+ .map((p) => unquotePartial(p.trim()).replace(/['"]$/, ''))
+ .filter((p) => p !== ''),
+ fragment: lastIsComplete ? '' : unquotePartial(last),
+ };
};
-// Build the de-duplicated, ordered list of keys to offer: reserved columns plus
-// distinct tag keys from the list response.
-export const buildSuggestionKeys = (availableTags: SelectedTag[]): string[] => {
- const tagKeys = availableTags.map((t) => t.key);
- return Array.from(new Set([...RESERVED_DSL_KEYS, ...tagKeys]));
+const valueSuggestions = (
+ ctx: CaretContext,
+ source: SuggestionSource,
+): Suggestion[] => {
+ if (VALUELESS_OPERATORS.has(ctx.operator)) {
+ return [];
+ }
+ const key = ctx.fieldKey.toLowerCase();
+ const type = classifyField(ctx.fieldKey);
+
+ // List operators (`IN`/`NOT IN`) take a `[...]` list: parse what's already in
+ // the brackets so we exclude entered values and append rather than replace.
+ const isList = LIST_OPERATORS.has(ctx.operator);
+ const list = isList ? parseListPartial(ctx.partial) : null;
+ // A fresh list has no `[` yet; once inside one the `]` already sits after the
+ // caret, so we omit the closing bracket when appending.
+ const inBracket = isList && /^\s*[[(]/.test(ctx.partial);
+ const needle = list ? list.fragment : unquotePartial(ctx.partial);
+
+ if (type === 'bool') {
+ return ['true', 'false']
+ .filter((v) => v.startsWith(needle.toLowerCase()))
+ .map((v) => ({ label: v, insertText: `${v} `, kind: 'value' }));
+ }
+
+ let raw: string[] = [];
+ if (key === 'created_by') {
+ const emails = source.currentUserEmail
+ ? dedupe([source.currentUserEmail, ...source.creatorEmails])
+ : source.creatorEmails;
+ raw = emails;
+ } else if (type === 'tag') {
+ raw = source.tagValuesByKey[key] ?? [];
+ } else {
+ // name / description / timestamps have no known value set — free text.
+ return [];
+ }
+
+ const committed = new Set(list?.committed ?? []);
+ return raw
+ .filter((v) => !committed.has(v) && includesInsensitive(v, needle))
+ .slice(0, VALUE_LIMIT)
+ .map((v) => {
+ const label =
+ v === source.currentUserEmail && key === 'created_by' ? `${v} (me)` : v;
+ if (isList) {
+ const values = [...(list?.committed ?? []), v].map(literal).join(', ');
+ return {
+ label,
+ // Append inside the existing `[...]` (its `]` stays after the caret),
+ // or open a fresh closed list. Either way the caret lands just before
+ // the `]` so the next pick continues the list.
+ insertText: inBracket ? `[${values}` : `[${values}]`,
+ kind: 'value',
+ caretOffset: inBracket ? 0 : 1,
+ };
+ }
+ return {
+ label,
+ // Trailing space so picking a value lands the caret in the connector slot.
+ insertText: `${literal(v)} `,
+ kind: 'value',
+ };
+ });
};
-// Keys matching the partial token (case-insensitive), excluding an exact match.
-export const matchKeys = (
- keys: string[],
- token: string,
- limit = 8,
-): string[] => {
- const lower = token.toLowerCase();
- return keys
- .filter((k) => k.toLowerCase().includes(lower) && k.toLowerCase() !== lower)
- .slice(0, limit);
+// AND / OR chaining after a complete term.
+const CONNECTORS = ['AND', 'OR'];
+
+const connectorSuggestions = (partial: string): Suggestion[] => {
+ const upper = partial.toUpperCase();
+ return CONNECTORS.filter((c) => c.startsWith(upper)).map((c) => ({
+ label: c,
+ insertText: `${c} `,
+ kind: 'connector',
+ }));
};
-// Replace the active partial key in `value` with the chosen key + a space, ready
-// for the user to type an operator.
-export const applyKeySuggestion = (
- value: string,
- active: ActiveKeyToken,
- key: string,
-): string => `${value.slice(0, active.start)}${key} `;
+// Compute the suggestions for the caret position, plus the caret context the
+// caller uses to splice a chosen suggestion back in.
+export const getSuggestions = (
+ query: string,
+ caret: number,
+ source: SuggestionSource,
+): SuggestionsResult => {
+ const ctx = getCaretContext(query, caret);
+ let items: Suggestion[] = [];
+ if (ctx.stage === 'key') {
+ items = keySuggestions(ctx.partial, source);
+ } else if (ctx.stage === 'operator') {
+ items = operatorSuggestions(ctx.fieldKey, ctx.partial);
+ } else if (ctx.stage === 'value') {
+ items = valueSuggestions(ctx, source);
+ } else if (ctx.stage === 'connector') {
+ items = connectorSuggestions(ctx.partial);
+ }
+ return { items, ctx };
+};
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.test.ts b/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.test.ts
new file mode 100644
index 0000000000..5de87e6e71
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.test.ts
@@ -0,0 +1,151 @@
+import {
+ getCaretContext,
+ spliceAtCaret,
+ splitTopLevelTerms,
+} from './dslTokenizer';
+
+describe('splitTopLevelTerms', () => {
+ it('splits on top-level AND/OR', () => {
+ const terms = splitTopLevelTerms('a AND b OR c');
+ expect(terms.map((t) => t.text.trim())).toStrictEqual(['a', 'b', 'c']);
+ expect(terms.map((t) => t.precedingJoiner)).toStrictEqual([
+ null,
+ 'AND',
+ 'OR',
+ ]);
+ });
+
+ it('ignores AND inside quotes', () => {
+ const terms = splitTopLevelTerms("name = 'a AND b' AND env = 'x'");
+ expect(terms).toHaveLength(2);
+ expect(terms[0].text.trim()).toBe("name = 'a AND b'");
+ expect(terms[1].text.trim()).toBe("env = 'x'");
+ });
+
+ it('ignores OR inside parentheses', () => {
+ const terms = splitTopLevelTerms('(a OR b) AND c');
+ expect(terms).toHaveLength(2);
+ expect(terms[1].precedingJoiner).toBe('AND');
+ });
+
+ it('keeps an IN list as a single term', () => {
+ const terms = splitTopLevelTerms("created_by IN ['a','b']");
+ expect(terms).toHaveLength(1);
+ });
+
+ it('does not split inside a bare word containing and/or', () => {
+ expect(splitTopLevelTerms('command = 1')).toHaveLength(1);
+ });
+});
+
+describe('getCaretContext — stage detection', () => {
+ const stageAt = (q: string, caret: number): string =>
+ getCaretContext(q, caret).stage;
+
+ it('is the key stage while typing the key', () => {
+ const ctx = getCaretContext('env', 3);
+ expect(ctx.stage).toBe('key');
+ expect(ctx.partial).toBe('env');
+ expect(ctx.replaceStart).toBe(0);
+ });
+
+ it('moves to the operator stage after the key + space', () => {
+ const ctx = getCaretContext('env ', 4);
+ expect(ctx.stage).toBe('operator');
+ expect(ctx.fieldKey).toBe('env');
+ expect(ctx.partial).toBe('');
+ });
+
+ it('stays on the operator while typing a partial operator', () => {
+ const ctx = getCaretContext('env NOT', 7);
+ expect(ctx.stage).toBe('operator');
+ expect(ctx.partial).toBe('NOT');
+ expect(ctx.replaceStart).toBe(4);
+ });
+
+ it('moves to the value stage after the operator + space', () => {
+ const ctx = getCaretContext('env = ', 6);
+ expect(ctx.stage).toBe('value');
+ expect(ctx.fieldKey).toBe('env');
+ expect(ctx.operator).toBe('=');
+ });
+
+ it('recognises a multi-word operator and moves to value', () => {
+ const ctx = getCaretContext('env NOT IN ', 11);
+ expect(ctx.stage).toBe('value');
+ expect(ctx.operator).toBe('NOT IN');
+ });
+
+ it('reports value partial inside an open quote', () => {
+ const ctx = getCaretContext("env = 'pr", 9);
+ expect(ctx.stage).toBe('value');
+ expect(ctx.partial).toBe("'pr");
+ expect(ctx.replaceStart).toBe(6);
+ });
+
+ it('chains a connector after EXISTS (no value stage)', () => {
+ expect(stageAt('env EXISTS ', 11)).toBe('connector');
+ });
+
+ it('moves to the connector stage after a complete value + space', () => {
+ const ctx = getCaretContext("env = 'prod' ", 13);
+ expect(ctx.stage).toBe('connector');
+ expect(ctx.partial).toBe('');
+ });
+
+ it('reports a partial connector keyword', () => {
+ const ctx = getCaretContext("env = 'prod' AN", 15);
+ expect(ctx.stage).toBe('connector');
+ expect(ctx.partial).toBe('AN');
+ expect(ctx.replaceStart).toBe(13);
+ });
+
+ it('handles a key operator with no whitespace', () => {
+ const ctx = getCaretContext("name='x", 7);
+ expect(ctx.stage).toBe('value');
+ expect(ctx.fieldKey).toBe('name');
+ expect(ctx.operator).toBe('=');
+ });
+
+ it('starts a fresh key after a top-level AND', () => {
+ const q = "created_by = 'a@x' AND ";
+ const ctx = getCaretContext(q, q.length);
+ expect(ctx.stage).toBe('key');
+ expect(ctx.partial).toBe('');
+ });
+
+ it('detects the stage of the term under a mid-string caret', () => {
+ const q = "env = AND team = 'core'";
+ // caret right after the first `env ` (index 4) is the operator stage
+ expect(stageAt(q, 4)).toBe('operator');
+ });
+});
+
+describe('spliceAtCaret', () => {
+ it('splices a key suggestion and returns the caret', () => {
+ const ctx = getCaretContext('env', 3);
+ const { next, caret } = spliceAtCaret('env', ctx, 'name ');
+ expect(next).toBe('name ');
+ expect(caret).toBe(5);
+ });
+
+ it('splices an operator into the gap', () => {
+ const ctx = getCaretContext('env ', 4);
+ const { next } = spliceAtCaret('env ', ctx, '= ');
+ expect(next).toBe('env = ');
+ });
+
+ it('splices a value over an open-quote partial', () => {
+ const q = "env = 'pr";
+ const ctx = getCaretContext(q, q.length);
+ const { next } = spliceAtCaret(q, ctx, "'prod'");
+ expect(next).toBe("env = 'prod'");
+ });
+
+ it('preserves text after the caret', () => {
+ const q = "env AND team = 'core'";
+ const ctx = getCaretContext(q, 4); // operator gap after `env`
+ const { next } = spliceAtCaret(q, ctx, '= ');
+ expect(next).toBe("env = AND team = 'core'");
+ });
+});
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.ts b/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.ts
new file mode 100644
index 0000000000..c5e02ac1d7
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPageV2/utils/dslTokenizer.ts
@@ -0,0 +1,351 @@
+// Quote/paren/bracket-aware scanning of the dashboards-list filter DSL, shared by
+// the autocomplete engine (dslSuggestions) and the clause splicer (filterQuery).
+// The DSL is a boolean composition of `key OP value` terms joined by AND/OR.
+import {
+ canonicalOperator,
+ isOperatorSymbolStart,
+ OPERATOR_PATTERN,
+ VALUELESS_OPERATORS,
+} from './dslGrammar';
+
+export interface Term {
+ // Raw substring of the term (may carry surrounding whitespace); callers trim.
+ text: string;
+ start: number; // absolute start index in the query (inclusive)
+ end: number; // absolute end index in the query (exclusive)
+ precedingJoiner: 'AND' | 'OR' | null;
+}
+
+// A top-level AND/OR keyword starting at index `i` (word-boundary aware), or null.
+const joinerAt = (
+ query: string,
+ i: number,
+): { value: 'AND' | 'OR'; length: number } | null => {
+ const c = query[i];
+ if (c !== 'A' && c !== 'a' && c !== 'O' && c !== 'o') {
+ return null;
+ }
+ const prev = i === 0 ? '' : query[i - 1];
+ if (!(i === 0 || /[^A-Za-z0-9_]/.test(prev))) {
+ return null;
+ }
+ const m = /^(AND|OR)\b/i.exec(query.slice(i));
+ return m
+ ? { value: m[1].toUpperCase() as 'AND' | 'OR', length: m[0].length }
+ : null;
+};
+
+// Index just past the string literal that opens at `start` (handles `\` escapes;
+// runs to end-of-input if unterminated).
+const skipString = (query: string, start: number): number => {
+ const quote = query[start];
+ let i = start + 1;
+ while (i < query.length) {
+ if (query[i] === '\\') {
+ i += 2;
+ } else if (query[i] === quote) {
+ return i + 1;
+ } else {
+ i += 1;
+ }
+ }
+ return i;
+};
+
+// Split a query into its top-level (depth-0, outside quotes) AND/OR-separated
+// terms. `AND`/`OR` inside quotes or brackets/parens are ignored.
+export const splitTopLevelTerms = (query: string): Term[] => {
+ const terms: Term[] = [];
+ let depth = 0;
+ let termStart = 0;
+ let precedingJoiner: 'AND' | 'OR' | null = null;
+ let i = 0;
+
+ const push = (end: number, next: 'AND' | 'OR' | null): void => {
+ terms.push({
+ text: query.slice(termStart, end),
+ start: termStart,
+ end,
+ precedingJoiner,
+ });
+ precedingJoiner = next;
+ };
+
+ while (i < query.length) {
+ const c = query[i];
+ if (c === "'" || c === '"') {
+ i = skipString(query, i);
+ continue;
+ }
+ if (c === '[' || c === '(') {
+ depth += 1;
+ } else if (c === ']' || c === ')') {
+ depth = Math.max(0, depth - 1);
+ } else if (depth === 0) {
+ const joiner = joinerAt(query, i);
+ if (joiner) {
+ push(i, joiner.value);
+ i += joiner.length;
+ termStart = i;
+ continue;
+ }
+ }
+ i += 1;
+ }
+ push(query.length, null);
+ return terms;
+};
+
+export interface TermScan {
+ key?: { start: number; end: number; text: string };
+ // The recognised operator (canonical form), if the second token parses as one.
+ operator?: { start: number; end: number; canonical: string };
+ // The second token when it is NOT (yet) a recognised operator — i.e. an
+ // operator the user is still typing.
+ operatorPartial?: { start: number; end: number; text: string };
+ value?: { start: number; end: number; text: string };
+}
+
+// Scan a single term (relative coordinates) into key / operator / value tokens.
+export const scanTerm = (text: string): TermScan => {
+ const n = text.length;
+ let i = 0;
+ const skipWs = (): void => {
+ while (i < n && /\s/.test(text[i])) {
+ i += 1;
+ }
+ };
+
+ skipWs();
+ const scan: TermScan = {};
+
+ // Key: a bare token up to whitespace or an operator symbol.
+ const ks = i;
+ while (i < n && !/\s/.test(text[i]) && !isOperatorSymbolStart(text[i])) {
+ i += 1;
+ }
+ if (i > ks) {
+ scan.key = { start: ks, end: i, text: text.slice(ks, i) };
+ }
+
+ skipWs();
+ if (i >= n) {
+ return scan;
+ }
+
+ // Operator: try to match a known operator at the current position.
+ const rest = text.slice(i);
+ const m = OPERATOR_PATTERN.exec(rest);
+ // A word operator must end on a boundary so `INDIA` isn't read as `IN`.
+ const wordBoundaryOk =
+ m &&
+ (/[^A-Za-z]$/.test(m[0]) ||
+ i + m[0].length >= n ||
+ /[^A-Za-z]/.test(text[i + m[0].length]));
+ if (m && wordBoundaryOk) {
+ scan.operator = {
+ start: i,
+ end: i + m[0].length,
+ canonical: canonicalOperator(m[0]),
+ };
+ i += m[0].length;
+ skipWs();
+ if (i < n) {
+ scan.value = { start: i, end: n, text: text.slice(i, n) };
+ }
+ return scan;
+ }
+
+ // Not a recognised operator yet — treat the second token as a partial op.
+ const os = i;
+ while (i < n && !/\s/.test(text[i])) {
+ i += 1;
+ }
+ scan.operatorPartial = { start: os, end: i, text: text.slice(os, i) };
+ return scan;
+};
+
+export type CaretStage = 'key' | 'operator' | 'value' | 'connector' | 'none';
+
+export interface CaretContext {
+ stage: CaretStage;
+ fieldKey: string; // key of the active term ('' when still typing the key)
+ operator: string; // canonical operator ('' when not yet parsed)
+ partial: string; // text typed so far in the active slot (for matching)
+ replaceStart: number; // absolute index to start replacing at
+ replaceEnd: number; // absolute index to stop replacing (the caret)
+}
+
+interface Slot {
+ stage: CaretStage;
+ operator: string;
+ partial: string;
+ replaceStartRel: number;
+}
+
+// Index where the value CONTENT ends (the value token's `end` is the whole term
+// tail, incl. trailing space). A quoted/bracketed value ends after its close; an
+// unterminated one runs to the end (still being typed); a bare one ends at space.
+const valueContentEnd = (text: string, start: number): number => {
+ const n = text.length;
+ const ch = text[start];
+ if (ch === '"' || ch === "'") {
+ for (let i = start + 1; i < n; i += 1) {
+ if (text[i] === ch) {
+ return i + 1;
+ }
+ }
+ return n;
+ }
+ if (ch === '[' || ch === '(') {
+ const close = ch === '[' ? ']' : ')';
+ for (let i = start + 1; i < n; i += 1) {
+ if (text[i] === close) {
+ return i + 1;
+ }
+ }
+ return n;
+ }
+ let i = start;
+ while (i < n && !/\s/.test(text[i])) {
+ i += 1;
+ }
+ return i;
+};
+
+// The connector slot: after a complete term, a (partial) AND/OR keyword sits in
+// the trailing whitespace, ready to chain the next term.
+const connectorSlot = (
+ text: string,
+ from: number,
+ rel: number,
+ operator: string,
+): Slot => {
+ const ws = /^\s*/.exec(text.slice(from, rel));
+ const start = from + (ws ? ws[0].length : 0);
+ return {
+ stage: 'connector',
+ operator,
+ partial: text.slice(start, rel),
+ replaceStartRel: start,
+ };
+};
+
+// Slot resolution once the caret is past the key: operator vs value.
+const afterKeySlot = (text: string, scan: TermScan, rel: number): Slot => {
+ const { operator, operatorPartial, value } = scan;
+
+ // Editing the operator (a partial second token, or within a recognised op).
+ if (operatorPartial && rel <= operatorPartial.end) {
+ return {
+ stage: 'operator',
+ operator: '',
+ partial: text.slice(operatorPartial.start, rel),
+ replaceStartRel: operatorPartial.start,
+ };
+ }
+ if (operator && rel <= operator.end) {
+ return {
+ stage: 'operator',
+ operator: '',
+ partial: text.slice(operator.start, rel),
+ replaceStartRel: operator.start,
+ };
+ }
+ // Whitespace right after the key, before any operator — starting the operator.
+ if (!operator && !operatorPartial) {
+ return { stage: 'operator', operator: '', partial: '', replaceStartRel: rel };
+ }
+ // Past a recognised operator — the value slot, or (once complete) the connector.
+ if (operator) {
+ if (VALUELESS_OPERATORS.has(operator.canonical)) {
+ // After a valueless op (e.g. EXISTS), trailing space → chain AND/OR.
+ return rel > operator.end
+ ? connectorSlot(text, operator.end, rel, operator.canonical)
+ : {
+ stage: 'none',
+ operator: operator.canonical,
+ partial: '',
+ replaceStartRel: rel,
+ };
+ }
+ if (value) {
+ // Caret past a complete value (into trailing space) → chain AND/OR.
+ const contentEnd = valueContentEnd(text, value.start);
+ if (rel > contentEnd) {
+ return connectorSlot(text, contentEnd, rel, operator.canonical);
+ }
+ return {
+ stage: 'value',
+ operator: operator.canonical,
+ partial: text.slice(value.start, rel),
+ replaceStartRel: value.start,
+ };
+ }
+ // No value typed yet — the (empty) value slot.
+ return {
+ stage: 'value',
+ operator: operator.canonical,
+ partial: '',
+ replaceStartRel: rel,
+ };
+ }
+ // A partial operator the caret has moved past — ambiguous, offer nothing.
+ return { stage: 'none', operator: '', partial: '', replaceStartRel: rel };
+};
+
+// Resolve which slot (key/operator/value) the caret is editing within a scanned
+// term, in term-relative coordinates.
+const resolveSlot = (text: string, scan: TermScan, rel: number): Slot => {
+ const { key } = scan;
+ // Still in/at the key token (or before it).
+ if (!key || rel <= key.end) {
+ const start = key ? key.start : rel;
+ return {
+ stage: 'key',
+ operator: '',
+ partial: key ? text.slice(key.start, rel) : '',
+ replaceStartRel: Math.min(start, rel),
+ };
+ }
+ return afterKeySlot(text, scan, rel);
+};
+
+// Determine what the caret is currently editing (key / operator / value) within
+// the top-level term it sits in, plus the range a suggestion should replace.
+export const getCaretContext = (query: string, caret: number): CaretContext => {
+ const pos = Math.max(0, Math.min(caret, query.length));
+ const terms = splitTopLevelTerms(query);
+ // The term the caret sits in: the first whose end >= caret (a joiner boundary
+ // counts as the end of the preceding term).
+ const term =
+ terms.find((t) => pos >= t.start && pos <= t.end) ?? terms[terms.length - 1];
+
+ const scan = scanTerm(term.text);
+ const slot = resolveSlot(term.text, scan, pos - term.start);
+ return {
+ stage: slot.stage,
+ fieldKey: scan.key ? scan.key.text : '',
+ operator: slot.operator,
+ partial: slot.partial,
+ replaceStart: term.start + slot.replaceStartRel,
+ replaceEnd: pos,
+ };
+};
+
+export interface SpliceResult {
+ next: string;
+ caret: number;
+}
+
+// Replace the active slot (ctx.replaceStart..replaceEnd) with `insertText`,
+// preserving everything after the caret, and return the new caret position.
+export const spliceAtCaret = (
+ query: string,
+ ctx: CaretContext,
+ insertText: string,
+): SpliceResult => {
+ const next =
+ query.slice(0, ctx.replaceStart) + insertText + query.slice(ctx.replaceEnd);
+ return { next, caret: ctx.replaceStart + insertText.length };
+};
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.test.ts b/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.test.ts
index fc60ee6629..291a64cc54 100644
--- a/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.test.ts
+++ b/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.test.ts
@@ -1,109 +1,124 @@
+import dayjs from 'dayjs';
+
import {
- areFilterStatesEqual,
- combineQueries,
- DEFAULT_FILTER_STATE,
- filterStateToQuery,
- isFilterStateEmpty,
+ areQueriesEqual,
+ createdByClause,
+ isQueryEmpty,
+ parseReflectedClauses,
+ spliceClause,
+ updatedWindowFromTimestamp,
} from './filterQuery';
-import type { DashboardFilterState } from '../types';
-const state = (patch: Partial<DashboardFilterState>): DashboardFilterState => ({
- ...DEFAULT_FILTER_STATE,
- ...patch,
+describe('createdByClause', () => {
+ it('is null for no emails, = for one, IN for many', () => {
+ expect(createdByClause([])).toBeNull();
+ expect(createdByClause(['[email protected]'])).toBe("created_by = '[email protected]'");
+ expect(createdByClause(['[email protected]', '[email protected]'])).toBe(
+ "created_by IN ['[email protected]', '[email protected]']",
+ );
+ });
});
-describe('filterStateToQuery', () => {
- it('passes the raw search through, wrapped in parentheses', () => {
- expect(filterStateToQuery(state({ search: 'name contains "prod"' }))).toBe(
- '(name contains "prod")',
- );
+describe('parseReflectedClauses', () => {
+ it('reflects a top-level created_by equality', () => {
+ expect(
+ parseReflectedClauses("created_by = '[email protected]'").createdBy,
+ ).toStrictEqual(['[email protected]']);
});
- it('emits an equality clause for a single creator', () => {
- expect(filterStateToQuery(state({ createdBy: ['[email protected]'] }))).toBe(
- "created_by = '[email protected]'",
- );
+ it('reflects a created_by IN list', () => {
+ expect(
+ parseReflectedClauses("created_by IN ['[email protected]','[email protected]']").createdBy,
+ ).toStrictEqual(['[email protected]', '[email protected]']);
});
- it('emits an IN clause for multiple creators', () => {
- expect(filterStateToQuery(state({ createdBy: ['[email protected]', '[email protected]'] }))).toBe(
- "created_by IN ['[email protected]', '[email protected]']",
- );
+ it('does not reflect a non =/IN created_by operator', () => {
+ expect(
+ parseReflectedClauses("created_by != '[email protected]'").createdBy,
+ ).toStrictEqual([]);
});
- it('emits an exact equality clause per selected tag', () => {
+ it('does not reflect a nested (parenthesised) clause', () => {
expect(
- filterStateToQuery(
- state({
- tags: [
- { key: 'env', value: 'prod' },
- { key: 'team', value: 'core' },
- ],
- }),
- ),
- ).toBe("env = 'prod' AND team = 'core'");
+ parseReflectedClauses("(created_by = '[email protected]') AND name = 'x'").createdBy,
+ ).toStrictEqual([]);
});
- it('ANDs raw search with the structured chips', () => {
+ it('does not reflect a duplicated key', () => {
expect(
- filterStateToQuery(
- state({
- search: 'name contains "x"',
- createdBy: ['[email protected]'],
- tags: [{ key: 'env', value: 'prod' }],
- }),
- ),
- ).toBe("(name contains \"x\") AND created_by = '[email protected]' AND env = 'prod'");
+ parseReflectedClauses("created_by = '[email protected]' AND created_by = '[email protected]'")
+ .createdBy,
+ ).toStrictEqual([]);
});
- it('returns an empty string for the default state', () => {
- expect(filterStateToQuery(DEFAULT_FILTER_STATE)).toBe('');
+ it('reflects a recent updated_at >= as the nearest window', () => {
+ const iso = dayjs().subtract(7, 'day').toISOString();
+ expect(parseReflectedClauses(`updated_at >= '${iso}'`).updated).toBe('7d');
+ });
+
+ it('falls back to any for an unrecognised updated_at cutoff', () => {
+ const iso = dayjs().subtract(400, 'day').toISOString();
+ expect(parseReflectedClauses(`updated_at >= '${iso}'`).updated).toBe('any');
});
});
-describe('isFilterStateEmpty', () => {
- it('is true for the default state', () => {
- expect(isFilterStateEmpty(DEFAULT_FILTER_STATE)).toBe(true);
+describe('spliceClause', () => {
+ it('appends a clause when the key is absent', () => {
+ expect(
+ spliceClause("name = 'x'", 'created_by', "created_by = '[email protected]'"),
+ ).toBe("name = 'x' AND created_by = '[email protected]'");
+ });
+
+ it('replaces an existing top-level clause for the key', () => {
+ expect(
+ spliceClause(
+ "created_by = 'old' AND name = 'x'",
+ 'created_by',
+ "created_by = 'new'",
+ ),
+ ).toBe("created_by = 'new' AND name = 'x'");
});
- it('is false when any tag is selected', () => {
+ it('removes the clause when passed null', () => {
expect(
- isFilterStateEmpty(state({ tags: [{ key: 'env', value: 'prod' }] })),
- ).toBe(false);
+ spliceClause("created_by = '[email protected]' AND name = 'x'", 'created_by', null),
+ ).toBe("name = 'x'");
});
-});
-describe('areFilterStatesEqual', () => {
- it('ignores tag ordering', () => {
- const a = state({
- tags: [
- { key: 'env', value: 'prod' },
- { key: 'team', value: 'core' },
- ],
- });
- const b = state({
- tags: [
- { key: 'team', value: 'core' },
- { key: 'env', value: 'prod' },
- ],
- });
- expect(areFilterStatesEqual(a, b)).toBe(true);
- });
-
- it('distinguishes differing tag selections', () => {
+ it('leaves a nested clause untouched and appends instead', () => {
expect(
- areFilterStatesEqual(
- state({ tags: [{ key: 'env', value: 'prod' }] }),
- state({ tags: [{ key: 'env', value: 'dev' }] }),
+ spliceClause(
+ "(created_by = 'a') AND name = 'x'",
+ 'created_by',
+ "created_by = 'b'",
),
- ).toBe(false);
+ ).toBe("(created_by = 'a') AND name = 'x' AND created_by = 'b'");
+ });
+
+ it('is a no-op removing an absent key', () => {
+ expect(spliceClause("name = 'x'", 'updated_at', null)).toBe("name = 'x'");
});
});
-describe('combineQueries', () => {
- it('drops empty fragments and ANDs the rest', () => {
- expect(combineQueries('locked = true', '', undefined, 'name = "x"')).toBe(
- 'locked = true AND name = "x"',
- );
+describe('updatedWindowFromTimestamp', () => {
+ it('maps a ~1 day cutoff to today', () => {
+ expect(
+ updatedWindowFromTimestamp(dayjs().subtract(1, 'day').toISOString()),
+ ).toBe('today');
+ });
+
+ it('returns null for an unquoted invalid value', () => {
+ expect(updatedWindowFromTimestamp('not-a-date')).toBeNull();
+ });
+});
+
+describe('query helpers', () => {
+ it('isQueryEmpty ignores whitespace', () => {
+ expect(isQueryEmpty(' ')).toBe(true);
+ expect(isQueryEmpty("name = 'x'")).toBe(false);
+ });
+
+ it('areQueriesEqual trims before comparing', () => {
+ expect(areQueriesEqual("name = 'x' ", " name = 'x'")).toBe(true);
});
});
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.ts b/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.ts
index d65471839c..2294d7a80b 100644
Binary files a/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.ts and b/frontend/src/pages/DashboardsListPageV2/utils/filterQuery.ts differ
diff --git a/frontend/src/pages/DashboardsListPageV2/utils/views.ts b/frontend/src/pages/DashboardsListPageV2/utils/views.ts
index 047e2782a3..e82e6f3cde 100644
--- a/frontend/src/pages/DashboardsListPageV2/utils/views.ts
+++ b/frontend/src/pages/DashboardsListPageV2/utils/views.ts
@@ -5,9 +5,9 @@
// - client: constrains by a client-side id set (Favorites, Recently viewed)
import { Clock, Layers, Lock, Pin, User } from '@signozhq/icons';
-import { DEFAULT_FILTER_STATE } from './filterQuery';
+import { createdByClause } from './filterQuery';
import { BuiltinViewId } from '../types';
-import type { DashboardFilterState, ViewSection } from '../types';
+import type { ViewSection } from '../types';
import type { DashboardListItem } from './helpers';
// All @signozhq icons share this component type.
@@ -49,28 +49,25 @@ export const BUILTIN_VIEWS: BuiltinView[] = [
export const isClientView = (id: string): boolean =>
id === BuiltinViewId.Pinned || id === BuiltinViewId.Recent;
-// DSL the Locked view seeds into the search box, so the constraint is visible
-// (and editable) rather than applied invisibly behind the scenes.
+// DSL the Locked view applies — visible and editable in the query box rather
+// than applied invisibly behind the scenes.
export const LOCKED_QUERY = 'locked = true';
-// The canonical filter snapshot a built-in view applies when selected. `null`
-// for ids that aren't built-in (custom views carry their own snapshot).
-export const builtinViewSnapshot = (
+// The canonical query string a built-in view applies when selected. `null` for
+// ids that aren't built-in (custom views carry their own query).
+export const builtinViewQuery = (
id: string,
userEmail: string,
-): DashboardFilterState | null => {
+): string | null => {
switch (id) {
case BuiltinViewId.Mine:
- return {
- ...DEFAULT_FILTER_STATE,
- createdBy: userEmail ? [userEmail] : [],
- };
+ return userEmail ? (createdByClause([userEmail]) ?? '') : '';
case BuiltinViewId.Locked:
- return { ...DEFAULT_FILTER_STATE, search: LOCKED_QUERY };
+ return LOCKED_QUERY;
case BuiltinViewId.All:
case BuiltinViewId.Pinned:
case BuiltinViewId.Recent:
- return { ...DEFAULT_FILTER_STATE };
+ return '';
default:
return null;
}