Compare commits

...

20 Commits

Author SHA1 Message Date
Abhi Kumar
3c4eda82eb Merge branch 'fix/dashboard-drilldown-variable-seed' into feat/dashboard-host-seams 2026-11-26 16:16:02 +05:30
Abhi Kumar
3ac1479cc3 fix(dashboard): count typed values when comparing variable selections
A seed that only adds the typed-value marker was skipped as unchanged, so a later reconcile
could still drop the value.
2026-11-26 16:15:39 +05:30
Abhi Kumar
79894a0f96 refactor(dashboard): name host controls for what they hold
Control-flag objects read as booleans, the runner arg shadowed fetch, and the stale check
takes options like the permission hooks.
2026-11-26 15:53:41 +05:30
Abhi Kumar
1d8655c606 Merge branch 'fix/dashboard-drilldown-variable-seed' into feat/dashboard-host-seams
# Conflicts:
#	frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useDrilldown.tsx
2026-11-26 15:53:41 +05:30
Abhi Kumar
a34b75f86d fix(dashboard): keep variable values a link or host sets
A custom variable keeps link-seeded values its list doesn't offer, as typed values. An auto-fill
computed before the seed landed no longer overwrites it a frame later.
2026-11-26 15:51:23 +05:30
Abhi Kumar
7339662720 fix(dashboard): offer drilldown Create var only on editable dashboards 2026-11-26 15:50:53 +05:30
Abhi Kumar
d1dd086cec fix(dashboard): skip drilldown on panels that draw only formulas
Formula series have no query to drill into, so a panel whose builder queries are all disabled
no longer offers the click or its tooltip hint.
2026-11-26 15:50:52 +05:30
Abhi Kumar
1c7a93bd7a Merge remote-tracking branch 'origin/main' into feat/dashboard-host-seams
# Conflicts:
#	frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardInfo/DashboardInfo.tsx
#	frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/DashboardEmptyState/DashboardEmptyState.tsx
#	frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useDrilldown.tsx
#	frontend/src/pages/DashboardPage/DashboardContainer/index.tsx
2026-11-26 15:03:00 +05:30
Abhi Kumar
3fd05f57ba fix(dashboard): hide the toolbar when a host turns every row off 2026-11-26 14:57:23 +05:30
Abhi Kumar
79f7d35033 fix(dashboard): offer drilldown Create var only on editable dashboards 2026-11-26 14:57:23 +05:30
Abhi Kumar
5c9379e4ad fix(dashboard): keep variable values a link or host sets
A custom variable keeps link-seeded values its list doesn't offer, as typed values. An auto-fill
computed before the seed landed no longer overwrites it a frame later.
2026-11-26 14:57:23 +05:30
Abhi Kumar
11bda9f282 fix(dashboard): skip drilldown on panels that draw only formulas
Formula series have no query to drill into, so a panel whose builder queries are all disabled
no longer offers the click or its tooltip hint.
2026-11-26 14:57:23 +05:30
Abhi Kumar
4225452554 test(dashboard): build controls test fixtures from typed builders 2026-11-13 14:13:49 +05:30
Abhi Kumar
50dfec7247 fix(dashboard): keep settings and empty-state actions in step with host controls
The settings drawer mounts once in the container, so Add variable still opens it when a
host hides the dashboard actions. The empty state's Configure and New Panel read the same
controls as the toolbar.
2026-11-13 14:13:42 +05:30
Abhi Kumar
e37e94af53 feat(dashboard): let hosts choose what runs panel queries
A host's queryRunner replaces only the network call; usePanelQuery still owns the window, the
request and the loading states, so renderers are untouched. The runner's key joins every panel
cache key, so results from different runners never mix.
2026-11-13 14:00:03 +05:30
Abhi Kumar
f060e262d2 feat(dashboard): let hosts turn off drag-to-zoom
CHARTS_ONLY lists its panel actions so zoom stays on.
2026-11-13 13:59:55 +05:30
Abhi Kumar
27a11ada95 feat(dashboard): add layout presets for host controls
EMBEDDED and CHARTS_ONLY name the layouts hosts repeat; withControls merges them with overrides item
by item. Presets only decide what shows: readOnly stays separate, so none can bring back a write.
2026-11-13 13:59:50 +05:30
Abhi Kumar
a4d83ea2fd feat(dashboard): let hosts choose which dashboard controls render
controls is grouped by area and on by default. Visibility is kept apart from readOnly: every
control declares whether it writes, and a read-only mount hides the writing ones whatever the
host asks for.

A lockdown test renders the container with every control off and fails on any interactive
element left, so a new control can't ship ungated.
2026-11-13 13:59:38 +05:30
Abhi Kumar
2e4d47a124 test(ai-observability): serve the system dashboard in the overview story
The mock builds the response from the backend's own definition JSON, so the story can't drift
from what the server serves.
2026-11-13 13:59:25 +05:30
Abhi Kumar
5a62bcd85c feat(dashboard): mount a dashboard read-only from any cache entry
The host tells the store where it cached the dashboard and the subtree observes that entry, so the
system dashboard no longer primes the dashboards API cache under a fake id.

readOnly replaces canEditDashboardOverride: it also rejects writes and skips edit-only requests.
2026-11-13 13:59:25 +05:30
61 changed files with 2432 additions and 649 deletions

View File

@@ -3,18 +3,6 @@
flex-direction: column;
gap: var(--spacing-8);
padding: var(--spacing-0) var(--spacing-0);
//TODO: remove this once we have a proper dashboard page.
// The embedded V2 DashboardContainer renders its own page header (dashboard
// title + share/feedback chrome) removed it for now
:global([class*='dashboardPageHeader']),
:global([class*='dashboardInfoWithActions']) {
display: none;
}
// Embedded read-only: the add-variable and panel-action triggers are dead here.
:global([class*='addSlot']),
:global([data-testid^='panel-actions-']) {
display: none;
}
}
.errorState {

View File

@@ -3,10 +3,21 @@ import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import Spinner from 'components/Spinner';
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
import { useSystemDashboard } from './hooks/useSystemDashboard';
import {
SYSTEM_DASHBOARD_SOURCE,
useSystemDashboard,
} from './hooks/useSystemDashboard';
import styles from './Overview.module.scss';
// Embedded under the AI Observability tabs, which own the page header.
const EMBEDDED_CONTROLS: DashboardControlsInput = {
header: false,
title: false,
dashboardActions: false,
};
function Overview(): JSX.Element {
const { dashboard, isLoading, isError, error, refetch } = useSystemDashboard();
@@ -51,7 +62,9 @@ function Overview(): JSX.Element {
<DashboardContainer
dashboard={dashboard}
refetch={refetch}
canEditDashboardOverride={false}
source={SYSTEM_DASHBOARD_SOURCE}
readOnly
controls={EMBEDDED_CONTROLS}
/>
);
};

View File

@@ -1,20 +1,34 @@
import { useCallback, useMemo } from 'react';
import { useQueryClient } from 'react-query';
import { useCallback } from 'react';
import {
getGetDashboardV2QueryKey,
getGetSystemDashboardQueryKey,
useGetSystemDashboard,
} from 'api/generated/services/dashboard';
import type { GetSystemDashboardQueryError } from 'api/generated/services/dashboard';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
GetSystemDashboard200,
} from 'api/generated/services/sigNoz.schemas';
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
const DASHBOARD_ID = 'llm-observability-overview';
// System dashboards have no `id`; a fixed one keys the store's per-dashboard state.
const selectDashboard = (
response: GetSystemDashboard200,
): DashboardtypesGettableDashboardV2DTO =>
({
...response.data,
id: DASHBOARD_ID,
}) as DashboardtypesGettableDashboardV2DTO;
export const SYSTEM_DASHBOARD_SOURCE: DashboardQuerySource = {
queryKey: getGetSystemDashboardQueryKey({ name: SYSTEM_DASHBOARD_NAME }),
select: selectDashboard,
};
export interface UseSystemDashboardResult {
dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
isLoading: boolean;
@@ -24,30 +38,23 @@ export interface UseSystemDashboardResult {
}
export function useSystemDashboard(): UseSystemDashboardResult {
const queryClient = useQueryClient();
const { data, isLoading, isError, error, refetch } = useGetSystemDashboard(
const {
data: dashboard,
isLoading,
isError,
error,
refetch,
} = useGetSystemDashboard(
{ name: SYSTEM_DASHBOARD_NAME },
{ query: { staleTime: Infinity, refetchOnMount: false } },
{
query: {
select: selectDashboard,
staleTime: Infinity,
refetchOnMount: false,
},
},
);
const dashboard = useMemo(
() =>
data
? ({
...data.data,
id: DASHBOARD_ID,
} as DashboardtypesGettableDashboardV2DTO)
: undefined,
[data],
);
if (dashboard) {
queryClient.setQueryData<GetDashboardV2200>(
getGetDashboardV2QueryKey({ id: DASHBOARD_ID }),
{ data: dashboard, status: 'success' },
);
}
const refetchDashboard = useCallback((): void => {
void refetch();
}, [refetch]);

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { FullScreenHandle } from 'react-full-screen';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import {
@@ -26,19 +26,21 @@ import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
import type {
AuthZDropdownItemType,
AuthZGroupChildType,
} from 'lib/authz/components/AuthZDropdown/types';
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { DashboardCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import DashboardSettings from '../../DashboardSettings';
import { useAddSection } from '../../PanelsAndSectionsLayout/Section/hooks/useAddSection';
import SectionTitleModal from '../../PanelsAndSectionsLayout/Section/SectionTitleModal';
import JsonEditorDrawer from '../JsonEditorDrawer/JsonEditorDrawer';
import SettingsDrawer from '../SettingsDrawer';
import styles from './DashboardActions.module.scss';
import { useDeleteDashboardAction } from './useDeleteDashboardAction';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
interface DashboardActionsProps {
title: string;
@@ -66,13 +68,14 @@ function DashboardActions({
deleteChecks,
deleteDisabledTooltip,
} = useDashboardEditContext();
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
const actionControls = useDashboardControlGroup('dashboardActions');
const requestSettings = useDashboardStore((s) => s.requestSettings);
const { safeNavigate } = useSafeNavigate();
const { showErrorModal } = useErrorModal();
const { disabledTooltip: lockDisabledTooltip } = useDashboardLockPermission({
dashboardId: dashboard.id,
source: dashboard.source,
enabled: actionControls.lock,
});
// Cloning creates a new dashboard, so it needs `create` too, and no lock gate.
@@ -81,8 +84,6 @@ function DashboardActions({
[editChecks],
);
const [isSettingsDrawerOpen, setIsSettingsDrawerOpen] =
useState<boolean>(false);
const [isJsonEditorOpen, setIsJsonEditorOpen] = useState<boolean>(false);
const [isCloning, setIsCloning] = useState<boolean>(false);
const [isNewSectionOpen, setIsNewSectionOpen] = useState<boolean>(false);
@@ -94,14 +95,6 @@ function DashboardActions({
panelCount: Object.keys(dashboard.spec.panels).length,
});
// Open the settings drawer when something in the tree requests it (e.g. the
// variables bar's "Add variable" button).
useEffect(() => {
if (settingsRequest) {
setIsSettingsDrawerOpen(true);
}
}, [settingsRequest]);
const { addSection, isSaving: isAddingSection } = useAddSection({
layouts: dashboard.spec.layouts,
});
@@ -143,8 +136,8 @@ function DashboardActions({
void logEvent(DashboardDetailEvents.SettingsOpened, {
dashboardId: dashboard.id,
});
setIsSettingsDrawerOpen(true);
}, [dashboard.id]);
requestSettings({ tab: 'Overview' });
}, [dashboard.id, requestSettings]);
const handleOpenJsonEditor = useCallback((): void => {
void logEvent(DashboardDetailEvents.JsonEditorOpened, {
@@ -162,61 +155,68 @@ function DashboardActions({
void handle.enter();
}, [dashboard.id, handle]);
// Unavailable items stay in the menu, carrying the reason.
const menuItems = useMemo<AuthZDropdownItemType[]>(
() => [
{
type: 'group',
value: 'group-dashboard',
label: 'Dashboard',
items: [
{
type: 'item',
value: 'rename',
testId: 'dashboard-action-rename',
label: 'Rename',
prefix: <PenLine size={14} />,
checks: editChecks,
...blockedBy(editDisabledTooltip),
onClick: onOpenRename,
},
// Clone creates a new dashboard, so it's not lock-gated.
{
type: 'item',
value: 'clone',
testId: 'dashboard-action-clone',
label: 'Clone dashboard',
prefix: <Copy size={14} />,
checks: cloneChecks,
loading: isCloning,
loadingTooltip: 'Cloning dashboard',
onClick: (): void => void handleClone(),
},
{
type: 'item',
value: 'lock',
testId: 'dashboard-action-lock',
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
prefix: <LockKeyhole size={14} />,
checks: editChecks,
...blockedBy(lockDisabledTooltip),
onClick: onLockToggle,
},
{
type: 'item',
value: 'fullscreen',
testId: 'dashboard-action-fullscreen',
label: 'Full screen',
prefix: <Fullscreen size={14} />,
onClick: handleEnterFullScreen,
},
],
},
{
type: 'group',
value: 'group-layout',
label: 'Layout',
items: [
// Unavailable items stay in the menu, carrying the reason; hidden ones are dropped.
const menuItems = useMemo<AuthZDropdownItemType[]>(() => {
const dashboardItems: AuthZGroupChildType[] = [
...(actionControls.rename
? [
{
type: 'item' as const,
value: 'rename',
testId: 'dashboard-action-rename',
label: 'Rename',
prefix: <PenLine size={14} />,
checks: editChecks,
...blockedBy(editDisabledTooltip),
onClick: onOpenRename,
},
]
: []),
// Clone creates a new dashboard, so it's not lock-gated.
...(actionControls.clone
? [
{
type: 'item' as const,
value: 'clone',
testId: 'dashboard-action-clone',
label: 'Clone dashboard',
prefix: <Copy size={14} />,
checks: cloneChecks,
loading: isCloning,
loadingTooltip: 'Cloning dashboard',
onClick: (): void => void handleClone(),
},
]
: []),
...(actionControls.lock
? [
{
type: 'item' as const,
value: 'lock',
testId: 'dashboard-action-lock',
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
prefix: <LockKeyhole size={14} />,
checks: editChecks,
...blockedBy(lockDisabledTooltip),
onClick: onLockToggle,
},
]
: []),
...(actionControls.fullscreen
? [
{
type: 'item' as const,
value: 'fullscreen',
testId: 'dashboard-action-fullscreen',
label: 'Full screen',
prefix: <Fullscreen size={14} />,
onClick: handleEnterFullScreen,
},
]
: []),
];
const layoutItems: AuthZGroupChildType[] = actionControls.newSection
? [
{
type: 'item',
value: 'new-section',
@@ -227,101 +227,124 @@ function DashboardActions({
...blockedBy(editDisabledTooltip),
onClick: (): void => setIsNewSectionOpen(true),
},
],
},
{ type: 'separator', value: 'divider-danger' },
{
type: 'item',
value: 'delete',
testId: 'dashboard-action-delete',
label: 'Delete dashboard',
prefix: <Trash2 size={14} />,
danger: true,
checks: deleteChecks,
// Independent of read/update, but a locked dashboard can't be removed.
...blockedBy(deleteDisabledTooltip),
onClick: confirmDeleteDashboard,
},
],
[
editChecks,
editDisabledTooltip,
deleteChecks,
deleteDisabledTooltip,
cloneChecks,
isCloning,
lockDisabledTooltip,
isDashboardLocked,
onOpenRename,
handleClone,
onLockToggle,
handleEnterFullScreen,
confirmDeleteDashboard,
],
);
]
: [];
return [
...(dashboardItems.length
? [
{
type: 'group' as const,
value: 'group-dashboard',
label: 'Dashboard',
items: dashboardItems,
},
]
: []),
...(layoutItems.length
? [
{
type: 'group' as const,
value: 'group-layout',
label: 'Layout',
items: layoutItems,
},
]
: []),
...(actionControls.delete
? [
{ type: 'separator' as const, value: 'divider-danger' },
{
type: 'item' as const,
value: 'delete',
testId: 'dashboard-action-delete',
label: 'Delete dashboard',
prefix: <Trash2 size={14} />,
danger: true,
checks: deleteChecks,
// Independent of read/update, but a locked dashboard can't be removed.
...blockedBy(deleteDisabledTooltip),
onClick: confirmDeleteDashboard,
},
]
: []),
];
}, [
actionControls,
editChecks,
editDisabledTooltip,
deleteChecks,
deleteDisabledTooltip,
cloneChecks,
isCloning,
lockDisabledTooltip,
isDashboardLocked,
onOpenRename,
handleClone,
onLockToggle,
handleEnterFullScreen,
confirmDeleteDashboard,
]);
return (
<div className={styles.dashboardActionsContainer}>
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
{menuItems.length > 0 && (
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
<Button
variant="solid"
color="secondary"
size="md"
prefix={<Grid3X3 size="md" />}
testId="options"
>
Actions
</Button>
</AuthZDropdown>
)}
{actionControls.configure && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="secondary"
prefix={<Configure size="md" />}
testId="actionControls-drawer"
disabled={!isEditable}
onClick={handleOpenSettings}
size="md"
>
Configure
</Button>
</AuthZTooltip>
)}
{actionControls.json && (
<Button
variant="solid"
color="secondary"
size="md"
prefix={<Grid3X3 size="md" />}
testId="options"
>
Actions
</Button>
</AuthZDropdown>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="secondary"
prefix={<Configure size="md" />}
testId="show-drawer"
disabled={!isEditable}
onClick={handleOpenSettings}
prefix={<Braces size="md" />}
testId="edit-json"
onClick={handleOpenJsonEditor}
size="md"
>
Configure
JSON
</Button>
</AuthZTooltip>
<SettingsDrawer
drawerTitle="Dashboard Configuration"
isOpen={isSettingsDrawerOpen}
destroyOnClose
onClose={(): void => {
setIsSettingsDrawerOpen(false);
clearSettingsRequest();
}}
>
<DashboardSettings dashboard={dashboard} />
</SettingsDrawer>
<Button
variant="solid"
color="secondary"
prefix={<Braces size="md" />}
testId="edit-json"
onClick={handleOpenJsonEditor}
size="md"
>
JSON
</Button>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="primary"
onClick={onAddPanel}
prefix={<Plus size="md" />}
testId="add-panel-header"
disabled={!isEditable}
size="md"
>
New Panel
</Button>
</AuthZTooltip>
)}
{actionControls.newPanel && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
variant="solid"
color="primary"
onClick={onAddPanel}
prefix={<Plus size="md" />}
testId="add-panel-header"
disabled={!isEditable}
size="md"
>
New Panel
</Button>
</AuthZTooltip>
)}
<JsonEditorDrawer
dashboard={dashboard}
isOpen={isJsonEditorOpen}

View File

@@ -23,12 +23,14 @@ import { openInNewTab } from 'utils/navigation';
import styles from './DashboardInfo.module.scss';
import TagsOverflowTooltip from './TagsOverflowTooltip';
import { getLockTooltip } from './utils';
import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
// The tag cluster keeps a fixed footprint so a long title ellipsizes around it
// instead of collapsing the tags: show up to two tags, then a `+N` overflow badge.
// instead of collapsing the tags: titleControls up to two tags, then a `+N` overflow badge.
const MAX_VISIBLE_TAGS = 2;
interface DashboardInfoProps {
@@ -74,27 +76,19 @@ function DashboardInfo({
}: DashboardInfoProps): JSX.Element {
const { isEditable: canEdit } = useDashboardEditContext();
const dashboardId = useDashboardStore((s) => s.dashboardId);
const titleControls = useDashboardControlGroup('title');
const hasTags = tags.length > 0;
const hasDescription = !isEmpty(description);
const hasTags = titleControls.tags && tags.length > 0;
const hasDescription = titleControls.description && !isEmpty(description);
const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS);
const remainingTags = tags.slice(MAX_VISIBLE_TAGS);
// Without a toggle, say why it can't be toggled rather than only restating the
// lock state.
let lockTooltip: string;
if (onToggleLock) {
lockTooltip = isDashboardLocked
? 'Locked — click to unlock'
: 'Unlocked — click to lock';
} else if (lockDisabledTooltip) {
lockTooltip = lockDisabledTooltip;
} else {
lockTooltip = isDashboardLocked
? 'This dashboard is locked'
: 'This dashboard is unlocked';
}
const lockTooltip = getLockTooltip({
isLocked: isDashboardLocked,
canToggle: !!onToggleLock,
disabledReason: lockDisabledTooltip,
});
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
if (event.key === 'Enter') {
@@ -143,68 +137,71 @@ function DashboardInfo({
return (
<div className={styles.dashboardInfo}>
<img src={image} alt={title} className={styles.dashboardImage} />
{titleControls.name && (
<img src={image} alt={title} className={styles.dashboardImage} />
)}
{isEditing ? (
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
<div className={styles.dashboardTitleInput}>
<Input
autoFocus
value={draft}
testId="dashboard-title-input"
maxLength={DASHBOARD_NAME_MAX_LENGTH}
onChange={(e): void => onDraftChange(e.target.value)}
onKeyDown={onKeyDown}
/>
</div>
<Button
type="button"
variant="solid"
color="primary"
size="sm"
icon
aria-label="Save title"
testId="dashboard-title-save"
onClick={onCommit}
>
<Check size={14} />
</Button>
<Button
type="button"
variant="outlined"
color="secondary"
size="sm"
icon
aria-label="Cancel title edit"
testId="dashboard-title-cancel"
onClick={onCancel}
>
<X size={14} />
</Button>
</div>
) : (
<>
{canEdit ? (
{titleControls.name &&
(isEditing ? (
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
<div className={styles.dashboardTitleInput}>
<Input
autoFocus
value={draft}
testId="dashboard-title-input"
maxLength={DASHBOARD_NAME_MAX_LENGTH}
onChange={(e): void => onDraftChange(e.target.value)}
onKeyDown={onKeyDown}
/>
</div>
<Button
type="button"
variant="link"
variant="solid"
color="primary"
size="sm"
icon
aria-label="Save title"
testId="dashboard-title-save"
onClick={onCommit}
>
<Check size={14} />
</Button>
<Button
type="button"
variant="outlined"
color="secondary"
size="sm"
onClick={onStartEdit}
icon
aria-label="Cancel title edit"
testId="dashboard-title-cancel"
onClick={onCancel}
>
{titleText}
<X size={14} />
</Button>
) : (
titleText
)}
<CopyButton
value={dashboardId}
ariaLabel="Copy dashboard ID"
testId="dashboard-copy-id"
onCopy={handleCopyId}
/>
</>
)}
</div>
) : (
<>
{canEdit ? (
<Button
type="button"
variant="link"
color="secondary"
size="sm"
onClick={onStartEdit}
>
{titleText}
</Button>
) : (
titleText
)}
<CopyButton
value={dashboardId}
ariaLabel="Copy dashboard ID"
testId="dashboard-copy-id"
onCopy={handleCopyId}
/>
</>
))}
{hasDescription && (
<Tooltip
@@ -223,7 +220,7 @@ function DashboardInfo({
</Tooltip>
)}
{isPublicDashboard && (
{titleControls.publicBadge && isPublicDashboard && (
<Tooltip title="This dashboard is publicly accessible. Click to open the public page.">
<Button
type="button"
@@ -240,7 +237,7 @@ function DashboardInfo({
</Tooltip>
)}
{showLockToggle && (
{titleControls.lock && showLockToggle && (
<Tooltip title={onToggleLock ? lockTooltip : undefined}>
<Button
disabledTooltip={lockTooltip}

View File

@@ -0,0 +1,19 @@
// Without a toggle, say why it can't be toggled rather than only restating the
// lock state.
export function getLockTooltip({
isLocked,
canToggle,
disabledReason,
}: {
isLocked: boolean;
canToggle: boolean;
disabledReason?: string;
}): string {
if (canToggle) {
return isLocked ? 'Locked — click to unlock' : 'Unlocked — click to lock';
}
if (disabledReason) {
return disabledReason;
}
return isLocked ? 'This dashboard is locked' : 'This dashboard is unlocked';
}

View File

@@ -0,0 +1,167 @@
import type { FullScreenHandle } from 'react-full-screen';
import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';
import { render, screen } from 'tests/test-utils';
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
import type { DashboardControlsInput } from '../../controls/types';
import { usePublicDashboardMeta } from '../../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
import { useDashboardStore } from '../../store/useDashboardStore';
import DashboardPageToolbar from '../index';
const { data: dashboard } = dashboardResponse({
panels: 0,
sectioned: false,
variables: [],
locked: true,
});
const handle: FullScreenHandle = {
active: false,
enter: jest.fn(),
exit: jest.fn(),
node: { current: null },
};
jest.mock('../DashboardActions/DashboardActions', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="dashboard-actions" />,
}));
jest.mock('../DashboardInfo/DashboardInfo', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="dashboard-info" />,
}));
jest.mock('../../VariablesBar/VariablesBar', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="variables-bar" />,
}));
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="time-selection" />,
}));
jest.mock(
'../../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal',
() => ({ __esModule: true, default: (): null => null }),
);
jest.mock('../../hooks/useCreatePanel', () => ({
useCreatePanel: (): unknown => ({
isPickerOpen: false,
openPicker: jest.fn(),
closePicker: jest.fn(),
createPanel: jest.fn(),
targetLayoutIndex: 0,
}),
}));
jest.mock('../../hooks/useOptimisticPatch', () => ({
useOptimisticPatch: (): unknown => ({ patchAsync: jest.fn() }),
}));
jest.mock('hooks/dashboards/useToggleDashboardLock', () => ({
useToggleDashboardLock: (): unknown => ({ toggleLock: jest.fn() }),
}));
jest.mock('hooks/dashboards/useDashboardLockPermission', () => ({
useDashboardLockPermission: jest.fn(() => ({
canToggleLock: false,
isLoading: false,
disabledTooltip: '',
})),
}));
jest.mock(
'../../DashboardSettings/PublicDashboard/usePublicDashboardMeta',
() => ({
usePublicDashboardMeta: jest.fn(() => ({
isPublic: false,
publicMeta: undefined,
})),
}),
);
function renderToolbar(
ctx: { readOnly?: boolean; controls?: DashboardControlsInput } = {},
): void {
useDashboardStore
.getState()
.setEditContext({ dashboardId: dashboard.id, refetch: jest.fn(), ...ctx });
render(<DashboardPageToolbar dashboard={dashboard} handle={handle} />);
}
describe('DashboardPageToolbar - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
jest.clearAllMocks();
});
it('renders every row and checks lock + share by default', () => {
renderToolbar();
expect(screen.getByTestId('dashboard-info')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-actions')).toBeInTheDocument();
expect(screen.getByTestId('time-selection')).toBeInTheDocument();
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
expect.objectContaining({ enabled: true }),
);
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
dashboard.id,
{
enabled: true,
},
);
});
it('skips the lock permission check on a read-only mount', () => {
renderToolbar({ readOnly: true });
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
expect.objectContaining({ enabled: false }),
);
});
it('drops the title row and actions the host hides, and their requests', () => {
renderToolbar({
readOnly: true,
controls: { title: false, dashboardActions: false },
});
expect(screen.queryByTestId('dashboard-info')).not.toBeInTheDocument();
expect(screen.queryByTestId('dashboard-actions')).not.toBeInTheDocument();
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
dashboard.id,
{
enabled: false,
},
);
});
it('hides the time range and keeps the variables bar mounted but hidden', () => {
renderToolbar({
controls: { toolbar: { timeRange: false, variables: false } },
});
expect(screen.queryByTestId('time-selection')).not.toBeInTheDocument();
expect(screen.getByTestId('variables-bar')).not.toBeVisible();
});
it('hides the whole toolbar when the host turns every row off', () => {
renderToolbar({
readOnly: true,
controls: { title: false, dashboardActions: false, toolbar: false },
});
expect(screen.getByTestId('dashboard-page-toolbar')).not.toBeVisible();
expect(screen.getByTestId('variables-bar')).toBeInTheDocument();
});
it('keeps the toolbar when only the variables bar is on', () => {
renderToolbar({
readOnly: true,
controls: {
title: false,
dashboardActions: false,
toolbar: { timeRange: false, autoRefresh: false, variables: true },
},
});
expect(screen.getByTestId('dashboard-page-toolbar')).toBeVisible();
});
});

View File

@@ -17,6 +17,7 @@ import { getAbsoluteUrl } from 'utils/basePath';
import { useCreatePanel } from '../hooks/useCreatePanel';
import { useOptimisticPatch } from '../hooks/useOptimisticPatch';
import { useDashboardControlGroup } from '../controls/useDashboardControlGroup';
import { usePublicDashboardMeta } from '../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
import PanelTypeSelectionModal from '../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
import DashboardActions from './DashboardActions/DashboardActions';
@@ -56,6 +57,16 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
[dashboard.tags],
);
const titleControls = useDashboardControlGroup('title');
const actionControls = useDashboardControlGroup('dashboardActions');
const toolbarControls = useDashboardControlGroup('toolbar');
const hasTitleRow = Object.values(titleControls).some(Boolean);
const hasActions = Object.values(actionControls).some(Boolean);
const hasVisibleRows =
hasTitleRow ||
hasActions ||
toolbarControls.timeRange ||
toolbarControls.variables;
const { showErrorModal } = useErrorModal();
const { patchAsync } = useOptimisticPatch();
const {
@@ -71,10 +82,13 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
useDashboardLockPermission({
dashboardId: id,
source: dashboard.source,
enabled: titleControls.lock || actionControls.lock,
});
// Public-sharing meta (deduped react-query read); drives the header globe.
const { isPublic, publicMeta } = usePublicDashboardMeta(id);
const { isPublic, publicMeta } = usePublicDashboardMeta(id, {
enabled: titleControls.publicBadge,
});
const publicUrl = getAbsoluteUrl(publicMeta?.publicPath ?? '');
// Shared with the list's row menu — it owns the API call, the toast and the
@@ -154,49 +168,71 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
}, [id, openPicker]);
return (
<section className={styles.dashboardPageToolbarContainer}>
<div className={styles.dashboardInfoWithActions}>
<DashboardInfo
title={title}
image={image}
tags={tags}
description={description}
isPublicDashboard={isPublic}
publicUrl={publicUrl}
isDashboardLocked={isDashboardLocked}
showLockToggle={showLockToggle}
onToggleLock={
canToggleLock
? (): void => handleLockDashboardToggle('header')
: undefined
}
lockDisabledTooltip={lockDisabledTooltip}
isEditing={isEditing}
draft={draft}
onDraftChange={setDraft}
onStartEdit={startEdit}
onCommit={commit}
onCancel={cancel}
/>
<DashboardActions
title={title}
dashboard={dashboard}
handle={handle}
isDashboardLocked={isDashboardLocked}
onAddPanel={onAddPanel}
onLockToggle={(): void => handleLockDashboardToggle('menu')}
onOpenRename={startEdit}
/>
</div>
<section
className={styles.dashboardPageToolbarContainer}
data-testid="dashboard-page-toolbar"
hidden={!hasVisibleRows}
>
{(hasTitleRow || hasActions) && (
<div className={styles.dashboardInfoWithActions}>
{hasTitleRow && (
<DashboardInfo
title={title}
image={image}
tags={tags}
description={description}
isPublicDashboard={isPublic}
publicUrl={publicUrl}
isDashboardLocked={isDashboardLocked}
showLockToggle={showLockToggle}
onToggleLock={
canToggleLock
? (): void => handleLockDashboardToggle('header')
: undefined
}
lockDisabledTooltip={lockDisabledTooltip}
isEditing={isEditing}
draft={draft}
onDraftChange={setDraft}
onStartEdit={startEdit}
onCommit={commit}
onCancel={cancel}
/>
)}
{hasActions && (
<DashboardActions
title={title}
dashboard={dashboard}
handle={handle}
isDashboardLocked={isDashboardLocked}
onAddPanel={onAddPanel}
onLockToggle={(): void => handleLockDashboardToggle('menu')}
onOpenRename={startEdit}
/>
)}
</div>
)}
{/* Row 2: the time selector floats top-right (declared first so the
variables bar's content wraps around it); the variables bar
collapses to one line and, when expanded, wraps full-width under it. */}
<div className={styles.toolbarRow}>
<div className={styles.timeCluster}>
<DateTimeSelectionV2 showAutoRefresh hideShareModal />
</div>
<VariablesBar dashboard={dashboard} />
{toolbarControls.timeRange && (
<div className={styles.timeCluster}>
<DateTimeSelectionV2
showAutoRefresh={toolbarControls.autoRefresh}
hideShareModal
/>
</div>
)}
{toolbarControls.variables ? (
<VariablesBar dashboard={dashboard} />
) : (
// Still mounted: the selectors seed and auto-select the values panels query with.
<div hidden>
<VariablesBar dashboard={dashboard} />
</div>
)}
</div>
<PanelTypeSelectionModal
open={isPickerOpen}

View File

@@ -26,9 +26,13 @@ const PUBLIC_META_STALE_TIME = 5 * 60 * 1000;
*/
export function usePublicDashboardMeta(
dashboardId: string,
options?: { enabled?: boolean },
): UsePublicDashboardMetaReturn {
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const enabled = !!dashboardId && (isCloudUser || isEnterpriseSelfHostedUser);
const enabled =
(options?.enabled ?? true) &&
!!dashboardId &&
(isCloudUser || isEnterpriseSelfHostedUser);
const { data, isLoading, isFetching, error, refetch } = useGetPublicDashboard(
{ id: dashboardId },

View File

@@ -2,33 +2,17 @@ import { renderHook } from '@testing-library/react';
import { useContextLinkVariables } from '../useContextLinkVariables';
const mockUseGetDashboardV2 = jest.fn();
const mockUseDashboardVariableNames = jest.fn();
const mockUseQueryBuilder = jest.fn();
jest.mock(
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
() => ({
useDashboardStore: (
selector: (s: { dashboardId: string }) => unknown,
): unknown => selector({ dashboardId: 'dash-1' }),
}),
);
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => mockUseQueryBuilder(),
}));
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
}));
// dtoToFormModel is exercised by its own suite; here we only need it to surface a name.
jest.mock(
'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableAdapters',
'pages/DashboardPage/DashboardContainer/hooks/useDashboardVariableNames',
() => ({
dtoToFormModel: (dto: { name: string }): { name: string } => ({
name: dto.name,
}),
useDashboardVariableNames: (): unknown => mockUseDashboardVariableNames(),
}),
);
@@ -45,11 +29,7 @@ describe('useContextLinkVariables', () => {
},
},
});
mockUseGetDashboardV2.mockReturnValue({
data: {
data: { spec: { variables: [{ name: 'region' }, { name: 'tier' }] } },
},
});
mockUseDashboardVariableNames.mockReturnValue(['region', 'tier']);
});
it('orders globals, then _prefixed query fields (deduped), then dashboard vars', () => {
@@ -69,9 +49,7 @@ describe('useContextLinkVariables', () => {
mockUseQueryBuilder.mockReturnValue({
currentQuery: { builder: { queryData: [] } },
});
// Loaded dashboard with no variables — useDashboardFetchRequired guarantees the
// dashboard is present, so the empty case is an empty spec, not `undefined`.
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
mockUseDashboardVariableNames.mockReturnValue([]);
const { result } = renderHook(() => useContextLinkVariables());

View File

@@ -11,6 +11,7 @@ import { useDashboardStore } from '../../store/useDashboardStore';
import PanelTypeSelectionModal from '../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
import styles from './DashboardEmptyState.module.scss';
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
import { useDashboardControl } from '../../controls/useDashboardControl';
interface DashboardEmptyStateProps {
canAddPanel: boolean;
@@ -24,9 +25,11 @@ function DashboardEmptyState({
const { isPickerOpen, openPicker, closePicker, createPanel } =
useCreatePanel();
const requestSettings = useDashboardStore((s) => s.requestSettings);
const showConfigure = useDashboardControl('dashboardActions.configure');
const showNewPanel = useDashboardControl('dashboardActions.newPanel');
return (
<section className={styles.emptyState}>
<section className={styles.emptyState} data-testid="dashboard-empty-state">
<div className={styles.content}>
<div className={styles.heading}>
<img src={dashboardEmojiUrl} alt="" className={styles.emoji} />
@@ -53,90 +56,94 @@ function DashboardEmptyState({
</div>
<div className={styles.steps}>
<div className={styles.step}>
<div className={styles.stepText}>
<Configure size={14} className={styles.stepIcon} />
<div className={styles.stepCopy}>
<Typography
variant="paragraph"
size="base"
weight="medium"
color="main"
as="span"
textOverflow="wrap"
>
Configure your new dashboard
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="tertiary"
as="span"
textOverflow="wrap"
>
Give it a name, add description, tags and variables
</Typography>
{showConfigure && (
<div className={styles.step}>
<div className={styles.stepText}>
<Configure size={14} className={styles.stepIcon} />
<div className={styles.stepCopy}>
<Typography
variant="paragraph"
size="base"
weight="medium"
color="main"
as="span"
textOverflow="wrap"
>
Configure your new dashboard
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="tertiary"
as="span"
textOverflow="wrap"
>
Give it a name, add description, tags and variables
</Typography>
</div>
</div>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="solid"
color="secondary"
width="140px"
prefix={<Configure size="md" />}
disabled={!isEditable}
onClick={(): void => requestSettings({ tab: 'Overview' })}
testId="empty-configure"
>
Configure
</Button>
</AuthZTooltip>
</div>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="solid"
color="secondary"
width="140px"
prefix={<Configure size="md" />}
disabled={!isEditable}
onClick={(): void => requestSettings({ tab: 'Overview' })}
testId="empty-configure"
>
Configure
</Button>
</AuthZTooltip>
</div>
)}
<div className={styles.step}>
<div className={styles.stepText}>
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
<div className={styles.stepCopy}>
<Typography
variant="paragraph"
size="base"
weight="medium"
color="main"
as="span"
textOverflow="wrap"
>
Add panels
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="tertiary"
as="span"
textOverflow="wrap"
>
Add panels to visualize your data
</Typography>
{showNewPanel && (
<div className={styles.step}>
<div className={styles.stepText}>
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
<div className={styles.stepCopy}>
<Typography
variant="paragraph"
size="base"
weight="medium"
color="main"
as="span"
textOverflow="wrap"
>
Add panels
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="tertiary"
as="span"
textOverflow="wrap"
>
Add panels to visualize your data
</Typography>
</div>
</div>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="solid"
color="primary"
prefix={<Plus size="md" />}
disabled={!canAddPanel}
onClick={(): void => openPicker()}
testId="add-panel"
>
New Panel
</Button>
</AuthZTooltip>
</div>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="solid"
color="primary"
prefix={<Plus size="md" />}
disabled={!canAddPanel}
onClick={(): void => openPicker()}
testId="add-panel"
>
New Panel
</Button>
</AuthZTooltip>
</div>
)}
</div>
</div>
<PanelTypeSelectionModal

View File

@@ -10,6 +10,7 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
import type { DashboardSection } from '../../../../utils';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import { usePanelActionItems } from '../usePanelActionItems';
/** Keys of the disabled items, in order. */
@@ -494,4 +495,43 @@ describe('usePanelActionItems', () => {
click(actionRow(result.current.items, 'create-alert'));
expect(mockCreateAlert).toHaveBeenCalledWith(mockPanel, 'panel-1');
});
describe('host controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('drops every writing action on a read-only mount', () => {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
readOnly: true,
});
const { result } = renderHook(() => usePanelActionItems(baseArgs));
expect(itemKeys(result.current)).toStrictEqual([
'view-panel',
'separator',
'download',
'create-alert',
]);
});
it('drops the actions the host hides', () => {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
controls: { panelActions: { createAlert: false, delete: false } },
});
const { result } = renderHook(() => usePanelActionItems(baseArgs));
expect(itemKeys(result.current)).not.toContain('create-alert');
expect(itemKeys(result.current)).not.toContain('delete-panel');
expect(itemKeys(result.current)).toContain('edit-panel');
});
});
});

View File

@@ -28,6 +28,7 @@ import { buildMoveItems } from '../utils/buildMoveItems';
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
// Stable fallback so renders without layout context don't churn the mutation
// hooks' deps (a fresh [] each render would re-create their callbacks).
@@ -64,6 +65,7 @@ export function usePanelActionItems({
const panelKind = panel.spec.plugin.kind;
const { isEditable, editChecks, editDisabledTooltip } =
useDashboardEditContext();
const panelControls = useDashboardControlGroup('panelActions');
const openPanelEditor = useOpenPanelEditor();
const createAlert = useCreateAlertFromPanel();
const { openView } = useViewPanel();
@@ -101,7 +103,7 @@ export function usePanelActionItems({
const editGate = { checks: editChecks, ...blockedBy(editDisabledTooltip) };
const panelGroup: AuthZDropdownItemType[] = [];
if (panelCapabilities.view) {
if (panelControls.view && panelCapabilities.view) {
panelGroup.push({
type: 'item',
value: 'view-panel',
@@ -110,7 +112,7 @@ export function usePanelActionItems({
onClick: (): void => openView(panelId, panel),
});
}
if (panelCapabilities.edit) {
if (panelControls.edit && panelCapabilities.edit) {
panelGroup.push({
type: 'item',
value: 'edit-panel',
@@ -120,7 +122,7 @@ export function usePanelActionItems({
onClick: (): void => openPanelEditor(panelId, { panel }),
});
}
if (panelCapabilities.clone) {
if (panelControls.clone && panelCapabilities.clone) {
// Needs section context to place the copy; disabled without it.
panelGroup.push({
type: 'item',
@@ -140,13 +142,13 @@ export function usePanelActionItems({
}
const dataGroup: AuthZDropdownItemType[] = [];
if (downloadItem) {
if (panelControls.download && downloadItem) {
dataGroup.push(downloadItem);
}
// Create Alerts opens a new tab and never mutates the dashboard, so —
// unlike edit/clone — it isn't gated on editability (V1 parity).
if (panelCapabilities.createAlert) {
if (panelControls.createAlert && panelCapabilities.createAlert) {
dataGroup.push({
type: 'item',
value: 'create-alert',
@@ -156,8 +158,9 @@ export function usePanelActionItems({
});
}
const moveGroup: AuthZDropdownItemType[] =
isEditable && panelActions
const moveGroup: AuthZDropdownItemType[] = !panelControls.move
? []
: isEditable && panelActions
? buildMoveItems({
sections,
currentLayoutIndex: panelActions.currentLayoutIndex,
@@ -174,17 +177,19 @@ export function usePanelActionItems({
},
];
const deleteGroup: AuthZDropdownItemType[] = [
{
type: 'item',
value: 'delete-panel',
label: 'Delete panel',
prefix: <Trash2 size={14} />,
danger: true,
...editGate,
onClick: (): void => requestDelete(),
},
];
const deleteGroup: AuthZDropdownItemType[] = !panelControls.delete
? []
: [
{
type: 'item',
value: 'delete-panel',
label: 'Delete panel',
prefix: <Trash2 size={14} />,
danger: true,
...editGate,
onClick: (): void => requestDelete(),
},
];
return [panelGroup, dataGroup, moveGroup, deleteGroup]
.filter((group) => group.length > 0)
@@ -194,6 +199,7 @@ export function usePanelActionItems({
: [{ type: 'separator', value: `separator-${index}` }, ...group],
);
}, [
panelControls,
isEditable,
editChecks,
editDisabledTooltip,

View File

@@ -14,6 +14,7 @@ import { EQueryType } from 'types/common/dashboard';
import styles from './ViewPanelModal.module.scss';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
import { useDashboardControl } from '../../../controls/useDashboardControl';
interface ViewPanelModalHeaderBaseProps {
onSwitchToEdit: () => void;
@@ -70,6 +71,7 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
editChecks,
editDisabledTooltip,
} = useDashboardEditContext();
const showSwitchToEdit = useDashboardControl('viewModal.switchToEdit');
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
const panelTypeItems = usePanelTypeSelectItems({
@@ -87,20 +89,22 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
onChange={onChangePanelKind}
/>
</div>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="outlined"
color="secondary"
prefix={<PenLine />}
disabled={!canSwitchToEdit}
onClick={onSwitchToEdit}
testId="view-panel-switch-to-edit"
>
Switch to Edit Mode
</Button>
</AuthZTooltip>
{showSwitchToEdit && (
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
disabledTooltip={undefined}
size="md"
variant="outlined"
color="secondary"
prefix={<PenLine />}
disabled={!canSwitchToEdit}
onClick={onSwitchToEdit}
testId="view-panel-switch-to-edit"
>
Switch to Edit Mode
</Button>
</AuthZTooltip>
)}
{query && (
<Button
size="md"

View File

@@ -0,0 +1,71 @@
import { render, screen } from 'tests/test-utils';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import ViewPanelModalHeader from '../ViewPanelModalHeader';
import type { DashboardControlsInput } from '../../../../controls/types';
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({
isEditable: true,
editChecks: [],
editDisabledTooltip: '',
}),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/usePanelTypeSelectItems',
() => ({ usePanelTypeSelectItems: (): unknown[] => [] }),
);
function renderHeader(
readOnly: boolean,
controls?: DashboardControlsInput,
): void {
useDashboardStore.getState().setEditContext({
dashboardId: 'dash-1',
refetch: jest.fn(),
readOnly,
controls,
});
render(
<ViewPanelModalHeader
mode="static"
panelKind="signoz/TimeSeriesPanel"
onChangePanelKind={jest.fn()}
onSwitchToEdit={jest.fn()}
/>,
);
}
describe('ViewPanelModalHeader - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('offers Switch to Edit Mode on an editable mount', () => {
renderHeader(false);
expect(screen.getByTestId('view-panel-switch-to-edit')).toBeInTheDocument();
});
it('hides Switch to Edit Mode on a read-only mount', () => {
renderHeader(true);
expect(screen.getByTestId('view-panel-type-selector')).toBeInTheDocument();
expect(
screen.queryByTestId('view-panel-switch-to-edit'),
).not.toBeInTheDocument();
});
it('hides Switch to Edit Mode when the host hides it', () => {
renderHeader(false, { viewModal: false });
expect(
screen.queryByTestId('view-panel-switch-to-edit'),
).not.toBeInTheDocument();
});
});

View File

@@ -169,6 +169,15 @@ describe('useDrilldown', () => {
expect(result.current.enableDrillDown).toBe(false);
});
it('is false when every builder query is disabled, leaving only formulas to draw', () => {
mockGetBuilderQueries.mockReturnValue([
{ name: 'A', disabled: true },
{ name: 'B', disabled: true },
]);
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
expect(result.current.enableDrillDown).toBe(false);
});
it.each([EQueryType.PROM, EQueryType.CLICKHOUSE, undefined])(
'is false when the query type is %s (not the builder)',
(queryType) => {

View File

@@ -18,17 +18,35 @@ let mockVariables: Array<{
let mockSelectionMap: Record<string, { value: unknown; allSelected: boolean }> =
{};
let mockIsEditable = true;
const mockSetVariableValue = jest.fn();
const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
const DYNAMIC_KIND = 'signoz/DynamicVariable';
const QUERY_KIND = 'signoz/QueryVariable';
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => ({
data: { data: { spec: { variables: mockVariables } } },
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired',
() => ({
useDashboardFetchRequired: (): unknown => ({
dashboard: { spec: { variables: mockVariables } },
variables: mockVariables,
refetch: jest.fn(),
}),
}),
}));
);
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({ isEditable: mockIsEditable }),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
() => ({
useDashboardEditContext: (): unknown => ({ isEditable: mockIsEditable }),
}),
);
jest.mock(
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
() => ({
@@ -97,6 +115,7 @@ function renderItems(): void {
describe('useDrilldownDashboardVariables', () => {
beforeEach(() => {
mockIsEditable = true;
jest.clearAllMocks();
mockVariables = [];
mockSelectionMap = {};
@@ -171,6 +190,17 @@ describe('useDrilldownDashboardVariables', () => {
});
});
it('offers nothing to create on a dashboard the viewer cannot edit', () => {
mockVariables = [];
mockIsEditable = false;
const { result } = renderHook(() =>
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
);
expect(result.current.actions).toStrictEqual([]);
expect(result.current.hasFieldVariables).toBe(false);
});
it('offers Create and persists a new dynamic variable when none matches', async () => {
mockVariables = [];
renderItems();

View File

@@ -0,0 +1,51 @@
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { CHARTS_ONLY } from '../../../../controls/presets';
import type { DashboardControlsInput } from '../../../../controls/types';
import { useDashboardStore } from '../../../../store/useDashboardStore';
import { usePanelInteractions } from '../usePanelInteractions';
function dragSelect(controls?: DashboardControlsInput): void {
useDashboardStore
.getState()
.setEditContext({ dashboardId: 'd1', refetch: jest.fn(), controls });
const { result } = renderHook(() => usePanelInteractions(), {
wrapper: AllTheProviders,
});
result.current.onDragSelect(1_000, 2_000);
}
describe('usePanelInteractions drag-to-zoom', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('writes the dragged range to the URL', () => {
dragSelect();
expect(safeNavigateMock).toHaveBeenCalledWith(
expect.stringContaining('startTime=1000&endTime=2000'),
);
});
it('does nothing when the host turns zoom off', () => {
dragSelect({ panelActions: { zoom: false } });
expect(safeNavigateMock).not.toHaveBeenCalled();
});
it('still zooms when the host hides the toolbar but leaves zoom on', () => {
dragSelect({ toolbar: false });
expect(safeNavigateMock).toHaveBeenCalled();
});
it('still zooms on a charts-only mount', () => {
dragSelect(CHARTS_ONLY);
expect(safeNavigateMock).toHaveBeenCalled();
});
});

View File

@@ -37,6 +37,7 @@ import { useDrilldownCoordinates } from './useDrilldownCoordinates';
import { useDrilldownDashboardVariables } from './useDrilldownDashboardVariables';
import { useDrilldownFilter } from './useDrilldownFilter';
import { useResolvedDrilldownQuery } from './useResolvedDrilldownQuery';
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
import { useViewPanel } from './useViewPanel';
/** Which menu the popover shows; extend as submenus are added (e.g. dashboard variables). */
@@ -87,16 +88,19 @@ export function useDrilldown(
const queries = panel.spec.queries;
// Drilldown only for builder-authored panels with a query to drill into (PromQL /
// ClickHouse have no builder context to refine).
// ClickHouse have no builder context to refine). A panel whose builder queries
// are all disabled draws only formulas, which have no series to drill into.
const showDrilldown = useDashboardControl('panelActions.drilldown');
const enableDrillDown = useMemo(() => {
const queryType = getPanelQueryType(panel);
return (
showDrilldown &&
getPanelDefinition(kind).actions.drilldown &&
!!queryType &&
isBuilderQueryType(queryType) &&
getBuilderQueries(queries).length > 0
getBuilderQueries(queries).some((query) => !query.disabled)
);
}, [kind, panel, queries]);
}, [showDrilldown, kind, panel, queries]);
const slotQuery = useMemo(
() => fromPerses(queries, panelType),

View File

@@ -12,6 +12,7 @@ import {
type VariableFormModel,
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableFormModel';
import { buildVariablesPatch } from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/utils/variablePatchOps';
import { useDashboardEditContext } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext';
import { useDashboardFetchRequired } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired';
import { useOptimisticPatch } from 'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch';
import { selectVariableValues } from 'pages/DashboardPage/DashboardContainer/store/slices/variableSelectionSlice';
@@ -44,7 +45,7 @@ export interface DrilldownVariableAction {
}
export interface UseDrilldownDashboardVariablesApi {
/** Whether the clicked point exposes any field to bind to a variable (gates the base-menu entry). */
/** Whether the submenu has any entry to offer (gates the base-menu entry). */
hasFieldVariables: boolean;
/** Resolved menu entries, one per group-by field on the clicked point. */
actions: DrilldownVariableAction[];
@@ -74,6 +75,8 @@ export function useDrilldownDashboardVariables({
const selection = useDashboardStore(selectVariableValues(dashboardId));
const setVariableValue = useDashboardStore((state) => state.setVariableValue);
const { patchAsync } = useOptimisticPatch();
// Create writes the dashboard spec; Set/Unset only change this view's selection.
const { isEditable } = useDashboardEditContext();
const fieldVariables = useMemo<[string, string | number][]>(
() =>
@@ -141,51 +144,57 @@ export function useDrilldownDashboardVariables({
const actions = useMemo<DrilldownVariableAction[]>(
() =>
fieldVariables.map(([fieldName, fieldValue]) => {
const existing = dynamicVariables.find(
(v) => v.dynamicAttribute === fieldName,
);
if (!existing) {
fieldVariables
.map(([fieldName, fieldValue]) => {
const existing = dynamicVariables.find(
(v) => v.dynamicAttribute === fieldName,
);
if (!existing) {
if (!isEditable) {
return null;
}
return {
fieldName,
fieldValue,
kind: DrilldownVariableActionKind.Create,
onClick: (): void => {
void handleCreate(fieldName, fieldValue);
},
};
}
const current = selection[existing.name]?.value;
const isSame = Array.isArray(current)
? current.length === 1 && current[0] === fieldValue
: current === fieldValue;
// Multi-select values must be arrays (a scalar renders as empty in the selector).
const cleared = existing.multiSelect ? [] : '';
const assigned = existing.multiSelect ? [fieldValue] : fieldValue;
return {
fieldName,
fieldValue,
kind: DrilldownVariableActionKind.Create,
kind: isSame
? DrilldownVariableActionKind.Unset
: DrilldownVariableActionKind.Set,
onClick: (): void => {
void handleCreate(fieldName, fieldValue);
void logEvent(DashboardDetailEvents.DrilldownAction, {
action: 'setVariable',
dashboardId,
});
setSelection(existing.name, {
value: isSame ? cleared : assigned,
allSelected: false,
});
onClose();
},
};
}
const current = selection[existing.name]?.value;
const isSame = Array.isArray(current)
? current.length === 1 && current[0] === fieldValue
: current === fieldValue;
// Multi-select values must be arrays (a scalar renders as empty in the selector).
const cleared = existing.multiSelect ? [] : '';
const assigned = existing.multiSelect ? [fieldValue] : fieldValue;
return {
fieldName,
fieldValue,
kind: isSame
? DrilldownVariableActionKind.Unset
: DrilldownVariableActionKind.Set,
onClick: (): void => {
void logEvent(DashboardDetailEvents.DrilldownAction, {
action: 'setVariable',
dashboardId,
});
setSelection(existing.name, {
value: isSame ? cleared : assigned,
allSelected: false,
});
onClose();
},
};
}),
})
.filter((action): action is DrilldownVariableAction => action !== null),
[
fieldVariables,
isEditable,
dynamicVariables,
selection,
setSelection,
@@ -195,5 +204,5 @@ export function useDrilldownDashboardVariables({
],
);
return { hasFieldVariables: fieldVariables.length > 0, actions };
return { hasFieldVariables: actions.length > 0, actions };
}

View File

@@ -13,6 +13,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
import logEvent from 'api/common/logEvent';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { UpdateTimeInterval } from 'store/actions';
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
export interface PanelInteractions {
/** Drag-select a chart range → write it to the URL + global time so every panel re-fetches the same range. */
@@ -43,8 +44,12 @@ export function usePanelInteractions(): PanelInteractions {
[syncMode, syncFilterMode, dashboardId],
);
const canZoom = useDashboardControl('panelActions.zoom');
const onDragSelect = useCallback(
(start: number, end: number): void => {
if (!canZoom) {
return;
}
const startTimestamp = Math.trunc(start);
const endTimestamp = Math.trunc(end);
@@ -57,7 +62,7 @@ export function usePanelInteractions(): PanelInteractions {
void logEvent(DashboardDetailEvents.PanelZoomed, { context: 'panel' });
}
},
[dispatch, pathname, safeNavigate, urlQuery],
[canZoom, dispatch, pathname, safeNavigate, urlQuery],
);
return { onDragSelect, dashboardPreference };

View File

@@ -8,12 +8,12 @@ import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { useCreatePanel } from '../../../hooks/useCreatePanel';
import type { DashboardSection } from '../../../utils';
import PanelTypeSelectionModal from '../../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
import { useCloneSection } from '../hooks/useCloneSection';
import { useDeleteSection } from '../hooks/useDeleteSection';
import { usePanelPickerHighlight } from '../hooks/usePanelPickerHighlight';
import { usePanelPickerReveal } from '../hooks/usePanelPickerReveal';
import { useRenameSection } from '../hooks/useRenameSection';
import { useScrollIntoView } from '../hooks/useScrollIntoView';
import { useSectionHeaderActions } from '../hooks/useSectionHeaderActions';
import { useToggleSectionCollapse } from '../hooks/useToggleSectionCollapse';
import SectionTitleModal from '../SectionTitleModal';
import SectionGrid from '../SectionGrid/SectionGrid';
@@ -66,7 +66,14 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
setIsDeleteOpen(false);
}, [deleteSection]);
const cloneSection = useCloneSection();
const openRename = useCallback((): void => setIsRenaming(true), []);
const openDelete = useCallback((): void => setIsDeleteOpen(true), []);
const actions = useSectionHeaderActions({
section,
openPicker,
openRename,
openDelete,
});
const sectionRef = useRef<HTMLDivElement>(null);
useScrollIntoView(section.id, sectionRef);
@@ -116,35 +123,30 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
dragHandle={dragHandle}
disabledChecks={editChecks}
disabledTooltip={editDisabledTooltip}
actions={{
onRename: (): void => setIsRenaming(true),
onAddPanel: (): void => openPicker(section.layoutIndex),
onCloneSection: (): void => void cloneSection(section),
onDeleteSection: (): void => setIsDeleteOpen(true),
}}
actions={actions}
/>
{open &&
(section.items.length > 0 || pickerTarget ? (
grid
) : (
<div className={styles.emptySection}>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
size="md"
type="button"
variant="dashed"
color="secondary"
prefix={<Plus size="md" />}
onClick={
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
}
testId={`section-add-panel-${section.id}`}
>
New Panel
</Button>
</AuthZTooltip>
</div>
))}
(section.items.length > 0 || pickerTarget
? grid
: actions.onAddPanel && (
<div className={styles.emptySection}>
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
<Button
size="md"
type="button"
variant="dashed"
color="secondary"
prefix={<Plus size="md" />}
onClick={
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
}
testId={`section-add-panel-${section.id}`}
>
New Panel
</Button>
</AuthZTooltip>
</div>
))}
<SectionTitleModal
open={isRenaming}
heading="Rename section"

View File

@@ -25,7 +25,7 @@ function SectionActionsMenu({
onRename,
onCloneSection,
onDeleteSection,
}: SectionActionsMenuProps): JSX.Element {
}: SectionActionsMenuProps): JSX.Element | null {
const items = useMemo<AuthZDropdownItemType[]>(() => {
const gate = { checks: disabledChecks, ...blockedBy(disabledTooltip) };
const result: AuthZDropdownItemType[] = [];
@@ -83,6 +83,10 @@ function SectionActionsMenu({
onDeleteSection,
]);
if (items.length === 0) {
return null;
}
return (
<AuthZDropdown
items={items}

View File

@@ -16,12 +16,12 @@ export interface SectionDragHandle {
setActivatorNodeRef: (element: HTMLElement | null) => void;
}
/** Editable-mode section actions — present together or not at all. */
/** Section actions; an absent one isn't offered. */
export interface SectionHeaderActions {
onRename: () => void;
onAddPanel: () => void;
onCloneSection: () => void;
onDeleteSection: () => void;
onRename?: () => void;
onAddPanel?: () => void;
onCloneSection?: () => void;
onDeleteSection?: () => void;
}
interface SectionHeaderProps {

View File

@@ -0,0 +1,38 @@
import { useMemo } from 'react';
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
import type { DashboardSection } from '../../../utils';
import type { SectionHeaderActions } from '../SectionHeader/SectionHeader';
import { useCloneSection } from './useCloneSection';
interface UseSectionHeaderActionsArgs {
section: DashboardSection;
openPicker: (layoutIndex: number) => void;
openRename: () => void;
openDelete: () => void;
}
/** The section menu's actions, minus the ones the host hides (`sectionActions`). */
export function useSectionHeaderActions({
section,
openPicker,
openRename,
openDelete,
}: UseSectionHeaderActionsArgs): SectionHeaderActions {
const sectionControls = useDashboardControlGroup('sectionActions');
const cloneSection = useCloneSection();
return useMemo(
() => ({
onRename: sectionControls.rename ? openRename : undefined,
onAddPanel: sectionControls.addPanel
? (): void => openPicker(section.layoutIndex)
: undefined,
onCloneSection: sectionControls.clone
? (): void => void cloneSection(section)
: undefined,
onDeleteSection: sectionControls.delete ? openDelete : undefined,
}),
[sectionControls, openRename, openPicker, section, cloneSection, openDelete],
);
}

View File

@@ -16,6 +16,7 @@ import { resolveDefaultSelection } from './utils/resolveVariableSelection';
import VariableSelector from './components/VariableSelector/VariableSelector';
import styles from './VariablesBar.module.scss';
import { useDashboardEditContext } from '../hooks/useDashboardEditContext';
import { useDashboardControl } from '../controls/useDashboardControl';
interface VariablesBarProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
@@ -39,6 +40,7 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
// Persisted per dashboard so the full/collapsed view survives reloads.
const expanded = useDashboardStore(selectVariablesExpanded(dashboardId));
const setVariablesExpanded = useDashboardStore((s) => s.setVariablesExpanded);
const showAddVariable = useDashboardControl('toolbar.addVariable');
const { containerRef, visibleCount, overflowCount } = useInlineOverflowCount({
itemCount: variables.length,
gap: 8,
@@ -49,7 +51,7 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
// Editors can add a variable even before any exist; viewers with no variables
// have nothing to show.
if (variables.length === 0 && !isEditable) {
if (variables.length === 0 && !(isEditable && showAddVariable)) {
return null;
}
@@ -131,13 +133,15 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
{/* After the more/less trigger, in every state. Kept inline (not block)
so the row still flows under the floated time selector, and always
mounted so measuring never toggles it. */}
<span className={styles.addSlot}>
<AddVariableIcon
checks={editChecks}
disabledTooltip={editDisabledTooltip}
isEditable={isEditable}
/>
</span>
{showAddVariable && (
<span className={styles.addSlot}>
<AddVariableIcon
checks={editChecks}
disabledTooltip={editDisabledTooltip}
isEditable={isEditable}
/>
</span>
)}
</div>
</div>
);

View File

@@ -0,0 +1,74 @@
import { render, screen } from 'tests/test-utils';
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
import { useDashboardStore } from '../../store/useDashboardStore';
import VariablesBar from '../VariablesBar';
import type { DashboardControlsInput } from '../../controls/types';
const { data: dashboard } = dashboardResponse({
panels: 0,
sectioned: false,
variables: [],
locked: false,
});
jest.mock('../../hooks/useDashboardEditContext', () => ({
useDashboardEditContext: (): unknown => ({
isEditable: false,
editChecks: [],
editDisabledTooltip: '',
}),
}));
jest.mock('../hooks/useVariableSelection', () => ({
useVariableSelection: (): unknown => ({
variables: [{ name: 'env' }],
selection: {},
setSelection: jest.fn(),
autoSelect: jest.fn(),
}),
}));
jest.mock('../components/VariableSelector/VariableSelector', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="variable-selector" />,
}));
function renderBar(readOnly: boolean, controls?: DashboardControlsInput): void {
useDashboardStore.getState().setEditContext({
dashboardId: dashboard.id,
refetch: jest.fn(),
readOnly,
controls,
});
render(<VariablesBar dashboard={dashboard} />);
}
describe('VariablesBar - controls', () => {
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('offers the add-variable trigger, disabled, to a viewer', () => {
renderBar(false);
expect(screen.getByTestId('dashboard-variables-add')).toBeInTheDocument();
});
it('renders the selectors but no add-variable trigger', () => {
renderBar(true);
expect(screen.getByTestId('variable-selector')).toBeInTheDocument();
expect(
screen.queryByTestId('dashboard-variables-add'),
).not.toBeInTheDocument();
});
it('renders no add-variable trigger when the host hides it', () => {
renderBar(false, { toolbar: { addVariable: false } });
expect(
screen.queryByTestId('dashboard-variables-add'),
).not.toBeInTheDocument();
});
});

View File

@@ -68,6 +68,49 @@ describe('useSeedVariableSelection', () => {
});
});
it('keeps URL values a custom list does not offer, as typed values', () => {
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
const dash = dashboard('d1', [
model({
name: 'ops',
type: 'CUSTOM',
multiSelect: true,
customValue: 'overflow_operation',
}),
]);
renderHook(() => useSeedVariableSelection(dash));
expect(seededValue('d1', 'ops')).toStrictEqual({
value: ['overflow_operation', 'GET /cart'],
allSelected: false,
customValues: ['GET /cart'],
});
});
it('marks typed URL values even when the store already holds them unmarked', () => {
useDashboardStore.getState().setVariableValues('d1', {
ops: { value: ['overflow_operation', 'GET /cart'], allSelected: false },
});
mockUrlValues = { ops: ['overflow_operation', 'GET /cart'] };
const dash = dashboard('d1', [
model({
name: 'ops',
type: 'CUSTOM',
multiSelect: true,
customValue: 'overflow_operation',
}),
]);
renderHook(() => useSeedVariableSelection(dash));
expect(seededValue('d1', 'ops')).toStrictEqual({
value: ['overflow_operation', 'GET /cart'],
allSelected: false,
customValues: ['GET /cart'],
});
});
it('falls back to the stored value when the URL has no entry', () => {
useDashboardStore
.getState()

View File

@@ -71,6 +71,15 @@ function fromUrlValue(
if (raw === ALL_SELECTED && model.multiSelect && model.showAllOption) {
return { value: null, allSelected: true };
}
// Values a link carries that the custom list doesn't offer were typed by whoever
// made it (or set by a host page); keep them as typed instead of dropping them.
if (model.type === 'CUSTOM' && model.multiSelect && Array.isArray(raw)) {
const options = knownVariableOptions(model);
const customValues = raw.map(String).filter((v) => !options.includes(v));
if (customValues.length > 0) {
return { value: raw, allSelected: false, customValues };
}
}
return { value: raw, allSelected: false };
}

View File

@@ -119,12 +119,29 @@ export function useVariableSelection(
// store write + one `enqueueDescendantsBatch` means dependents re-fetch once
// with the settled parent values, instead of once per fill.
const pendingAutoFillRef = useRef<VariableSelectionMap>({});
// The selection each pending fill was computed from.
const pendingAutoFillBaseRef = useRef<
Record<string, VariableSelection | undefined>
>({});
const autoFillFrameRef = useRef<number | null>(null);
const flushAutoFills = useCallback((): void => {
autoFillFrameRef.current = null;
const fills = pendingAutoFillRef.current;
const bases = pendingAutoFillBaseRef.current;
pendingAutoFillRef.current = {};
pendingAutoFillBaseRef.current = {};
// A fill reconciles the selection it saw. If that selection has moved since (the
// seed committed a typed value, the user picked one), the fill answers a question
// nobody is asking any more and would overwrite the newer value.
Object.keys(fills).forEach((name) => {
const base = bases[name];
const now = selectionRef.current[name];
const moved = base && now ? !areSelectionsEqual(base, now) : base !== now;
if (moved) {
delete fills[name];
}
});
const names = Object.keys(fills);
if (names.length === 0 || !dashboardId) {
return;
@@ -146,6 +163,9 @@ export function useVariableSelection(
const autoSelect = useCallback(
(name: string, next: VariableSelection): void => {
if (!(name in pendingAutoFillBaseRef.current)) {
pendingAutoFillBaseRef.current[name] = selectionRef.current[name];
}
pendingAutoFillRef.current[name] = next;
if (autoFillFrameRef.current == null) {
autoFillFrameRef.current = requestAnimationFrame(flushAutoFills);

View File

@@ -237,13 +237,14 @@ function valueSetKey(value: SelectedVariableValue): string {
return list.map(String).sort().join('||');
}
/** True when two selections carry the same ALL flag and the same value set. */
/** True when two selections carry the same ALL flag, value set and typed values. */
export function areSelectionsEqual(
a: VariableSelection,
b: VariableSelection,
): boolean {
return (
!!a.allSelected === !!b.allSelected &&
valueSetKey(a.value) === valueSetKey(b.value)
valueSetKey(a.value) === valueSetKey(b.value) &&
valueSetKey(a.customValues ?? []) === valueSetKey(b.customValues ?? [])
);
}

View File

@@ -0,0 +1,104 @@
import { useQuery } from 'react-query';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { render, screen, waitFor } from 'tests/test-utils';
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
import { DEFAULT_CONTROLS } from '../controls/dashboardControls';
import type { DashboardControlsInput } from '../controls/types';
import DashboardContainer from '../index';
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
const QUERY_KEY = ['lockdown-dashboard'];
const ALL_CONTROLS_OFF = Object.fromEntries(
Object.keys(DEFAULT_CONTROLS).map((group) => [group, false]),
) as DashboardControlsInput;
const select = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
/**
* Interactive elements a host can't turn off: they read, never write, and the
* page is unusable without them. Anything else here must be a control.
*/
const ALLOWED_TEST_ID_PREFIXES = [
// Collapses a section in this browser only; it also carries the section title.
'dashboard-section-toggle-',
];
const INTERACTIVE =
'button, a[href], input, select, textarea, [role="button"], [role="menuitem"], [role="combobox"], [role="switch"], [role="checkbox"]';
function LockdownHost({ panels }: { panels: number }): JSX.Element | null {
const { data } = useQuery(QUERY_KEY, () =>
dashboardResponse({
panels,
sectioned: panels > 0,
variables: ['custom'],
locked: false,
}),
);
if (!data) {
return null;
}
return (
<DashboardContainer
dashboard={data.data}
refetch={jest.fn()}
source={SOURCE}
readOnly
controls={ALL_CONTROLS_OFF}
/>
);
}
function visibleInteractive(): Element[] {
return Array.from(
// oxlint-disable-next-line signoz/no-dom-node-access -- sweeps every interactive element, whatever role or test id it carries
document.body.querySelectorAll(INTERACTIVE),
).filter(
// oxlint-disable-next-line signoz/no-dom-node-access -- a `hidden` ancestor is what hides it, not a queryable element
(element) => !element.closest('[hidden]'),
);
}
function describeElement(element: Element): string {
return (
element.getAttribute('data-testid') ??
`<${element.tagName.toLowerCase()} aria-label="${element.getAttribute('aria-label') ?? ''}">${element.textContent?.trim().slice(0, 40) ?? ''}`
);
}
function leakedInteractive(): string[] {
return visibleInteractive()
.map(describeElement)
.filter(
(id) => !ALLOWED_TEST_ID_PREFIXES.some((prefix) => id.startsWith(prefix)),
);
}
describe('DashboardContainer lockdown', () => {
// A control a host can't switch off, or one read-only doesn't remove, fails here.
it('renders nothing interactive with every control off on a read-only mount', async () => {
render(<LockdownHost panels={3} />);
await waitFor(() =>
expect(screen.getAllByTestId(/^panel-/).length).toBeGreaterThan(0),
);
expect(leakedInteractive()).toStrictEqual([]);
});
it('renders nothing interactive on an empty dashboard', async () => {
render(<LockdownHost panels={0} />);
await screen.findByTestId('dashboard-empty-state');
expect(leakedInteractive()).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,61 @@
import { useQuery } from 'react-query';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { act, render, screen } from 'tests/test-utils';
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
import DashboardContainer from '../index';
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
import { useDashboardStore } from '../store/useDashboardStore';
jest.mock('../DashboardSettings', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="dashboard-settings" />,
}));
const QUERY_KEY = ['settings-drawer-dashboard'];
const select = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
function Host(): JSX.Element | null {
const { data } = useQuery(QUERY_KEY, () =>
dashboardResponse({
panels: 0,
sectioned: false,
variables: [],
locked: false,
}),
);
if (!data) {
return null;
}
return (
<DashboardContainer
dashboard={data.data}
refetch={jest.fn()}
source={SOURCE}
controls={{ dashboardActions: false }}
/>
);
}
describe('DashboardContainer settings drawer', () => {
it('opens on request when the host hides the dashboard actions', async () => {
render(<Host />);
await screen.findByTestId('dashboard-empty-state');
act(() => {
useDashboardStore
.getState()
.requestSettings({ tab: 'Variables', addVariable: true });
});
await expect(
screen.findByTestId('dashboard-settings'),
).resolves.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,85 @@
import { useQuery } from 'react-query';
import type {
DashboardtypesGettableDashboardV2DTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { render, waitFor } from 'tests/test-utils';
import { dashboardResponse } from '../../stories/__story_mockdata__/dashboard';
import DashboardContainer from '../index';
import type { DashboardQuerySource } from '../store/slices/editContextSlice';
import { useDashboardStore } from '../store/useDashboardStore';
const QUERY_KEY = ['variable-seed-dashboard'];
const select = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select };
function withOperationsVariable(): GetDashboardV2200 {
const response = dashboardResponse({
panels: 0,
sectioned: false,
variables: [],
locked: false,
});
response.data.spec.variables = [
{
kind: 'ListVariable',
spec: {
name: 'ops',
display: { name: 'ops' },
allowMultiple: true,
allowAllValue: false,
sort: 'none',
plugin: {
kind: 'signoz/CustomVariable',
spec: { customValue: 'overflow_operation' },
},
},
},
] as GetDashboardV2200['data']['spec']['variables'];
return response;
}
function Host(): JSX.Element | null {
const { data } = useQuery(QUERY_KEY, withOperationsVariable);
if (!data) {
return null;
}
return (
<DashboardContainer
dashboard={data.data}
refetch={jest.fn()}
source={SOURCE}
readOnly
/>
);
}
describe('DashboardContainer variable seeding', () => {
it('keeps custom-variable values a link seeds that the list does not offer', async () => {
const seeded = ['overflow_operation', 'GET /cart', 'POST /checkout'];
render(<Host />, undefined, {
initialRoute: `/?variables=${encodeURIComponent(JSON.stringify({ ops: seeded }))}`,
});
// The selector's first auto-fill is scheduled for the next frame; let it run.
await waitFor(() =>
expect(
useDashboardStore.getState().variableValues[
useDashboardStore.getState().dashboardId
]?.ops?.value,
).toStrictEqual(seeded),
);
await new Promise((resolve) => {
requestAnimationFrame(resolve);
});
expect(
useDashboardStore.getState().variableValues[
useDashboardStore.getState().dashboardId
]?.ops?.value,
).toStrictEqual(seeded);
});
});

View File

@@ -7,6 +7,7 @@ import { UpdateTimeInterval } from 'store/actions';
import { act, render, screen } from 'tests/test-utils';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { resolveControls } from '../controls/dashboardControls';
import DashboardContainer from '../index';
jest.mock('store/actions', () => ({
@@ -21,7 +22,11 @@ const mockSelectorMount = jest.fn() as jest.MockedFunction<
const mockPanelMount = jest.fn() as jest.MockedFunction<
(search: string) => void
>;
const mockStore = { resetVariableFetch: jest.fn(), setEditContext: jest.fn() };
const mockStore = {
resetVariableFetch: jest.fn(),
setEditContext: jest.fn(),
controls: resolveControls(undefined, false),
};
jest.mock('../store/useDashboardStore', () => ({
useDashboardStore: (selector: (state: typeof mockStore) => unknown): unknown =>
selector(mockStore),
@@ -68,6 +73,13 @@ jest.mock('../components/LockedIndicator/LockedIndicator', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock(
'../components/DashboardSettingsDrawer/DashboardSettingsDrawer',
() => ({
__esModule: true,
default: (): null => null,
}),
);
jest.mock(
'../components/DashboardChangedDialog/DashboardChangedDialog',
() => ({ __esModule: true, default: (): null => null }),

View File

@@ -1,6 +1,7 @@
import { memo } from 'react';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
import DashboardPageBreadcrumbs from './DashboardPageBreadcrumbs';
import { useShareVariablesOption } from './useShareVariablesOption';
@@ -16,13 +17,16 @@ function DashboardPageHeader({
image,
}: DashboardPageHeaderProps): JSX.Element {
const shareVariablesOption = useShareVariablesOption();
const headerControls = useDashboardControlGroup('header');
return (
<div className={styles.dashboardPageHeader}>
<DashboardPageBreadcrumbs title={title} image={image} />
{headerControls.breadcrumbs && (
<DashboardPageBreadcrumbs title={title} image={image} />
)}
<HeaderRightSection
enableAnnouncements={false}
enableShare
enableFeedback
enableShare={headerControls.share}
enableFeedback={headerControls.feedback}
shareModalExtraOption={shareVariablesOption}
/>
</div>

View File

@@ -0,0 +1,33 @@
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import DashboardSettings from '../../DashboardSettings';
import SettingsDrawer from '../../DashboardPageToolbar/SettingsDrawer';
import { useDashboardStore } from '../../store/useDashboardStore';
interface DashboardSettingsDrawerProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
}
/**
* Opens on any `requestSettings` in the tree. Mounted by the container, so it
* works whichever controls a host hides.
*/
function DashboardSettingsDrawer({
dashboard,
}: DashboardSettingsDrawerProps): JSX.Element {
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
return (
<SettingsDrawer
drawerTitle="Dashboard Configuration"
isOpen={!!settingsRequest}
destroyOnClose
onClose={clearSettingsRequest}
>
<DashboardSettings dashboard={dashboard} />
</SettingsDrawer>
);
}
export default DashboardSettingsDrawer;

View File

@@ -0,0 +1,57 @@
import {
WRITING_CONTROLS,
DEFAULT_CONTROLS,
isControlVisible,
resolveControls,
} from '../dashboardControls';
import type { DashboardControlId } from '../types';
const ALL_IDS = Object.keys(WRITING_CONTROLS) as DashboardControlId[];
describe('resolveControls', () => {
it('shows every control when the host passes nothing', () => {
expect(resolveControls(undefined, false)).toStrictEqual(DEFAULT_CONTROLS);
});
it('hides a whole group from one boolean', () => {
const controls = resolveControls({ header: false }, false);
expect(controls.header).toStrictEqual({
breadcrumbs: false,
share: false,
feedback: false,
});
expect(controls.title.name).toBe(true);
});
it('hides single items and keeps the rest of the group', () => {
const controls = resolveControls(
{ panelActions: { createAlert: false } },
false,
);
expect(controls.panelActions.createAlert).toBe(false);
expect(controls.panelActions.download).toBe(true);
});
it('hides every writing control on a read-only mount, whatever the host asked', () => {
const controls = resolveControls(
{ dashboardActions: true, panelActions: { edit: true } },
true,
);
ALL_IDS.forEach((id) => {
expect([id, isControlVisible(controls, id)]).toStrictEqual([
id,
!WRITING_CONTROLS[id],
]);
});
});
it('still lets the host hide non-writing controls on a read-only mount', () => {
const controls = resolveControls({ panelActions: { download: false } }, true);
expect(controls.panelActions.download).toBe(false);
expect(controls.panelActions.view).toBe(true);
});
});

View File

@@ -0,0 +1,48 @@
import { resolveControls } from '../dashboardControls';
import { CHARTS_ONLY, EMBEDDED, withControls } from '../presets';
describe('withControls', () => {
it('adds an override group the preset leaves alone', () => {
expect(
withControls(EMBEDDED, { toolbar: { autoRefresh: false } }),
).toStrictEqual({
header: false,
title: false,
dashboardActions: false,
toolbar: { autoRefresh: false },
});
});
it('turns single items back on inside a group the preset hides', () => {
const merged = withControls(CHARTS_ONLY, { panelActions: { view: true } });
const controls = resolveControls(merged, false);
expect(controls.panelActions.view).toBe(true);
expect(controls.panelActions.download).toBe(false);
expect(controls.panelActions.drilldown).toBe(false);
});
it('lets a later whole-group boolean replace earlier items', () => {
expect(
withControls(
{ panelActions: { createAlert: false } },
{ panelActions: true },
),
).toStrictEqual({ panelActions: true });
});
it('lets later items win over earlier ones', () => {
expect(
withControls(
{ toolbar: { timeRange: false, autoRefresh: false } },
{ toolbar: { timeRange: true } },
),
).toStrictEqual({ toolbar: { timeRange: true, autoRefresh: false } });
});
it('cannot turn a writing control back on for a read-only mount', () => {
const merged = withControls(EMBEDDED, { dashboardActions: { delete: true } });
expect(resolveControls(merged, true).dashboardActions.delete).toBe(false);
});
});

View File

@@ -0,0 +1,136 @@
import type {
DashboardControlGroup,
DashboardControlId,
DashboardControls,
DashboardControlsInput,
} from './types';
export const DEFAULT_CONTROLS: DashboardControls = {
header: { breadcrumbs: true, share: true, feedback: true },
title: {
name: true,
description: true,
tags: true,
lock: true,
publicBadge: true,
},
toolbar: {
timeRange: true,
autoRefresh: true,
variables: true,
addVariable: true,
},
dashboardActions: {
fullscreen: true,
rename: true,
clone: true,
lock: true,
newSection: true,
delete: true,
configure: true,
json: true,
newPanel: true,
},
sectionActions: { addPanel: true, rename: true, clone: true, delete: true },
panelActions: {
view: true,
edit: true,
clone: true,
download: true,
createAlert: true,
move: true,
delete: true,
drilldown: true,
zoom: true,
},
viewModal: { switchToEdit: true },
};
/**
* Whether each control writes to the dashboard. A read-only mount hides every
* `true` here regardless of what the host asked for. Exhaustive, so a new
* control can't ship without deciding.
*/
export const WRITING_CONTROLS: Record<DashboardControlId, boolean> = {
'header.breadcrumbs': false,
'header.share': false,
'header.feedback': false,
'title.name': false,
'title.description': false,
'title.tags': false,
'title.lock': true,
'title.publicBadge': false,
'toolbar.timeRange': false,
'toolbar.autoRefresh': false,
'toolbar.variables': false,
'toolbar.addVariable': true,
'dashboardActions.fullscreen': false,
'dashboardActions.rename': true,
'dashboardActions.clone': true,
'dashboardActions.lock': true,
'dashboardActions.newSection': true,
'dashboardActions.delete': true,
'dashboardActions.configure': true,
// Opens read-only on a non-editable mount.
'dashboardActions.json': false,
'dashboardActions.newPanel': true,
'sectionActions.addPanel': true,
'sectionActions.rename': true,
'sectionActions.clone': true,
'sectionActions.delete': true,
'panelActions.view': false,
'panelActions.edit': true,
'panelActions.clone': true,
'panelActions.download': false,
'panelActions.createAlert': false,
'panelActions.move': true,
'panelActions.delete': true,
'panelActions.drilldown': false,
'panelActions.zoom': false,
'viewModal.switchToEdit': true,
};
function resolveGroup<G extends DashboardControlGroup>(
group: G,
input: DashboardControlsInput | undefined,
readOnly: boolean,
): DashboardControls[G] {
const defaults: Record<string, boolean> = DEFAULT_CONTROLS[group];
const override = input?.[group] as
| boolean
| Partial<Record<string, boolean>>
| undefined;
const items = Object.keys(defaults).map((item): [string, boolean] => {
const requested =
typeof override === 'boolean'
? override
: (override?.[item] ?? defaults[item]);
const writes = WRITING_CONTROLS[`${group}.${item}` as DashboardControlId];
return [item, requested && !(readOnly && writes)];
});
return Object.fromEntries(items) as DashboardControls[G];
}
/** Host input over the defaults, then every writing control off when read-only. */
export function resolveControls(
input: DashboardControlsInput | undefined,
readOnly: boolean,
): DashboardControls {
return {
header: resolveGroup('header', input, readOnly),
title: resolveGroup('title', input, readOnly),
toolbar: resolveGroup('toolbar', input, readOnly),
dashboardActions: resolveGroup('dashboardActions', input, readOnly),
sectionActions: resolveGroup('sectionActions', input, readOnly),
panelActions: resolveGroup('panelActions', input, readOnly),
viewModal: resolveGroup('viewModal', input, readOnly),
};
}
export function isControlVisible(
controls: DashboardControls,
id: DashboardControlId,
): boolean {
const [group, item] = id.split('.') as [DashboardControlGroup, string];
return (controls[group] as Record<string, boolean>)[item];
}

View File

@@ -0,0 +1,74 @@
import { DEFAULT_CONTROLS } from './dashboardControls';
import type {
DashboardControlGroup,
DashboardControls,
DashboardControlsInput,
} from './types';
/**
* The host page owns the header, the title row and the dashboard-level actions.
* Layout presets only: `readOnly` stays a separate switch, so no preset can turn
* a writing control back on.
*/
export const EMBEDDED: DashboardControlsInput = {
header: false,
title: false,
dashboardActions: false,
};
/** Embedded, and panels are just charts: no panel menu, no drilldown. Charts still zoom. */
export const CHARTS_ONLY: DashboardControlsInput = {
...EMBEDDED,
panelActions: {
view: false,
edit: false,
clone: false,
download: false,
createAlert: false,
move: false,
delete: false,
drilldown: false,
},
};
type GroupInput<G extends DashboardControlGroup> =
| boolean
| Partial<DashboardControls[G]>;
function mergeGroup<G extends DashboardControlGroup>(
group: G,
base: GroupInput<G> | undefined,
next: GroupInput<G> | undefined,
): GroupInput<G> | undefined {
if (next === undefined) {
return base;
}
if (typeof next === 'boolean' || base === undefined) {
return next;
}
// A whole-group boolean underneath expands to its items before the override.
const expanded: Partial<DashboardControls[G]> =
typeof base === 'boolean'
? (Object.fromEntries(
Object.keys(DEFAULT_CONTROLS[group]).map((item) => [item, base]),
) as Partial<DashboardControls[G]>)
: base;
return { ...expanded, ...next };
}
/** Merges presets and overrides; later inputs win, item by item. */
export function withControls(
...inputs: DashboardControlsInput[]
): DashboardControlsInput {
const groups = Object.keys(DEFAULT_CONTROLS) as DashboardControlGroup[];
return inputs.reduce<DashboardControlsInput>((merged, input) => {
const result: DashboardControlsInput = { ...merged };
groups.forEach((group) => {
const value = mergeGroup(group, merged[group], input[group]);
if (value !== undefined) {
(result as Record<string, unknown>)[group] = value;
}
});
return result;
}, {});
}

View File

@@ -0,0 +1,53 @@
import type { PanelActionId } from '../PanelsAndSectionsLayout/Panel/PanelActionsMenu/panelActionMeta';
/** Every control a host can show or hide, grouped by where it renders. */
export interface DashboardControls {
header: { breadcrumbs: boolean; share: boolean; feedback: boolean };
title: {
name: boolean;
description: boolean;
tags: boolean;
lock: boolean;
publicBadge: boolean;
};
toolbar: {
timeRange: boolean;
autoRefresh: boolean;
variables: boolean;
addVariable: boolean;
};
dashboardActions: {
fullscreen: boolean;
rename: boolean;
clone: boolean;
lock: boolean;
newSection: boolean;
delete: boolean;
configure: boolean;
json: boolean;
newPanel: boolean;
};
sectionActions: {
addPanel: boolean;
rename: boolean;
clone: boolean;
delete: boolean;
};
// Keyed by the panel menu's own ids, so a new panel action needs a control.
// `drilldown` (click) and `zoom` (drag-select a time range) act on the chart itself.
panelActions: Record<PanelActionId | 'drilldown' | 'zoom', boolean>;
viewModal: { switchToEdit: boolean };
}
export type DashboardControlGroup = keyof DashboardControls;
export type DashboardControlId = {
[
G in DashboardControlGroup
]: `${G}.${Extract<keyof DashboardControls[G], string>}`;
}[DashboardControlGroup];
/** A whole group as one boolean, or single items; omitted means shown. */
export type DashboardControlsInput = {
[G in DashboardControlGroup]?: boolean | Partial<DashboardControls[G]>;
};

View File

@@ -0,0 +1,12 @@
import { useDashboardStore } from '../store/useDashboardStore';
import { isControlVisible } from './dashboardControls';
import type { DashboardControlId } from './types';
/**
* Whether a control renders on this mount: the host's `controls`, with every
* writing control off when read-only. Lock and permission state stay with
* `useDashboardEditContext`, which decides disabled + reason.
*/
export function useDashboardControl(id: DashboardControlId): boolean {
return useDashboardStore((s) => isControlVisible(s.controls, id));
}

View File

@@ -0,0 +1,9 @@
import { useDashboardStore } from '../store/useDashboardStore';
import type { DashboardControlGroup, DashboardControls } from './types';
/** Every control in a group, resolved for this mount (see `useDashboardControl`). */
export function useDashboardControlGroup<G extends DashboardControlGroup>(
group: G,
): DashboardControls[G] {
return useDashboardStore((s) => s.controls[group]);
}

View File

@@ -11,6 +11,7 @@ import {
buildDashboardUpdatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useDashboardEditContext } from '../useDashboardEditContext';
const DASHBOARD_ID = 'dash-1';
@@ -44,6 +45,23 @@ describe('useDashboardEditContext - AuthZ', () => {
afterEach(() => {
jest.restoreAllMocks();
server.resetHandlers();
useDashboardStore.setState({ readOnly: false });
});
// A host-forced view-only mount outranks every grant.
it('is read-only on a read-only mount despite full permissions', async () => {
server.use(setupAuthzAdmin());
useDashboardStore.setState({ readOnly: true });
const { result } = renderGuard();
await waitFor(() =>
expect(result.current.editDisabledTooltip).toBe('dashboard_read_only_here'),
);
expect(result.current.isEditable).toBe(false);
expect(result.current.canEditDashboard).toBe(false);
expect(result.current.canDeleteDashboard).toBe(false);
expect(result.current.deleteDisabledTooltip).toBe('dashboard_read_only_here');
});
describe('permission granted', () => {

View File

@@ -1,57 +1,115 @@
import { renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { renderHook } from 'tests/test-utils';
import {
type DashboardtypesGettableDashboardV2DTO,
type DashboardtypesVariableDTO,
DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesTextVariableSpecDTOKind as TextVariableKind,
} from 'api/generated/services/sigNoz.schemas';
import type { DashboardQuerySource } from '../../store/slices/editContextSlice';
import { useDashboardFetchRequired } from '../useDashboardFetchRequired';
const mockUseGetDashboardV2 = jest.fn();
const QUERY_KEY = ['/api/v2/dashboards/dash-1'];
const mockRefetch = jest.fn();
let mockSource: DashboardQuerySource | null;
jest.mock(
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
() => ({
useDashboardStore: (
selector: (s: { dashboardId: string }) => unknown,
): unknown => selector({ dashboardId: 'dash-1' }),
selector: (s: {
dashboardId: string;
dashboardQuerySource: DashboardQuerySource | null;
refetch: () => void;
}) => unknown,
): unknown =>
selector({
dashboardId: 'dash-1',
dashboardQuerySource: mockSource,
refetch: mockRefetch,
}),
}),
);
jest.mock('api/generated/services/dashboard', () => ({
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
}));
function textVariable(name: string): DashboardtypesVariableDTO {
return {
kind: TextVariableKind.TextVariable,
spec: { name, display: { name }, value: '' },
};
}
function dashboardWith(
spec: Partial<DashboardtypesGettableDashboardV2DTO['spec']>,
): DashboardtypesGettableDashboardV2DTO {
return { id: 'dash-1', spec } as DashboardtypesGettableDashboardV2DTO;
}
function renderWithCache(
cached?: unknown,
): ReturnType<
typeof renderHook<ReturnType<typeof useDashboardFetchRequired>, void>
> {
const queryClient = new QueryClient();
if (cached !== undefined) {
queryClient.setQueryData(mockSource?.queryKey ?? QUERY_KEY, cached);
}
return renderHook(() => useDashboardFetchRequired(), {
wrapper: ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});
}
describe('useDashboardFetchRequired', () => {
it('returns the loaded dashboard and its variables', () => {
const dashboard = {
spec: { variables: [{ name: 'region' }, { name: 'tier' }] },
};
mockUseGetDashboardV2.mockReturnValue({ data: { data: dashboard } });
beforeEach(() => {
mockSource = null;
});
const { result } = renderHook(() => useDashboardFetchRequired());
it('reads the dashboards API entry when the host sets no source', () => {
const variables = [textVariable('region'), textVariable('tier')];
const dashboard = dashboardWith({ variables });
const { result } = renderWithCache({ data: dashboard, status: 'success' });
expect(result.current.dashboard).toBe(dashboard);
expect(result.current.variables).toStrictEqual([
{ name: 'region' },
{ name: 'tier' },
]);
expect(result.current.variables).toBe(variables);
expect(result.current.refetch).toBe(mockRefetch);
});
it("reads a host's own cache entry through its select", () => {
const systemDashboard = { name: 'ai-o11y-overview', spec: {} };
mockSource = {
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
select: (response: { data: typeof systemDashboard }) =>
({
...response.data,
id: 'system-id',
}) as DashboardtypesGettableDashboardV2DTO,
};
const { result } = renderWithCache({ data: systemDashboard });
expect(result.current.dashboard).toStrictEqual({
name: 'ai-o11y-overview',
spec: {},
id: 'system-id',
});
});
it('normalizes variables to an empty array when the spec has none', () => {
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
const { result } = renderHook(() => useDashboardFetchRequired());
const { result } = renderWithCache({ data: dashboardWith({}) });
expect(result.current.variables).toStrictEqual([]);
});
it('throws when used outside a loaded dashboard subtree', () => {
mockUseGetDashboardV2.mockReturnValue({ data: undefined });
it('throws when the source entry is empty', () => {
// Suppress React's expected render-error logging for this case.
const consoleError = jest
.spyOn(console, 'error')
.mockImplementation(() => undefined);
expect(() => renderHook(() => useDashboardFetchRequired())).toThrow(
/outside a loaded dashboard subtree/,
);
expect(() => renderWithCache()).toThrow(/outside a loaded dashboard subtree/);
consoleError.mockRestore();
});

View File

@@ -111,3 +111,32 @@ describe('useGetQueryRangeV5 enabled gating', () => {
expect(mockQueryRangeV5).toHaveBeenCalledTimes(2);
});
});
describe('useGetQueryRangeV5 host fetch', () => {
it('fetches through the host fetch instead of query_range', async () => {
mockQueryRangeV5.mockReset();
const runQueryRange = jest
.fn()
.mockResolvedValue({ status: 'success', data: {} } as QueryRangeV5200);
const wrapper = ({ children }: PropsWithChildren): JSX.Element => (
<QueryClientProvider client={new QueryClient()}>
{children}
</QueryClientProvider>
);
renderHook(
() =>
useGetQueryRangeV5({
requestPayload: REQUEST,
queryKey: KEY_A,
enabled: true,
runQueryRange,
}),
{ wrapper },
);
await waitFor(() => expect(runQueryRange).toHaveBeenCalledTimes(1));
expect(runQueryRange.mock.calls[0][0]).toBe(REQUEST);
expect(mockQueryRangeV5).not.toHaveBeenCalled();
});
});

View File

@@ -19,10 +19,12 @@ jest.mock('api/generated/services/dashboard', () => ({
getGetDashboardV2QueryKey: jest.fn(() => ['/api/v2/dashboards/dash-1']),
}));
let mockReadOnly = false;
jest.mock('../../store/useDashboardStore', () => ({
useDashboardStore: jest.fn(
(selector: (s: { dashboardId: string; isEditable: boolean }) => unknown) =>
selector({ dashboardId: 'dash-1', isEditable: true }),
(selector: (s: { dashboardId: string; readOnly: boolean }) => unknown) =>
selector({ dashboardId: 'dash-1', readOnly: mockReadOnly }),
),
}));
@@ -35,6 +37,7 @@ const queryClient = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let captured: { fn: (ops: any) => unknown; options: any };
let mockMutateAsync: jest.Mock;
function dashboardEnvelope(name: string): GetDashboardV2200 {
return {
@@ -50,10 +53,12 @@ const replaceNameOp = {
beforeEach(() => {
jest.clearAllMocks();
mockReadOnly = false;
mockMutateAsync = jest.fn().mockResolvedValue(undefined);
(useQueryClient as jest.Mock).mockReturnValue(queryClient);
(useMutation as jest.Mock).mockImplementation((fn, options) => {
captured = { fn, options };
return { mutateAsync: jest.fn(), isLoading: false };
return { mutateAsync: mockMutateAsync, isLoading: false };
});
renderHook(() => useOptimisticPatch());
});
@@ -119,4 +124,22 @@ describe('useOptimisticPatch', () => {
// No follow-up GET (that could read stale data and flicker the UI back).
expect(queryClient.invalidateQueries).not.toHaveBeenCalled();
});
it('patchAsync rejects without sending on a read-only mount', async () => {
mockReadOnly = true;
const { result } = renderHook(() => useOptimisticPatch());
await expect(result.current.patchAsync([replaceNameOp])).rejects.toThrow(
'dashboard_read_only_here',
);
expect(mockMutateAsync).not.toHaveBeenCalled();
});
it('patchAsync sends the ops when the mount is editable', async () => {
const { result } = renderHook(() => useOptimisticPatch());
await result.current.patchAsync([replaceNameOp]);
expect(mockMutateAsync).toHaveBeenCalledWith([replaceNameOp]);
});
});

View File

@@ -11,6 +11,7 @@ import {
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
} from 'constants/queryCacheTime';
import { useDashboardStore } from '../../store/useDashboardStore';
import { usePanelQuery } from '../usePanelQuery';
import { useGetQueryRangeV5 } from '../useGetQueryRangeV5';
@@ -598,4 +599,58 @@ describe('usePanelQuery', () => {
expect(cacheTime).toBe(DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED);
});
});
describe('with a host query runner', () => {
const runner = {
key: 'public:abc',
run: jest.fn().mockResolvedValue({ status: 'success', data: {} }),
};
beforeEach(() => {
useDashboardStore.getState().setEditContext({
dashboardId: 'd1',
refetch: jest.fn(),
queryRunner: runner,
});
});
afterEach(() => {
useDashboardStore
.getState()
.setEditContext({ dashboardId: '', refetch: jest.fn() });
});
it('keys the cache by the runner and runs the query through it with the panel id', async () => {
renderHook(() =>
usePanelQuery({
panel: builderPanel(),
panelId: 'p1',
queryCapabilities: TIME_SERIES_CAPABILITIES,
}),
);
const [{ queryKey, runQueryRange, requestPayload }] =
mockUseGetQueryRangeV5.mock.calls[0];
expect(queryKey).toContain('public:abc');
await runQueryRange(requestPayload);
expect(runner.run).toHaveBeenCalledWith({
panelId: 'p1',
requestPayload,
signal: undefined,
});
});
});
it('runs on query_range when no host runner is set', () => {
renderHook(() =>
usePanelQuery({
panel: builderPanel(),
panelId: 'p1',
queryCapabilities: TIME_SERIES_CAPABILITIES,
}),
);
const [{ runQueryRange }] = mockUseGetQueryRangeV5.mock.calls[0];
expect(runQueryRange).toBeUndefined();
});
});

View File

@@ -17,6 +17,7 @@ import { useDashboardFetchRequired } from './useDashboardFetchRequired';
*/
export function useDashboardEditContext(): DashboardEditContext {
const { dashboard } = useDashboardFetchRequired();
const readOnly = useDashboardStore((s) => s.readOnly);
const {
canRead,
canEdit,
@@ -24,12 +25,8 @@ export function useDashboardEditContext(): DashboardEditContext {
editChecks,
deletePermission,
areOtherPermissionsLoading,
} = useDashboardPermissions(dashboard.id);
} = useDashboardPermissions(dashboard.id, { enabled: !readOnly });
const { t } = useTranslation('dashboard');
const readOnlyOverride = useDashboardStore(
(s) => s.canEditDashboardOverride === false,
);
const deleteChecks = useMemo(() => [deletePermission], [deletePermission]);
return deriveEditContext({
@@ -44,6 +41,6 @@ export function useDashboardEditContext(): DashboardEditContext {
locked: t('dashboard_locked'),
readOnly: t('dashboard_read_only_here'),
},
readOnlyOverride,
readOnlyOverride: readOnly,
});
}

View File

@@ -1,34 +1,52 @@
import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { getGetDashboardV2QueryKey } from 'api/generated/services/dashboard';
import type {
DashboardtypesGettableDashboardV2DTO,
DashboardtypesVariableDTO,
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
import { useDashboardStore } from 'pages/DashboardPage/DashboardContainer/store/useDashboardStore';
import { useDashboardFetch } from './useDashboardFetch';
import type { UseDashboardFetchResult } from './useDashboardFetch';
export interface UseDashboardFetchRequiredResult {
/** Guaranteed present — the hook throws otherwise. */
dashboard: DashboardtypesGettableDashboardV2DTO;
/** Always an array, so callers skip `?? []` guards. */
variables: DashboardtypesVariableDTO[];
refetch: UseDashboardFetchResult['refetch'];
refetch: () => void;
}
const selectDashboardV2 = (
response: GetDashboardV2200,
): DashboardtypesGettableDashboardV2DTO => response.data;
/**
* Dashboard accessor for components rendered inside a loaded dashboard subtree. The
* root pages own the fetch and gate on a resolved dashboard before mounting their
* subtree, so this reuses the shared react-query cache entry and throws if the
* dashboard is missing — turning a silent `undefined` into a loud programmer error. It
* also derives spec collections (`variables`) since the dashboard is guaranteed here.
* root owns the fetch and publishes where it cached the dashboard
* (`dashboardQuerySource`); this observes that entry without fetching, and throws if
* it's empty — turning a silent `undefined` into a loud programmer error. It also
* derives spec collections (`variables`) since the dashboard is guaranteed here.
*
* Prefer this over `useDashboardFetch` outside the two root pages; the
* `signoz/no-dashboard-fetch-outside-root` lint rule enforces the split.
*/
export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
const dashboardId = useDashboardStore((s) => s.dashboardId);
const { dashboard, refetch } = useDashboardFetch(dashboardId);
const source = useDashboardStore((s) => s.dashboardQuerySource);
const queryKey =
source?.queryKey ?? getGetDashboardV2QueryKey({ id: dashboardId });
const select = source?.select ?? selectDashboardV2;
const refetch = useDashboardStore((s) => s.refetch);
// Observe only: the root owns the request, so this never fetches.
const { data: dashboard } = useQuery<
never,
unknown,
DashboardtypesGettableDashboardV2DTO | undefined
>({
queryKey,
select,
enabled: false,
});
const variables = useMemo(
() => dashboard?.spec?.variables ?? [],
@@ -39,7 +57,7 @@ export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
throw new Error(
'useDashboardFetchRequired was used outside a loaded dashboard subtree — the ' +
'dashboard is undefined. Only call it below a root page that gates rendering ' +
'on useDashboardFetch (DashboardPage / PanelEditorPage).',
'on its fetch and seeds the edit context (DashboardContainer / PanelEditorPage).',
);
}

View File

@@ -21,7 +21,9 @@ interface UseDashboardStaleCheck {
export function useDashboardStaleCheck(
dashboard: DashboardtypesGettableDashboardV2DTO,
refetch: () => void,
options?: { enabled?: boolean },
): UseDashboardStaleCheck {
const enabled = options?.enabled ?? true;
const {
id: dashboardId,
updatedAt: loadedUpdatedAt,
@@ -34,7 +36,7 @@ export function useDashboardStaleCheck(
const [dismissedAt, setDismissedAt] = useState<string | null>(null);
useEffect(() => {
if (!dashboardId) {
if (!dashboardId || !enabled) {
return undefined;
}
const probe = async (): Promise<void> => {
@@ -56,7 +58,7 @@ export function useDashboardStaleCheck(
document.removeEventListener('visibilitychange', probe);
window.removeEventListener('focus', probe);
};
}, [dashboardId]);
}, [dashboardId, enabled]);
const serverUpdatedAt = server?.updatedAt;

View File

@@ -15,6 +15,11 @@ export interface UseGetQueryRangeV5Args {
keepPreviousData?: boolean;
/** Unused-entry TTL; callers drop to 0 under auto-refresh to bound cache growth (V1 parity). */
cacheTime?: number;
/** Replaces the `query_range` call; the caller keys the cache for it. */
runQueryRange?: (
requestPayload: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
) => Promise<QueryRangeV5200>;
}
/**
@@ -49,6 +54,7 @@ export function useGetQueryRangeV5({
enabled,
keepPreviousData,
cacheTime,
runQueryRange,
}: UseGetQueryRangeV5Args): UseQueryResult<QueryRangeV5200, Error> {
const queryClient = useQueryClient();
// An errored key has no data, so it is always stale; keep it enabled so
@@ -57,7 +63,8 @@ export function useGetQueryRangeV5({
return useQuery<QueryRangeV5200, Error>({
queryKey,
queryFn: ({ signal }) => queryRangeV5(requestPayload, signal),
queryFn: ({ signal }) =>
(runQueryRange ?? queryRangeV5)(requestPayload, signal),
enabled: enabled || hasErrored,
retry: retryUnlessClientError,
keepPreviousData,

View File

@@ -39,6 +39,7 @@ export function useOptimisticPatch(
const storeDashboardId = useDashboardStore((s) => s.dashboardId);
const dashboardId = dashboardIdOverride ?? storeDashboardId;
const { t } = useTranslation('dashboard');
const readOnly = useDashboardStore((s) => s.readOnly);
const queryClient = useQueryClient();
const queryKey = getGetDashboardV2QueryKey({ id: dashboardId });
@@ -78,6 +79,10 @@ export function useOptimisticPatch(
const { mutateAsync } = mutation;
const patchAsync = useCallback(
(ops: DashboardtypesJSONPatchOperationDTO[]): Promise<unknown> => {
// The UI renders no edit affordance on a read-only mount, so reaching here is a bug.
if (readOnly) {
return Promise.reject(new Error(t('dashboard_read_only_here')));
}
// Defense-in-depth against a lock, read straight from the cache this hook
// already owns. Permission is enforced by the UI and, definitively, by the
// backend — checking it here would drag authz into every mutation.
@@ -87,7 +92,7 @@ export function useOptimisticPatch(
}
return mutateAsync(ops);
},
[queryClient, queryKey, mutateAsync],
[readOnly, queryClient, queryKey, mutateAsync, t],
);
return {

View File

@@ -2,7 +2,11 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports -- TODO: migrate global time selector off redux
import { useSelector } from 'react-redux';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import type {
DashboardtypesPanelDTO,
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import {
DASHBOARD_CACHE_TIME,
DASHBOARD_CACHE_TIME_ON_REFRESH_ENABLED,
@@ -126,6 +130,7 @@ export function usePanelQuery({
// use it (V1 parity). Names come from the fetch context (all variables, even
// unresolved ones); null before the variable bar initializes it.
const dashboardId = useDashboardStore((s) => s.dashboardId);
const queryRunner = useDashboardStore((s) => s.queryRunner);
const variables = useDashboardStore(selectResolvedVariables(dashboardId));
const fetchContext = useDashboardStore((s) => s.variableFetchContext);
@@ -233,6 +238,7 @@ export function usePanelQuery({
// Only the variables this panel references re-key the cache, so an unrelated
// variable change doesn't refetch it.
scopedVariables,
queryRunner?.key ?? null,
],
[
panelId,
@@ -249,10 +255,24 @@ export function usePanelQuery({
offset,
pageSize,
scopedVariables,
queryRunner?.key,
],
);
const runQueryRange = useMemo(
() =>
queryRunner
? (
payload: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
): Promise<QueryRangeV5200> =>
queryRunner.run({ panelId, requestPayload: payload, signal })
: undefined,
[queryRunner, panelId],
);
const response = useGetQueryRangeV5({
runQueryRange,
requestPayload,
queryKey,
enabled: enabled && runnable && !isWaitingOnVariable,

View File

@@ -9,10 +9,17 @@ import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';
import { useResolvedVariables } from './hooks/useResolvedVariables';
import { useSyncVariablesForSuggestions } from './hooks/useSyncVariablesForSuggestions';
import { useDashboardStore } from './store/useDashboardStore';
import type {
DashboardQuerySource,
QueryRunner,
} from './store/slices/editContextSlice';
import type { DashboardControlsInput } from './controls/types';
import { useDashboardControlGroup } from './controls/useDashboardControlGroup';
import styles from './DashboardContainer.module.scss';
import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageHeader';
import LockedIndicator from './components/LockedIndicator/LockedIndicator';
import DashboardChangedDialog from './components/DashboardChangedDialog/DashboardChangedDialog';
import DashboardSettingsDrawer from './components/DashboardSettingsDrawer/DashboardSettingsDrawer';
import { useDashboardStaleCheck } from './hooks/useDashboardStaleCheck';
import { useDashboardDefaultTime } from './hooks/useDashboardDefaultTime';
import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';
@@ -20,20 +27,23 @@ import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/da
interface DashboardContainerProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
refetch: () => void;
/**
* @deprecated
* `canEditDashboardOverride` is a temporary solution to allow the dashboard to be view only.
* This is only used for LLM Observability.
* It will be removed in the future.
* TODO: @Ashwin / @Abhi — remove when the final solution is implemented.
*/
canEditDashboardOverride?: boolean;
/** Where the host cached `dashboard`; defaults to the dashboards API entry. */
source?: DashboardQuerySource;
/** View-only mount: no edit affordance, no write, no server freshness probe. */
readOnly?: boolean;
/** What renders; omitted controls are shown. Writing controls are off when read-only. */
controls?: DashboardControlsInput;
/** Runs panel queries; omitted runs them on `query_range`. */
queryRunner?: QueryRunner;
}
function DashboardContainer({
dashboard,
refetch,
canEditDashboardOverride,
source,
readOnly = false,
controls,
queryRunner,
}: DashboardContainerProps): JSX.Element | null {
const spec = dashboard.spec;
const isTimeInitialized = useDashboardDefaultTime(dashboard.id, spec.duration);
@@ -57,7 +67,10 @@ function DashboardContainer({
setEditContext({
dashboardId: dashboard.id,
refetch,
canEditDashboardOverride,
source,
readOnly,
controls,
queryRunner,
});
// Resolve the variable selection into the V5 query payload and publish it to
@@ -68,7 +81,12 @@ function DashboardContainer({
// suggests them ($variable) in the panel editor and dashboards-page builder.
useSyncVariablesForSuggestions(dashboard);
const staleCheck = useDashboardStaleCheck(dashboard, refetch);
const staleCheck = useDashboardStaleCheck(dashboard, refetch, {
enabled: !readOnly,
});
const showHeader = Object.values(useDashboardControlGroup('header')).some(
Boolean,
);
if (!isTimeInitialized) {
return null;
@@ -84,12 +102,13 @@ function DashboardContainer({
<AutoRefreshTicker />
) : (
<>
<DashboardPageHeader title={name} image={image} />
{showHeader && <DashboardPageHeader title={name} image={image} />}
<DashboardPageToolbar dashboard={dashboard} handle={fullScreenHandle} />
</>
)}
<PanelsAndSectionsLayout layouts={spec.layouts} panels={spec.panels} />
{!!dashboard.locked && <LockedIndicator />}
{!!dashboard.locked && !readOnly && <LockedIndicator />}
{!readOnly && <DashboardSettingsDrawer dashboard={dashboard} />}
<DashboardChangedDialog
open={staleCheck.showPrompt}
onReload={staleCheck.reload}

View File

@@ -0,0 +1,119 @@
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
import { useDashboardStore } from '../../useDashboardStore';
import type { DashboardQuerySource } from '../editContextSlice';
const refetch = (): void => undefined;
const systemSource: DashboardQuerySource = {
queryKey: ['/api/v2/dashboards/system/ai-o11y-overview'],
select: (response: { data: DashboardtypesGettableDashboardV2DTO }) =>
response.data,
};
function store(): ReturnType<typeof useDashboardStore.getState> {
return useDashboardStore.getState();
}
describe('editContextSlice.setEditContext', () => {
beforeEach(() => {
store().setEditContext({ dashboardId: '', refetch });
});
it('defaults to the dashboards API entry and an editable mount', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(store().dashboardQuerySource).toBeNull();
expect(store().readOnly).toBe(false);
});
it("stores a host's source and read-only flag", () => {
store().setEditContext({
dashboardId: 'system',
refetch,
source: systemSource,
readOnly: true,
});
expect(store().dashboardQuerySource).toBe(systemSource);
expect(store().readOnly).toBe(true);
});
it('clears read-only when the next mount does not ask for it', () => {
store().setEditContext({
dashboardId: 'system',
refetch,
source: systemSource,
readOnly: true,
});
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(store().readOnly).toBe(false);
expect(store().dashboardQuerySource).toBeNull();
});
// Called during render: a set on every call would re-render subscribers in a loop.
it('is a no-op when called again with equal values', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch });
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({ dashboardId: 'dash-1', refetch });
expect(listener).not.toHaveBeenCalled();
unsubscribe();
});
it('is a no-op for an equal inline controls object', () => {
store().setEditContext({
dashboardId: 'dash-1',
refetch,
controls: { header: false },
});
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({
dashboardId: 'dash-1',
refetch,
controls: { header: false },
});
expect(listener).not.toHaveBeenCalled();
expect(store().controls.header.share).toBe(false);
unsubscribe();
});
it('resolves controls against read-only', () => {
store().setEditContext({ dashboardId: 'dash-1', refetch, readOnly: true });
expect(store().controls.panelActions.edit).toBe(false);
expect(store().controls.panelActions.view).toBe(true);
});
it('treats a runner with the same key as unchanged, a new key as a change', () => {
const run = jest.fn();
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:a', run },
});
const listener = jest.fn();
const unsubscribe = useDashboardStore.subscribe(listener);
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:a', run: jest.fn() },
});
expect(listener).not.toHaveBeenCalled();
store().setEditContext({
dashboardId: 'dash-1',
refetch,
queryRunner: { key: 'public:b', run },
});
expect(store().queryRunner?.key).toBe('public:b');
unsubscribe();
});
});

View File

@@ -1,24 +1,65 @@
import { isEqual } from 'lodash-es';
import type { QueryKey } from 'react-query';
import type { StateCreator } from 'zustand';
import type {
DashboardtypesGettableDashboardV2DTO,
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { resolveControls } from '../../controls/dashboardControls';
import type {
DashboardControls,
DashboardControlsInput,
} from '../../controls/types';
import type { DashboardStore } from '../useDashboardStore';
/**
* The one piece of page context the subtree can't derive for itself: which
* dashboard is open, and how to refetch it. Editability is deliberately absent —
* `useDashboardEditContext` derives it from the caches.
* The react-query entry a host loaded the dashboard into, and how to read the
* dashboard out of it. Must be referentially stable (module-level).
*/
export interface DashboardQuerySource {
queryKey: QueryKey;
// `never` accepts any host's response type; the one caller casts at the boundary.
select: (response: never) => DashboardtypesGettableDashboardV2DTO | undefined;
}
/**
* Runs a panel's query, when not via `POST /api/v5/query_range`. `key` joins
* every panel cache key, so results from different runners never mix.
*/
export interface QueryRunner {
key: string;
run: (request: {
panelId: string;
requestPayload: Querybuildertypesv5QueryRangeRequestDTO;
signal?: AbortSignal;
}) => Promise<QueryRangeV5200>;
}
/**
* The page context the subtree can't derive for itself: which dashboard is open,
* where its cached copy lives, how to refetch it, and whether the host forces it
* view-only. Editability is deliberately absent — `useDashboardEditContext`
* derives it from the caches.
*/
export interface EditContextSlice {
dashboardId: string;
/** `null` reads the dashboards API entry for `dashboardId`. */
dashboardQuerySource: DashboardQuerySource | null;
refetch: () => void;
/**
* @deprecated Forces a view-only mount regardless of permissions. Used only by
* LLM Observability; see SigNoz/pulse-pod#283.
*/
canEditDashboardOverride?: boolean;
readOnly: boolean;
/** Resolved: the host's `controls` over the defaults, writing ones off when read-only. */
controls: DashboardControls;
/** `null` runs panel queries on `query_range`. */
queryRunner: QueryRunner | null;
setEditContext: (ctx: {
dashboardId: string;
refetch: () => void;
canEditDashboardOverride?: boolean;
source?: DashboardQuerySource;
readOnly?: boolean;
controls?: DashboardControlsInput;
queryRunner?: QueryRunner;
}) => void;
}
@@ -29,22 +70,37 @@ export const createEditContextSlice: StateCreator<
EditContextSlice
> = (set, get) => ({
dashboardId: '',
dashboardQuerySource: null,
refetch: (): void => undefined,
canEditDashboardOverride: undefined,
readOnly: false,
controls: resolveControls(undefined, false),
queryRunner: null,
// Idempotent (no-op when unchanged) so it's safe to call during render.
setEditContext: (ctx): void => {
const prev = get();
const source = ctx.source ?? null;
const readOnly = ctx.readOnly ?? false;
// Hosts pass `controls` inline, so compare by value, not reference.
const controls = resolveControls(ctx.controls, readOnly);
const queryRunner = ctx.queryRunner ?? null;
if (
prev.dashboardId === ctx.dashboardId &&
prev.refetch === ctx.refetch &&
prev.canEditDashboardOverride === ctx.canEditDashboardOverride
prev.readOnly === readOnly &&
prev.dashboardQuerySource === source &&
isEqual(prev.controls, controls) &&
// The key identifies a runner, so an inline one doesn't re-seed on every render.
prev.queryRunner?.key === queryRunner?.key
) {
return;
}
set({
dashboardId: ctx.dashboardId,
dashboardQuerySource: source,
refetch: ctx.refetch,
canEditDashboardOverride: ctx.canEditDashboardOverride,
readOnly,
controls,
queryRunner,
});
},
});

View File

@@ -3,7 +3,6 @@
* Do not hand-edit: regenerate instead.
*/
import { StatusCodes } from 'http-status-codes';
import ROUTES from 'constants/routes';
import { rest } from 'msw';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
@@ -16,15 +15,12 @@ import {
LLM_MODELS,
LLM_SERVICES,
llmPanelResponse,
llmSystemDashboardResponse,
} from './__story_mockdata__/llmOverview';
const PANELS = 'AI overview · panels';
/**
* The dashboard itself is bundled with the app rather than fetched, so the only
* thing left to answer is the panels, the variables and the share state its
* header reads.
*/
/** The system dashboard definition, its panels and its variables. */
export const llmOverviewMocks = defineStoryMocks({
controls: {
series: countControl('Breakdown series', {
@@ -36,6 +32,10 @@ export const llmOverviewMocks = defineStoryMocks({
}),
},
handlers: (values, response) => [
rest.get(
'http://localhost/api/v2/dashboards/system/ai-o11y-overview',
response.json(() => llmSystemDashboardResponse()),
),
rest.post(
'http://localhost/api/v5/query_range',
response.json(async (req) =>
@@ -58,22 +58,6 @@ export const llmOverviewMocks = defineStoryMocks({
};
}),
),
// The header reads the share state on every load, so it answers even while
// the panels are held in the loading or failed state.
rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>
res(
ctx.status(StatusCodes.NOT_FOUND),
ctx.json({
status: 'error',
error: {
code: 'public_dashboard_not_found',
message: "the AI observability overview isn't public",
url: '',
errors: [],
},
}),
),
),
],
config: () => ({ route: ROUTES.AI_OBSERVABILITY_OVERVIEW }),
});

View File

@@ -11,8 +11,8 @@ type LLMOverviewArgs = PageStoryArgs<typeof llmOverviewMocks>;
const pageStory = storyMocks(llmOverviewMocks, { layout: 'app' });
/**
* The AI observability overview: cost, token and latency panels over
* `query_range`.
* The AI observability overview: the read-only system dashboard, with cost, token
* and latency panels over `query_range`.
*
* Route: `/ai-observability/overview`.
*/
@@ -20,8 +20,7 @@ const meta = {
title: 'Pages/AI Observability/Overview',
component: LLMObservabilityPage,
...pageStory,
// The header's public-dashboard lookup is expected to 404, so every story opts out.
parameters: { ...pageStory.parameters, allowConsoleErrors: true },
parameters: { ...pageStory.parameters },
} satisfies Meta<LLMOverviewArgs>;
export default meta;
@@ -29,7 +28,7 @@ export default meta;
type Story = StoryObj<LLMOverviewArgs>;
/**
* The bundled overview dashboard: spend, tokens, latency and errors across
* The system overview dashboard: spend, tokens, latency and errors across
* every model the workspace calls, scoped by the model, environment and
* service variables above it.
*/

View File

@@ -3,6 +3,13 @@
* Do not hand-edit: regenerate instead.
*/
import {
DashboardtypesSourceDTO,
type DashboardtypesGettableSystemDashboardDTO,
type GetSystemDashboard200,
} from 'api/generated/services/sigNoz.schemas';
// The backend's own definition, so the story renders what the server serves.
import aiOverviewDefinition from '../../../../../../../pkg/modules/dashboard/impldashboard/fs/definitions/ai-o11y-overview.json';
import type {
MetricRangePayloadV5,
QueryRangeRequestV5,
@@ -161,3 +168,19 @@ export const llmPanelResponse = (
},
]);
};
export function llmSystemDashboardResponse(): GetSystemDashboard200 {
const { definition } = aiOverviewDefinition;
return {
status: 'success',
data: {
orgId: 'storybook-org',
locked: true,
source: DashboardtypesSourceDTO.system,
name: definition.name,
schemaVersion: definition.schemaVersion,
tags: [],
spec: definition.spec as DashboardtypesGettableSystemDashboardDTO['spec'],
},
};
}