Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Unify alert metric editing across responsive layouts

rcourtmanbd54435e249f
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index b8a4b49f31..52bb4266f1 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -710,6 +710,27 @@ threshold row keeps the live `guestID-disk-*` alert resource identity for
active-state and intent-policy linkage while persisting through the stable
`guest-disk:*` override identity.
+Numeric threshold editing is owned by
+`frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx`.
+The table and card layouts delegate global defaults and resource overrides to
+that control, so input bounds, empty-input handling and Off/inherit transitions
+cannot diverge by layout. Table rows save when focus leaves the owning row.
+Focus movement between sliders, inputs, toggles and Cancel stays inside that
+edit, so Cancel cannot commit the value before its click runs. Cards retain
+explicit Save. The responsive table owner identifies the active layout.
+Retiring a row during a resize transfers the draft and metric focus instead
+of saving it. Both layouts focus the first supported numeric metric when
+editing starts from the resource action.
+Clearing an override shows the inherited metric state. When that default is
+Off, the badge remains Off and the table slider stays disabled. Enabling
+from that state stages the factory value in one toggle and leaves the group
+default unchanged. Existing Off/inherit serialization remains compatible.
+Table sliders sit above the numeric control so editing does not widen the table
+and hide the resource identity. Backup, snapshot and offline controls keep their
+separate configuration contracts. Global default cells never route backup or
+snapshot into numeric thresholds. Host cards preserve the canonical cluster
+context shown by table rows, so identically named hosts remain distinguishable.
+
A per-metric threshold is off whenever its trigger is `<= 0`. That boundary is
engine truth (`internal/alerts/canonical_metric.go`,
`internal/alerts/config_runtime.go`), not a display convention: `-1` is the
diff --git a/frontend-modern/browser-verification/5d8649d926bdaea1.json b/frontend-modern/browser-verification/5d8649d926bdaea1.json
new file mode 100644
index 0000000000..8cd7908d2f
--- /dev/null
+++ b/frontend-modern/browser-verification/5d8649d926bdaea1.json
@@ -0,0 +1,77 @@
+{
+ "version": 1,
+ "base_sha": "4337c2767fb5ad8347978a989e58a4bddd67f9df",
+ "verified_at": "2026-10-12T14:49:38Z",
+ "result": "passed",
+ "content_sha256": {
+ "frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx": "0065ae99c8b76856831d7e7e289d7eecb736f7d127b01e0b3a7becfc06b88eb7",
+ "frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx": "f3a67323c52fa65071c7dbe178aacecae31433ddcaae4ca30c5ee7eb24843daa",
+ "frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx": "4ca3631056d98cedd2aa5ace6f354d1a5b003713c60845f7edbf19a55ef45b11",
+ "frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx": "570e49903d0991445a89c60d5b7f1281cb167c6b6290774145718ee7a087a2fd",
+ "frontend-modern/src/components/Alerts/ResourceTable.tsx": "400f73d3ae2de0e9ec4ffd4f821100734d1e4c16d46b57bf8089689017325269",
+ "frontend-modern/src/components/Alerts/alertResourceTableModel.ts": "7d786f179ab9e233d613b39bd4ae643434dd4bf51e4105bd0758db3ff67755f8"
+ },
+ "routes": [
+ "/alerts/thresholds/proxmox",
+ "/alerts/thresholds/truenas"
+ ],
+ "viewports": [
+ {
+ "width": 1920,
+ "height": 1080
+ },
+ {
+ "width": 1280,
+ "height": 1080
+ },
+ {
+ "width": 900,
+ "height": 1080
+ },
+ {
+ "width": 390,
+ "height": 844
+ },
+ {
+ "width": 2400,
+ "height": 1080
+ }
+ ],
+ "states": [
+ "Host row and card editing with canonical cluster context",
+ "Enabled and Off global defaults, disabled input and keyboard enable overlay",
+ "Resource Off saved as negative trigger, read back after reload and returned to inheritance",
+ "Cleared override inherits, numeric zero rejected and Cancel discards draft",
+ "Cleared global default remains mid-edit and reload retains saved value",
+ "Guest Off changes only its scoped override, with separate backup and snapshot controls",
+ "TrueNAS global disk temperature follows per-type policy after Off, save, reload and enable",
+ "Empty search and restored results",
+ "Desktop edit stays within table width and resource name remains visible",
+ "Memory draft and focus retained desktop to phone to desktop, final phone Cancel leaves no unsaved config",
+ "Actual pixels inspected for focused fields, Off states, responsive wrapping, cluster context and disk fallback",
+ "Clearing an override beneath a saved Off global default shows Off and disables the desktop slider"
+ ],
+ "interactions": [
+ "Log in to isolated synthetic runtime",
+ "Expand alert groups and open host and guest editors",
+ "Edit number and cancel with pointer",
+ "Tab from number to Off control and activate with Enter",
+ "Move focus to slider and adjacent metric, use ArrowRight and pointer then cancel",
+ "Save row by focus exit and card by explicit Save",
+ "Save configuration and reload persisted global and per-resource Off",
+ "Enable inherited resource default and global factory default",
+ "Clear numeric field, reject invalid zero and cancel",
+ "Filter to empty results and restore",
+ "Resize editing Memory93 through both layouts and cancel",
+ "Inspect deep TrueNAS disk fallback controls after save/reload",
+ "Type81, clear to inherit Off, enable once to80 and Cancel without changing the persisted parent default at every host viewport"
+ ],
+ "changed_paths": [
+ "frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx",
+ "frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx",
+ "frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx",
+ "frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx",
+ "frontend-modern/src/components/Alerts/ResourceTable.tsx",
+ "frontend-modern/src/components/Alerts/alertResourceTableModel.ts"
+ ]
+}
diff --git a/frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx b/frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx
new file mode 100644
index 0000000000..2d19c19415
--- /dev/null
+++ b/frontend-modern/src/components/Alerts/AlertResourceMetricEditor.tsx
@@ -0,0 +1,119 @@
+import { Show } from 'solid-js';
+import { StatusBadge } from '@/components/shared/StatusBadge';
+import {
+ getAlertResourceTableMetricInputTitle,
+ getAlertResourceTableMetricOffToggleProps,
+ getAlertResourceTableMetricPlaceholder,
+} from '@/utils/alertResourceTablePresentation';
+import {
+ ALERT_RESOURCE_METRIC_OFF_VALUE,
+ getAlertResourceMetricBounds,
+ getAlertResourceMetricStep,
+ isAlertResourceMetricOff,
+ resolveAlertResourceGlobalDefaultCell,
+ resolveAlertResourceMetricEnableValue,
+ type AlertResourceGlobalDefaultFallback,
+} from './alertResourceTableModel';
+
+interface AlertResourceMetricEditorProps {
+ metric: string;
+ column: string;
+ scope: 'default' | 'override';
+ layout: 'table' | 'card';
+ value: number | undefined;
+ inheritedDefault?: number;
+ fallback?: AlertResourceGlobalDefaultFallback;
+ onChange: (value: number | undefined) => void;
+ autoFocus?: boolean;
+ onFocus?: () => void;
+}
+
+/** Numeric threshold editing owns one Off/inherit contract across both layouts. */
+export function AlertResourceMetricEditor(props: AlertResourceMetricEditorProps) {
+ const bounds = () => getAlertResourceMetricBounds(props.metric);
+ const defaultCell = () =>
+ resolveAlertResourceGlobalDefaultCell(props.metric, props.value, props.fallback);
+ const isDefault = () => props.scope === 'default';
+ const isOff = () =>
+ isDefault()
+ ? defaultCell().isOff
+ : isAlertResourceMetricOff(props.value, props.inheritedDefault);
+ const follows = () => isDefault() && defaultCell().follows;
+ const enableValue = () =>
+ isDefault()
+ ? defaultCell().enableValue
+ : resolveAlertResourceMetricEnableValue(props.inheritedDefault, props.metric);
+
+ const inputClass = () => {
+ if (props.layout === 'card') {
+ return isDefault()
+ ? `min-h-11 w-full rounded-sm border p-1 text-center text-sm sm:min-h-0 ${isOff() ? 'bg-surface-hover' : 'border-border'}`
+ : 'min-h-11 w-16 text-right text-xs p-1 rounded-sm border border-border bg-surface';
+ }
+ return `${follows() && !isOff() ? 'w-20' : 'w-16'} px-2 py-0.5 text-sm text-center border rounded ${
+ isOff()
+ ? 'border-border bg-surface-alt text-muted'
+ : 'border-border text-base-content focus:border-blue-500 focus:ring-1 focus:ring-blue-500'
+ }`;
+ };
+
+ return (
+ <div
+ class={`flex items-center gap-1.5 ${props.layout === 'card' ? '[&_button]:min-h-11' : 'justify-center'} ${isDefault() ? 'w-full' : ''}`}
+ >
+ <div class={`relative ${props.layout === 'card' && isDefault() ? 'flex-1 min-w-0' : ''}`}>
+ <input
+ ref={(input) => {
+ queueMicrotask(() => {
+ if (!props.autoFocus || !input.isConnected) return;
+ input.focus();
+ input.select();
+ });
+ }}
+ type="number"
+ onFocus={props.onFocus}
+ min={bounds().min}
+ max={bounds().max}
+ step={getAlertResourceMetricStep(props.metric)}
+ value={isOff() || follows() ? '' : (props.value ?? '')}
+ placeholder={
+ follows() && !isOff()
+ ? props.fallback?.label
+ : getAlertResourceTableMetricPlaceholder(isOff())
+ }
+ title={follows() ? props.fallback?.title : getAlertResourceTableMetricInputTitle(isOff())}
+ disabled={isDefault() && isOff()}
+ class={inputClass()}
+ onInput={(event) => {
+ const raw = event.currentTarget.value;
+ // Clearing an override inherits. A blank global default is mid-edit.
+ if (raw === '') {
+ if (!isDefault()) props.onChange(undefined);
+ return;
+ }
+ const value = parseFloat(raw);
+ if (Number.isFinite(value) && value >= bounds().min && value <= bounds().max) {
+ props.onChange(value);
+ }
+ }}
+ />
+ <Show when={isDefault() && isOff()}>
+ <button
+ type="button"
+ class="absolute inset-0 w-full rounded-sm cursor-pointer focus:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-400"
+ onClick={() => props.onChange(enableValue())}
+ title={getAlertResourceTableMetricInputTitle(true)}
+ aria-label={`Enable ${props.column} default`}
+ />
+ </Show>
+ </div>
+ <div onMouseDown={(event) => event.preventDefault()}>
+ <StatusBadge
+ isEnabled={!isOff()}
+ onToggle={() => props.onChange(isOff() ? enableValue() : ALERT_RESOURCE_METRIC_OFF_VALUE)}
+ {...getAlertResourceTableMetricOffToggleProps()}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx b/frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx
index 92232f4ee8..ec8426dda0 100644
--- a/frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx
+++ b/frontend-modern/src/components/Alerts/AlertResourceTableDesktop.tsx
@@ -25,29 +25,23 @@ import {
getPlatformTableHeadClassForKind,
} from '@/features/platformPage/sharedPlatformPage';
import { PlatformWindowedRows } from '@/features/platformPage/PlatformWindowedRows';
+import { AlertResourceMetricEditor } from './AlertResourceMetricEditor';
import { AlertResourceTableRow } from './AlertResourceTableRow';
import { AlertResourceGroupHeader } from './AlertResourceGroupHeader';
import {
getAlertResourceTableAlertDelayLabel,
getAlertResourceTableCustomBadgeLabel,
getAlertResourceTableEmptyState,
- getAlertResourceTableMetricInputTitle,
- getAlertResourceTableMetricOffToggleProps,
- getAlertResourceTableMetricPlaceholder,
getAlertResourceTableOfflineStateOrder,
getAlertResourceTableOfflineStatePresentation,
getAlertResourceTableResetFactoryDefaultsLabel,
getAlertResourceTableNoResultsState,
} from '@/utils/alertResourceTablePresentation';
import {
- ALERT_RESOURCE_METRIC_OFF_VALUE,
getAlertResourceColumnKind,
getAlertResourceColumnHeaderTooltip,
- getAlertResourceMetricBounds,
getAlertResourceMetricDelayOverride,
- getAlertResourceMetricStep,
normalizeAlertResourceMetricKey,
- resolveAlertResourceGlobalDefaultCell,
} from './alertResourceTableModel';
import type { OfflineState, Resource, ResourceTableProps } from './ResourceTable';
@@ -61,6 +55,7 @@ interface AlertResourceTableDesktopProps {
table: ResourceTableProps;
hasRows: () => boolean;
hasCustomGlobalDefaults: () => boolean;
+ isActiveLayout: () => boolean;
activeMetricInput: () => { resourceId: string; metric: string } | null;
setActiveMetricInput: (value: { resourceId: string; metric: string } | null) => void;
showDelayRow: () => boolean;
@@ -166,6 +161,7 @@ export function AlertResourceTableDesktop(props: AlertResourceTableDesktopProps)
editingNote={props.table.editingNote}
setEditingNote={props.table.setEditingNote}
activeMetricInput={props.activeMetricInput}
+ isActiveLayout={props.isActiveLayout}
setActiveMetricInput={props.setActiveMetricInput}
showBulkSelection={Boolean(props.table.onBulkEdit)}
selected={props.selectedIds().has(resource.id)}
@@ -282,94 +278,34 @@ export function AlertResourceTableDesktop(props: AlertResourceTableDesktopProps)
<For each={props.table.columns}>
{(column) => {
const metric = normalizeAlertResourceMetricKey(column);
- const bounds = getAlertResourceMetricBounds(metric);
- const value = () => props.table.globalDefaults?.[metric];
- const fallback = () => props.table.globalDefaultFallbacks?.[metric];
- // An unset default and a stored 0 are both disabled to the
- // alert engine, so neither may render as On, unless the
- // metric's unset default follows another setting.
- const cell = () =>
- resolveAlertResourceGlobalDefaultCell(metric, value(), fallback());
- const isOff = () => cell().isOff;
-
return (
<TableCell
class={`${getPlatformTableCellClassForKind(getAlertResourceColumnKind(column))} align-middle`}
>
- <div class="flex items-center justify-center gap-1.5 w-full">
- <div class="relative">
- <input
- type="number"
- min={bounds.min}
- max={bounds.max}
- step={getAlertResourceMetricStep(metric)}
- value={isOff() || cell().follows ? '' : (value() ?? '')}
- placeholder={
- cell().follows && !isOff()
- ? fallback()?.label
- : getAlertResourceTableMetricPlaceholder(isOff())
- }
- disabled={isOff()}
- onInput={(e) => {
- const nextValue = parseFloat(e.currentTarget.value);
- // An empty box is mid-edit, not a disable request:
- // coercing it to 0 used to disable the metric in the
- // engine while the row still claimed On. Use the Off
- // toggle to disable.
- if (Number.isNaN(nextValue)) {
- return;
- }
- if (nextValue < bounds.min || nextValue > bounds.max) {
- return;
- }
- props.table.setGlobalDefaults?.((prev) => ({
- ...prev,
- [metric]: nextValue,
- }));
- props.table.setHasUnsavedChanges?.(true);
- }}
- class={`${cell().follows && !isOff() ? 'w-20' : 'w-16'} px-2 py-0.5 text-sm text-center border rounded ${
- isOff()
- ? 'border-border bg-surface-alt text-muted italic placeholder: dark:placeholder: placeholder:opacity-60 pointer-events-none'
- : 'border-border text-base-content focus:border-blue-500 focus:ring-1 focus:ring-blue-500'
- }`}
- title={
- cell().follows
- ? fallback()?.title
- : getAlertResourceTableMetricInputTitle(isOff())
- }
- />
- <Show when={isOff()}>
- <button
- type="button"
- class="absolute inset-0 w-full rounded-sm cursor-pointer focus:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-400"
- onClick={() => {
- props.table.setGlobalDefaults?.((prev) => ({
- ...prev,
- [metric]: cell().enableValue,
- }));
- props.table.setHasUnsavedChanges?.(true);
- }}
- title={getAlertResourceTableMetricInputTitle(true)}
- >
- <span class="sr-only">Enable {column} default</span>
- </button>
- </Show>
- </div>
- <StatusBadge
- isEnabled={!isOff()}
- onToggle={() => {
+ <Show
+ when={metric !== 'backup' && metric !== 'snapshot'}
+ fallback={
+ <span class="text-sm text-muted" aria-hidden="true">
+ -
+ </span>
+ }
+ >
+ <AlertResourceMetricEditor
+ metric={metric}
+ column={column}
+ scope="default"
+ layout="table"
+ value={props.table.globalDefaults?.[metric]}
+ fallback={props.table.globalDefaultFallbacks?.[metric]}
+ onChange={(value) => {
props.table.setGlobalDefaults?.((prev) => ({
...prev,
- [metric]: isOff()
- ? cell().enableValue
- : ALERT_RESOURCE_METRIC_OFF_VALUE,
+ [metric]: value,
}));
props.table.setHasUnsavedChanges?.(true);
}}
- {...getAlertResourceTableMetricOffToggleProps()}
/>
- </div>
+ </Show>
</TableCell>
);
}}
diff --git a/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx b/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx
index 6d72d6f892..67fb5990c7 100644
--- a/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx
+++ b/frontend-modern/src/components/Alerts/AlertResourceTableMobile.tsx
@@ -10,32 +10,26 @@ import { Card } from '@/components/shared/Card';
import { FormTextarea } from '@/components/shared/FormTextarea';
import { TogglePrimitive } from '@/components/shared/Toggle';
import { StatusBadge } from '@/components/shared/StatusBadge';
+import { AlertResourceMetricEditor } from './AlertResourceMetricEditor';
import { AlertResourceGroupHeader } from './AlertResourceGroupHeader';
import { PlatformWindowedList } from '@/features/platformPage/PlatformWindowedList';
import {
getAlertResourceTableCustomBadgeLabel,
getAlertResourceTableEditNotePlaceholder,
getAlertResourceTableEmptyState,
- getAlertResourceTableMetricOffToggleProps,
- getAlertResourceTableMetricPlaceholder,
getAlertResourceTableOfflineStateOrder,
getAlertResourceTableOfflineStatePresentation,
getAlertResourceTableRevertToDefaultsLabel,
} from '@/utils/alertResourceTablePresentation';
import {
- ALERT_RESOURCE_METRIC_OFF_VALUE,
alertResourceSupportsMetric,
buildAlertResourceEditPayload,
getAlertResourceLabel,
- getAlertResourceMetricBounds,
+ getAlertResourceInitialEditMetric,
getAlertResourceMetricDisplayValue,
- getAlertResourceMetricStep,
getAlertResourceRelaxedTriggerSummary,
- isAlertResourceMetricOff,
isAlertResourceMetricOverridden,
normalizeAlertResourceMetricKey,
- resolveAlertResourceGlobalDefaultCell,
- resolveAlertResourceMetricEnableValue,
} from './alertResourceTableModel';
import type { Resource } from '@/features/alerts/thresholds/tableTypes';
import { AlertResourceRelaxedTriggers } from './AlertResourceRelaxedTriggers';
@@ -45,6 +39,7 @@ interface AlertResourceTableMobileProps {
table: ResourceTableProps;
hasRows: () => boolean;
hasCustomGlobalDefaults: () => boolean;
+ activeMetricInput: () => { resourceId: string; metric: string } | null;
setActiveMetricInput: (value: { resourceId: string; metric: string } | null) => void;
}
@@ -90,8 +85,10 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
if (resource.editable === false) {
return;
}
- if (metric) {
- props.setActiveMetricInput({ resourceId: resource.id, metric });
+ const initialMetric =
+ metric ?? getAlertResourceInitialEditMetric(props.table.columns, resource.type);
+ if (initialMetric) {
+ props.setActiveMetricInput({ resourceId: resource.id, metric: initialMetric });
}
const payload = buildAlertResourceEditPayload(resource);
props.table.onEdit(resource.id, payload.thresholds, payload.defaults, payload.note);
@@ -213,83 +210,21 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
>
{(column) => {
const metric = normalizeAlertResourceMetricKey(column);
- const bounds = getAlertResourceMetricBounds(metric);
- const value = () => props.table.globalDefaults?.[metric];
- const fallback = () => props.table.globalDefaultFallbacks?.[metric];
- // An unset default and a stored 0 are both disabled to the alert
- // engine, so neither may render as On, unless the metric's unset
- // default follows another setting.
- const cell = () =>
- resolveAlertResourceGlobalDefaultCell(metric, value(), fallback());
- const isOff = () => cell().isOff;
-
return (
<div class="p-2 bg-surface rounded-sm border border-border-subtle flex flex-col gap-1">
<span class="text-[10px] uppercase text-slate-500 font-medium">{column}</span>
- <div class="flex items-center gap-1.5">
- <div class="relative flex-1">
- <input
- type="number"
- min={bounds.min}
- max={bounds.max}
- step={getAlertResourceMetricStep(metric)}
- value={isOff() || cell().follows ? '' : (value() ?? '')}
- placeholder={
- cell().follows && !isOff()
- ? fallback()?.label
- : getAlertResourceTableMetricPlaceholder(isOff())
- }
- title={cell().follows ? fallback()?.title : undefined}
- disabled={isOff()}
- class={`min-h-11 w-full rounded-sm border p-1 text-center text-sm sm:min-h-0 ${isOff() ? 'bg-surface-hover' : ' border-border'}`}
- onInput={(e) => {
- const nextValue = parseFloat(e.currentTarget.value);
- // An empty box is mid-edit, not a disable request:
- // coercing it to 0 used to disable the metric in the
- // engine while the card still claimed On. Use the Off
- // toggle to disable.
- if (Number.isNaN(nextValue)) {
- return;
- }
- if (nextValue < bounds.min || nextValue > bounds.max) {
- return;
- }
- props.table.setGlobalDefaults?.((prev) => ({
- ...prev,
- [metric]: nextValue,
- }));
- props.table.setHasUnsavedChanges?.(true);
- }}
- />
- <Show when={isOff()}>
- <button
- type="button"
- class="absolute inset-0 w-full"
- onClick={() => {
- props.table.setGlobalDefaults?.((prev) => ({
- ...prev,
- [metric]: cell().enableValue,
- }));
- props.table.setHasUnsavedChanges?.(true);
- }}
- aria-label={`Enable ${column} default`}
- />
- </Show>
- </div>
- <StatusBadge
- isEnabled={!isOff()}
- onToggle={() => {
- props.table.setGlobalDefaults?.((prev) => ({
- ...prev,
- [metric]: isOff()
- ? cell().enableValue
- : ALERT_RESOURCE_METRIC_OFF_VALUE,
- }));
- props.table.setHasUnsavedChanges?.(true);
- }}
- {...getAlertResourceTableMetricOffToggleProps()}
- />
- </div>
+ <AlertResourceMetricEditor
+ metric={metric}
+ column={column}
+ scope="default"
+ layout="card"
+ value={props.table.globalDefaults?.[metric]}
+ fallback={props.table.globalDefaultFallbacks?.[metric]}
+ onChange={(value) => {
+ props.table.setGlobalDefaults?.((prev) => ({ ...prev, [metric]: value }));
+ props.table.setHasUnsavedChanges?.(true);
+ }}
+ />
</div>
);
}}
@@ -406,6 +341,11 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
<div class="font-medium text-sm truncate">
{getAlertResourceLabel(resource)}
</div>
+ <Show when={resource.type === 'agent' && resource.clusterName}>
+ <span class="block text-xs text-muted whitespace-normal break-words">
+ {resource.clusterName}
+ </span>
+ </Show>
<Show when={resource.subtitle}>
<div
class="text-xs text-muted"
@@ -557,10 +497,6 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
);
}
- const isDisabled = () => isAlertResourceMetricOff(thresholds()?.[metric]);
- const inheritedDefault = () => resource.defaults?.[metric];
- const bounds = getAlertResourceMetricBounds(metric);
-
return (
<div class="flex justify-between items-center p-1.5 bg-surface-alt rounded-sm">
<span class="text-[10px] uppercase font-bold tracking-wider">
@@ -585,44 +521,28 @@ export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
</button>
}
>
- <div class="flex items-center gap-1.5 [&_button]:min-h-11">
- <input
- type="number"
- min={bounds.min}
- max={bounds.max}
- value={isDisabled() ? '' : (thresholds()?.[metric] ?? '')}
- placeholder={getAlertResourceTableMetricPlaceholder(isDisabled())}
- class="min-h-11 w-16 text-right text-xs p-1 rounded-sm border border-border bg-surface"
- onInput={(e) => {
- const nextValue = parseFloat(e.currentTarget.value);
- if (
- !Number.isNaN(nextValue) &&
- (nextValue < bounds.min || nextValue > bounds.max)
- ) {
- return;
- }
- props.table.setEditingThresholds({
- ...props.table.editingThresholds(),
- [metric]: Number.isNaN(nextValue) ? undefined : nextValue,
- });
- }}
- />
- <StatusBadge
- isEnabled={!isDisabled()}
- onToggle={() =>
- props.table.setEditingThresholds({
- ...props.table.editingThresholds(),
- [metric]: isDisabled()
- ? resolveAlertResourceMetricEnableValue(
- inheritedDefault(),
- metric,
- )
- : ALERT_RESOURCE_METRIC_OFF_VALUE,
- })
- }
- {...getAlertResourceTableMetricOffToggleProps()}
- />
- </div>
+ <AlertResourceMetricEditor
+ metric={metric}
+ column={column}
+ scope="override"
+ layout="card"
+ value={thresholds()?.[metric]}
+ inheritedDefault={resource.defaults?.[metric]}
+ onFocus={() =>
+ props.setActiveMetricInput({ resourceId: resource.id, metric })
+ }
+ autoFocus={
+ isEditing() &&
+ props.activeMetricInput()?.resourceId === resource.id &&
+ props.activeMetricInput()?.metric === metric
+ }
+ onChange={(value) =>
+ props.table.setEditingThresholds({
+ ...props.table.editingThresholds(),
+ [metric]: value,
+ })
+ }
+ />
</Show>
</div>
);
diff --git a/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx b/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx
index d183128be1..01fd5c02a7 100644
--- a/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx
+++ b/frontend-modern/src/components/Alerts/AlertResourceTableRow.tsx
@@ -15,33 +15,29 @@ import { getPlatformTableCellClassForKind } from '@/features/platformPage/shared
import {
getAlertResourceTableCustomBadgeLabel,
getAlertResourceTableEditMetricTitle,
- getAlertResourceTableMetricInputTitle,
- getAlertResourceTableMetricOffToggleProps,
- getAlertResourceTableMetricPlaceholder,
getAlertResourceTableOfflineStateOrder,
getAlertResourceTableOfflineStatePresentation,
getAlertResourceTableOverrideNotePlaceholder,
getAlertResourceTableRevertToDefaultsLabel,
} from '@/utils/alertResourceTablePresentation';
import {
- ALERT_RESOURCE_METRIC_OFF_VALUE,
ALERT_RESOURCE_TABLE_SLIDER_METRICS,
alertResourceSupportsMetric,
getAlertResourceColumnKind,
getAlertResourceLabel,
+ getAlertResourceInitialEditMetric,
getAlertResourceMetricBounds,
getAlertResourceMetricDisplayValue,
- getAlertResourceMetricStep,
getAlertResourceRelaxedTriggerSummary,
isAlertResourceMetricOff,
isAlertResourceMetricOverridden,
normalizeAlertResourceMetricKey,
- resolveAlertResourceMetricEnableValue,
type AlertResourceThresholdMap,
} from './alertResourceTableModel';
import type { Alert } from '@/types/api';
import type { AlertIntentSignal } from '@/api/alertIntentPolicies';
import type { Resource } from '@/features/alerts/thresholds/tableTypes';
+import { AlertResourceMetricEditor } from './AlertResourceMetricEditor';
import { AlertResourceRelaxedTriggers } from './AlertResourceRelaxedTriggers';
type OfflineState = 'off' | 'warning' | 'critical';
@@ -77,6 +73,7 @@ interface AlertResourceTableRowProps {
editingNote: () => string;
setEditingNote: (value: string) => void;
activeMetricInput: () => { resourceId: string; metric: string } | null;
+ isActiveLayout: () => boolean;
setActiveMetricInput: (value: { resourceId: string; metric: string } | null) => void;
showBulkSelection?: boolean;
selected?: boolean;
@@ -118,13 +115,18 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
const getThresholds = (): AlertResourceThresholdMap => thresholds();
+ let hasEditingFocus = false;
+
const startEditing = (metric?: string, event?: MouseEvent) => {
event?.stopPropagation();
if (props.resource.editable === false) {
return;
}
- if (metric) {
- props.setActiveMetricInput({ resourceId: props.resource.id, metric });
+ hasEditingFocus = false;
+ const initialMetric =
+ metric ?? getAlertResourceInitialEditMetric(props.columns, props.resource.type);
+ if (initialMetric) {
+ props.setActiveMetricInput({ resourceId: props.resource.id, metric: initialMetric });
}
props.onEdit(
props.resource.id,
@@ -135,11 +137,13 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
};
const cancelEditing = () => {
+ hasEditingFocus = false;
props.onCancelEdit();
props.setActiveMetricInput(null);
};
const saveEditing = () => {
+ hasEditingFocus = false;
props.onSaveEdit(props.resource.id);
props.setActiveMetricInput(null);
};
@@ -228,6 +232,18 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
return (
<TableRow
+ onFocusIn={() => {
+ if (isEditing()) hasEditingFocus = true;
+ }}
+ onFocusOut={(event) => {
+ // Removing this layout during a resize transfers the draft to cards.
+ // It is not the user leaving the editor to save a row.
+ if (!props.isActiveLayout()) return;
+ if (!hasEditingFocus || props.editingId() !== props.resource.id) return;
+ const nextFocus = event.relatedTarget;
+ if (nextFocus instanceof Node && event.currentTarget.contains(nextFocus)) return;
+ saveEditing();
+ }}
class={`transition-colors ${props.resource.disabled || props.globalDisableFlag?.() ? 'opacity-40' : ''} ${props.resource.hasOverride ? 'bg-sky-50/50 hover:bg-sky-50/80 dark:bg-sky-900/20 dark:hover:bg-sky-900/30 border-l-[3px] border-l-sky-400 dark:border-l-sky-500' : 'hover:bg-surface-hover'}`}
>
<Show when={props.showBulkSelection}>
@@ -356,10 +372,9 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
{(column) => {
const metric = normalizeAlertResourceMetricKey(column);
const bounds = getAlertResourceMetricBounds(metric);
- const isDisabled = () => isAlertResourceMetricOff(getThresholds()?.[metric]);
- const inheritedDefault = () => props.resource.defaults?.[metric];
+ const isDisabled = () =>
+ isAlertResourceMetricOff(getThresholds()?.[metric], props.resource.defaults?.[metric]);
const isSpecialToggle = metric === 'backup' || metric === 'snapshot';
- let metricEditor: HTMLDivElement | undefined;
if (isSpecialToggle) {
const config = metric === 'backup' ? props.resource.backup : props.resource.snapshot;
@@ -432,7 +447,7 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
</div>
}
>
- <div class="flex w-full items-center justify-center gap-3">
+ <div class="flex w-full flex-col items-center justify-center gap-1.5">
<Show when={ALERT_RESOURCE_TABLE_SLIDER_METRICS.has(metric)}>
{(() => {
const isTemperatureMetric =
@@ -483,73 +498,23 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
);
})()}
</Show>
- <div class="flex items-center justify-center gap-1.5" ref={metricEditor}>
- <input
- type="number"
- min={bounds.min}
- max={bounds.max}
- step={getAlertResourceMetricStep(metric)}
- value={isDisabled() ? '' : (getThresholds()?.[metric] ?? '')}
- placeholder={getAlertResourceTableMetricPlaceholder(isDisabled())}
- title={getAlertResourceTableMetricInputTitle(isDisabled())}
- ref={(el) => {
- if (
- isEditing() &&
- props.activeMetricInput()?.resourceId === props.resource.id &&
- props.activeMetricInput()?.metric === metric
- ) {
- queueMicrotask(() => {
- el.focus();
- el.select();
- });
- }
- }}
- onInput={(e) => {
- const raw = e.currentTarget.value;
- if (raw === '') {
- updateEditingThreshold(metric, undefined);
- return;
- }
- const val = parseFloat(raw);
- if (!Number.isNaN(val) && val >= bounds.min && val <= bounds.max) {
- updateEditingThreshold(metric, val);
- }
- }}
- onBlur={(event) => {
- if (props.editingId() !== props.resource.id) {
- return;
- }
- // Tabbing to the Off toggle must not save and close the
- // editor before the toggle can be operated.
- const nextFocus = event.relatedTarget;
- if (nextFocus instanceof Node && metricEditor?.contains(nextFocus)) {
- return;
- }
- saveEditing();
- }}
- class={`w-16 px-2 py-0.5 text-sm text-center border rounded ${
- isDisabled()
- ? 'bg-surface-alt text-slate-400 border-border'
- : ' text-base-content border-border'
- }`}
- />
- {/* mousedown would blur the input, which saves and closes
- the editor before this toggle's click can land */}
- <div onMouseDown={(event) => event.preventDefault()}>
- <StatusBadge
- isEnabled={!isDisabled()}
- onToggle={() =>
- updateEditingThreshold(
- metric,
- isDisabled()
- ? resolveAlertResourceMetricEnableValue(inheritedDefault(), metric)
- : ALERT_RESOURCE_METRIC_OFF_VALUE,
- )
- }
- {...getAlertResourceTableMetricOffToggleProps()}
- />
- </div>
- </div>
+ <AlertResourceMetricEditor
+ metric={metric}
+ column={column}
+ scope="override"
+ layout="table"
+ value={getThresholds()?.[metric]}
+ inheritedDefault={props.resource.defaults?.[metric]}
+ onFocus={() =>
+ props.setActiveMetricInput({ resourceId: props.resource.id, metric })
+ }
+ onChange={(value) => updateEditingThreshold(metric, value)}
+ autoFocus={
+ isEditing() &&
+ props.activeMetricInput()?.resourceId === props.resource.id &&
+ props.activeMetricInput()?.metric === metric
+ }
+ />
</div>
</Show>
</Show>
@@ -619,6 +584,7 @@ export function AlertResourceTableRow(props: AlertResourceTableRowProps) {
fallback={
<ActionIconButton
onClick={cancelEditing}
+ onMouseDown={(event) => event.preventDefault()}
label="Cancel editing"
tone="muted"
size="xs"
diff --git a/frontend-modern/src/components/Alerts/ResourceTable.test.tsx b/frontend-modern/src/components/Alerts/ResourceTable.test.tsx
index 5810870e33..42faa82cc7 100644
--- a/frontend-modern/src/components/Alerts/ResourceTable.test.tsx
+++ b/frontend-modern/src/components/Alerts/ResourceTable.test.tsx
@@ -1,12 +1,13 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createSignal } from 'solid-js';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { waitFor, cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { ALERT_BULK_EDIT_CLEAR_LABEL } from '@/utils/alertBulkEditPresentation';
import resourceTableSource from '@/components/Alerts/ResourceTable.tsx?raw';
import alertResourceGroupHeaderSource from '@/components/Alerts/AlertResourceGroupHeader.tsx?raw';
import alertResourceTableDesktopSource from '@/components/Alerts/AlertResourceTableDesktop.tsx?raw';
import alertResourceTableMobileSource from '@/components/Alerts/AlertResourceTableMobile.tsx?raw';
import alertResourceTableRowSource from '@/components/Alerts/AlertResourceTableRow.tsx?raw';
+import alertResourceMetricEditorSource from '@/components/Alerts/AlertResourceMetricEditor.tsx?raw';
import alertResourceTableModelSource from '@/components/Alerts/alertResourceTableModel.ts?raw';
import alertResourceTableStateSource from '@/components/Alerts/useAlertResourceTableState.ts?raw';
import {
@@ -78,7 +79,11 @@ vi.mock('@/components/shared/Table', () => ({
),
TableHeader: (props: any) => <thead>{props.children}</thead>,
TableBody: (props: any) => <tbody class={props.class}>{props.children}</tbody>,
- TableRow: (props: any) => <tr class={props.class}>{props.children}</tr>,
+ TableRow: (props: any) => (
+ <tr class={props.class} onFocusOut={props.onFocusOut} onFocusIn={props.onFocusIn}>
+ {props.children}
+ </tr>
+ ),
TableHead: (props: any) => (
<th class={props.class} title={props.title}>
{props.children}
@@ -374,7 +379,7 @@ describe('ResourceTable', () => {
expect(alertResourceTableMobileSource).toContain('AlertResourceGroupHeader');
expect(alertResourceTableMobileSource).toContain('FormTextarea');
expect(alertResourceTableMobileSource).toContain('ActionIconButton');
- expect(alertResourceTableMobileSource).toContain(
+ expect(alertResourceMetricEditorSource).toContain(
'min-h-11 w-full rounded-sm border p-1 text-center text-sm sm:min-h-0',
);
expect(alertResourceTableMobileSource).not.toContain(['<', 'textarea'].join(''));
@@ -916,6 +921,41 @@ describe('ResourceTable', () => {
});
});
+ it.each([false, true])(
+ 'preserves host cluster context in threshold layouts (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ render(() => (
+ <ResourceTable
+ {...makeProps({
+ resources: [makeResource({ type: 'agent', name: 'A', clusterName: 'Analytics' })],
+ })}
+ />
+ ));
+ expect(screen.getByText('Analytics')).toBeInTheDocument();
+ },
+ );
+
+ it.each([false, true])(
+ 'keeps backup and snapshot configs out of numeric defaults (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ render(() => (
+ <ResourceTable
+ {...makeProps({
+ resources: [],
+ columns: ['CPU %', 'Backup', 'Snapshot'],
+ globalDefaults: { cpu: 80 },
+ setGlobalDefaults: vi.fn(),
+ setHasUnsavedChanges: vi.fn(),
+ })}
+ />
+ ));
+ expect(screen.getAllByRole('spinbutton')).toHaveLength(1);
+ expect(screen.getAllByTestId('status-badge')).toHaveLength(1);
+ },
+ );
+
describe('metric off toggles', () => {
// The alert engine disables a metric whenever its trigger is <= 0, so every
// editor here has to agree on that reading and has to write a value the
@@ -928,73 +968,138 @@ describe('ResourceTable', () => {
});
}
- it('reads a stored 0 override as Off in the row editor', () => {
- const props = editorProps({
- resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 0 }, defaults: { cpu: 80 } })],
- editingThresholds: () => ({ cpu: 0 }),
- });
- render(() => <ResourceTable {...props} />);
+ it.each([false, true])(
+ 'reads a stored 0 override as Off in the row editor (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 0 }, defaults: { cpu: 80 } })],
+ editingThresholds: () => ({ cpu: 0 }),
+ });
+ render(() => <ResourceTable {...props} />);
- expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
- });
+ expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
+ },
+ );
- it('does not stage 0 through the row numeric input', () => {
- const setEditingThresholds = vi.fn();
- const props = editorProps({
- resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
- editingThresholds: () => ({ cpu: 80 }),
- setEditingThresholds,
- });
- render(() => <ResourceTable {...props} />);
+ it.each([false, true])(
+ 'does not stage 0 through the row numeric input (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const setEditingThresholds = vi.fn();
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
+ editingThresholds: () => ({ cpu: 80 }),
+ setEditingThresholds,
+ });
+ render(() => <ResourceTable {...props} />);
- fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '0' } });
+ fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '0' } });
- expect(setEditingThresholds).not.toHaveBeenCalled();
- });
+ expect(setEditingThresholds).not.toHaveBeenCalled();
+ },
+ );
- it('stages an explicit threshold when the inherited default is itself off', () => {
- // Clearing the override would only re-inherit the disabled default, so
- // the save path would drop the change and the metric would stay off.
- const setEditingThresholds = vi.fn();
- const props = editorProps({
- resources: [makeResource({ id: 'vm-1', thresholds: {}, defaults: { cpu: -1 } })],
- editingThresholds: () => ({ cpu: -1 }),
- setEditingThresholds,
- });
- render(() => <ResourceTable {...props} />);
+ it.each([false, true])(
+ 'stages an explicit threshold when the inherited default is itself off (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ // Clearing the override would only re-inherit the disabled default, so
+ // the save path would drop the change and the metric would stay off.
+ const setEditingThresholds = vi.fn();
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: {}, defaults: { cpu: -1 } })],
+ editingThresholds: () => ({ cpu: -1 }),
+ setEditingThresholds,
+ });
+ render(() => <ResourceTable {...props} />);
+
+ fireEvent.click(screen.getByTestId('status-badge'));
+
+ expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: 80 });
+ },
+ );
- fireEvent.click(screen.getByTestId('status-badge'));
+ it.each([false, true])(
+ 'clears the override when the inherited default is already enabled (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const setEditingThresholds = vi.fn();
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: { cpu: -1 }, defaults: { cpu: 80 } })],
+ editingThresholds: () => ({ cpu: -1 }),
+ setEditingThresholds,
+ });
+ render(() => <ResourceTable {...props} />);
- expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: 80 });
- });
+ fireEvent.click(screen.getByTestId('status-badge'));
- it('clears the override when the inherited default is already enabled', () => {
- const setEditingThresholds = vi.fn();
- const props = editorProps({
- resources: [makeResource({ id: 'vm-1', thresholds: { cpu: -1 }, defaults: { cpu: 80 } })],
- editingThresholds: () => ({ cpu: -1 }),
- setEditingThresholds,
- });
- render(() => <ResourceTable {...props} />);
+ expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: undefined });
+ },
+ );
- fireEvent.click(screen.getByTestId('status-badge'));
+ it.each([false, true])(
+ 'turns a metric off with the canonical -1 sentinel (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const setEditingThresholds = vi.fn();
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
+ editingThresholds: () => ({ cpu: 80 }),
+ setEditingThresholds,
+ });
+ render(() => <ResourceTable {...props} />);
- expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: undefined });
- });
+ fireEvent.click(screen.getByTestId('status-badge'));
- it('turns a metric off with the canonical -1 sentinel', () => {
- const setEditingThresholds = vi.fn();
- const props = editorProps({
- resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
- editingThresholds: () => ({ cpu: 80 }),
- setEditingThresholds,
- });
- render(() => <ResourceTable {...props} />);
+ expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: -1 });
+ },
+ );
- fireEvent.click(screen.getByTestId('status-badge'));
+ it.each([false, true])(
+ 'clears an override to inherit without disabling (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const setEditingThresholds = vi.fn();
+ const props = editorProps({
+ resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 90 }, defaults: { cpu: 80 } })],
+ editingThresholds: () => ({ cpu: 90 }),
+ setEditingThresholds,
+ });
+ render(() => <ResourceTable {...props} />);
+ fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '' } });
+ expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: undefined });
+ },
+ );
- expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: -1 });
- });
+ it.each([false, true])(
+ 'clearing an override inherits Off and enables in one toggle (mobile=%s)',
+ (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const [editingThresholds, setEditingThresholds] = createSignal<
+ Record<string, number | undefined>
+ >({ cpu: 81 });
+ render(() => (
+ <ResourceTable
+ {...editorProps({
+ editingThresholds,
+ setEditingThresholds,
+ resources: [
+ makeResource({ id: 'vm-1', thresholds: { cpu: 81 }, defaults: { cpu: 0 } }),
+ ],
+ })}
+ />
+ ));
+ fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '' } });
+ expect(editingThresholds().cpu).toBeUndefined();
+ expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
+ if (!mobile) expect(screen.getByRole('slider')).toBeDisabled();
+ fireEvent.click(screen.getByTestId('status-badge'));
+ expect(editingThresholds().cpu).toBe(80);
+ expect(screen.getByRole('spinbutton')).toHaveValue(80);
+ expect(screen.getByTestId('status-badge')).toHaveTextContent('On');
+ },
+ );
it('keeps the editor open when focus moves from the input to the off toggle', () => {
// Tabbing to the toggle must not save and close the row before the toggle
@@ -1008,8 +1113,142 @@ describe('ResourceTable', () => {
render(() => <ResourceTable {...props} />);
const input = screen.getByRole('spinbutton');
- fireEvent.blur(input, { relatedTarget: screen.getByTestId('status-badge') });
+ fireEvent.focusOut(input, { relatedTarget: screen.getByTestId('status-badge') });
+
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])(
+ 'opens from the focused edit button and focuses the first input (mobile=%s)',
+ async (mobile) => {
+ mockIsMobile.mockReturnValue(mobile);
+ const [editingId, setEditingId] = createSignal<string | null>(null);
+ const onSaveEdit = vi.fn();
+ render(() => (
+ <>
+ <button data-testid="outside-entry">Other action</button>
+ <ResourceTable
+ {...editorProps({
+ editingId,
+ onSaveEdit,
+ onEdit: () => setEditingId('vm-1'),
+ resources: [makeResource({ id: 'vm-1' })],
+ })}
+ />
+ </>
+ ));
+ const edit = screen.getByLabelText('Edit thresholds for Test VM');
+ edit.focus();
+ fireEvent.click(edit);
+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('spinbutton')));
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ screen.getByTestId('outside-entry').focus();
+ if (mobile) {
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByLabelText('Save threshold edits for Test VM'));
+ }
+ expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
+ },
+ );
+ it.each([false, true])(
+ 'transfers the current metric focus and draft between layouts (mobile=%s)',
+ async (initialMobile) => {
+ const [mobile, setMobile] = createSignal(initialMobile);
+ mockIsMobile.mockImplementation(mobile);
+ const onSaveEdit = vi.fn();
+ const [editingThresholds, setEditingThresholds] = createSignal({ cpu: 80, memory: 85 });
+ render(() => (
+ <ResourceTable
+ {...editorProps({
+ columns: ['CPU %', 'Memory %'],
+ editingThresholds,
+ setEditingThresholds,
+ onSaveEdit,
+ resources: [makeResource({ id: 'vm-1', defaults: { cpu: 80, memory: 85 } })],
+ })}
+ />
+ ));
+ const memory = screen.getAllByRole('spinbutton')[1];
+ memory.focus();
+ fireEvent.input(memory, { target: { value: '93' } });
+ setMobile(!initialMobile);
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getAllByRole('spinbutton')[1]),
+ );
+ expect(screen.getAllByRole('spinbutton')[1]).toHaveValue(93);
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ setMobile(initialMobile);
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getAllByRole('spinbutton')[1]),
+ );
+ expect(screen.getAllByRole('spinbutton')[1]).toHaveValue(93);
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps the editor open when focus moves from the number to its slider', () => {
+ const onSaveEdit = vi.fn();
+ render(() => (
+ <ResourceTable
+ {...editorProps({ onSaveEdit, resources: [makeResource({ id: 'vm-1' })] })}
+ />
+ ));
+ screen.getByRole('spinbutton').focus();
+ screen.getByRole('slider').focus();
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ });
+
+ it('saves when focus leaves the edited row after the Off toggle', () => {
+ const onSaveEdit = vi.fn();
+ render(() => (
+ <>
+ <button data-testid="outside-row">Other action</button>
+ <ResourceTable
+ {...editorProps({ onSaveEdit, resources: [makeResource({ id: 'vm-1' })] })}
+ />
+ </>
+ ));
+ screen.getByRole('spinbutton').focus();
+ screen.getByTestId('status-badge').focus();
+ screen.getByTestId('outside-row').focus();
+ expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
+ });
+
+ it('lets Cancel discard a focused threshold without saving', () => {
+ const onSaveEdit = vi.fn();
+ const onCancelEdit = vi.fn();
+ render(() => (
+ <ResourceTable
+ {...editorProps({
+ onSaveEdit,
+ onCancelEdit,
+ resources: [makeResource({ id: 'vm-1' })],
+ })}
+ />
+ ));
+ screen.getByRole('spinbutton').focus();
+ const cancel = screen.getByLabelText('Cancel editing');
+ cancel.focus();
+ fireEvent.click(cancel);
+ expect(onCancelEdit).toHaveBeenCalledOnce();
+ expect(onSaveEdit).not.toHaveBeenCalled();
+ });
+
+ it('keeps editing when keyboard focus moves to another metric in the row', () => {
+ const onSaveEdit = vi.fn();
+ render(() => (
+ <ResourceTable
+ {...editorProps({
+ onSaveEdit,
+ columns: ['CPU %', 'Memory %'],
+ resources: [makeResource({ id: 'vm-1' })],
+ })}
+ />
+ ));
+ const inputs = screen.getAllByRole('spinbutton');
+ inputs[0].focus();
+ inputs[1].focus();
expect(onSaveEdit).not.toHaveBeenCalled();
});
@@ -1022,7 +1261,8 @@ describe('ResourceTable', () => {
});
render(() => <ResourceTable {...props} />);
- fireEvent.blur(screen.getByRole('spinbutton'), { relatedTarget: null });
+ screen.getByRole('spinbutton').focus();
+ fireEvent.focusOut(screen.getByRole('spinbutton'), { relatedTarget: null });
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
});
@@ -1935,7 +2175,7 @@ describe('ResourceTable', () => {
expect(setEditingThresholds).toHaveBeenCalledWith(expect.objectContaining({ cpu: 95 }));
});
- it('calls onSaveEdit on input blur', () => {
+ it('calls onSaveEdit when focus leaves the edited row', () => {
const onSaveEdit = vi.fn();
const props = makeProps({
resources: undefined,
@@ -1953,7 +2193,8 @@ describe('ResourceTable', () => {
'input[type="number"][title="Use the Off control to disable alerts for this metric"]',
);
expect(editInputs.length).toBeGreaterThanOrEqual(1);
- fireEvent.blur(editInputs[0]);
+ (editInputs[0] as HTMLInputElement).focus();
+ fireEvent.focusOut(editInputs[0]);
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
});
diff --git a/frontend-modern/src/components/Alerts/ResourceTable.tsx b/frontend-modern/src/components/Alerts/ResourceTable.tsx
index 9f3ae7ba22..84e2499c5a 100644
--- a/frontend-modern/src/components/Alerts/ResourceTable.tsx
+++ b/frontend-modern/src/components/Alerts/ResourceTable.tsx
@@ -139,6 +139,7 @@ export function ResourceTable(props: ResourceTableProps) {
table={props}
hasRows={hasRows}
hasCustomGlobalDefaults={hasCustomGlobalDefaults}
+ activeMetricInput={activeMetricInput}
setActiveMetricInput={setActiveMetricInput}
/>
}
@@ -147,6 +148,7 @@ export function ResourceTable(props: ResourceTableProps) {
table={props}
hasRows={hasRows}
hasCustomGlobalDefaults={hasCustomGlobalDefaults}
+ isActiveLayout={() => !useCardLayout()}
activeMetricInput={activeMetricInput}
setActiveMetricInput={setActiveMetricInput}
showDelayRow={showDelayRow}
diff --git a/frontend-modern/src/components/Alerts/alertResourceTableModel.ts b/frontend-modern/src/components/Alerts/alertResourceTableModel.ts
index c23a97acce..c07bffa712 100644
--- a/frontend-modern/src/components/Alerts/alertResourceTableModel.ts
+++ b/frontend-modern/src/components/Alerts/alertResourceTableModel.ts
@@ -213,8 +213,14 @@ export const ALERT_RESOURCE_METRIC_OFF_VALUE = -1;
* save payload writes an Off global default as `0`, because the backend reads
* a negative default as unset.
*/
-export function isAlertResourceMetricOff(value: number | undefined | null): boolean {
- return typeof value === 'number' && Number.isFinite(value) && value <= 0;
+export function isAlertResourceMetricOff(
+ value: number | undefined | null,
+ inheritedDefault?: number,
+): boolean {
+ const effectiveValue = value ?? inheritedDefault;
+ return (
+ typeof effectiveValue === 'number' && Number.isFinite(effectiveValue) && effectiveValue <= 0
+ );
}
/**
@@ -313,6 +319,17 @@ export function getAlertResourceColumnKind(column: string): PlatformTableColumnK
return 'numeric-value';
}
+export function getAlertResourceInitialEditMetric(columns: string[], resourceType?: string) {
+ return columns
+ .map(normalizeAlertResourceMetricKey)
+ .find(
+ (metric) =>
+ metric !== 'backup' &&
+ metric !== 'snapshot' &&
+ alertResourceSupportsMetric(resourceType, metric),
+ );
+}
+
export function alertResourceSupportsMetric(
resourceType: string | undefined,
metric: string,
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index d851d6e1dd..a1701f1a33 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -380,6 +380,7 @@ import alertResourceGroupHeaderSource from '@/components/Alerts/AlertResourceGro
import alertResourceTableDesktopSource from '@/components/Alerts/AlertResourceTableDesktop.tsx?raw';
import alertResourceTableMobileSource from '@/components/Alerts/AlertResourceTableMobile.tsx?raw';
import alertResourceTableRowSource from '@/components/Alerts/AlertResourceTableRow.tsx?raw';
+import alertResourceMetricEditorSource from '@/components/Alerts/AlertResourceMetricEditor.tsx?raw';
import alertResourceTableSource from '@/components/Alerts/ResourceTable.tsx?raw';
import alertResourceTableStateSource from '@/components/Alerts/useAlertResourceTableState.ts?raw';
import emailProviderSelectSource from '@/components/Alerts/EmailProviderSelect.tsx?raw';
@@ -4140,19 +4141,22 @@ describe('frontend resource type boundaries', () => {
'getAlertResourceTableResetFactoryDefaultsLabel',
);
expect(alertResourceTableDesktopSource).toContain('getAlertResourceTableAlertDelayLabel');
- expect(alertResourceTableDesktopSource).toContain('getAlertResourceTableMetricInputTitle');
+ expect(alertResourceTableDesktopSource).toContain('AlertResourceMetricEditor');
expect(alertResourceTableDesktopSource).toContain('getAlertResourceTableEmptyState');
expect(alertResourceTableDesktopSource).toContain('getAlertResourceTableNoResultsState');
expect(alertResourceTableMobileSource).toContain('export function AlertResourceTableMobile');
expect(alertResourceTableMobileSource).toContain('AlertResourceGroupHeader');
expect(alertResourceTableMobileSource).toContain('buildAlertResourceEditPayload');
expect(alertResourceTableMobileSource).toContain('getAlertResourceTableCustomBadgeLabel');
- expect(alertResourceTableMobileSource).toContain('getAlertResourceTableMetricPlaceholder');
+ expect(alertResourceTableMobileSource).toContain('AlertResourceMetricEditor');
expect(alertResourceTableMobileSource).toContain('getAlertResourceTableEmptyState');
expect(alertResourceTableRowSource).toContain('export function AlertResourceTableRow');
expect(alertResourceTableRowSource).toContain('alertResourceSupportsMetric');
expect(alertResourceTableRowSource).toContain('getAlertResourceTableOverrideNotePlaceholder');
- expect(alertResourceTableRowSource).toContain('getAlertResourceTableMetricInputTitle');
+ expect(alertResourceTableRowSource).toContain('AlertResourceMetricEditor');
+ expect(alertResourceMetricEditorSource).toContain('getAlertResourceTableMetricInputTitle');
+ expect(alertResourceMetricEditorSource).toContain('getAlertResourceTableMetricPlaceholder');
+ expect(alertResourceMetricEditorSource).toContain('getAlertResourceTableMetricOffToggleProps');
expect(alertResourceTableRowSource).toContain('getAlertResourceTableEditMetricTitle');
expect(alertResourceTableModelSource).toContain(
'export function normalizeAlertResourceMetricKey',