diff --git a/.changeset/chart-explorer-ui-refresh.md b/.changeset/chart-explorer-ui-refresh.md new file mode 100644 index 0000000000..c054b06b14 --- /dev/null +++ b/.changeset/chart-explorer-ui-refresh.md @@ -0,0 +1,20 @@ +--- +'@hyperdx/app': minor +--- + +feat: refresh the chart explorer and chart editor UI + +- The AI assistant is a sparkles button in the page header that opens a popover, + and its last change can be undone. +- "Save to dashboard" is a labeled button, and explorer charts are named + automatically when saved. +- The explorer has a sticky page header: mode switch and source on the left of + the first row with Save to dashboard and the AI assistant on the right; chart + type on the left of the second row with the time range, granularity and Run on + the right. +- Chart type is an icon switcher that names the selected type, and the header is + the same in every mode. +- Each series and formula sits in a card with the color the chart draws it in. +- Display Settings opens in the editor's side panel next to the alert panel, not + in a drawer. +- Series display settings open in a popover. diff --git a/.claude/skills/page-layout/SKILL.md b/.claude/skills/page-layout/SKILL.md index 2a4577cc77..d0a47aa6fd 100644 --- a/.claude/skills/page-layout/SKILL.md +++ b/.claude/skills/page-layout/SKILL.md @@ -1,30 +1,50 @@ --- name: page-layout -description: Add or update app page headers and layout using PageHeader and PageLayout. Use when creating a new page, fixing inconsistent headers, or migrating Service Map / Kubernetes / dashboard pages to the shared layout. +description: + Add or update app page headers and layout using PageHeader and PageLayout. Use + when creating a new page, fixing inconsistent headers, or migrating Service + Map / Kubernetes / dashboard pages to the shared layout. --- # Page layout and headers -Read **`agent_docs/page_layout.md`** before changing any page shell. It is the source of truth for API, examples, and migration steps. +Read **`agent_docs/page_layout.md`** before changing any page shell. It is the +source of truth for API, examples, and migration steps. ## Quick rules -1. **Default for new pages**: `PageLayout` with `title`, optional `leading` / `actions`, and `content` — only when the sticky bar is **text-only** (no inputs in that bar). -2. **Sticky bar contains inputs** (source pickers, SQL/search, sliders, time range, Run, etc.): **do not** use `PageHeader` / `PageLayout` **`title`**. The sticky row is for controls only. Put **where you are** in the **`breadcrumbs` prop** (renders **inside the sticky `PageHeader`**, above the toolbar) when the page lives under a hierarchy (e.g. `Dashboards` → `Kubernetes`); otherwise you may omit `breadcrumbs` and rely on ``, the sidebar active item, and the empty state copy. -3. **Never** duplicate location: do not set `title="Kubernetes Dashboard"` **and** breadcrumbs that repeat the same page name. +1. **Default for new pages**: `PageLayout` with `title`, optional `leading` / + `actions`, and `content` — only when the sticky bar is **text-only** (no + inputs in that bar). +2. **Sticky bar contains inputs** (source pickers, SQL/search, sliders, time + range, Run, etc.): **do not** use `PageHeader` / `PageLayout` **`title`**. + The sticky row is for controls only. Put **where you are** in the + **`breadcrumbs` prop** (renders **inside the sticky `PageHeader`**, above the + toolbar) when the page lives under a hierarchy (e.g. `Dashboards` → + `Kubernetes`); otherwise you may omit `breadcrumbs` and rely on + `<Head><title>`, the sidebar active item, and the empty state copy. +3. **Never** duplicate location: do not set `title="Kubernetes Dashboard"` + **and** breadcrumbs that repeat the same page name. 4. **Never** use `<Text size="xl">` as the page title in the body. -5. **Global controls** (time range, Run, Save, sampling) go in `actions`, right-aligned. **Context** pickers go in `leading` (no `title` when those slots are used for inputs). **Breadcrumbs** use the `breadcrumbs` prop so they stay in the sticky header, not in `content`. +5. **Global controls** (time range, Run, Save, sampling) go in `actions`, + right-aligned. **Context** pickers go in `leading` (no `title` when those + slots are used for inputs). **Breadcrumbs** use the `breadcrumbs` prop so + they stay in the sticky header, not in `content`. 6. **Full-height tools** (maps, large charts): `fillViewport` on `PageLayout`. -7. **Search / Chart Explorer**: keep bespoke toolbars unless the task is explicitly to redesign them. +7. **Search**: keep the bespoke toolbar unless the task is explicitly to + redesign it. **Chart Explorer** uses a custom `PageHeader` fed by + `EditTimeChartForm`'s `toolbarTargets`; see `agent_docs/page_layout.md`. ## Workflow 1. Read `agent_docs/page_layout.md`. -2. Open a similar page already on `PageHeader` / `PageLayout` (e.g. `AlertsPage.tsx`, `DBServiceMapPage.tsx`, `KubernetesDashboardPage.tsx`). +2. Open a similar page already on `PageHeader` / `PageLayout` (e.g. + `AlertsPage.tsx`, `DBServiceMapPage.tsx`, `KubernetesDashboardPage.tsx`). 3. Implement using `@/components/PageLayout` or `@/components/PageHeader`. 4. Preserve or add `data-testid` on the page root for E2E tests. 5. Run `yarn lint:fix` in the repo root when done. -6. If the page has E2E coverage, run the relevant spec under `packages/app/tests/e2e/`. +6. If the page has E2E coverage, run the relevant spec under + `packages/app/tests/e2e/`. ## Imports @@ -35,10 +55,10 @@ import { PageLayout } from '@/components/PageLayout'; ## Reference implementations -| Page | File | Pattern | -|------|------|---------| -| List page | `AlertsPage.tsx` | `PageHeader` + `title` + `Container` (no inputs in header) | -| Tool page with inputs + hierarchy | `KubernetesDashboardPage.tsx`, `ClickhousePage.tsx` | `PageLayout` **without** `title`; **`breadcrumbs`** + `leading` + `actions` in one sticky header | -| Tool page (top-level) | `DBServiceMapPage.tsx` | `PageLayout` **without** `title`; `leading` / `actions` only; no duplicate breadcrumb unless you add a real hierarchy | -| Custom toolbar | `SessionsPage.tsx` | `PageLayout` + `header` = custom `PageHeader` `children` with `growing` (single-row inputs, no `title`) | -| Custom title | `TeamPage.tsx` | `PageHeader` with `children` only | +| Page | File | Pattern | +| --------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| List page | `AlertsPage.tsx` | `PageHeader` + `title` + `Container` (no inputs in header) | +| Tool page with inputs + hierarchy | `KubernetesDashboardPage.tsx`, `ClickhousePage.tsx` | `PageLayout` **without** `title`; **`breadcrumbs`** + `leading` + `actions` in one sticky header | +| Tool page (top-level) | `DBServiceMapPage.tsx` | `PageLayout` **without** `title`; `leading` / `actions` only; no duplicate breadcrumb unless you add a real hierarchy | +| Custom toolbar | `SessionsPage.tsx` | `PageLayout` + `header` = custom `PageHeader` `children` with `growing` (single-row inputs, no `title`) | +| Custom title | `TeamPage.tsx` | `PageHeader` with `children` only | diff --git a/agent_docs/page_layout.md b/agent_docs/page_layout.md index cde50f3c04..59b690c48c 100644 --- a/agent_docs/page_layout.md +++ b/agent_docs/page_layout.md @@ -1,15 +1,19 @@ # Page layout and headers -ClickStack app pages share a sticky top header bar and a scrollable content region below it. Use the shared layout primitives so titles, controls, and spacing stay consistent across Search, list pages, and tool pages (Service Map, Kubernetes, Chart Explorer). +ClickStack app pages share a sticky top header bar and a scrollable content +region below it. Use the shared layout primitives so titles, controls, and +spacing stay consistent across Search, list pages, and tool pages (Service Map, +Kubernetes, Chart Explorer). ## Components -| Component | Path | Use when | -|-----------|------|----------| -| `PageHeader` | `packages/app/src/components/PageHeader.tsx` | You only need the header bar (page already has its own content wrapper). | +| Component | Path | Use when | +| ------------ | -------------------------------------------- | --------------------------------------------------------------------------------- | +| `PageHeader` | `packages/app/src/components/PageHeader.tsx` | You only need the header bar (page already has its own content wrapper). | | `PageLayout` | `packages/app/src/components/PageLayout.tsx` | You want header + flex content column in one wrapper (recommended for new pages). | -Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps pages with the left nav and scroll container. +Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps +pages with the left nav and scroll container. ## PageHeader API @@ -28,16 +32,21 @@ Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps pag </PageHeader> ``` -| Prop | Purpose | -|------|---------| -| `title` | Plain page title (`<h1>`). **Use only when the sticky bar has no inputs** (list/settings pages). If the bar has pickers, search, sliders, or Run, omit `title` and use **`breadcrumbs`** (or rely on nav + document title only). | -| `breadcrumbs` | Location trail **inside the sticky header**, rendered above the toolbar when `leading` / `actions` are set. Use Mantine `Breadcrumbs` (e.g. `Dashboards` → current page). Do not duplicate the same text as `title`. | -| `leading` | Left cluster: source picker, badges, or other controls. When inputs are present, **do not** pair with `title` for the same page name. | -| `actions` | Right-aligned cluster: time range, Run/Save, sampling, refresh. | -| `children` | Full custom header when slots are not enough. Do not combine with `title` / `leading` / `actions` / `breadcrumbs` unless you use the breadcrumbs-only branch. | -| `growing` | Opt in to block padding that only shows once the toolbar outgrows `min-height`. Sessions uses this for its multi-line search; title-only pages omit it. | - -Header styling is defined in `PageHeader.module.scss`: sticky top, bottom border, horizontal padding `var(--mantine-spacing-sm)` (same as Search `px="sm"`). Single-row headers keep `min-height: 60px`; stacked header (breadcrumbs + toolbar) grows with content. Pass `growing` when the toolbar can outgrow that min-height (Sessions' multi-line search) so block padding appears only once the row is taller than the bar. +| Prop | Purpose | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | Plain page title (`<h1>`). **Use only when the sticky bar has no inputs** (list/settings pages). If the bar has pickers, search, sliders, or Run, omit `title` and use **`breadcrumbs`** (or rely on nav + document title only). | +| `breadcrumbs` | Location trail **inside the sticky header**, rendered above the toolbar when `leading` / `actions` are set. Use Mantine `Breadcrumbs` (e.g. `Dashboards` → current page). Do not duplicate the same text as `title`. | +| `leading` | Left cluster: source picker, badges, or other controls. When inputs are present, **do not** pair with `title` for the same page name. | +| `actions` | Right-aligned cluster: time range, Run/Save, sampling, refresh. | +| `children` | Full custom header when slots are not enough. Do not combine with `title` / `leading` / `actions` / `breadcrumbs` unless you use the breadcrumbs-only branch. | +| `growing` | Opt in to block padding that only shows once the toolbar outgrows `min-height`. Sessions uses this for its multi-line search; title-only pages omit it. | + +Header styling is defined in `PageHeader.module.scss`: sticky top, bottom +border, horizontal padding `var(--mantine-spacing-sm)` (same as Search +`px="sm"`). Single-row headers keep `min-height: 60px`; stacked header +(breadcrumbs + toolbar) grows with content. Pass `growing` when the toolbar can +outgrow that min-height (Sessions' multi-line search) so block padding appears +only once the row is taller than the bar. ## PageLayout API @@ -52,36 +61,55 @@ Header styling is defined in `PageHeader.module.scss`: sticky top, bottom border /> ``` -| Prop | Purpose | -|------|---------| -| `title`, `leading`, `actions`, `breadcrumbs`, `children` | Forwarded to `PageHeader` (same rules as above). | -| `header` | Replace the default `PageHeader` entirely. | -| `content` | Main page body below the header (required). | -| `fillViewport` | Set `height: 100vh` on the page root for full-height canvases (maps, charts). | -| `contentClassName` | Extra class on the content region (e.g. padding). | +| Prop | Purpose | +| -------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `title`, `leading`, `actions`, `breadcrumbs`, `children` | Forwarded to `PageHeader` (same rules as above). | +| `header` | Replace the default `PageHeader` entirely. | +| `content` | Main page body below the header (required). | +| `fillViewport` | Set `height: 100vh` on the page root for full-height canvases (maps, charts). | +| `contentClassName` | Extra class on the content region (e.g. padding). | ## When to use which pattern ### List / settings pages (Alerts, Dashboards, Saved Searches, Team) - Use `PageHeader` at the top of the page. -- Put filters, tables, and tabs in a `Container` below the header (see `AlertsPage.tsx`, `DashboardsListPage.tsx`). -- Simple title-only pages: `<PageHeader title="Dashboards" />` — **only** when the header row has **no** inputs. +- Put filters, tables, and tabs in a `Container` below the header (see + `AlertsPage.tsx`, `DashboardsListPage.tsx`). +- Simple title-only pages: `<PageHeader title="Dashboards" />` — **only** when + the header row has **no** inputs. ### Tool / canvas pages (Service Map, Kubernetes, Clickhouse, Chart Explorer) -- Prefer `PageLayout` with `fillViewport` when the main UI should fill remaining height. -- Put **global** controls in `actions` (time picker, sampling, Run)—not inside the canvas. +- Prefer `PageLayout` with `fillViewport` when the main UI should fill remaining + height. +- Put **global** controls in `actions` (time picker, sampling, Run)—not inside + the canvas. - Put **context** controls in `leading` (source picker, environment). -- **If the sticky header row includes any inputs** (selectors, sliders, search, time range, Run): **omit `title`**. Express location with the **`breadcrumbs` prop** on `PageLayout` / `PageHeader` so the trail stays **inside the sticky header** above the toolbar (see `KubernetesDashboardPage.tsx`). Do **not** repeat the same label as both `title` and the last breadcrumb. Top-level tools (e.g. Service Map) may omit `breadcrumbs` if `<Head><title>` and the sidebar active state are enough. +- **If the sticky header row includes any inputs** (selectors, sliders, search, + time range, Run): **omit `title`**. Express location with the **`breadcrumbs` + prop** on `PageLayout` / `PageHeader` so the trail stays **inside the sticky + header** above the toolbar (see `KubernetesDashboardPage.tsx`). Do **not** + repeat the same label as both `title` and the last breadcrumb. Top-level tools + (e.g. Service Map) may omit `breadcrumbs` if `<Head><title>` and the sidebar + active state are enough. ### Search and Chart Explorer (complex query chrome) -These pages use bespoke multi-row toolbars instead of a single title row. That is intentional until those flows are redesigned. Do not force a `title` on them; if you add a header row, use `PageHeader` `children` or a dedicated toolbar component, not ad-hoc `Text size="xl"` in the body. +Search uses a bespoke multi-row toolbar instead of a single title row. That is +intentional until the flow is redesigned. Chart Explorer uses a custom +`PageHeader` (`DBChartPage.tsx`): the form portals its mode and source controls +and its time range, granularity and Run controls into header slots +(`toolbarTargets` on `EditTimeChartForm`), and keeps them inline wherever the +form is embedded (tile editor, inline-alert editor). Do not force a `title` on +either; if you add a header row, use `PageHeader` `children` or a dedicated +toolbar component, not ad-hoc `Text size="xl"` in the body. ### Client Sessions (query + list) -Sessions keeps a **single-row** query toolbar (source, where filter, time range, Run). Put the full toolbar in a custom `PageHeader` via `PageLayout` `header` — do not split controls across `title` / `leading` / `actions` / `content`. +Sessions keeps a **single-row** query toolbar (source, where filter, time range, +Run). Put the full toolbar in a custom `PageHeader` via `PageLayout` `header` — +do not split controls across `title` / `leading` / `actions` / `content`. ## Do / don't @@ -116,10 +144,13 @@ Sessions keeps a **single-row** query toolbar (source, where filter, time range, ## Migrating an existing page -1. Replace `Text size="xl"` title + `Group justify="space-between"` with `PageLayout` or `PageHeader` slots. +1. Replace `Text size="xl"` title + `Group justify="space-between"` with + `PageLayout` or `PageHeader` slots. 2. Move time picker and primary actions to `actions`. 3. Move source pickers and badges to `leading`. -4. If the sticky bar has inputs, **do not** set `title`; pass **`breadcrumbs`** on `PageLayout` when the route has a hierarchy (breadcrumbs render inside the sticky `PageHeader`, not in `content`). +4. If the sticky bar has inputs, **do not** set `title`; pass **`breadcrumbs`** + on `PageLayout` when the route has a hierarchy (breadcrumbs render inside the + sticky `PageHeader`, not in `content`). 5. Keep `data-testid` on `PageLayout` / page root for E2E tests. 6. Run affected Playwright tests (`packages/app/tests/e2e/`). @@ -127,25 +158,44 @@ Sessions keeps a **single-row** query toolbar (source, where filter, time range, - Alerts, Dashboards, Saved Searches — `PageHeader` with `title` - Team — custom `PageHeader` `children` (editable name) -- Service Map — `PageLayout` with `fillViewport`, `leading` / `actions` only (no `title`; top-level tool) -- Kubernetes Dashboard, Clickhouse Dashboard — `PageLayout` with `breadcrumbs`, `leading`, `actions`, `padded` (no `title`) -- Client Sessions — `PageLayout` with custom `PageHeader` containing the full single-row query toolbar +- Service Map — `PageLayout` with `fillViewport`, `leading` / `actions` only (no + `title`; top-level tool) +- Kubernetes Dashboard, Clickhouse Dashboard — `PageLayout` with `breadcrumbs`, + `leading`, `actions`, `padded` (no `title`) +- Client Sessions — `PageLayout` with custom `PageHeader` containing the full + single-row query toolbar ## Compact viewports -A viewport under 900px is compact. `useCompactViewport` (`packages/app/src/components/CompactViewport/useCompactViewport.ts`) is the cutoff, and the nav collapses on the same width. Pages that switch layout use this hook. +A viewport under 900px is compact. `useCompactViewport` +(`packages/app/src/components/CompactViewport/useCompactViewport.ts`) is the +cutoff, and the nav collapses on the same width. Pages that switch layout use +this hook. -A page that is a side panel plus a main pane uses `ResponsiveSidePanel` (`packages/app/src/components/CompactViewport/ResponsiveSidePanel.tsx`): +A page that is a side panel plus a main pane uses `ResponsiveSidePanel` +(`packages/app/src/components/CompactViewport/ResponsiveSidePanel.tsx`): - Wide: the panel sits beside the main pane. -- Compact: the main pane uses the full width. The panel opens in a drawer and does not take horizontal space. Pass a `title`; the drawer has no default. The panel stays unmounted until the first open, then stays mounted so closing the drawer does not drop its state. +- Compact: the main pane uses the full width. The panel opens in a drawer and + does not take horizontal space. Pass a `title`; the drawer has no default. The + panel stays unmounted until the first open, then stays mounted so closing the + drawer does not drop its state. -The caller owns whether the panel is open. Keep that state separate from any desktop collapse preference stored in localStorage. A phone session that wrote the desktop preference would hide the panel the next time the same browser opened the page on a desktop. +The caller owns whether the panel is open. Keep that state separate from any +desktop collapse preference stored in localStorage. A phone session that wrote +the desktop preference would hide the panel the next time the same browser +opened the page on a desktop. -Give the main pane `flex: 1` and `min-height: 0` inside a full-height column, so it keeps the space under the toolbar and scrolls inside itself. A hard `min-width` on the panel inside `overflow: hidden` clips the main pane on a phone. +Give the main pane `flex: 1` and `min-height: 0` inside a full-height column, so +it keeps the space under the toolbar and scrolls inside itself. A hard +`min-width` on the panel inside `overflow: hidden` clips the main pane on a +phone. -Search is the first page on this pattern. Other side-panel pages should adopt it the same way instead of a one-off media query. +Search is the first page on this pattern. Other side-panel pages should adopt it +the same way instead of a one-off media query. ## Knip -`packages/app` Knip entry roots are `pages/`, `scripts/`, and e2e tests. After you add or move a `PageLayout` import, run `yarn knip` from the repo root (or `yarn knip` in `packages/app` if configured) so new consumers stay wired. +`packages/app` Knip entry roots are `pages/`, `scripts/`, and e2e tests. After +you add or move a `PageLayout` import, run `yarn knip` from the repo root (or +`yarn knip` in `packages/app` if configured) so new consumers stay wired. diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx index f889fc753e..ca9cbae90c 100644 --- a/packages/app/src/ChartUtils.tsx +++ b/packages/app/src/ChartUtils.tsx @@ -640,6 +640,14 @@ export interface LineData { isDashed?: boolean; } +/** The colors a time chart assigned, keyed by the value column they plot. */ +export interface TimeChartSeriesColors { + valueColumns: string[]; + colorByColumn: Record<string, string>; + /** Grouped charts color per group, so a column has no single color. */ + isGrouped: boolean; +} + interface LineDataWithOptionalColor extends Omit<LineData, 'color'> { color?: string; } diff --git a/packages/app/src/DBChartPage.tsx b/packages/app/src/DBChartPage.tsx index 186499a751..2dca9e77f9 100644 --- a/packages/app/src/DBChartPage.tsx +++ b/packages/app/src/DBChartPage.tsx @@ -3,210 +3,37 @@ import dynamic from 'next/dynamic'; import Head from 'next/head'; import Link from 'next/link'; import { parseAsJson, parseAsString, useQueryState } from 'nuqs'; -import { useForm } from 'react-hook-form'; import { useHotkeys } from 'react-hotkeys-hook'; -import { Badge, Separator } from '@clickhouse/click-ui'; -import { SavedChartConfig, SourceKind } from '@hyperdx/common-utils/dist/types'; -import { - Alert, - Anchor, - Box, - Button, - Collapse, - Divider, - Group, - Loader, - Skeleton, - Stack, - Text, -} from '@mantine/core'; +import { SavedChartConfig } from '@hyperdx/common-utils/dist/types'; +import { Anchor, Flex, Skeleton, Stack } from '@mantine/core'; import { notifications } from '@mantine/notifications'; -import { - IconChevronDown, - IconChevronUp, - IconInfoCircle, -} from '@tabler/icons-react'; import { useQueryClient } from '@tanstack/react-query'; import api from '@/api'; -import { useBrandDisplayName, usePageTitle } from '@/brand'; +import { usePageTitle } from '@/brand'; import { DEFAULT_CHART_CONFIG } from '@/ChartUtils'; +import { + ChartAssistantPopover, + ChartAssistantUnavailableAlert, +} from '@/components/ChartAssistant/ChartAssistant'; import EditTimeChartForm from '@/components/DBEditTimeChartForm'; -import { InputControlled } from '@/components/InputControlled'; -import { SourceSelectControlled } from '@/components/SourceSelect'; import { IS_ALERT_DETAILS_ENABLED } from '@/config'; -import { useChartAssistant } from '@/hooks/ai'; import { useAlertSeededChartConfig } from '@/hooks/useAlertSeededChartConfig'; import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam'; import { withAppNavForSurface } from '@/layout'; import { useSources } from '@/source'; import { useDefaultTimeRange, useNewTimeQuery } from '@/timeQuery'; -import { useLocalStorage } from '@/utils'; import { buildInlineAlertPayload } from '@/utils/alerts'; import { getApiErrorMessage } from '@/utils/apiErrors'; import OnboardingModal from './components/OnboardingModal'; +import { PageHeader } from './components/PageHeader'; +import { PageLayout } from './components/PageLayout'; // Autocomplete can focus on column/map keys // Sampled field discovery and full field discovery -function AIAssistant({ - setConfig, - onTimeRangeSelect, - submitRef, - aiAssistantEnabled, -}: { - setConfig: (config: SavedChartConfig) => void; - onTimeRangeSelect: (start: Date, end: Date) => void; - submitRef: React.RefObject<(() => void) | undefined>; - aiAssistantEnabled: boolean; -}) { - const brandName = useBrandDisplayName(); - const [opened, setOpened] = useState(false); - const [alertDismissed, setAlertDismissed] = useLocalStorage( - 'ai-assistant-alert-dismissed', - false, - ); - const { control, handleSubmit } = useForm<{ - text: string; - source: string; - }>({ - defaultValues: { - text: '', - source: '', - }, - }); - - const chartAssistant = useChartAssistant(); - - const onSubmit = (data: { text: string; source: string }) => { - chartAssistant.mutate( - { - sourceId: data.source, - text: data.text, - }, - { - onSuccess(data) { - setConfig({ ...data, where: '' }); - onTimeRangeSelect( - new Date(data.dateRange[0]), - new Date(data.dateRange[1]), - ); - - // FIXME: This is a hack to submit after the form has been updated - setTimeout(() => { - if (submitRef.current) { - submitRef.current(); - } - }, 100); - - notifications.show({ - color: 'green', - message: 'Chart generated successfully', - autoClose: 2000, - }); - }, - onError(err) { - notifications.show({ - color: 'red', - title: 'Error Generating Chart', - message: err.message, - autoClose: 2000, - }); - }, - }, - ); - }; - - useHotkeys( - 'a', - () => { - setOpened(v => !v); - }, - { - preventDefault: true, - }, - ); - - if (!aiAssistantEnabled && !alertDismissed) { - return ( - <Box mb="sm"> - <Alert - color="dark" - icon={<IconInfoCircle size={16} />} - variant="outline" - withCloseButton - onClose={() => setAlertDismissed(true)} - p="xxs" - > - <Text size="xs" pt="2px"> - New AI Assistant available, enable with configuring the{' '} - <code>ANTHROPIC_API_KEY</code> environment variable on the{' '} - {brandName} server. - </Text> - </Alert> - <Divider mt="sm" /> - </Box> - ); - } else if (!aiAssistantEnabled) { - return null; - } - - return ( - <Box mb="sm"> - <Group gap="md" align="center" mb="sm"> - <Button onClick={() => setOpened(o => !o)} size="xs" variant="subtle"> - <Group gap="xs"> - {opened ? ( - <IconChevronUp size={14} /> - ) : ( - <IconChevronDown size={14} /> - )} - <Text size="xxs">AI Assistant [A]</Text> - </Group> - </Button> - <Badge size="sm" text="Experimental" state="info" /> - </Group> - <Collapse expanded={opened}> - {opened && ( - // eslint-disable-next-line react-hooks/refs - <form onSubmit={handleSubmit(onSubmit)}> - <Group mb="md"> - <SourceSelectControlled - autoFocus - size="xs" - control={control} - name="source" - data-testid="source-selector" - allowedSourceKinds={[SourceKind.Log, SourceKind.Trace]} - /> - <Box style={{ flexGrow: 1, minWidth: 100 }}> - <InputControlled - placeholder="ex. Error counts by service over last 2 hours" - data-testid="save-search-name-input" - control={control} - name="text" - rules={{ required: true }} - size="xs" - /> - </Box> - {chartAssistant.isPending ? ( - <Loader size="xs" type="dots" /> - ) : ( - <Button type="submit" size="xs" variant="primary"> - Generate - </Button> - )} - </Group> - </form> - )} - </Collapse> - <Separator size="xs" /> - </Box> - ); -} - const DEFAULT_INTERVAL = 'Past 1h'; function DBChartExplorerPage() { @@ -229,6 +56,22 @@ function DBChartExplorerPage() { const { data: me } = api.useMe(); const queryClient = useQueryClient(); const createAlert = api.useCreateAlert(); + const aiAssistantEnabled = me?.aiAssistantEnabled ?? false; + const [assistantOpened, setAssistantOpened] = useState(false); + const [leadingTarget, setLeadingTarget] = useState<HTMLElement | null>(null); + const [chartTypeTarget, setChartTypeTarget] = useState<HTMLElement | null>( + null, + ); + const [saveTarget, setSaveTarget] = useState<HTMLElement | null>(null); + const [actionsTarget, setActionsTarget] = useState<HTMLElement | null>(null); + + useHotkeys( + 'a', + () => { + if (aiAssistantEnabled) setAssistantOpened(v => !v); + }, + { preventDefault: true }, + ); const [rawChartConfig, setChartConfig] = useQueryState( 'config', @@ -313,47 +156,91 @@ function DBChartExplorerPage() { [createAlert, queryClient, setChartConfig], ); + const aiAssistantButton = aiAssistantEnabled ? ( + <ChartAssistantPopover + currentConfig={rawChartConfig} + searchedTimeRange={searchedTimeRange} + setConfig={setChartConfig} + onTimeRangeSelect={onTimeRangeSelect} + submitRef={submitRef} + opened={assistantOpened} + onOpenChange={setAssistantOpened} + /> + ) : null; + return ( - <Box data-testid="chart-explorer-page" p="sm"> - <Head> - <title>{title} - - - - {/* Held back until an `alertId` seed resolves: the form auto-runs once - on mount, and mounting it early would run the default config and - then swap the query out from under the result. */} - {isSeedingFromAlert ? ( - - - - - ) : ( - { - setChartConfig(config); - }} - dateRange={searchedTimeRange} - setDisplayedTimeInputValue={setDisplayedTimeInputValue} - displayedTimeInputValue={displayedTimeInputValue} - onTimeRangeSearch={onSearch} - onTimeRangeSelect={onTimeRangeSelect} - submitRef={submitRef} - autoRun - enableAlerts - onSaveAlert={onSaveAlert} - saveAlertLabel="Create alert" - isSavingAlert={createAlert.isPending} - /> - )} - + + + + + + + {aiAssistantButton} + + + + + + + + + } + padded + content={ + <> + + {title} + + + + {/* Held back until an `alertId` seed resolves: the form auto-runs once + on mount, and mounting it early would run the default config and + then swap the query out from under the result. */} + {isSeedingFromAlert ? ( + + + + + ) : ( + { + setChartConfig(config); + }} + dateRange={searchedTimeRange} + setDisplayedTimeInputValue={setDisplayedTimeInputValue} + displayedTimeInputValue={displayedTimeInputValue} + onTimeRangeSearch={onSearch} + onTimeRangeSelect={onTimeRangeSelect} + submitRef={submitRef} + showChartName={false} + autoRun + enableAlerts + onSaveAlert={onSaveAlert} + saveAlertLabel="Create alert" + isSavingAlert={createAlert.isPending} + toolbarTargets={{ + leading: leadingTarget, + chartType: chartTypeTarget, + save: saveTarget, + actions: actionsTarget, + }} + /> + )} + + } + /> ); } diff --git a/packages/app/src/components/AlertPanel.tsx b/packages/app/src/components/AlertPanel.tsx index 4de9aa501d..105db3d2a7 100644 --- a/packages/app/src/components/AlertPanel.tsx +++ b/packages/app/src/components/AlertPanel.tsx @@ -136,6 +136,9 @@ export function AlertPanelLayout({ actions, onOpen, onCancel, + sidePanel, + sidePanelOpened, + onSidePanelClose, children, ...props }: BoxProps & { @@ -150,6 +153,14 @@ export function AlertPanelLayout({ onOpen?: () => void; /** Undoes the panel's changes when it is closed without confirming them. */ onCancel?: (isDraft: boolean) => void; + /** + * Another panel that shares this slot (the chart's display settings). It + * takes the slot while open, and the alert panel waits behind it with its + * changes intact. Opening the alert panel calls `onSidePanelClose`. + */ + sidePanel?: ReactNode; + sidePanelOpened?: boolean; + onSidePanelClose?: () => void; children: ReactNode; }) { const [opened, setOpened] = useState(defaultOpened); @@ -157,8 +168,19 @@ export function AlertPanelLayout({ const [target, setTarget] = useState(null); const [hasContent, setHasContent] = useState(false); const [root, setRoot] = useState(null); - const showPanel = opened && hasContent; + const sidePanelVisible = sidePanelOpened === true && sidePanel != null; + const alertVisible = opened && hasContent && !sidePanelVisible; + const showPanel = alertVisible || sidePanelVisible; const bounds = usePanelBounds(root, showPanel); + const openAlertPanel = useCallback( + (nextOpened: boolean) => { + if (nextOpened) { + onSidePanelClose?.(); + } + setOpened(nextOpened); + }, + [onSidePanelClose], + ); // The handle sits on the panel's left edge, so dragging left widens it. const { size: widthPercent, startResize } = useResizable( DEFAULT_PANEL_WIDTH_PERCENT, @@ -174,7 +196,7 @@ export function AlertPanelLayout({ const value = useMemo( () => ({ opened, - setOpened, + setOpened: openAlertPanel, isDraft, setIsDraft, onOpen, @@ -184,7 +206,7 @@ export function AlertPanelLayout({ setTarget, setHasContent, }), - [opened, isDraft, onOpen, onCancel, actions, target], + [opened, openAlertPanel, isDraft, onOpen, onCancel, actions, target], ); return ( @@ -214,12 +236,18 @@ export function AlertPanelLayout({ onMouseDown={startResize} data-testid="alert-panel-resize-handle" /> - + {alertVisible ? ( + + ) : ( + + {sidePanel} + + )} )} diff --git a/packages/app/src/components/ChartAssistant/ChartAssistant.tsx b/packages/app/src/components/ChartAssistant/ChartAssistant.tsx new file mode 100644 index 0000000000..1812e6def8 --- /dev/null +++ b/packages/app/src/components/ChartAssistant/ChartAssistant.tsx @@ -0,0 +1,239 @@ +import type { RefObject } from 'react'; +import { useForm } from 'react-hook-form'; +import { SavedChartConfig, SourceKind } from '@hyperdx/common-utils/dist/types'; +import { + ActionIcon, + Alert, + Box, + Button, + Divider, + Group, + Kbd, + Loader, + Popover, + Stack, + Text, + Tooltip, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; +import { IconInfoCircle, IconSparkles } from '@tabler/icons-react'; + +import { useBrandDisplayName } from '@/brand'; +import { InputControlled } from '@/components/InputControlled'; +import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useChartAssistant } from '@/hooks/ai'; +import { useLocalStorage } from '@/utils'; + +const POPOVER_WIDTH = 360; + +const UNDO_NOTIFICATION_MS = 8000; + +interface ChartAssistantFormValues { + text: string; + source: string; +} + +export function ChartAssistantUnavailableAlert({ + aiAssistantEnabled, +}: { + aiAssistantEnabled: boolean; +}) { + const brandName = useBrandDisplayName(); + const [alertDismissed, setAlertDismissed] = useLocalStorage( + 'ai-assistant-alert-dismissed', + false, + ); + + if (aiAssistantEnabled || alertDismissed) return null; + + return ( + + } + variant="outline" + withCloseButton + onClose={() => setAlertDismissed(true)} + p="xxs" + > + + New AI Assistant available, enable with configuring the{' '} + ANTHROPIC_API_KEY environment variable on the {brandName}{' '} + server. + + + + + ); +} + +export interface ChartAssistantPopoverProps { + currentConfig: SavedChartConfig; + searchedTimeRange: [Date, Date]; + setConfig: (config: SavedChartConfig) => void; + onTimeRangeSelect: (start: Date, end: Date) => void; + submitRef: RefObject<(() => void) | undefined>; + opened: boolean; + onOpenChange: (opened: boolean) => void; +} + +/** + * Generates a chart from a prompt, from a sparkles button in the page header. + * The generated chart replaces the current one, so the notification after a + * successful generation offers to restore the previous chart and time range. + */ +export function ChartAssistantPopover({ + currentConfig, + searchedTimeRange, + setConfig, + onTimeRangeSelect, + submitRef, + opened, + onOpenChange, +}: ChartAssistantPopoverProps) { + const { control, handleSubmit, reset } = useForm({ + defaultValues: { + text: '', + source: '', + }, + }); + const chartAssistant = useChartAssistant(); + + const onSubmit = (data: ChartAssistantFormValues) => { + const previousConfig = currentConfig; + const [previousStart, previousEnd] = searchedTimeRange; + + chartAssistant.mutate( + { + sourceId: data.source, + text: data.text, + }, + { + onSuccess(generated) { + reset(); + onOpenChange(false); + setConfig({ ...generated, where: '' }); + onTimeRangeSelect( + new Date(generated.dateRange[0]), + new Date(generated.dateRange[1]), + ); + + // FIXME: This is a hack to submit after the form has been updated + setTimeout(() => { + if (submitRef.current) { + submitRef.current(); + } + }, 100); + + const notificationId = notifications.show({ + color: 'green', + autoClose: UNDO_NOTIFICATION_MS, + message: ( + + Chart generated. + + + ), + }); + }, + onError(err) { + notifications.show({ + color: 'red', + title: 'Error generating chart', + message: err.message, + autoClose: 2000, + }); + }, + }, + ); + }; + + return ( + + + + AI assistant + A + + } + > + onOpenChange(!opened)} + > + + + + + + + + AI assistant + + + Describe the chart you want. It replaces the current chart, and you + can undo it. + + {/* eslint-disable-next-line react-hooks/refs */} +
+ + + + + {chartAssistant.isPending ? ( + + ) : ( + + )} + + +
+
+
+
+ ); +} diff --git a/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx b/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx new file mode 100644 index 0000000000..6b3f8cd72f --- /dev/null +++ b/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx @@ -0,0 +1,110 @@ +import { SavedChartConfig } from '@hyperdx/common-utils/dist/types'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { DEFAULT_CHART_CONFIG } from '@/ChartUtils'; +import { ChartAssistantPopover } from '@/components/ChartAssistant/ChartAssistant'; + +const mockMutate = jest.fn(); +jest.mock('@/hooks/ai', () => ({ + useChartAssistant: () => ({ mutate: mockMutate, isPending: false }), +})); + +jest.mock('@/components/SourceSelect', () => ({ + SourceSelectControlled: () =>
, +})); + +const mockNotificationShow = jest.fn(); +jest.mock('@mantine/notifications', () => ({ + notifications: { + show: (...args: unknown[]) => mockNotificationShow(...args), + update: jest.fn(), + }, +})); + +const previousConfig: SavedChartConfig = { + ...DEFAULT_CHART_CONFIG, + source: 'previous-source', + where: 'service:api', +}; +const previousRange: [Date, Date] = [ + new Date('2026-11-27T00:00:00Z'), + new Date('2026-11-27T01:00:00Z'), +]; +const generatedResponse = { + ...DEFAULT_CHART_CONFIG, + source: 'generated-source', + where: 'generated', + dateRange: ['2026-11-26T00:00:00Z', '2026-11-26T06:00:00Z'], +}; + +// jsdom has no layout, so the popover dropdown stays `display: none`; query +// hidden elements. +function renderPanel() { + const setConfig = jest.fn(); + const onTimeRangeSelect = jest.fn(); + const onOpenChange = jest.fn(); + renderWithMantine( + , + ); + return { setConfig, onTimeRangeSelect, onOpenChange }; +} + +describe('ChartAssistantPopover', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('replaces the chart on success and offers an undo that restores it', async () => { + const user = userEvent.setup(); + const { setConfig, onTimeRangeSelect, onOpenChange } = renderPanel(); + + await user.type( + screen.getByTestId('save-search-name-input'), + 'errors by service', + ); + await user.click( + screen.getByRole('button', { name: 'Generate', hidden: true }), + ); + + const [input, options] = mockMutate.mock.calls[0]; + expect(input).toEqual({ sourceId: '', text: 'errors by service' }); + + options.onSuccess(generatedResponse); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(setConfig).toHaveBeenCalledWith({ ...generatedResponse, where: '' }); + expect(onTimeRangeSelect).toHaveBeenCalledWith( + new Date('2026-11-26T00:00:00Z'), + new Date('2026-11-26T06:00:00Z'), + ); + + const [{ message }] = mockNotificationShow.mock.calls[0]; + renderWithMantine(<>{message}); + setConfig.mockClear(); + onTimeRangeSelect.mockClear(); + + await user.click(screen.getByRole('button', { name: 'Undo' })); + + expect(setConfig).toHaveBeenCalledWith(previousConfig); + expect(onTimeRangeSelect).toHaveBeenCalledWith(...previousRange); + }); + + it('does not submit an empty prompt', async () => { + const user = userEvent.setup(); + renderPanel(); + + await user.click( + screen.getByRole('button', { name: 'Generate', hidden: true }), + ); + + await waitFor(() => expect(mockMutate).not.toHaveBeenCalled()); + }); +}); diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 498fe93ab1..6564747b62 100644 --- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx +++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx @@ -22,7 +22,7 @@ import { Box, Button, Checkbox, - Drawer, + CloseButton, Group, Input, NumberInput, @@ -322,13 +322,21 @@ export default function ChartDisplaySettingsDrawer({ // Log scale only means something on a numeric (distribution mode) y axis const showHeatmapScale = isDistributionHeatmap; + // Rendered in the chart editor's side panel (see AlertPanelLayout), so it + // mounts only while open and drops unapplied edits on close. + if (!opened) { + return null; + } + return ( - + + + Display Settings + + {isTimeChart && ( <> @@ -638,6 +646,6 @@ export default function ChartDisplaySettingsDrawer({ - + ); } diff --git a/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx b/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx index a97e302986..fb75d1c2c7 100644 --- a/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx +++ b/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx @@ -2,9 +2,10 @@ import { ReactNode } from 'react'; import { Control, Path } from 'react-hook-form'; import { NumberFormat } from '@hyperdx/common-utils/dist/types'; import { - ActionIcon, Button, + ColorSwatch, Divider, + Flex, Group, Text, Tooltip, @@ -17,7 +18,7 @@ import { } from '@tabler/icons-react'; import { TextInputControlled } from '@/components/InputControlled'; -import { FORMAT_ICONS } from '@/components/NumberFormat'; +import SeriesNumberFormatPopover from '@/components/SeriesNumberFormatPopover'; import { ChartEditorFormState } from './types'; @@ -32,9 +33,11 @@ export function ChartSeriesControls({ onSwap, onRemove, onDuplicate, - onOpenNumberFormat, + onNumberFormatChange, leadingSection, trailingSection, + card = false, + color, }: { control: Control; aliasName: Path; @@ -47,92 +50,120 @@ export function ChartSeriesControls({ onRemove?: (index: number) => void; onDuplicate?: (index: number) => void; /** Absent where the row has no format of its own. */ - onOpenNumberFormat?: () => void; + onNumberFormatChange?: (format: { numberFormat?: NumberFormat }) => void; /** Rendered before the alias (the builder's formula reference badge). */ leadingSection?: ReactNode; /** Rendered after the format button (the builder's color picker). */ trailingSection?: ReactNode; + /** Lay the row out as a card header (alias left, actions right). */ + card?: boolean; + /** The color the chart draws this series in, shown as a swatch. */ + color?: string; }) { const isFirst = index <= 0; const isLast = index >= length - 1; + const aliasInput = ( +
+ onSubmit()} + size="xs" + data-testid="series-alias-input" + /> +
+ ); + + const actions = ( + <> + {onSwap && !isFirst && ( + + )} + {onSwap && !isLast && ( + + )} + {onDuplicate && ( + + )} + {onRemove && ( + + )} + {onNumberFormatChange && ( + + )} + {trailingSection} + + ); + + if (card) { + return ( + + + {color && ( + + + + )} + {leadingSection} + Alias + {aliasInput} + + {actions} + + ); + } + return ( {leadingSection} Alias - -
- onSubmit()} - size="xs" - data-testid="series-alias-input" - /> -
- {onSwap && !isFirst && ( - - )} - {onSwap && !isLast && ( - - )} - {onDuplicate && ( - - )} - {onRemove && ( - - )} - {onOpenNumberFormat && ( - - - {FORMAT_ICONS[numberFormat?.output ?? 'number']} - - - )} - {trailingSection} + {aliasInput} + {actions} } labelPosition="right" diff --git a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx index 9a7942579e..38be79b99f 100644 --- a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx @@ -16,11 +16,11 @@ import { PromqlHeatmapMode, SourceKind, } from '@hyperdx/common-utils/dist/types'; -import { Box, Button, Divider, Flex, Group, Text } from '@mantine/core'; +import { Box, Button, Divider, Flex, Group } from '@mantine/core'; import { IconCirclePlus } from '@tabler/icons-react'; +import { DisplaySettingsButton } from '@/components/DBEditTimeChartForm/DisplaySettingsButton'; import { HeatmapModeControl } from '@/components/DBEditTimeChartForm/HeatmapModeControl'; -import { SourceSelectControlled } from '@/components/SourceSelect'; import { useResolvedReference } from '@/components/sourceSelectUtils'; import { usePromqlMetricNames } from '@/hooks/usePromqlMetadata'; import { useSource } from '@/source'; @@ -32,7 +32,6 @@ import { promqlExpressionPlaceholder } from './utils'; export default function PromqlChartEditor({ control, getValues, - allowedSourceKinds, onSubmit, onOpenDisplaySettings, heatmapMode, @@ -40,7 +39,6 @@ export default function PromqlChartEditor({ }: { control: Control; getValues: UseFormGetValues; - allowedSourceKinds: SourceKind[]; onSubmit: (suppressErrorNotification?: boolean) => void; onOpenDisplaySettings: () => void; heatmapMode: PromqlHeatmapMode; @@ -98,19 +96,6 @@ export default function PromqlChartEditor({ return ( <> - - - Data Source - - - {displayType === DisplayType.Heatmap && ( )} - + ); diff --git a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx index 7dff69c168..2efdfffa2f 100644 --- a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo } from 'react'; import { Control, UseFormSetValue, useWatch } from 'react-hook-form'; import { displayTypeSupportsRawSqlAlerts, @@ -9,30 +9,15 @@ import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVari import { ChartVariable, RawSqlChartConfig, - SourceKind, } from '@hyperdx/common-utils/dist/types'; import { DisplayType, isMetricSource } from '@hyperdx/common-utils/dist/types'; -import { - Alert, - Box, - Button, - Group, - List, - Stack, - Text, - Tooltip, -} from '@mantine/core'; +import { Alert, Box, Group, List, Stack } from '@mantine/core'; import { useDebouncedValue } from '@mantine/hooks'; -import { IconHelpCircle } from '@tabler/icons-react'; -import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; import { AlertPanelButton } from '@/components/DBEditTimeChartForm/AlertPanelButton'; +import { DisplaySettingsButton } from '@/components/DBEditTimeChartForm/DisplaySettingsButton'; import { OnClickFormButton } from '@/components/DBEditTimeChartForm/OnClickForm/OnClickFormButton'; import { TileAlertEditor } from '@/components/DBEditTimeChartForm/TileAlertEditor'; -import SourceSchemaPreview, { - isSourceSchemaPreviewEnabled, -} from '@/components/SourceSchemaPreview'; -import { SourceSelectControlled } from '@/components/SourceSelect'; import { useResolvedReference } from '@/components/sourceSelectUtils'; import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor'; import { type SQLCompletion } from '@/components/SQLEditor/utils'; @@ -53,7 +38,6 @@ import resizeStyles from '@/../styles/ResizablePanel.module.scss'; export default function RawSqlChartEditor({ control, setValue, - allowedSourceKinds, onOpenDisplaySettings, onSubmit, isDashboardForm, @@ -66,7 +50,6 @@ export default function RawSqlChartEditor({ }: { control: Control; setValue: UseFormSetValue; - allowedSourceKinds: SourceKind[]; onOpenDisplaySettings: () => void; onSubmit: (suppressErrorNotification?: boolean) => void; isDashboardForm: boolean; @@ -175,9 +158,6 @@ export default function RawSqlChartEditor({ [displayType, variables], ); - const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = - useState(false); - const tableConnections = useMemo( () => getTableConnectionsForConnection(sources, connection), [sources, connection], @@ -196,83 +176,28 @@ export default function RawSqlChartEditor({ return ( - - - - Connection - - - - - Source - - {isDashboardForm && ( - - - - )} - - + {displayType === DisplayType.Table && ( + setIsSourceSchemaPreviewOpen(true)} - isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(sourceObject)} + setValue={setValue} + onSubmit={onSubmit} /> - setIsSourceSchemaPreviewOpen(false)} + )} + {showAlertButton && ( + + setValue('alert', { + ...DEFAULT_TILE_ALERT, + ...(chartName && { displayName: chartName }), + }) + } /> - - - {showAlertButton && ( - - setValue('alert', { - ...DEFAULT_TILE_ALERT, - ...(chartName && { displayName: chartName }), - }) - } - /> - )} - - {displayType === DisplayType.Table && ( - - )} - - - + )} + + {color && ( + + )} + {children} + + ); +} diff --git a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts index a8da9b70a4..75398a9f48 100644 --- a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts @@ -24,6 +24,7 @@ import { convertFormStateToSavedChartConfig, convertSavedChartConfigToFormState, getAllowedSourceKinds, + getDefaultChartName, getInterchangeableSourceKind, promqlExpressionPlaceholder, validateChartForm, @@ -2805,3 +2806,30 @@ describe('getInterchangeableSourceKind', () => { }, ); }); + +describe('getDefaultChartName', () => { + it('names a count without a group by', () => { + expect(getDefaultChartName({ aggFn: 'count' }, undefined)).toBe( + 'Count of events', + ); + }); + + it('adds the group by', () => { + expect(getDefaultChartName({ aggFn: 'count' }, 'ServiceName')).toBe( + 'Count of events by ServiceName', + ); + }); + + it('names a measure after its column', () => { + expect( + getDefaultChartName( + { aggFn: 'avg', valueExpression: 'Duration' }, + 'ServiceName', + ), + ).toBe('avg of Duration by ServiceName'); + }); + + it('falls back when there is no series', () => { + expect(getDefaultChartName(undefined, undefined)).toBe('Untitled chart'); + }); +}); diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index e6f2dba3e3..5a4d139d5d 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -830,3 +830,21 @@ export const validateChartForm = ( return errors; }; + +/** + * Name for a chart the user has not named, from its first series and group by. + * It becomes the tile name on save and the default alert name, so an unnamed + * chart still has a name where it is stored. + */ +export function getDefaultChartName( + firstSeries: { aggFn?: string; valueExpression?: string } | undefined, + groupBy: string | undefined, +): string { + if (firstSeries?.aggFn == null) return 'Untitled chart'; + const measure = + firstSeries.aggFn === 'count' + ? 'Count of events' + : `${firstSeries.aggFn} of ${firstSeries.valueExpression?.trim() || 'events'}`; + const by = groupBy?.trim(); + return by ? `${measure} by ${by}` : measure; +} diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx index aa25ac16cb..e1f8eb83c6 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx @@ -1,20 +1,9 @@ +import { createPortal } from 'react-dom'; import { Control, useWatch } from 'react-hook-form'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; import { isRangeQuery } from '@hyperdx/common-utils/dist/core/promql'; -import { - ActionIcon, - Box, - Button, - Flex, - Menu, - Switch, - Tooltip, -} from '@mantine/core'; -import { - IconDotsVertical, - IconLayoutGrid, - IconPlayerPlay, -} from '@tabler/icons-react'; +import { Box, Button, Flex, Switch, Tooltip } from '@mantine/core'; +import { IconLayoutGrid, IconPlayerPlay } from '@tabler/icons-react'; import { ChartEditorFormState } from '@/components/ChartEditor/types'; import { isPromqlDisplayType } from '@/components/ChartEditor/utils'; @@ -59,6 +48,30 @@ function DashboardFiltersToggle({ ); } +export function canSaveToDashboard({ + showSaveToDashboard, + dashboardId, +}: { + showSaveToDashboard?: boolean; + dashboardId?: string; +}) { + return !IS_LOCAL_MODE && (showSaveToDashboard ?? !dashboardId); +} + +export function SaveToDashboardButton({ onClick }: { onClick: () => void }) { + return ( + + ); +} + type ChartActionBarProps = { control: Control; tableConnection: TableConnection; @@ -81,6 +94,14 @@ type ChartActionBarProps = { onTimeRangeSearch?: (value: string) => void; filtersToggle?: DashboardFiltersToggleProps; setSaveToDashboardModalOpen: (open: boolean) => void; + /** + * When set, the time range, granularity, Run and Save controls render into + * this element (a page header) instead of inline. ORDER BY is part of the + * query, so it stays with the editor, and Save to dashboard is left to the + * caller (see `SaveToDashboardButton`). A page that hosts the form passes + * `null` until its header mounts, which renders nothing in the meantime. + */ + actionsTarget?: HTMLElement | null; }; export function ChartActionBar({ @@ -100,6 +121,7 @@ export function ChartActionBar({ onTimeRangeSearch, filtersToggle, setSaveToDashboardModalOpen, + actionsTarget, }: ChartActionBarProps) { const configType = useWatch({ control, name: 'configType' }); const displayType = useWatch({ control, name: 'displayType' }); @@ -119,83 +141,94 @@ export function ChartActionBar({ displayType, })); - return ( - - - {filtersToggle != null && tabQueriesData(activeTab) && ( - - - - )} - {(activeTab === 'table' || - activeTab === 'pie' || - activeTab === 'bar') && - !isRawSqlInput && - configType !== 'promql' && ( -
- -
- )} - {tabQueriesData(activeTab) && - setDisplayedTimeInputValue != null && - displayedTimeInputValue != null && - onTimeRangeSearch != null && ( - { - onTimeRangeSearch(range); - }} - onSubmit={range => { - onTimeRangeSearch(range); - }} - /> - )} - {showGranularity && ( - + const showOrderBy = + (activeTab === 'table' || activeTab === 'pie' || activeTab === 'bar') && + !isRawSqlInput && + configType !== 'promql'; + + const orderBy = showOrderBy ? ( +
+ +
+ ) : null; + + const controls = ( + <> + {filtersToggle != null && tabQueriesData(activeTab) && ( + + + + )} + {tabQueriesData(activeTab) && + setDisplayedTimeInputValue != null && + displayedTimeInputValue != null && + onTimeRangeSearch != null && ( + { + onTimeRangeSearch(range); + }} + onSubmit={range => { + onTimeRangeSearch(range); + }} + /> )} - {tabQueriesData(activeTab) && ( - + {showGranularity && ( + + )} + {tabQueriesData(activeTab) && ( + + )} + {actionsTarget === undefined && + canSaveToDashboard({ showSaveToDashboard, dashboardId }) && ( + setSaveToDashboardModalOpen(true)} + /> )} - {!IS_LOCAL_MODE && (showSaveToDashboard ?? !dashboardId) && ( - - - - - - - - } - onClick={() => setSaveToDashboardModalOpen(true)} - > - Save to Dashboard - - - + + ); + + if (actionsTarget !== undefined) { + return ( + <> + {orderBy != null && ( + + {orderBy} + )} + {actionsTarget != null && createPortal(controls, actionsTarget)} + + ); + } + + return ( + + + {orderBy} + {controls} ); diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartDataSource.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartDataSource.tsx new file mode 100644 index 0000000000..06a0668e92 --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/ChartDataSource.tsx @@ -0,0 +1,68 @@ +import { useState } from 'react'; +import { Control } from 'react-hook-form'; +import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; +import { + ChartConfigWithOptTimestamp, + SourceKind, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { Group } from '@mantine/core'; + +import { ChartEditorFormState } from '@/components/ChartEditor/types'; +import MVOptimizationIndicator from '@/components/MaterializedViews/MVOptimizationIndicator'; +import SourceSchemaPreview, { + isSourceSchemaPreviewEnabled, +} from '@/components/SourceSchemaPreview'; +import { SourceSelectControlled } from '@/components/SourceSelect'; + +type ChartDataSourceProps = { + control: Control; + tableSource?: TSource; + allowedSourceKinds: SourceKind[]; + activeTab: string; + chartConfigForExplanations?: ChartConfigWithOptTimestamp; +}; + +export function ChartDataSource({ + control, + tableSource, + allowedSourceKinds, + activeTab, + chartConfigForExplanations, +}: ChartDataSourceProps) { + const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = + useState(false); + + return ( + + setIsSourceSchemaPreviewOpen(true)} + isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(tableSource)} + /> + setIsSourceSchemaPreviewOpen(false)} + /> + {tableSource && + activeTab !== 'search' && + activeTab !== 'heatmap' && + activeTab !== 'event_patterns' && + chartConfigForExplanations && + isBuilderChartConfig(chartConfigForExplanations) && ( + + )} + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 7c5d577cd3..ef4e50916b 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo } from 'react'; import { Control, FieldArrayWithId, @@ -10,9 +10,7 @@ import { } from 'react-hook-form'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; import { displayTypeSupportsBuilderAlerts } from '@hyperdx/common-utils/dist/core/utils'; -import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { - ChartConfigWithOptTimestamp, DisplayType, HeatmapMode, SourceKind, @@ -26,16 +24,12 @@ import { SavedChartConfigWithSelectArray, } from '@/components/ChartEditor/types'; import { + getDefaultChartName, isFormulaDisplayType, isFormulaSourceKind, } from '@/components/ChartEditor/utils'; import { EDITOR_INPUT_HEIGHTS } from '@/components/editorInputHeights'; -import MVOptimizationIndicator from '@/components/MaterializedViews/MVOptimizationIndicator'; import SearchWhereInput from '@/components/SearchInput/SearchWhereInput'; -import SourceSchemaPreview, { - isSourceSchemaPreviewEnabled, -} from '@/components/SourceSchemaPreview'; -import { SourceSelectControlled } from '@/components/SourceSelect'; import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; import { IS_LOCAL_MODE } from '@/config'; import { getEventBody, isSingleExpression } from '@/source'; @@ -45,7 +39,9 @@ import { OnClickFormButton } from './OnClickForm/OnClickFormButton'; import { AlertPanelButton } from './AlertPanelButton'; import { ChartFormulaEditor } from './ChartFormulaEditor'; import { ChartSeriesEditor } from './ChartSeriesEditor'; +import { DisplaySettingsButton } from './DisplaySettingsButton'; import { HeatmapSeriesEditor } from './HeatmapSeriesEditor'; +import { type SeriesChartColors } from './seriesChartColors'; import { TileAlertEditor } from './TileAlertEditor'; import { buildGroupByConnectionProps } from './utils'; @@ -61,13 +57,11 @@ type ChartEditorControlsProps = { duplicateSeries: (index: number) => void; tableSource?: TSource; tableConnection: TableConnection; - allowedSourceKinds: SourceKind[]; databaseName?: string; tableName?: string; dateRange: [Date, Date]; select: ChartEditorFormState['select']; displayType: DisplayType; - activeTab: string; seriesReturnType: ChartEditorFormState['seriesReturnType']; ratioMode: ChartEditorFormState['ratioMode']; alert: ChartEditorFormState['alert']; @@ -79,11 +73,12 @@ type ChartEditorControlsProps = { isRawSqlInput: boolean; dashboardId?: string; parentRef: HTMLElement | null; - chartConfigForExplanations?: ChartConfigWithOptTimestamp; onSubmit: (suppressErrorNotification?: boolean) => void; openDisplaySettings: () => void; heatmapMode: HeatmapMode; onHeatmapModeChange: (mode: HeatmapMode) => void; + /** Line colors from the last run chart, by series and formula position. */ + seriesChartColors?: SeriesChartColors; }; export function ChartEditorControls({ @@ -98,13 +93,11 @@ export function ChartEditorControls({ duplicateSeries, tableSource, tableConnection, - allowedSourceKinds, databaseName, tableName, dateRange, select, displayType, - activeTab, seriesReturnType, ratioMode, alert, @@ -114,11 +107,11 @@ export function ChartEditorControls({ isRawSqlInput, dashboardId, parentRef, - chartConfigForExplanations, onSubmit, openDisplaySettings, heatmapMode, onHeatmapModeChange, + seriesChartColors, }: ChartEditorControlsProps) { // Formulas (HDX-5080): derived series computed from the chart's series via // letter-ref arithmetic expressions. Metric and event (log/trace) sources, @@ -168,9 +161,6 @@ export function ChartEditorControls({ // ratio mode); Line/Table types remain unbounded. With formulas the // series are operands (e.g. A / (A + B + C)), so the cap is lifted. !(displayType === DisplayType.Number && fields.length >= 2 && !hasFormulas); - const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = - useState(false); - // The chart-level Group By must be valid against every series query. For // metric sources (which fan out to per-type tables) this means offering the // intersection of each series' fields; see buildGroupByConnectionProps. @@ -200,42 +190,6 @@ export function ChartEditorControls({ return ( <> - - - - Data Source - - setIsSourceSchemaPreviewOpen(true)} - isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(tableSource)} - /> - setIsSourceSchemaPreviewOpen(false)} - /> - - - {tableSource && - activeTab !== 'search' && - activeTab !== 'heatmap' && - activeTab !== 'event_patterns' && - chartConfigForExplanations && - isBuilderChartConfig(chartConfigForExplanations) && ( - - )} - - {displayType === DisplayType.Heatmap && Array.isArray(select) ? ( ))} {sourceSupportsFormulas && @@ -336,6 +295,12 @@ export function ChartEditorControls({ onRemoveFormula={handleRemoveFormula} onSubmit={onSubmit} setValue={setValue} + chartColor={ + seriesChartColors?.series.length === fields.length && + seriesChartColors.formulas.length === formulaFields.length + ? seriesChartColors.formulas[index] + : undefined + } /> ))} {fields.length > 1 && displayType !== DisplayType.Number && ( @@ -509,6 +474,15 @@ export function ChartEditorControls({ checked={ratioMode === 'share_of_total'} /> )} + + + {displayType === DisplayType.Table && ( + + )} {showAlertButton && ( setValue('alert', { ...DEFAULT_TILE_ALERT, - ...(chartName && { displayName: chartName }), + displayName: + chartName || + getDefaultChartName( + series?.[0], + typeof groupBy === 'string' ? groupBy : undefined, + ), }) } /> )} - - - {displayType === DisplayType.Table && ( - - )} - +
diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartFormulaEditor.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartFormulaEditor.tsx index 1387092fef..dd4cc73c6c 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartFormulaEditor.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartFormulaEditor.tsx @@ -8,11 +8,10 @@ import { import { Badge } from '@clickhouse/click-ui'; import { validateFormula } from '@hyperdx/common-utils/dist/core/formula'; import { TextInput } from '@mantine/core'; -import { useDisclosure } from '@mantine/hooks'; import { ChartSeriesControls } from '@/components/ChartEditor/ChartSeriesControls'; +import { SeriesCard } from '@/components/ChartEditor/SeriesCard'; import { ChartEditorFormState } from '@/components/ChartEditor/types'; -import SeriesNumberFormatDrawer from '@/components/SeriesNumberFormatDrawer'; type ChartFormulaEditorProps = { control: Control; @@ -21,6 +20,8 @@ type ChartFormulaEditorProps = { onRemoveFormula: (index: number) => void; onSubmit: () => void; setValue: UseFormSetValue; + /** The color the chart draws this formula in, when it has a single one. */ + chartColor?: string; }; /** @@ -38,6 +39,7 @@ export function ChartFormulaEditor({ onRemoveFormula, onSubmit, setValue, + chartColor, }: ChartFormulaEditorProps) { const series = useWatch({ control, name: 'series' }); const seriesCount = Array.isArray(series) ? series.length : 0; @@ -66,14 +68,11 @@ export function ChartFormulaEditor({ name: `${namePrefix}numberFormat`, }); - const [ - isNumberFormatOpen, - { open: openNumberFormat, close: closeNumberFormat }, - ] = useDisclosure(false); - return ( - <> + { + setValue(`${namePrefix}numberFormat`, format.numberFormat); + onSubmit(); + }} leadingSection={} /> )} /> - { - setValue(`${namePrefix}numberFormat`, format.numberFormat); - onSubmit(); - }} - onClose={closeNumberFormat} - /> - + ); } diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx index 737d3cc26e..59706ebe2c 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx @@ -16,7 +16,7 @@ import { Accordion, Box, Divider, Stack, Text } from '@mantine/core'; import { IconList } from '@tabler/icons-react'; import { SortingState } from '@tanstack/react-table'; -import { buildTableRowSearchUrl } from '@/ChartUtils'; +import { buildTableRowSearchUrl, TimeChartSeriesColors } from '@/ChartUtils'; import { getAlertReferenceLines, getAlertReferenceLineValues, @@ -183,6 +183,8 @@ type ChartPreviewPanelProps = { setValue: (name: 'orderBy', value: string) => void; setDisplayType: (displayType: DisplayType) => void; onSubmit: () => void; + /** Forwarded to the time chart; must be referentially stable. */ + onSeriesColorsChange?: (colors: TimeChartSeriesColors | undefined) => void; }; export function ChartPreviewPanel({ @@ -204,6 +206,7 @@ export function ChartPreviewPanel({ setValue, setDisplayType, onSubmit, + onSeriesColorsChange, }: ChartPreviewPanelProps) { const [isSampleEventsOpen, setIsSampleEventsOpen] = useState(false); @@ -343,6 +346,7 @@ export function ChartPreviewPanel({ // DBTimeChart skip the extra MV-optimization EXPLAIN query, which // otherwise fires on every edit-modal open / submit. showDateRangeIndicator={false} + onSeriesColorsChange={onSeriesColorsChange} />
)} diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartRawSqlSource.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartRawSqlSource.tsx new file mode 100644 index 0000000000..d02af0744f --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/ChartRawSqlSource.tsx @@ -0,0 +1,73 @@ +import { useState } from 'react'; +import { Control, useWatch } from 'react-hook-form'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { Group, Tooltip } from '@mantine/core'; +import { IconHelpCircle } from '@tabler/icons-react'; + +import { ChartEditorFormState } from '@/components/ChartEditor/types'; +import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; +import SourceSchemaPreview, { + isSourceSchemaPreviewEnabled, +} from '@/components/SourceSchemaPreview'; +import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; +import { useSources } from '@/source'; + +/** The connection and optional source a raw SQL chart queries. */ +export function ChartRawSqlSource({ + control, + allowedSourceKinds, + isDashboardForm, +}: { + control: Control; + allowedSourceKinds: SourceKind[]; + isDashboardForm: boolean; +}) { + const { data: sources } = useSources(); + // A variable reference resolves to the connection and source it selects. + const storedConnection = useWatch({ control, name: 'connection' }); + const connection = useResolvedReference(storedConnection); + const source = useResolvedReference(useWatch({ control, name: 'source' })); + const sourceObject = sources?.find(s => s.id === source); + const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = + useState(false); + + return ( + + + setIsSourceSchemaPreviewOpen(true)} + isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(sourceObject)} + /> + {isDashboardForm && ( + + + + )} + setIsSourceSchemaPreviewOpen(false)} + /> + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartSeriesEditor.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartSeriesEditor.tsx index 6cecf7c2d4..897ef845b0 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartSeriesEditor.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartSeriesEditor.tsx @@ -26,6 +26,7 @@ import { HISTOGRAM_SUPPORTED_AGG_FNS, } from '@/components/AggFnSelect'; import { ChartSeriesControls } from '@/components/ChartEditor/ChartSeriesControls'; +import { SeriesCard } from '@/components/ChartEditor/SeriesCard'; import { ChartEditorFormState, SavedChartConfigWithSelectArray, @@ -41,7 +42,6 @@ import { import { MetricNameSelect } from '@/components/MetricNameSelect'; import SearchWhereInput from '@/components/SearchInput/SearchWhereInput'; import SeriesColorDrawer from '@/components/SeriesColorDrawer'; -import SeriesNumberFormatDrawer from '@/components/SeriesNumberFormatDrawer'; import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; import { useFetchMetricMetadata } from '@/hooks/useFetchMetricMetadata'; import { @@ -77,6 +77,8 @@ type ChartSeriesEditorProps = { tableSource?: TSource; errors?: FieldErrors; clearErrors: UseFormClearErrors; + /** The color the chart draws this series in, when it has a single one. */ + chartColor?: string; }; export function ChartSeriesEditor({ @@ -102,6 +104,7 @@ export function ChartSeriesEditor({ tableSource, errors, clearErrors, + chartColor, }: ChartSeriesEditorProps) { const aggFn = useWatch({ control, name: `${namePrefix}aggFn` }); const aggConditionLanguage = useWatch({ @@ -274,11 +277,6 @@ export function ChartSeriesEditor({ name: `${namePrefix}numberFormat`, }); - const [ - isSeriesNumberFormatOpen, - { open: openSeriesNumberFormat, close: closeSeriesNumberFormat }, - ] = useDisclosure(false); - const seriesColor = useWatch({ control, name: `${namePrefix}color` }); const seriesColorRules = useWatch({ control, @@ -290,261 +288,261 @@ export function ChartSeriesEditor({ { open: openSeriesColor, close: closeSeriesColor }, ] = useDisclosure(false); + const pinnedColor = + seriesColor && isChartPaletteToken(seriesColor) + ? getColorFromCSSToken(seriesColor) + : undefined; + // Tables pin a color per column; charts report the one they drew. + const cardColor = showColor ? pinnedColor : chartColor; + return ( <> - 1 ? onRemoveSeries : undefined} - onDuplicate={showDuplicate ? onDuplicateSeries : undefined} - onOpenNumberFormat={ - showSeriesNumberFormat ? openSeriesNumberFormat : undefined - } - leadingSection={ - isFormulaSourceKind(tableSource?.kind) ? ( - - - - ) : undefined - } - trailingSection={ - showColor ? ( - - - - - - ) : undefined - } - /> - -
- -
- {tableSource?.kind === SourceKind.Metric && metricType && ( -
- -
- { - setValue(`${namePrefix}metricName`, value); - setValue(`${namePrefix}valueExpression`, 'Value'); - }} - setMetricType={value => - setValue(`${namePrefix}metricType`, value) - } - metricSource={tableSource} - dateRange={dateRange} - data-testid="metric-name-selector" - error={errors?.metricName?.message} - onFocus={() => clearErrors(`${namePrefix}metricName`)} + + 1 ? onRemoveSeries : undefined} + onDuplicate={showDuplicate ? onDuplicateSeries : undefined} + onNumberFormatChange={ + showSeriesNumberFormat + ? format => { + setValue(`${namePrefix}numberFormat`, format.numberFormat); + onSubmit(); + } + : undefined + } + leadingSection={ + isFormulaSourceKind(tableSource?.kind) ? ( + + -
- + + ) : undefined + } + trailingSection={ + showColor ? ( + - + -
- - {metricType === 'gauge' && ( - - )} -
- )} - {tableSource?.kind !== SourceKind.Metric && aggFn !== 'count' && ( + ) : undefined + } + /> +
-
- )} - {(showWhere || showGroupBy || showHaving) && ( -
- {showWhere && ( - <> - - Where - -
- -
- - )} - {showGroupBy && ( - <> - - - Group By - - -
- + +
+ { + setValue(`${namePrefix}metricName`, value); + setValue(`${namePrefix}valueExpression`, 'Value'); + }} + setMetricType={value => + setValue(`${namePrefix}metricType`, value) + } + metricSource={tableSource} dateRange={dateRange} - control={control} - name={`groupBy`} - placeholder="SQL Columns" - disableKeywordAutocomplete - onSubmit={onSubmit} - enableVariables + data-testid="metric-name-selector" + error={errors?.metricName?.message} + onFocus={() => clearErrors(`${namePrefix}metricName`)} />
- {showHaving && ( - <> - - - Having - - -
- -
- - )} - - )} -
- )} - - {tableSource?.kind === SourceKind.Metric && metricName && metricType && ( - - )} - { - setValue(`${namePrefix}numberFormat`, format.numberFormat); - onSubmit(); - }} - onClose={() => { - closeSeriesNumberFormat(); - }} - /> + + + + + + + + {metricType === 'gauge' && ( + + )} +
+ )} + {tableSource?.kind !== SourceKind.Metric && aggFn !== 'count' && ( +
+ +
+ )} + {(showWhere || showGroupBy || showHaving) && ( +
+ {showWhere && ( + <> +
+ +
+ + )} + {showGroupBy && ( + <> + + + Group By + + +
+ +
+ {showHaving && ( + <> + + + Having + + +
+ +
+ + )} + + )} +
+ )} +
+ {tableSource?.kind === SourceKind.Metric && + metricName && + metricType && ( + + )} + {showColor && ( ; + isDashboardForm: boolean; +}) { + return ( + { + const selectedType = isTimeSeriesDisplayType(value) + ? DisplayType.Line + : value; + // Markdown tiles are a dashboard feature; the explorer has no place to + // save one, so only offer it on dashboard forms (or keep it when the + // current value already is markdown). + const options = CHART_TYPE_OPTIONS.filter( + option => + option.value !== DisplayType.Markdown || + isDashboardForm || + value === DisplayType.Markdown, + ); + return ( + { + // Line, stacked bar and stacked line share one "Time Series" + // option, so picking it must not reset a stacked variant. + if (v === DisplayType.Line && isTimeSeriesDisplayType(value)) + return; + onChange(v); + }} + data={options.map(({ value: optionValue, label, Icon }) => { + const selected = optionValue === selectedType; + return { + value: optionValue, + label: ( + + + + {selected && ( + + {label} + + )} + + + ), + }; + })} + /> + ); + }} + /> + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/DisplaySettingsButton.tsx b/packages/app/src/components/DBEditTimeChartForm/DisplaySettingsButton.tsx new file mode 100644 index 0000000000..ce15df01ee --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/DisplaySettingsButton.tsx @@ -0,0 +1,17 @@ +import { Button } from '@mantine/core'; +import { IconAdjustmentsHorizontal } from '@tabler/icons-react'; + +export function DisplaySettingsButton({ onClick }: { onClick: () => void }) { + return ( + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index dc5110b1b5..1a361244a1 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { isEqual } from 'lodash'; +import { createPortal } from 'react-dom'; import { Controller, type Resolver, @@ -16,7 +17,6 @@ import { isReducibleRangeQuery } from '@hyperdx/common-utils/dist/core/promql'; import { displayTypeSupportsBuilderAlerts, displayTypeSupportsRawSqlAlerts, - isTimeSeriesDisplayType, } from '@hyperdx/common-utils/dist/core/utils'; import { displayTypeRequiresSource, @@ -45,26 +45,14 @@ import { Box, Flex, SegmentedControl, - Tabs, Text, Textarea, } from '@mantine/core'; import { useDisclosure, usePrevious } from '@mantine/hooks'; import { notifications } from '@mantine/notifications'; -import { - IconAlertTriangle, - IconBracketsContain, - IconChartBar, - IconChartLine, - IconChartPie, - IconGrid3x3, - IconList, - IconMarkdown, - IconNumbers, - IconTable, -} from '@tabler/icons-react'; - -import { getPreviousDateRange } from '@/ChartUtils'; +import { IconAlertTriangle } from '@tabler/icons-react'; + +import { getPreviousDateRange, TimeChartSeriesColors } from '@/ChartUtils'; import { AlertPanelLayout } from '@/components/AlertPanel'; import ChartDisplaySettingsDrawer, { ChartConfigDisplaySettings, @@ -94,7 +82,7 @@ import { } from '@/components/DBHeatmapChart'; import { ErrorBoundary } from '@/components/Error/ErrorBoundary'; import { getExemplarToggleState } from '@/components/Exemplars'; -import { InputControlled } from '@/components/InputControlled'; +import { InlineNameInputControlled } from '@/components/InlineNameInput/InlineNameInput'; import SaveToDashboardModal from '@/components/SaveToDashboardModal'; import { getStoredLanguage } from '@/components/SearchInput/SearchWhereInput'; import { @@ -115,11 +103,20 @@ import { import { normalizeNoOpAlertScheduleFields } from '@/utils/alerts'; import { AlertPanelPrimaryAction } from './AlertPanelPrimaryAction'; -import { ChartActionBar, DashboardFiltersToggleProps } from './ChartActionBar'; +import { + canSaveToDashboard, + ChartActionBar, + DashboardFiltersToggleProps, + SaveToDashboardButton, +} from './ChartActionBar'; +import { ChartDataSource } from './ChartDataSource'; import { ChartEditorControls } from './ChartEditorControls'; import { ChartPreviewPanel } from './ChartPreviewPanel'; +import { ChartRawSqlSource } from './ChartRawSqlSource'; import { ChartSaveActions } from './ChartSaveActions'; +import { ChartTypeSwitcher } from './ChartTypeSwitcher'; import { ErrorNotificationMessage } from './ErrorNotificationMessage'; +import { getSeriesChartColors } from './seriesChartColors'; import { useBuilderToSqlConversion } from './useBuilderToSqlConversion'; import { useDebouncedFormValues } from './useDebouncedFormValues'; import { @@ -155,6 +152,11 @@ type EditTimeChartFormProps = { 'data-testid'?: string; submitRef?: React.MutableRefObject<(() => void) | undefined>; isDashboardForm?: boolean; + /** + * Whether to show the chart name field. The explorer hides it: a name typed + * there has no saved object to live on until the chart is saved as a tile. + */ + showChartName?: boolean; autoRun?: boolean; /** * Whether the editor offers an alert. Defaults to "inside a dashboard", @@ -176,6 +178,20 @@ type EditTimeChartFormProps = { isAlertRequired?: boolean; /** Whether to offer "Save to dashboard". Defaults to "outside a dashboard". */ showSaveToDashboard?: boolean; + /** + * Lets a page hoist the form's toolbar into its own header: `leading` takes + * the Builder/SQL/PromQL switch and source controls, `chartType` the chart + * type switcher, `save` the Save to dashboard button, and `actions` the time + * range, granularity and Run controls. Elements are `null` until + * the header mounts. Omit to keep the toolbar inside the form, as the tile + * and inline-alert editors do. + */ + toolbarTargets?: { + leading: HTMLElement | null; + chartType: HTMLElement | null; + save: HTMLElement | null; + actions: HTMLElement | null; + }; }; const zodChartFormResolver = zodResolver(zSavedChartConfig); @@ -269,6 +285,7 @@ export default function EditTimeChartForm({ 'data-testid': dataTestId, submitRef, isDashboardForm = false, + showChartName = true, autoRun = false, enableAlerts, onSaveAlert, @@ -276,6 +293,7 @@ export default function EditTimeChartForm({ isSavingAlert, isAlertRequired = false, showSaveToDashboard, + toolbarTargets, }: EditTimeChartFormProps) { const formValue: ChartEditorFormState = useMemo( () => convertSavedChartConfigToFormState(chartConfig), @@ -670,6 +688,13 @@ export default function EditTimeChartForm({ }; }, [queriedConfig, previewDashboardFilters]); + const [timeChartSeriesColors, setTimeChartSeriesColors] = + useState(); + const seriesChartColors = useMemo( + () => getSeriesChartColors(previewConfig, timeChartSeriesColors), + [previewConfig, timeChartSeriesColors], + ); + const debouncedForm = useDebouncedFormValues(watch, getValues, 300); // With no selection for a variable it references the tile has nothing to @@ -1281,6 +1306,47 @@ export default function EditTimeChartForm({ [displayType], ); + const sourceControls = ( + <> + {configTypeOptions.length > 1 && ( + ( + option.value === value) + ? value + : 'builder' + } + onChange={onChange} + data={configTypeOptions} + /> + )} + /> + )} + {isRawSqlInput ? ( + + ) : ( + + )} + + ); + + const chartTypeSwitcher = ( + + ); + return ( // The panel opens on request, except where the alert is what is being // edited (the inline-alert modal). @@ -1289,6 +1355,34 @@ export default function EditTimeChartForm({ defaultOpened={isAlertRequired} onOpen={snapshotAlert} onCancel={cancelAlertChanges} + sidePanelOpened={displaySettingsOpened} + onSidePanelClose={closeDisplaySettings} + sidePanel={ + + } actions={
- + {(showChartName || isDashboardForm) && ( - - - Chart Name - - - + {showChartName && ( + + + + )} {isDashboardForm && ( @@ -1350,109 +1446,43 @@ export default function EditTimeChartForm({ )} - {configTypeOptions.length > 1 && ( - ( - option.value === value) - ? value - : 'builder' - } - onChange={onChange} - data={configTypeOptions} - /> - )} - /> - )} - - - ( - { - if (v === DisplayType.Line && isTimeSeriesDisplayType(value)) - return; - onChange(v); - }} - radius={'xs'} - mb="md" - data-testid="chart-type-input" + )} + {toolbarTargets == null ? ( + + {sourceControls} + - - } - > - Time Series - - } - > - Table - - } - > - Number - - } - > - Bar - - } - > - Pie - - } - > - Search - - } - > - Heatmap - - } - > - Patterns - - } - > - Markdown - - - - )} - /> + {chartTypeSwitcher} + + + + ) : ( + <> + {toolbarTargets.leading != null && + createPortal(sourceControls, toolbarTargets.leading)} + {toolbarTargets.chartType != null && + createPortal(chartTypeSwitcher, toolbarTargets.chartType)} + {toolbarTargets.save != null && + canSaveToDashboard({ showSaveToDashboard, dashboardId }) && + createPortal( + setSaveToDashboardModalOpen(true)} + />, + toolbarTargets.save, + )} + + )} {activeTab === 'markdown' ? (