diff --git a/.changeset/alert-side-panel.md b/.changeset/alert-side-panel.md new file mode 100644 index 0000000000..f76017b3e8 --- /dev/null +++ b/.changeset/alert-side-panel.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: Edit chart alerts in a side panel docked beside the chart editor, so the preview chart stays in view while the alert is tuned. "Add alert" / "Edit alert" opens the panel; a new alert is kept with "Add alert" and an existing one with "Update alert", while closing the panel discards the changes. The panel fills the editor's visible height and can be resized from its left edge. Save and Cancel move to the chart name row. diff --git a/packages/app/src/components/AlertPanel.tsx b/packages/app/src/components/AlertPanel.tsx new file mode 100644 index 0000000000..4de9aa501d --- /dev/null +++ b/packages/app/src/components/AlertPanel.tsx @@ -0,0 +1,289 @@ +import { + createContext, + type ReactNode, + use, + useCallback, + useLayoutEffect, + useMemo, + useState, +} from 'react'; +import { createPortal } from 'react-dom'; +import { Box, type BoxProps, Flex } from '@mantine/core'; + +import useResizable from '@/hooks/useResizable'; + +import resizeStyles from '@styles/ResizablePanel.module.scss'; + +// Widths as percentages of the window, the unit useResizable drags in. +const DEFAULT_PANEL_WIDTH_PERCENT = 33; +// Wider than this squeezes the editor beside it past usable, inside a modal +// that is itself narrower than the window. +const MAX_PANEL_WIDTH_PERCENT = 50; +// The alert form's inline trigger row stops fitting below this. +const MIN_PANEL_WIDTH = 360; +const PANEL_BOTTOM_GAP = 12; +const MIN_PANEL_HEIGHT = 320; + +/** The nearest ancestor that scrolls its content, or null for the document. */ +function getScrollParent(element: HTMLElement): HTMLElement | null { + let node = element.parentElement; + while (node != null) { + const { overflowY } = getComputedStyle(node); + if (overflowY === 'auto' || overflowY === 'scroll') { + return node; + } + node = node.parentElement; + } + return null; +} + +/** + * The height the scroll area shows once its content fills it. A centered + * modal grows with its content up to a max height, so its current height is + * no guide: sizing the panel to it would shrink the modal, and then the panel, + * on every resize. + */ +function getVisibleHeight(scrollParent: HTMLElement | null): number { + if (scrollParent == null) { + return window.innerHeight; + } + const maxHeight = parseFloat(getComputedStyle(scrollParent).maxHeight); + return Number.isFinite(maxHeight) + ? Math.min(maxHeight, window.innerHeight) + : scrollParent.clientHeight; +} + +/** + * Pins the panel where the layout starts within the area that scrolls it, and + * sizes it to the rest of that area. Measured rather than derived from the + * viewport: a centered modal's scroll area is a fraction of the viewport, and + * pages and titled modals have chrome above the editor, so any fixed offset + * leaves the footer off screen somewhere. + */ +function usePanelBounds(root: HTMLElement | null, enabled: boolean) { + const [bounds, setBounds] = useState<{ top: number; height: number }>(); + + useLayoutEffect(() => { + if (root == null || !enabled) return; + const scrollParent = getScrollParent(root); + + const measure = () => { + const top = + scrollParent != null + ? root.getBoundingClientRect().top - + scrollParent.getBoundingClientRect().top - + scrollParent.clientTop + + scrollParent.scrollTop + : root.getBoundingClientRect().top + window.scrollY; + const next = { + top: Math.max(0, Math.round(top)), + height: Math.max( + MIN_PANEL_HEIGHT, + Math.round(getVisibleHeight(scrollParent) - top - PANEL_BOTTOM_GAP), + ), + }; + setBounds(prev => + prev?.top === next.top && prev.height === next.height ? prev : next, + ); + }; + + measure(); + const observer = new ResizeObserver(measure); + observer.observe(scrollParent ?? document.documentElement); + window.addEventListener('resize', measure); + return () => { + observer.disconnect(); + window.removeEventListener('resize', measure); + }; + }, [root, enabled]); + + return bounds; +} + +/** + * A docked side panel for the chart editor's alert settings, so the preview + * chart stays in view while the alert is tuned against it. + * + * The alert editor is rendered by whichever editor mode is active (builder or + * SQL), each with its own warnings and errors, so it portals itself into the + * panel rather than being rendered by the layout. The panel only opens while + * an alert editor is mounted to fill it. + * + * Changes made in the panel are kept by confirming them with the panel's + * action; closing the panel instead cancels them. For a newly added alert (a + * draft) that discards the alert; for an existing one it reverts the edits. + * Either way the preview reflects the edits live while the panel is open. + */ +const AlertPanelContext = createContext< + | { + opened: boolean; + setOpened: (opened: boolean) => void; + isDraft: boolean; + setIsDraft: (isDraft: boolean) => void; + onOpen?: () => void; + onCancel?: (isDraft: boolean) => void; + actions?: ReactNode; + target: HTMLElement | null; + setTarget: (target: HTMLElement | null) => void; + setHasContent: (hasContent: boolean) => void; + } + | undefined +>(undefined); + +/** Lays out its children beside the alert panel. */ +export function AlertPanelLayout({ + defaultOpened = false, + actions, + onOpen, + onCancel, + children, + ...props +}: BoxProps & { + defaultOpened?: boolean; + /** + * The alert's primary action. The alert form places it under its inputs + * with `AlertPanelActions`, so it reads as part of the alert rather than + * the whole editor. + */ + actions?: ReactNode; + /** Called when the panel opens on an existing alert, before any edits. */ + onOpen?: () => void; + /** Undoes the panel's changes when it is closed without confirming them. */ + onCancel?: (isDraft: boolean) => void; + children: ReactNode; +}) { + const [opened, setOpened] = useState(defaultOpened); + const [isDraft, setIsDraft] = useState(false); + const [target, setTarget] = useState(null); + const [hasContent, setHasContent] = useState(false); + const [root, setRoot] = useState(null); + const showPanel = opened && hasContent; + const bounds = usePanelBounds(root, showPanel); + // The handle sits on the panel's left edge, so dragging left widens it. + const { size: widthPercent, startResize } = useResizable( + DEFAULT_PANEL_WIDTH_PERCENT, + 'right', + { + minPercent: + typeof window === 'undefined' + ? undefined + : (MIN_PANEL_WIDTH / window.innerWidth) * 100, + maxPercent: MAX_PANEL_WIDTH_PERCENT, + }, + ); + const value = useMemo( + () => ({ + opened, + setOpened, + isDraft, + setIsDraft, + onOpen, + onCancel, + actions, + target, + setTarget, + setHasContent, + }), + [opened, isDraft, onOpen, onCancel, actions, target], + ); + + return ( + + + + {children} + + {showPanel && ( + +
+ + + )} + + + ); +} + +/** Controls the alert panel. Undefined outside an `AlertPanelLayout`. */ +export function useAlertPanel() { + const context = use(AlertPanelContext); + const setOpened = context?.setOpened; + const setIsDraft = context?.setIsDraft; + const opened = context?.opened ?? false; + const isDraft = context?.isDraft ?? false; + const onOpen = context?.onOpen; + const onCancel = context?.onCancel; + + /** Opens the panel on the chart's existing alert. */ + const open = useCallback(() => { + if (!opened) { + onOpen?.(); + } + setOpened?.(true); + }, [onOpen, opened, setOpened]); + /** Opens the panel on an alert that was just added. */ + const openDraft = useCallback(() => { + setIsDraft?.(true); + setOpened?.(true); + }, [setIsDraft, setOpened]); + /** Keeps the panel's changes and closes it. */ + const confirm = useCallback(() => { + setIsDraft?.(false); + setOpened?.(false); + }, [setIsDraft, setOpened]); + /** Closes the panel, cancelling its changes. */ + const close = useCallback(() => { + onCancel?.(isDraft); + setIsDraft?.(false); + setOpened?.(false); + }, [isDraft, onCancel, setIsDraft, setOpened]); + + if (context == null) return undefined; + return { opened, isDraft, open, openDraft, confirm, close }; +} + +/** + * Renders its children in the alert panel: nothing while the panel is closed, + * and in place when there is no panel at all. + */ +export function AlertPanelFill({ children }: { children: ReactNode }) { + const context = use(AlertPanelContext); + const setHasContent = context?.setHasContent; + + // A layout effect lets the panel open in the same frame the content mounts. + useLayoutEffect(() => { + setHasContent?.(true); + return () => setHasContent?.(false); + }, [setHasContent]); + + if (context == null) return children; + return context.target ? createPortal(children, context.target) : null; +} + +/** Renders the alert panel's primary action, if it has one. */ +export function AlertPanelActions() { + return use(AlertPanelContext)?.actions ?? null; +} diff --git a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx index a9d1949642..ea2304d038 100644 --- a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx @@ -31,9 +31,10 @@ import { Tooltip, } from '@mantine/core'; import { useDebouncedValue } from '@mantine/hooks'; -import { IconBell, IconHelpCircle } from '@tabler/icons-react'; +import { IconHelpCircle } from '@tabler/icons-react'; import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; +import { AlertPanelButton } from '@/components/DBEditTimeChartForm/AlertPanelButton'; import { OnClickFormButton } from '@/components/DBEditTimeChartForm/OnClickForm/OnClickFormButton'; import { TileAlertEditor } from '@/components/DBEditTimeChartForm/TileAlertEditor'; import SourceSchemaPreview, { @@ -256,6 +257,12 @@ export default function RawSqlChartEditor({ ? 'The threshold will be evaluated against the last numeric column in the first query result' : 'The threshold will be evaluated against the last numeric column in each query result'; + const showAlertButton = + alert != null || + (displayTypeSupportsRawSqlAlerts(displayType) && + alertsEnabled && + !IS_LOCAL_MODE); + return ( @@ -301,27 +308,19 @@ export default function RawSqlChartEditor({ /> - {displayTypeSupportsRawSqlAlerts(displayType) && - alertsEnabled && - !alert && - !IS_LOCAL_MODE && ( - - )} - + {showAlertButton && ( + + setValue('alert', { + ...DEFAULT_TILE_ALERT, + ...(chartName && { displayName: chartName }), + }) + } + /> + )} {displayType === DisplayType.Table && ( void; + /** + * The alert's error and warning. Their badges render in the panel, which an + * existing alert opens closed, so the button carries them while it is. + */ + error?: string; + warning?: string; +}) { + const alertPanel = useAlertPanel(); + const isConfirmed = hasAlert && !alertPanel?.isDraft; + const issue = + hasAlert && !alertPanel?.opened ? (error ?? warning) : undefined; + + return ( + + + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/AlertPanelPrimaryAction.tsx b/packages/app/src/components/DBEditTimeChartForm/AlertPanelPrimaryAction.tsx new file mode 100644 index 0000000000..a2f5e0a2e3 --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/AlertPanelPrimaryAction.tsx @@ -0,0 +1,81 @@ +import { + FieldErrors, + UseFormHandleSubmit, + UseFormTrigger, +} from 'react-hook-form'; +import { Button } from '@mantine/core'; +import { IconBell } from '@tabler/icons-react'; + +import { useAlertPanel } from '@/components/AlertPanel'; +import { ChartEditorFormState } from '@/components/ChartEditor/types'; + +/** + * A `handleSubmit` error handler that opens the alert panel when the alert is + * what failed validation, since its field errors render there. + */ +export function useShowAlertErrors() { + const alertPanel = useAlertPanel(); + return (errors: FieldErrors) => { + if (errors.alert != null) { + alertPanel?.open(); + } + }; +} + +/** + * The alert's primary action, shown under its inputs in the alert panel. + * Where the alert saves on its own (the chart explorer, or the edit-alert + * modal) it saves it. Elsewhere the alert saves with the chart, so this keeps + * the panel's changes (adding a new alert, or updating an existing one) and + * closes the panel. + */ +export function AlertPanelPrimaryAction({ + trigger, + handleSubmit, + handleSaveAlert, + saveAlertLabel = 'Save alert', + isSavingAlert, +}: { + trigger: UseFormTrigger; + handleSubmit: UseFormHandleSubmit; + handleSaveAlert?: (form: ChartEditorFormState) => void; + saveAlertLabel?: string; + isSavingAlert?: boolean; +}) { + const alertPanel = useAlertPanel(); + const showAlertErrors = useShowAlertErrors(); + + if (handleSaveAlert != null) { + return ( + + ); + } + + return ( + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx index 0929551d54..aa25ac16cb 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartActionBar.tsx @@ -1,7 +1,6 @@ -import { Control, UseFormHandleSubmit, useWatch } from 'react-hook-form'; +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 { SavedChartConfig } from '@hyperdx/common-utils/dist/types'; import { ActionIcon, Box, @@ -12,7 +11,6 @@ import { Tooltip, } from '@mantine/core'; import { - IconBell, IconDotsVertical, IconLayoutGrid, IconPlayerPlay, @@ -63,7 +61,6 @@ function DashboardFiltersToggle({ type ChartActionBarProps = { control: Control; - handleSubmit: UseFormHandleSubmit; tableConnection: TableConnection; sourceId?: string; dateRange?: [Date, Date]; @@ -73,16 +70,6 @@ type ChartActionBarProps = { parentRef: HTMLElement | null; groupBy: ChartEditorFormState['groupBy']; onSubmit: (suppressErrorNotification?: boolean) => void; - handleSave: (form: ChartEditorFormState) => void; - onSave?: (chart: SavedChartConfig) => void; - onClose?: () => void; - isSaving?: boolean; - /** Whether the edited chart currently carries an alert. */ - hasAlert?: boolean; - handleSaveAlert?: (form: ChartEditorFormState) => void; - onSaveAlert?: (chart: SavedChartConfig) => void; - saveAlertLabel?: string; - isSavingAlert?: boolean; /** * Whether to offer "Save to dashboard". Defaults to "outside a dashboard". * The inline-alert editor turns it off: saving that chart as a tile would @@ -98,7 +85,6 @@ type ChartActionBarProps = { export function ChartActionBar({ control, - handleSubmit, tableConnection, sourceId, dateRange, @@ -108,15 +94,6 @@ export function ChartActionBar({ parentRef, groupBy, onSubmit, - handleSave, - onSave, - onClose, - isSaving, - hasAlert, - handleSaveAlert, - onSaveAlert, - saveAlertLabel = 'Save alert', - isSavingAlert, showSaveToDashboard, displayedTimeInputValue, setDisplayedTimeInputValue, @@ -143,42 +120,7 @@ export function ChartActionBar({ })); return ( - - - {onSave != null && ( - - )} - {/* Only once an alert exists on the chart: with none there is nothing - to save, and the button would read as a second way to add one. */} - {onSaveAlert != null && handleSaveAlert != null && hasAlert && ( - - )} - {onClose != null && ( - - )} - + {filtersToggle != null && tabQueriesData(activeTab) && ( diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 6e597d06ae..4524f411ab 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -18,12 +18,8 @@ import { SourceKind, TSource, } from '@hyperdx/common-utils/dist/types'; -import { Box, Button, Divider, Flex, Group, Switch, Text } from '@mantine/core'; -import { - IconBell, - IconCirclePlus, - IconMathFunction, -} from '@tabler/icons-react'; +import { Button, Divider, Flex, Group, Switch, Text } from '@mantine/core'; +import { IconCirclePlus, IconMathFunction } from '@tabler/icons-react'; import { ChartEditorFormState, @@ -46,6 +42,7 @@ import { getEventBody, isSingleExpression } from '@/source'; import { DEFAULT_TILE_ALERT } from '@/utils/alerts'; import { OnClickFormButton } from './OnClickForm/OnClickFormButton'; +import { AlertPanelButton } from './AlertPanelButton'; import { ChartFormulaEditor } from './ChartFormulaEditor'; import { ChartSeriesEditor } from './ChartSeriesEditor'; import { HeatmapSeriesEditor } from './HeatmapSeriesEditor'; @@ -189,6 +186,18 @@ export function ChartEditorControls({ const chartName = useWatch({ control, name: 'name' }); const hasGroupBy = typeof groupBy === 'string' && groupBy.trim().length > 0; + const showAlertButton = + (alert != null && !isRawSqlInput) || + (displayTypeSupportsBuilderAlerts(displayType) && + alertsEnabled && + !IS_LOCAL_MODE); + + const alertWarning = useMemo( + () => + additionalWarnings?.length ? additionalWarnings.join(' ') : undefined, + [additionalWarnings], + ); + return ( <> @@ -499,25 +508,18 @@ export function ChartEditorControls({ checked={ratioMode === 'share_of_total'} /> )} - {displayTypeSupportsBuilderAlerts(displayType) && - alertsEnabled && - !alert && - !IS_LOCAL_MODE && ( - - )} + {showAlertButton && ( + + setValue('alert', { + ...DEFAULT_TILE_ALERT, + ...(chartName && { displayName: chartName }), + }) + } + /> + )} {displayType === DisplayType.Table && ( @@ -577,22 +579,16 @@ export function ChartEditorControls({ )} {alert && !isRawSqlInput && ( - - setValue('alert', undefined) - } - warning={ - additionalWarnings?.length - ? additionalWarnings.join(' ') - : undefined - } - /> - + setValue('alert', undefined) + } + warning={alertWarning} + /> )} ); diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartSaveActions.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartSaveActions.tsx new file mode 100644 index 0000000000..f6827bda4d --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/ChartSaveActions.tsx @@ -0,0 +1,51 @@ +import { UseFormHandleSubmit } from 'react-hook-form'; +import { SavedChartConfig } from '@hyperdx/common-utils/dist/types'; +import { Button, Group } from '@mantine/core'; + +import { ChartEditorFormState } from '@/components/ChartEditor/types'; + +import { useShowAlertErrors } from './AlertPanelPrimaryAction'; + +/** The chart editor's Save and Cancel, each shown only when handled. */ +export function ChartSaveActions({ + handleSubmit, + handleSave, + onSave, + onClose, + isSaving, +}: { + handleSubmit: UseFormHandleSubmit; + handleSave: (form: ChartEditorFormState) => void; + onSave?: (chart: SavedChartConfig) => void; + onClose?: () => void; + isSaving?: boolean; +}) { + const showAlertErrors = useShowAlertErrors(); + + if (onSave == null && onClose == null) return null; + + return ( + + {onSave != null && ( + + )} + {onClose != null && ( + + )} + + ); +} diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index 3523e0205e..bf2043d055 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -34,7 +34,6 @@ import { import { getAlertVariableWarning } from '@hyperdx/common-utils/dist/variables'; import { Box, - Divider, Flex, SegmentedControl, Tabs, @@ -56,6 +55,7 @@ import { } from '@tabler/icons-react'; import { getPreviousDateRange } from '@/ChartUtils'; +import { AlertPanelLayout } from '@/components/AlertPanel'; import ChartDisplaySettingsDrawer, { ChartConfigDisplaySettings, } from '@/components/ChartDisplaySettingsDrawer'; @@ -98,9 +98,11 @@ import { } from '@/source'; import { normalizeNoOpAlertScheduleFields } from '@/utils/alerts'; +import { AlertPanelPrimaryAction } from './AlertPanelPrimaryAction'; import { ChartActionBar, DashboardFiltersToggleProps } from './ChartActionBar'; import { ChartEditorControls } from './ChartEditorControls'; import { ChartPreviewPanel } from './ChartPreviewPanel'; +import { ChartSaveActions } from './ChartSaveActions'; import { ErrorNotificationMessage } from './ErrorNotificationMessage'; import { useBuilderToSqlConversion } from './useBuilderToSqlConversion'; import { @@ -255,6 +257,7 @@ export default function EditTimeChartForm({ handleSubmit, register, setError, + trigger, clearErrors, formState: { errors, isDirty, dirtyFields }, } = useForm({ @@ -731,6 +734,31 @@ export default function EditTimeChartForm({ [validateAndNormalize, onSaveAlert], ); + // The edit-alert modal requires the alert and saves it by saving the chart, + // so there the panel's action saves too instead of only closing the panel. + const panelSaveAlert = + onSaveAlert != null + ? handleSaveAlert + : isAlertRequired && onSave != null + ? handleSave + : undefined; + + // The alert as it was when its panel opened, restored if the panel is closed + // without confirming. Cloned: the form updates nested values in place. + const alertSnapshotRef = useRef(formValue.alert); + const snapshotAlert = useCallback(() => { + alertSnapshotRef.current = structuredClone(getValues('alert')); + }, [getValues]); + const cancelAlertChanges = useCallback( + (isDraft: boolean) => { + setValue('alert', isDraft ? undefined : alertSnapshotRef.current); + // setValue keeps errors from a failed confirm, which the next draft or + // the reverted alert would otherwise show straight away. + clearErrors('alert'); + }, + [setValue, clearErrors], + ); + // Track previous values for detecting changes const prevGranularityRef = useRef(granularity); const prevDisplayTypeRef = useRef(displayType); @@ -1073,267 +1101,281 @@ export default function EditTimeChartForm({ ); return ( -
- - ( - - - } - > - Time Series - - } - > - Table - - } - > - Number - - } - > - Bar - - } - > - Pie - - } - > - Search - - } - > - Heatmap - - } - > - Patterns - - } - > - Markdown - - - - )} + // The panel opens on request, except where the alert is what is being + // edited (the inline-alert modal). + - - - Chart Name - - - {configTypeOptions.length > 1 && ( - +
+ + + + Chart Name + + ( - option.value === value) - ? value - : 'builder' - } - onChange={onChange} - data={configTypeOptions} - /> - )} + flex={1} + type="text" + placeholder="My Chart Name" + data-testid="chart-name-input" /> - )} - - - {activeTab === 'markdown' ? ( -
-