Camera profile support (#22482)

* add CameraProfileConfig model for named config overrides

* add profiles field to CameraConfig

* add active_profile field to FrigateConfig

Runtime-only field excluded from YAML serialization, tracks which
profile is currently active.

* add ProfileManager for profile activation and persistence

Handles snapshotting base configs, applying profile overrides via
deep_merge + apply_section_update, publishing ZMQ updates, and
persisting active profile to /config/.active_profile.

* add profile API endpoints (GET /profiles, GET/PUT /profile)

* add MQTT and dispatcher integration for profiles

- Subscribe to frigate/profile/set MQTT topic
- Publish profile/state and profiles/available on connect
- Add _on_profile_command handler to dispatcher
- Broadcast active profile state on WebSocket connect

* wire ProfileManager into app startup and FastAPI

- Create ProfileManager after dispatcher init
- Restore persisted profile on startup
- Pass dispatcher and profile_manager to FastAPI app

* add tests for invalid profile values and keys

Tests that Pydantic rejects: invalid field values (fps: "not_a_number"),
unknown section keys (ffmpeg in profile), invalid nested values, and
invalid profiles in full config parsing.

* formatting

* fix CameraLiveConfig JSON serialization error on profile activation

refactor _publish_updates to only publish ZMQ updates for
sections that actually changed, not all sections on affected cameras.

* consolidate

* add enabled field to camera profiles for enabling/disabling cameras

* add zones support to camera profiles

* add frontend profile types, color utility, and config save support

* add profile state management and save preview support

* add profileName prop to BaseSection for profile-aware config editing

* add profile section dropdown and wire into camera settings pages

* add per-profile camera enable/disable to Camera Management view

* add profiles summary page with card-based layout and fix backend zone comparison bug

* add active profile badge to settings toolbar

* i18n

* add red dot for any pending changes including profiles

* profile support for mask and zone editor

* fix hidden field validation errors caused by lodash wildcard and schema gaps

lodash unset does not support wildcard (*) segments, so hidden fields like
filters.*.mask were never stripped from form data, leaving null raw_coordinates
that fail RJSF anyOf validation. Add unsetWithWildcard helper and also strip
hidden fields from the JSON schema itself as defense-in-depth.

* add face_recognition and lpr to profile-eligible sections

* move profile dropdown from section panes to settings header

* add profiles enable toggle and improve empty state

* formatting

* tweaks

* tweak colors and switch

* fix profile save diff, masksAndZones delete, and config sync

* ui tweaks

* ensure profile manager gets updated config

* rename profile settings to ui settings

* refactor profilesview and add dots/border colors when overridden

* implement an update_config method for profile manager

* fix mask deletion

* more unique colors

* add top-level profiles config section with friendly names

* implement profile friendly names and improve profile UI

- Add ProfileDefinitionConfig type and profiles field to FrigateConfig
- Use ProfilesApiResponse type with friendly_name support throughout
- Replace Record<string, unknown> with proper JsonObject/JsonValue types
- Add profile creation form matching zone pattern (Zod + NameAndIdFields)
- Add pencil icon for renaming profile friendly names in ProfilesView
- Move Profiles menu item to first under Camera Configuration
- Add activity indicators on save/rename/delete buttons
- Display friendly names in CameraManagementView profile selector
- Fix duplicate colored dots in management profile dropdown
- Fix i18n namespace for overridden base config tooltips
- Move profile override deletion from dropdown trash icon to footer
  button with confirmation dialog, matching Reset to Global pattern
- Remove Add Profile from section header dropdown to prevent saving
  camera overrides before top-level profile definition exists
- Clean up newProfiles state after API profile deletion
- Refresh profiles SWR cache after saving profile definitions

* remove profile badge in settings and add profiles to main menu

* use icon only on mobile

* change color order

* docs

* show activity indicator on trash icon while deleting a profile

* tweak language

* immediately create profiles on backend instead of deferring to Save All

* hide restart-required fields when editing a profile section

fields that require a restart cannot take effect via profile switching,
so they are merged into hiddenFields when profileName is set

* show active profile indicator in desktop status bar

* fix profile config inheritance bug where Pydantic defaults override base values

The /config API was dumping profile overrides with model_dump() which included
all Pydantic defaults. When the frontend merged these over
the camera's base config, explicitly-set base values were
lost. Now profile overrides are re-dumped with exclude_unset=True so only
user-specified fields are returned.

Also fixes the Save All path generating spurious deletion markers for
restart-required fields that are hidden during profile
editing but not excluded from the raw data sanitization in
prepareSectionSavePayload.

* docs tweaks

* docs tweak

* formatting

* formatting

* fix typing

* fix test pollution

test_maintainer was injecting MagicMock() into sys.modules["frigate.config.camera.updater"] at module load time and never restoring it. When the profile tests later imported CameraConfigUpdateEnum and CameraConfigUpdateTopic from that module, they got mock objects instead of the real dataclass/enum, so equality comparisons always failed

* remove

* fix settings showing profile-merged values when editing base config

When a profile is active, the in-memory config contains effective
(profile-merged) values. The settings UI was displaying these merged
values even when the "Base Config" view was selected.

Backend: snapshot pre-profile base configs in ProfileManager and expose
them via a `base_config` key in the /api/config camera response when a
profile is active. The top-level sections continue to reflect the
effective running config.

Frontend: read from `base_config` when available in BaseSection,
useConfigOverride, useAllCameraOverrides, and prepareSectionSavePayload.
Include formData labels in Object/Audio switches widgets so that labels
added only by a profile override remain visible when editing that profile.

* use rasterized_mask as field

makes it easier to exclude from the schema with exclude=True
prevents leaking of the field when using model_dump for profiles

* fix zones

- Fix zone colors not matching across profiles by falling back to base zone color when profile zone data lacks a color field
- Use base_config for base-layer values in masks/zones view so profile-merged values don't pollute the base config editing view
- Handle zones separately in profile manager snapshot/restore since ZoneConfig requires special serialization (color as private attr, contour generation)
- Inherit base zone color and generate contours for profile zone overrides in profile manager

* formatting

* don't require restart for camera enabled change for profiles

* publish camera state when changing profiles

* formatting

* remove available profiles from mqtt

* improve typing
This commit is contained in:
Josh Hawkins
2026-03-19 09:47:57 -05:00
committed by GitHub
parent a05f35c747
commit c93dad9bd9
47 changed files with 4591 additions and 458 deletions
@@ -26,13 +26,25 @@ import axios from "axios";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
import type { ProfileState } from "@/types/profile";
import { getProfileColor } from "@/utils/profileColors";
import { cn } from "@/lib/utils";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
type CameraManagementViewProps = {
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
profileState?: ProfileState;
};
export default function CameraManagementView({
setUnsavedChanges,
profileState,
}: CameraManagementViewProps) {
const { t } = useTranslation(["views/settings"]);
@@ -200,6 +212,17 @@ export default function CameraManagementView({
)}
</SettingsGroupCard>
)}
{profileState &&
profileState.allProfileNames.length > 0 &&
enabledCameras.length > 0 && (
<ProfileCameraEnableSection
profileState={profileState}
cameras={enabledCameras}
config={config}
onConfigChanged={updateConfig}
/>
)}
</div>
</>
) : (
@@ -364,3 +387,192 @@ function CameraConfigEnableSwitch({
</div>
);
}
type ProfileCameraEnableSectionProps = {
profileState: ProfileState;
cameras: string[];
config: FrigateConfig | undefined;
onConfigChanged: () => Promise<unknown>;
};
function ProfileCameraEnableSection({
profileState,
cameras,
config,
onConfigChanged,
}: ProfileCameraEnableSectionProps) {
const { t } = useTranslation(["views/settings", "common"]);
const [selectedProfile, setSelectedProfile] = useState<string>(
profileState.allProfileNames[0] ?? "",
);
const [savingCamera, setSavingCamera] = useState<string | null>(null);
// Optimistic local state: the parsed config API doesn't reflect profile
// enabled changes until Frigate restarts, so we track saved values locally.
const [localOverrides, setLocalOverrides] = useState<
Record<string, Record<string, string>>
>({});
const handleEnabledChange = useCallback(
async (camera: string, value: string) => {
setSavingCamera(camera);
try {
const enabledValue =
value === "enabled" ? true : value === "disabled" ? false : null;
const configData =
enabledValue === null
? {
cameras: {
[camera]: {
profiles: { [selectedProfile]: { enabled: "" } },
},
},
}
: {
cameras: {
[camera]: {
profiles: { [selectedProfile]: { enabled: enabledValue } },
},
},
};
await axios.put("config/set", {
requires_restart: 0,
config_data: configData,
});
await onConfigChanged();
setLocalOverrides((prev) => ({
...prev,
[selectedProfile]: {
...prev[selectedProfile],
[camera]: value,
},
}));
toast.success(t("toast.save.success", { ns: "common" }), {
position: "top-center",
});
} catch {
toast.error(t("toast.save.error.title", { ns: "common" }), {
position: "top-center",
});
} finally {
setSavingCamera(null);
}
},
[selectedProfile, onConfigChanged, t],
);
const getEnabledState = useCallback(
(camera: string): string => {
// Check optimistic local state first
const localValue = localOverrides[selectedProfile]?.[camera];
if (localValue) return localValue;
const profileData =
config?.cameras?.[camera]?.profiles?.[selectedProfile];
if (!profileData || profileData.enabled === undefined) return "inherit";
return profileData.enabled ? "enabled" : "disabled";
},
[config, selectedProfile, localOverrides],
);
if (!selectedProfile) return null;
return (
<SettingsGroupCard
title={t("cameraManagement.profiles.title", {
ns: "views/settings",
})}
>
<div className={SPLIT_ROW_CLASS_NAME}>
<div className="space-y-1.5">
<Label>
{t("cameraManagement.profiles.selectLabel", {
ns: "views/settings",
})}
</Label>
<p className="text-sm text-muted-foreground">
{t("cameraManagement.profiles.description", {
ns: "views/settings",
})}
</p>
</div>
<div className={`${CONTROL_COLUMN_CLASS_NAME} space-y-4`}>
<Select value={selectedProfile} onValueChange={setSelectedProfile}>
<SelectTrigger className="w-full max-w-[200px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{profileState.allProfileNames.map((profile) => {
const color = getProfileColor(
profile,
profileState.allProfileNames,
);
return (
<SelectItem key={profile} value={profile}>
<div className="flex items-center gap-2">
<span
className={cn(
"h-2 w-2 shrink-0 rounded-full",
color.dot,
)}
/>
{profileState.profileFriendlyNames.get(profile) ??
profile}
</div>
</SelectItem>
);
})}
</SelectContent>
</Select>
<div className="max-w-md space-y-2 rounded-lg bg-secondary p-4">
{cameras.map((camera) => {
const state = getEnabledState(camera);
const isSaving = savingCamera === camera;
return (
<div
key={camera}
className="flex flex-row items-center justify-between"
>
<CameraNameLabel camera={camera} />
{isSaving ? (
<ActivityIndicator className="h-5 w-20" size={16} />
) : (
<Select
value={state}
onValueChange={(v) => handleEnabledChange(camera, v)}
>
<SelectTrigger className="h-7 w-[120px] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="inherit">
{t("cameraManagement.profiles.inherit", {
ns: "views/settings",
})}
</SelectItem>
<SelectItem value="enabled">
{t("cameraManagement.profiles.enabled", {
ns: "views/settings",
})}
</SelectItem>
<SelectItem value="disabled">
{t("cameraManagement.profiles.disabled", {
ns: "views/settings",
})}
</SelectItem>
</SelectContent>
</Select>
)}
</div>
);
})}
</div>
</div>
</div>
</SettingsGroupCard>
);
}
+312 -40
View File
@@ -1,4 +1,4 @@
import { FrigateConfig } from "@/types/frigateConfig";
import { CameraConfig, FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -35,17 +35,19 @@ import { useTranslation } from "react-i18next";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { cn } from "@/lib/utils";
import { ProfileState } from "@/types/profile";
type MasksAndZoneViewProps = {
selectedCamera: string;
selectedZoneMask?: PolygonType[];
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
profileState?: ProfileState;
};
export default function MasksAndZonesView({
selectedCamera,
selectedZoneMask,
setUnsavedChanges,
profileState,
}: MasksAndZoneViewProps) {
const { t } = useTranslation(["views/settings"]);
const { getLocaleDocUrl } = useDocDomain();
@@ -70,6 +72,10 @@ export default function MasksAndZonesView({
const [activeLine, setActiveLine] = useState<number | undefined>();
const [snapPoints, setSnapPoints] = useState(false);
// Profile state
const currentEditingProfile =
profileState?.editingProfile[selectedCamera] ?? null;
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
@@ -228,18 +234,94 @@ export default function MasksAndZonesView({
[allPolygons, scaledHeight, scaledWidth, t],
);
// Helper to dim colors for base polygons in profile mode
const dimColor = useCallback(
(color: number[]): number[] => {
if (!currentEditingProfile) return color;
return color.map((c) => Math.round(c * 0.4 + 153 * 0.6));
},
[currentEditingProfile],
);
useEffect(() => {
if (cameraConfig && containerRef.current && scaledWidth && scaledHeight) {
const zones = Object.entries(cameraConfig.zones).map(
([name, zoneData], index) => ({
const profileData = currentEditingProfile
? cameraConfig.profiles?.[currentEditingProfile]
: undefined;
// When a profile is active, the top-level sections contain
// effective (profile-merged) values. Use base_config for the
// original base values so the "Base Config" view is accurate and
// the base layer for profile merging is correct.
const baseMotion = (cameraConfig.base_config?.motion ??
cameraConfig.motion) as typeof cameraConfig.motion;
const baseObjects = (cameraConfig.base_config?.objects ??
cameraConfig.objects) as typeof cameraConfig.objects;
const baseZones = (cameraConfig.base_config?.zones ??
cameraConfig.zones) as typeof cameraConfig.zones;
// Build base zone names set for source tracking
const baseZoneNames = new Set(Object.keys(baseZones));
const profileZoneNames = new Set(Object.keys(profileData?.zones ?? {}));
const baseMotionMaskNames = new Set(Object.keys(baseMotion.mask || {}));
const profileMotionMaskNames = new Set(
Object.keys(profileData?.motion?.mask ?? {}),
);
const baseGlobalObjectMaskNames = new Set(
Object.keys(baseObjects.mask || {}),
);
const profileGlobalObjectMaskNames = new Set(
Object.keys(profileData?.objects?.mask ?? {}),
);
// Merge zones: profile zones override base zones with same name
const mergedZones = new Map<
string,
{
data: CameraConfig["zones"][string];
source: "base" | "profile" | "override";
}
>();
for (const [name, zoneData] of Object.entries(baseZones)) {
if (currentEditingProfile && profileZoneNames.has(name)) {
// Profile overrides this base zone
mergedZones.set(name, {
data: profileData!.zones![name]!,
source: "override",
});
} else {
mergedZones.set(name, {
data: zoneData,
source: currentEditingProfile ? "base" : "base",
});
}
}
// Add profile-only zones
if (profileData?.zones) {
for (const [name, zoneData] of Object.entries(profileData.zones)) {
if (!baseZoneNames.has(name)) {
mergedZones.set(name, { data: zoneData!, source: "profile" });
}
}
}
let zoneIndex = 0;
const zones: Polygon[] = [];
for (const [name, { data: zoneData, source }] of mergedZones) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = zoneData.color ??
baseZones[name]?.color ?? [128, 128, 0];
zones.push({
type: "zone" as PolygonType,
typeIndex: index,
typeIndex: zoneIndex,
camera: cameraConfig.name,
name,
friendly_name: zoneData.friendly_name,
enabled: zoneData.enabled,
enabled_in_config: zoneData.enabled_in_config,
objects: zoneData.objects,
objects: zoneData.objects ?? [],
points: interpolatePoints(
parseCoordinates(zoneData.coordinates),
1,
@@ -248,21 +330,60 @@ export default function MasksAndZonesView({
scaledHeight,
),
distances:
zoneData.distances?.map((distance) => parseFloat(distance)) ?? [],
zoneData.distances?.map((distance: string) =>
parseFloat(distance),
) ?? [],
isFinished: true,
color: zoneData.color,
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
zoneIndex++;
}
let motionMasks: Polygon[] = [];
let globalObjectMasks: Polygon[] = [];
let objectMasks: Polygon[] = [];
// Merge motion masks
const mergedMotionMasks = new Map<
string,
{
data: CameraConfig["motion"]["mask"][string];
source: "base" | "profile" | "override";
}
>();
// Motion masks are a dict with mask_id as key
motionMasks = Object.entries(cameraConfig.motion.mask || {}).map(
([maskId, maskData], index) => ({
for (const [maskId, maskData] of Object.entries(baseMotion.mask || {})) {
if (currentEditingProfile && profileMotionMaskNames.has(maskId)) {
mergedMotionMasks.set(maskId, {
data: profileData!.motion!.mask![maskId],
source: "override",
});
} else {
mergedMotionMasks.set(maskId, {
data: maskData,
source: currentEditingProfile ? "base" : "base",
});
}
}
if (profileData?.motion?.mask) {
for (const [maskId, maskData] of Object.entries(
profileData.motion.mask,
)) {
if (!baseMotionMaskNames.has(maskId)) {
mergedMotionMasks.set(maskId, {
data: maskData,
source: "profile",
});
}
}
}
let motionMaskIndex = 0;
const motionMasks: Polygon[] = [];
for (const [maskId, { data: maskData, source }] of mergedMotionMasks) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = [0, 0, 255];
motionMasks.push({
type: "motion_mask" as PolygonType,
typeIndex: index,
typeIndex: motionMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
@@ -278,15 +399,59 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [0, 0, 255],
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
motionMaskIndex++;
}
// Global object masks are a dict with mask_id as key
globalObjectMasks = Object.entries(cameraConfig.objects.mask || {}).map(
([maskId, maskData], index) => ({
// Merge global object masks
const mergedGlobalObjectMasks = new Map<
string,
{
data: CameraConfig["objects"]["mask"][string];
source: "base" | "profile" | "override";
}
>();
for (const [maskId, maskData] of Object.entries(baseObjects.mask || {})) {
if (currentEditingProfile && profileGlobalObjectMaskNames.has(maskId)) {
mergedGlobalObjectMasks.set(maskId, {
data: profileData!.objects!.mask![maskId],
source: "override",
});
} else {
mergedGlobalObjectMasks.set(maskId, {
data: maskData,
source: currentEditingProfile ? "base" : "base",
});
}
}
if (profileData?.objects?.mask) {
for (const [maskId, maskData] of Object.entries(
profileData.objects.mask,
)) {
if (!baseGlobalObjectMaskNames.has(maskId)) {
mergedGlobalObjectMasks.set(maskId, {
data: maskData,
source: "profile",
});
}
}
}
let objectMaskIndex = 0;
const globalObjectMasks: Polygon[] = [];
for (const [
maskId,
{ data: maskData, source },
] of mergedGlobalObjectMasks) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = [128, 128, 128];
globalObjectMasks.push({
type: "object_mask" as PolygonType,
typeIndex: index,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
@@ -302,13 +467,41 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [128, 128, 128],
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
objectMaskIndex++;
}
let objectMaskIndex = globalObjectMasks.length;
objectMaskIndex = globalObjectMasks.length;
objectMasks = Object.entries(cameraConfig.objects.filters)
// Build per-object filter mask names for profile tracking
const baseFilterMaskNames = new Set<string>();
for (const [, filterConfig] of Object.entries(
baseObjects.filters || {},
)) {
for (const maskId of Object.keys(filterConfig.mask || {})) {
if (!maskId.startsWith("global_")) {
baseFilterMaskNames.add(maskId);
}
}
}
const profileFilterMaskNames = new Set<string>();
if (profileData?.objects?.filters) {
for (const [, filterConfig] of Object.entries(
profileData.objects.filters,
)) {
if (filterConfig?.mask) {
for (const maskId of Object.keys(filterConfig.mask)) {
profileFilterMaskNames.add(maskId);
}
}
}
}
// Per-object filter masks (base)
const objectMasks: Polygon[] = Object.entries(baseObjects.filters || {})
.filter(
([, filterConfig]) =>
filterConfig.mask && Object.keys(filterConfig.mask).length > 0,
@@ -316,22 +509,36 @@ export default function MasksAndZonesView({
.flatMap(([objectName, filterConfig]): Polygon[] => {
return Object.entries(filterConfig.mask || {}).flatMap(
([maskId, maskData]) => {
// Skip if this mask is a global mask (prefixed with "global_")
if (maskId.startsWith("global_")) {
return [];
}
const newMask = {
const source: "base" | "override" = currentEditingProfile
? profileFilterMaskNames.has(maskId)
? "override"
: "base"
: "base";
const isBase = source === "base" && !!currentEditingProfile;
// If override, use profile data
const finalData =
source === "override" && profileData?.objects?.filters
? (profileData.objects.filters[objectName]?.mask?.[maskId] ??
maskData)
: maskData;
const baseColor = [128, 128, 128];
const newMask: Polygon = {
type: "object_mask" as PolygonType,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
enabled: maskData.enabled,
enabled_in_config: maskData.enabled_in_config,
friendly_name: finalData.friendly_name,
enabled: finalData.enabled,
enabled_in_config: finalData.enabled_in_config,
objects: [objectName],
points: interpolatePoints(
parseCoordinates(maskData.coordinates),
parseCoordinates(finalData.coordinates),
1,
1,
scaledWidth,
@@ -339,7 +546,8 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [128, 128, 128],
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
};
objectMaskIndex++;
return [newMask];
@@ -347,6 +555,45 @@ export default function MasksAndZonesView({
);
});
// Add profile-only per-object filter masks
if (profileData?.objects?.filters) {
for (const [objectName, filterConfig] of Object.entries(
profileData.objects.filters,
)) {
if (filterConfig?.mask) {
for (const [maskId, maskData] of Object.entries(
filterConfig.mask,
)) {
if (!baseFilterMaskNames.has(maskId) && maskData) {
const baseColor = [128, 128, 128];
objectMasks.push({
type: "object_mask" as PolygonType,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
enabled: maskData.enabled,
enabled_in_config: maskData.enabled_in_config,
objects: [objectName],
points: interpolatePoints(
parseCoordinates(maskData.coordinates),
1,
1,
scaledWidth,
scaledHeight,
),
distances: [],
isFinished: true,
color: baseColor,
polygonSource: "profile",
});
objectMaskIndex++;
}
}
}
}
}
setAllPolygons([
...zones,
...motionMasks,
@@ -386,7 +633,14 @@ export default function MasksAndZonesView({
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cameraConfig, containerRef, scaledHeight, scaledWidth]);
}, [
cameraConfig,
containerRef,
scaledHeight,
scaledWidth,
currentEditingProfile,
dimColor,
]);
useEffect(() => {
if (editPane === undefined) {
@@ -403,6 +657,15 @@ export default function MasksAndZonesView({
}
}, [selectedCamera]);
// Cancel editing when profile selection changes
useEffect(() => {
if (editPaneRef.current !== undefined) {
handleCancel();
}
// we only want to react to profile changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentEditingProfile]);
useSearchEffect("object_mask", (coordinates: string) => {
if (!scaledWidth || !scaledHeight || isLoading) {
return false;
@@ -473,6 +736,7 @@ export default function MasksAndZonesView({
setActiveLine={setActiveLine}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane == "motion_mask" && (
@@ -488,6 +752,7 @@ export default function MasksAndZonesView({
onSave={handleSave}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane == "object_mask" && (
@@ -503,13 +768,14 @@ export default function MasksAndZonesView({
onSave={handleSave}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane === undefined && (
<>
<Heading as="h4" className="mb-2">
{t("menu.masksAndZones")}
</Heading>
<div className="mb-2 flex items-center justify-between">
<Heading as="h4">{t("menu.masksAndZones")}</Heading>
</div>
<div className="flex w-full flex-col">
{(selectedZoneMask === undefined ||
selectedZoneMask.includes("zone" as PolygonType)) && (
@@ -575,6 +841,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>
@@ -649,6 +917,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>
@@ -723,6 +993,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>
+733
View File
@@ -0,0 +1,733 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import useSWR from "swr";
import axios from "axios";
import { toast } from "sonner";
import { Pencil, Trash2 } from "lucide-react";
import { LuChevronDown, LuChevronRight, LuPlus } from "react-icons/lu";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { JsonObject } from "@/types/configForm";
import type { ProfileState, ProfilesApiResponse } from "@/types/profile";
import { getProfileColor } from "@/utils/profileColors";
import { PROFILE_ELIGIBLE_SECTIONS } from "@/utils/configUtil";
import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
import { cn } from "@/lib/utils";
import Heading from "@/components/ui/heading";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import NameAndIdFields from "@/components/input/NameAndIdFields";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import ActivityIndicator from "@/components/indicators/activity-indicator";
type ProfilesViewProps = {
setUnsavedChanges?: React.Dispatch<React.SetStateAction<boolean>>;
profileState?: ProfileState;
profilesUIEnabled?: boolean;
setProfilesUIEnabled?: React.Dispatch<React.SetStateAction<boolean>>;
};
export default function ProfilesView({
profileState,
profilesUIEnabled,
setProfilesUIEnabled,
}: ProfilesViewProps) {
const { t } = useTranslation(["views/settings", "common"]);
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");
const { data: profilesData, mutate: updateProfiles } =
useSWR<ProfilesApiResponse>("profiles");
const [activating, setActivating] = useState(false);
const [deleteProfile, setDeleteProfile] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [renameProfile, setRenameProfile] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [renaming, setRenaming] = useState(false);
const [expandedProfiles, setExpandedProfiles] = useState<Set<string>>(
new Set(),
);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const allProfileNames = useMemo(
() => profileState?.allProfileNames ?? [],
[profileState?.allProfileNames],
);
const addProfileSchema = useMemo(
() =>
z.object({
name: z
.string()
.min(2, {
message: t("profiles.error.mustBeAtLeastTwoCharacters", {
ns: "views/settings",
}),
})
.refine((value) => !value.includes("."), {
message: t("profiles.error.mustNotContainPeriod", {
ns: "views/settings",
}),
})
.refine((value) => !allProfileNames.includes(value), {
message: t("profiles.error.alreadyExists", {
ns: "views/settings",
}),
}),
friendly_name: z.string().min(2, {
message: t("profiles.error.mustBeAtLeastTwoCharacters", {
ns: "views/settings",
}),
}),
}),
[t, allProfileNames],
);
type AddProfileForm = z.infer<typeof addProfileSchema>;
const addForm = useForm<AddProfileForm>({
resolver: zodResolver(addProfileSchema),
defaultValues: { friendly_name: "", name: "" },
});
const profileFriendlyNames = profileState?.profileFriendlyNames;
useEffect(() => {
document.title = t("documentTitle.profiles", {
ns: "views/settings",
});
}, [t]);
const activeProfile = profilesData?.active_profile ?? null;
// Build overview data: for each profile, which cameras have which sections
const profileOverviewData = useMemo(() => {
if (!config || allProfileNames.length === 0) return {};
const data: Record<string, Record<string, string[]>> = {};
const cameras = Object.keys(config.cameras).sort();
for (const profile of allProfileNames) {
data[profile] = {};
for (const camera of cameras) {
const profileData = config.cameras[camera]?.profiles?.[profile];
if (!profileData) continue;
const sections: string[] = [];
for (const section of PROFILE_ELIGIBLE_SECTIONS) {
if (
profileData[section as keyof typeof profileData] !== undefined &&
profileData[section as keyof typeof profileData] !== null
) {
sections.push(section);
}
}
if (profileData.enabled !== undefined && profileData.enabled !== null) {
sections.push("enabled");
}
if (sections.length > 0) {
data[profile][camera] = sections;
}
}
}
return data;
}, [config, allProfileNames]);
const [addingProfile, setAddingProfile] = useState(false);
const handleAddSubmit = useCallback(
async (data: AddProfileForm) => {
const id = data.name.trim();
const friendlyName = data.friendly_name.trim();
if (!id || !friendlyName) return;
setAddingProfile(true);
try {
await axios.put("config/set", {
requires_restart: 0,
config_data: {
profiles: { [id]: { friendly_name: friendlyName } },
},
});
await updateConfig();
await updateProfiles();
toast.success(
t("profiles.createSuccess", {
ns: "views/settings",
profile: friendlyName,
}),
{ position: "top-center" },
);
setAddDialogOpen(false);
addForm.reset();
} catch {
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
position: "top-center",
});
} finally {
setAddingProfile(false);
}
},
[updateConfig, updateProfiles, addForm, t],
);
const handleActivateProfile = useCallback(
async (profile: string | null) => {
setActivating(true);
try {
await axios.put("profile/set", {
profile: profile || null,
});
await updateProfiles();
toast.success(
profile
? t("profiles.activated", {
ns: "views/settings",
profile: profileFriendlyNames?.get(profile) ?? profile,
})
: t("profiles.deactivated", { ns: "views/settings" }),
{ position: "top-center" },
);
} catch (err) {
const message =
axios.isAxiosError(err) && err.response?.data?.message
? String(err.response.data.message)
: undefined;
toast.error(
message || t("profiles.activateFailed", { ns: "views/settings" }),
{ position: "top-center" },
);
} finally {
setActivating(false);
}
},
[updateProfiles, profileFriendlyNames, t],
);
const handleDeleteProfile = useCallback(async () => {
if (!deleteProfile || !config) return;
setDeleting(true);
try {
// If this profile is active, deactivate it first
if (activeProfile === deleteProfile) {
await axios.put("profile/set", { profile: null });
}
// Remove the profile from all cameras and the top-level definition
const cameraData: JsonObject = {};
for (const camera of Object.keys(config.cameras)) {
if (config.cameras[camera]?.profiles?.[deleteProfile]) {
cameraData[camera] = {
profiles: { [deleteProfile]: "" },
};
}
}
const configData: JsonObject = {
profiles: { [deleteProfile]: "" },
};
if (Object.keys(cameraData).length > 0) {
configData.cameras = cameraData;
}
await axios.put("config/set", {
requires_restart: 0,
config_data: configData,
});
await updateConfig();
await updateProfiles();
toast.success(
t("profiles.deleteSuccess", {
ns: "views/settings",
profile: profileFriendlyNames?.get(deleteProfile) ?? deleteProfile,
}),
{ position: "top-center" },
);
} catch (err) {
const errorMessage =
axios.isAxiosError(err) && err.response?.data?.message
? String(err.response.data.message)
: undefined;
toast.error(
errorMessage || t("toast.save.error.noMessage", { ns: "common" }),
{ position: "top-center" },
);
} finally {
setDeleting(false);
setDeleteProfile(null);
}
}, [
deleteProfile,
activeProfile,
config,
profileFriendlyNames,
updateConfig,
updateProfiles,
t,
]);
const toggleExpanded = useCallback((profile: string) => {
setExpandedProfiles((prev) => {
const next = new Set(prev);
if (next.has(profile)) {
next.delete(profile);
} else {
next.add(profile);
}
return next;
});
}, []);
const handleRename = useCallback(async () => {
if (!renameProfile || !renameValue.trim()) return;
setRenaming(true);
try {
await axios.put("config/set", {
requires_restart: 0,
config_data: {
profiles: {
[renameProfile]: { friendly_name: renameValue.trim() },
},
},
});
await updateConfig();
await updateProfiles();
toast.success(
t("profiles.renameSuccess", {
ns: "views/settings",
profile: renameValue.trim(),
}),
{ position: "top-center" },
);
} catch {
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
position: "top-center",
});
} finally {
setRenaming(false);
setRenameProfile(null);
}
}, [renameProfile, renameValue, updateConfig, updateProfiles, t]);
if (!config || !profilesData) {
return null;
}
const hasProfiles = allProfileNames.length > 0;
return (
<div className="flex size-full max-w-5xl flex-col lg:pr-2">
<Heading as="h4">{t("profiles.title", { ns: "views/settings" })}</Heading>
<div className="my-1 text-sm text-muted-foreground">
{t("profiles.disabledDescription", { ns: "views/settings" })}
</div>
{/* Enable Profiles Toggle — shown only when no profiles exist */}
{!hasProfiles && setProfilesUIEnabled && (
<div className="my-6 max-w-xl rounded-lg border border-border/70 bg-card/30 p-4">
<div className="flex items-center justify-between">
<Label htmlFor="profiles-toggle" className="cursor-pointer">
{t("profiles.enableSwitch", { ns: "views/settings" })}
</Label>
<Switch
id="profiles-toggle"
checked={profilesUIEnabled ?? false}
onCheckedChange={setProfilesUIEnabled}
/>
</div>
</div>
)}
{profilesUIEnabled && !hasProfiles && (
<p className="mb-5 max-w-xl text-sm text-primary-variant">
{t("profiles.enabledDescription", { ns: "views/settings" })}
</p>
)}
{/* Active Profile + Add Profile bar */}
{(hasProfiles || profilesUIEnabled) && (
<div className="my-4 flex items-center justify-between rounded-lg border border-border/70 bg-card/30 p-4">
{hasProfiles && (
<div className="flex items-center gap-3">
<span className="text-sm font-semibold text-primary-variant">
{t("profiles.activeProfile", { ns: "views/settings" })}
</span>
<Select
value={activeProfile ?? "__none__"}
onValueChange={(v) =>
handleActivateProfile(v === "__none__" ? null : v)
}
disabled={activating}
>
<SelectTrigger className="">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">
{t("profiles.noActiveProfile", { ns: "views/settings" })}
</SelectItem>
{allProfileNames.map((profile) => {
const color = getProfileColor(profile, allProfileNames);
return (
<SelectItem key={profile} value={profile}>
<div className="flex items-center gap-2">
<span
className={cn(
"h-2 w-2 shrink-0 rounded-full",
color.dot,
)}
/>
{profileFriendlyNames?.get(profile) ?? profile}
</div>
</SelectItem>
);
})}
</SelectContent>
</Select>
{activating && <ActivityIndicator className="size-4" />}
</div>
)}
<Button
variant="default"
size="sm"
onClick={() => setAddDialogOpen(true)}
>
<LuPlus className="mr-1.5 size-4" />
{t("profiles.addProfile", { ns: "views/settings" })}
</Button>
</div>
)}
{/* Profile List */}
{!hasProfiles ? (
profilesUIEnabled ? (
<p className="text-sm text-muted-foreground">
{t("profiles.noProfiles", { ns: "views/settings" })}
</p>
) : (
<div />
)
) : (
<div className="flex flex-col gap-2">
{allProfileNames.map((profile) => {
const color = getProfileColor(profile, allProfileNames);
const isActive = activeProfile === profile;
const cameraData = profileOverviewData[profile] ?? {};
const cameras = Object.keys(cameraData).sort();
const isExpanded = expandedProfiles.has(profile);
return (
<Collapsible
key={profile}
open={isExpanded}
onOpenChange={() => toggleExpanded(profile)}
>
<div
className={cn(
"rounded-lg border",
isActive
? "border-selected bg-selected/5"
: "border-border/70",
)}
>
<CollapsibleTrigger asChild>
<div className="flex cursor-pointer items-center justify-between px-4 py-3 hover:bg-secondary/30">
<div className="flex items-center gap-3">
{isExpanded ? (
<LuChevronDown className="size-4 text-muted-foreground" />
) : (
<LuChevronRight className="size-4 text-muted-foreground" />
)}
<span
className={cn(
"size-2.5 shrink-0 rounded-full",
color.dot,
)}
/>
<span className="font-medium">
{profileFriendlyNames?.get(profile) ?? profile}
</span>
<Button
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-primary"
onClick={(e) => {
e.stopPropagation();
setRenameProfile(profile);
setRenameValue(
profileFriendlyNames?.get(profile) ?? profile,
);
}}
>
<Pencil className="size-3" />
</Button>
{isActive && (
<Badge
variant="secondary"
className="text-xs text-primary-variant"
>
{t("profiles.active", { ns: "views/settings" })}
</Badge>
)}
</div>
<div className="flex items-center gap-3">
<span className="text-sm text-muted-foreground">
{cameras.length > 0
? t("profiles.cameraCount", {
ns: "views/settings",
count: cameras.length,
})
: t("profiles.noOverrides", {
ns: "views/settings",
})}
</span>
<Button
variant="ghost"
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
disabled={deleting && deleteProfile === profile}
onClick={(e) => {
e.stopPropagation();
setDeleteProfile(profile);
}}
>
{deleting && deleteProfile === profile ? (
<ActivityIndicator className="size-4" />
) : (
<Trash2 className="size-4" />
)}
</Button>
</div>
</div>
</CollapsibleTrigger>
<CollapsibleContent>
{cameras.length > 0 ? (
<div className="mx-4 mb-3 ml-11 border-l border-border/50 pl-4">
{cameras.map((camera) => {
const sections = cameraData[camera];
return (
<div
key={camera}
className="flex items-baseline gap-3 py-1.5"
>
<span className="min-w-[120px] shrink-0 truncate text-sm font-medium">
{resolveCameraName(config, camera)}
</span>
<span className="text-sm text-muted-foreground">
{sections
.map((section) =>
t(`configForm.sections.${section}`, {
ns: "views/settings",
defaultValue: section,
}),
)
.join(", ")}
</span>
</div>
);
})}
</div>
) : (
<div className="mx-4 mb-3 ml-11 text-sm text-muted-foreground">
{t("profiles.noOverrides", { ns: "views/settings" })}
</div>
)}
</CollapsibleContent>
</div>
</Collapsible>
);
})}
</div>
)}
{/* Add Profile Dialog */}
<Dialog
open={addDialogOpen}
onOpenChange={(open) => {
setAddDialogOpen(open);
if (!open) {
addForm.reset();
}
}}
>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>
{t("profiles.newProfile", { ns: "views/settings" })}
</DialogTitle>
</DialogHeader>
<FormProvider {...addForm}>
<form
onSubmit={addForm.handleSubmit(handleAddSubmit)}
className="space-y-4 py-2"
>
<NameAndIdFields<AddProfileForm>
control={addForm.control}
type="profile"
nameField="friendly_name"
idField="name"
nameLabel={t("profiles.friendlyNameLabel", {
ns: "views/settings",
})}
idLabel={t("profiles.profileIdLabel", {
ns: "views/settings",
})}
idDescription={t("profiles.profileIdDescription", {
ns: "views/settings",
})}
placeholderName={t("profiles.profileNamePlaceholder", {
ns: "views/settings",
})}
/>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setAddDialogOpen(false)}
disabled={addingProfile}
>
{t("button.cancel", { ns: "common" })}
</Button>
<Button
type="submit"
variant="select"
disabled={
addingProfile ||
!addForm.watch("friendly_name").trim() ||
!addForm.watch("name").trim()
}
>
{addingProfile && (
<ActivityIndicator className="mr-2 size-4" />
)}
{t("button.add", { ns: "common" })}
</Button>
</DialogFooter>
</form>
</FormProvider>
</DialogContent>
</Dialog>
{/* Delete Profile Confirmation */}
<AlertDialog
open={!!deleteProfile}
onOpenChange={(open) => {
if (!open) setDeleteProfile(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("profiles.deleteProfile", { ns: "views/settings" })}
</AlertDialogTitle>
<AlertDialogDescription>
{t("profiles.deleteProfileConfirm", {
ns: "views/settings",
profile: deleteProfile
? (profileFriendlyNames?.get(deleteProfile) ?? deleteProfile)
: "",
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-white hover:bg-destructive/90"
onClick={(e) => {
e.preventDefault();
handleDeleteProfile();
}}
disabled={deleting}
>
{deleting && <ActivityIndicator className="mr-2 size-4" />}
{t("button.delete", { ns: "common" })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Rename Profile Dialog */}
<Dialog
open={!!renameProfile}
onOpenChange={(open) => {
if (!open) setRenameProfile(null);
}}
>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>
{t("profiles.renameProfile", { ns: "views/settings" })}
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
placeholder={t("profiles.profileNamePlaceholder", {
ns: "views/settings",
})}
/>
<DialogFooter>
<Button
variant="outline"
onClick={() => setRenameProfile(null)}
disabled={renaming}
>
{t("button.cancel", { ns: "common" })}
</Button>
<Button
variant="select"
onClick={handleRename}
disabled={renaming || !renameValue.trim()}
>
{renaming && <ActivityIndicator className="mr-2 size-4" />}
{t("button.save", { ns: "common" })}
</Button>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
</div>
);
}
+85 -10
View File
@@ -4,8 +4,16 @@ import type { SectionConfig } from "@/components/config-form/sections";
import { ConfigSectionTemplate } from "@/components/config-form/sections";
import type { PolygonType } from "@/types/canvas";
import { Badge } from "@/components/ui/badge";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import type { ConfigSectionData } from "@/types/configForm";
import type { ProfileState } from "@/types/profile";
import { getSectionConfig } from "@/utils/configUtil";
import { getProfileColor } from "@/utils/profileColors";
import { cn } from "@/lib/utils";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { Link } from "react-router-dom";
import { LuExternalLink } from "react-icons/lu";
@@ -20,17 +28,24 @@ export type SettingsPageProps = {
level: "global" | "camera",
status: SectionStatus,
) => void;
pendingDataBySection?: Record<string, unknown>;
pendingDataBySection?: Record<string, ConfigSectionData>;
onPendingDataChange?: (
sectionKey: string,
cameraName: string | undefined,
data: ConfigSectionData | null,
) => void;
profileState?: ProfileState;
/** Callback to delete the current profile's overrides for the current section */
onDeleteProfileSection?: (profileName: string) => void;
profilesUIEnabled?: boolean;
setProfilesUIEnabled?: React.Dispatch<React.SetStateAction<boolean>>;
};
export type SectionStatus = {
hasChanges: boolean;
isOverridden: boolean;
/** Where the override comes from: "global" = camera overrides global, "profile" = profile overrides base */
overrideSource?: "global" | "profile";
hasValidationErrors: boolean;
};
@@ -56,6 +71,8 @@ export function SingleSectionPage({
onSectionStatusChange,
pendingDataBySection,
onPendingDataChange,
profileState,
onDeleteProfileSection,
}: SingleSectionPageProps) {
const sectionNamespace =
level === "camera" ? "config/cameras" : "config/global";
@@ -78,6 +95,24 @@ export function SingleSectionPage({
? getLocaleDocUrl(resolvedSectionConfig.sectionDocs)
: undefined;
const currentEditingProfile = selectedCamera
? (profileState?.editingProfile[selectedCamera] ?? null)
: null;
const profileColor = useMemo(
() =>
currentEditingProfile && profileState?.allProfileNames
? getProfileColor(currentEditingProfile, profileState.allProfileNames)
: undefined,
[currentEditingProfile, profileState?.allProfileNames],
);
const handleDeleteProfileSection = useCallback(() => {
if (currentEditingProfile && onDeleteProfileSection) {
onDeleteProfileSection(currentEditingProfile);
}
}, [currentEditingProfile, onDeleteProfileSection]);
const handleSectionStatusChange = useCallback(
(status: SectionStatus) => {
setSectionStatus(status);
@@ -127,15 +162,44 @@ export function SingleSectionPage({
{level === "camera" &&
showOverrideIndicator &&
sectionStatus.isOverridden && (
<Badge
variant="secondary"
className="cursor-default border-2 border-selected text-xs text-primary-variant"
>
{t("button.overridden", {
ns: "common",
defaultValue: "Overridden",
})}
</Badge>
<Tooltip>
<TooltipTrigger asChild>
<Badge
variant="secondary"
className={cn(
"cursor-default border-2 text-center text-xs text-primary-variant",
sectionStatus.overrideSource === "profile" &&
profileColor
? profileColor.border
: "border-selected",
)}
>
{sectionStatus.overrideSource === "profile"
? t("button.overriddenBaseConfig", {
ns: "views/settings",
defaultValue: "Overridden (Base Config)",
})
: t("button.overriddenGlobal", {
ns: "views/settings",
defaultValue: "Overridden (Global)",
})}
</Badge>
</TooltipTrigger>
<TooltipContent>
{sectionStatus.overrideSource === "profile"
? t("button.overriddenBaseConfigTooltip", {
ns: "views/settings",
profile: currentEditingProfile
? (profileState?.profileFriendlyNames.get(
currentEditingProfile,
) ?? currentEditingProfile)
: "",
})
: t("button.overriddenGlobalTooltip", {
ns: "views/settings",
})}
</TooltipContent>
</Tooltip>
)}
{sectionStatus.hasChanges && (
<Badge
@@ -160,6 +224,17 @@ export function SingleSectionPage({
onPendingDataChange={onPendingDataChange}
requiresRestart={requiresRestart}
onStatusChange={handleSectionStatusChange}
profileName={currentEditingProfile ?? undefined}
profileFriendlyName={
currentEditingProfile
? (profileState?.profileFriendlyNames.get(currentEditingProfile) ??
currentEditingProfile)
: undefined
}
profileBorderColor={profileColor?.border}
onDeleteProfileSection={
currentEditingProfile ? handleDeleteProfileSection : undefined
}
/>
</div>
);
+3 -3
View File
@@ -212,10 +212,10 @@ export default function UiSettingsView() {
return (
<div className="flex size-full flex-col">
<Toaster position="top-center" closeButton={true} />
<Heading as="h4" className="mb-3">
{t("general.title")}
</Heading>
<div className="scrollbar-container mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2">
<Heading as="h4" className="mb-3">
{t("general.title")}
</Heading>
<div className="w-full max-w-5xl space-y-6">
<SettingsGroupCard title={t("general.liveDashboard.title")}>
<div className="space-y-6">