mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-16 10:33:00 +03:00
Merge branch 'dev' into feature/share-review-timestamp
This commit is contained in:
@@ -4,8 +4,12 @@ import {
|
||||
StatusMessage,
|
||||
} from "@/context/statusbar-provider";
|
||||
import useStats, { useAutoFrigateStats } from "@/hooks/use-stats";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ProfilesApiResponse } from "@/types/profile";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
import { useContext, useEffect, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { FaCheck } from "react-icons/fa";
|
||||
import { IoIosWarning } from "react-icons/io";
|
||||
@@ -46,6 +50,21 @@ export default function Statusbar() {
|
||||
});
|
||||
}, [potentialProblems, addMessage, clearMessages]);
|
||||
|
||||
const { data: profilesData } = useSWR<ProfilesApiResponse>("profiles");
|
||||
|
||||
const activeProfile = useMemo(() => {
|
||||
if (!profilesData?.active_profile || !profilesData.profiles) return null;
|
||||
const info = profilesData.profiles.find(
|
||||
(p) => p.name === profilesData.active_profile,
|
||||
);
|
||||
const allNames = profilesData.profiles.map((p) => p.name).sort();
|
||||
return {
|
||||
name: profilesData.active_profile,
|
||||
friendlyName: info?.friendly_name ?? profilesData.active_profile,
|
||||
color: getProfileColor(profilesData.active_profile, allNames),
|
||||
};
|
||||
}, [profilesData]);
|
||||
|
||||
const { payload: reindexState } = useEmbeddingsReindexProgress();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -136,6 +155,21 @@ export default function Statusbar() {
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{activeProfile && (
|
||||
<Link to="/settings?page=profiles">
|
||||
<div className="flex cursor-pointer items-center gap-2 text-sm hover:underline">
|
||||
<span
|
||||
className={cn(
|
||||
"size-2 shrink-0 rounded-full",
|
||||
activeProfile.color.dot,
|
||||
)}
|
||||
/>
|
||||
<span className="max-w-[150px] truncate">
|
||||
{activeProfile.friendlyName}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<div className="no-scrollbar flex h-full max-w-[50%] items-center gap-2 overflow-x-auto">
|
||||
{Object.entries(messages).length === 0 ? (
|
||||
|
||||
@@ -213,6 +213,7 @@ export function AnimatedEventCard({
|
||||
playsInline
|
||||
muted
|
||||
disableRemotePlayback
|
||||
disablePictureInPicture
|
||||
loop
|
||||
onTimeUpdate={() => {
|
||||
if (!isLoaded) {
|
||||
|
||||
@@ -11,7 +11,24 @@ import { baseUrl } from "@/api/baseUrl";
|
||||
import { isMobile } from "react-device-detect";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { TooltipPortal } from "@radix-ui/react-tooltip";
|
||||
import { IoIosWarning } from "react-icons/io";
|
||||
import { LuRefreshCw } from "react-icons/lu";
|
||||
|
||||
export type Step3FormData = {
|
||||
examplesGenerated: boolean;
|
||||
@@ -47,6 +64,7 @@ export default function Step3ChooseExamples({
|
||||
const [selectedImages, setSelectedImages] = useState<Set<string>>(new Set());
|
||||
const [cacheKey, setCacheKey] = useState<number>(Date.now());
|
||||
const [loadedImages, setLoadedImages] = useState<Set<string>>(new Set());
|
||||
const [showRefreshConfirm, setShowRefreshConfirm] = useState(false);
|
||||
|
||||
const handleImageLoad = useCallback((imageName: string) => {
|
||||
setLoadedImages((prev) => new Set(prev).add(imageName));
|
||||
@@ -484,8 +502,52 @@ export default function Step3ChooseExamples({
|
||||
}
|
||||
}, [currentClassIndex, allClasses, imageClassifications, onBack]);
|
||||
|
||||
const doRefresh = useCallback(() => {
|
||||
setCurrentClassIndex(0);
|
||||
setSelectedImages(new Set());
|
||||
setImageClassifications({});
|
||||
setLoadedImages(new Set());
|
||||
setShowRefreshConfirm(false);
|
||||
generateExamples();
|
||||
}, [generateExamples]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
if (Object.keys(imageClassifications).length > 0) {
|
||||
setShowRefreshConfirm(true);
|
||||
} else {
|
||||
doRefresh();
|
||||
}
|
||||
}, [imageClassifications, doRefresh]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<AlertDialog
|
||||
open={showRefreshConfirm}
|
||||
onOpenChange={setShowRefreshConfirm}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("wizard.step3.refreshConfirm.title")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("wizard.step3.refreshConfirm.description")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("button.cancel", { ns: "common" })}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={doRefresh}
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
>
|
||||
{t("button.continue", { ns: "common" })}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{isTraining ? (
|
||||
<div className="flex flex-col items-center gap-6 py-12">
|
||||
<ActivityIndicator className="size-12" />
|
||||
@@ -514,15 +576,43 @@ export default function Step3ChooseExamples({
|
||||
</div>
|
||||
</div>
|
||||
) : hasGenerated ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="relative flex flex-col gap-4">
|
||||
<Tooltip open={showRefreshConfirm ? false : undefined}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 size-8"
|
||||
onClick={handleRefresh}
|
||||
disabled={isGenerating || isProcessing}
|
||||
>
|
||||
<LuRefreshCw className="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>
|
||||
{t("wizard.step3.refreshExamples")}
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
{showMissingStatesWarning && (
|
||||
<Alert variant="destructive">
|
||||
<IoIosWarning className="size-5" />
|
||||
<AlertTitle>
|
||||
{t("wizard.step3.missingStatesWarning.title")}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
<AlertDescription className="flex flex-col gap-2">
|
||||
{t("wizard.step3.missingStatesWarning.description")}
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={handleRefresh}
|
||||
disabled={isGenerating || isProcessing}
|
||||
>
|
||||
<LuRefreshCw className="mr-1.5 size-3.5" />
|
||||
{t("wizard.step3.refreshExamples")}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -13,7 +13,7 @@ const audio: SectionConfigOverrides = {
|
||||
"num_threads",
|
||||
],
|
||||
fieldGroups: {
|
||||
detection: ["enabled", "listen", "filters"],
|
||||
detection: ["listen", "filters"],
|
||||
sensitivity: ["min_volume", "max_not_heard"],
|
||||
},
|
||||
hiddenFields: ["enabled_in_config"],
|
||||
|
||||
@@ -18,7 +18,7 @@ const detect: SectionConfigOverrides = {
|
||||
],
|
||||
restartRequired: [],
|
||||
fieldGroups: {
|
||||
resolution: ["enabled", "width", "height", "fps"],
|
||||
resolution: ["width", "height", "fps"],
|
||||
tracking: ["min_initialized", "max_disappeared"],
|
||||
},
|
||||
hiddenFields: ["enabled_in_config"],
|
||||
|
||||
@@ -6,7 +6,7 @@ const faceRecognition: SectionConfigOverrides = {
|
||||
restartRequired: [],
|
||||
fieldOrder: ["enabled", "min_area"],
|
||||
hiddenFields: [],
|
||||
advancedFields: ["min_area"],
|
||||
advancedFields: [],
|
||||
overrideFields: ["enabled", "min_area"],
|
||||
},
|
||||
global: {
|
||||
|
||||
@@ -4,39 +4,50 @@ const genai: SectionConfigOverrides = {
|
||||
base: {
|
||||
sectionDocs: "/configuration/genai/config",
|
||||
restartRequired: [
|
||||
"provider",
|
||||
"api_key",
|
||||
"base_url",
|
||||
"model",
|
||||
"provider_options",
|
||||
"runtime_options",
|
||||
"*.provider",
|
||||
"*.api_key",
|
||||
"*.base_url",
|
||||
"*.model",
|
||||
"*.provider_options",
|
||||
"*.runtime_options",
|
||||
],
|
||||
fieldOrder: [
|
||||
"provider",
|
||||
"api_key",
|
||||
"base_url",
|
||||
"model",
|
||||
"provider_options",
|
||||
"runtime_options",
|
||||
],
|
||||
advancedFields: ["base_url", "provider_options", "runtime_options"],
|
||||
advancedFields: ["*.base_url", "*.provider_options", "*.runtime_options"],
|
||||
hiddenFields: ["genai.enabled_in_config"],
|
||||
uiSchema: {
|
||||
api_key: {
|
||||
"ui:options": { size: "md" },
|
||||
"ui:options": { disableNestedCard: true },
|
||||
"*": {
|
||||
"ui:options": { disableNestedCard: true },
|
||||
"ui:order": [
|
||||
"provider",
|
||||
"api_key",
|
||||
"base_url",
|
||||
"model",
|
||||
"provider_options",
|
||||
"runtime_options",
|
||||
"*",
|
||||
],
|
||||
},
|
||||
base_url: {
|
||||
"*.roles": {
|
||||
"ui:widget": "genaiRoles",
|
||||
},
|
||||
"*.api_key": {
|
||||
"ui:options": { size: "lg" },
|
||||
},
|
||||
model: {
|
||||
"ui:options": { size: "md" },
|
||||
"*.base_url": {
|
||||
"ui:options": { size: "lg" },
|
||||
},
|
||||
provider_options: {
|
||||
"*.model": {
|
||||
"ui:options": { size: "xs" },
|
||||
},
|
||||
"*.provider": {
|
||||
"ui:options": { size: "xs" },
|
||||
},
|
||||
"*.provider_options": {
|
||||
additionalProperties: {
|
||||
"ui:options": { size: "lg" },
|
||||
},
|
||||
},
|
||||
runtime_options: {
|
||||
"*.runtime_options": {
|
||||
additionalProperties: {
|
||||
"ui:options": { size: "lg" },
|
||||
},
|
||||
|
||||
@@ -7,9 +7,9 @@ const lpr: SectionConfigOverrides = {
|
||||
enhancement: "/configuration/license_plate_recognition#enhancement",
|
||||
},
|
||||
restartRequired: [],
|
||||
fieldOrder: ["enabled", "expire_time", "min_area", "enhancement"],
|
||||
fieldOrder: ["enabled", "min_area", "enhancement", "expire_time"],
|
||||
hiddenFields: [],
|
||||
advancedFields: ["expire_time", "min_area", "enhancement"],
|
||||
advancedFields: ["expire_time", "enhancement"],
|
||||
overrideFields: ["enabled", "min_area", "enhancement"],
|
||||
},
|
||||
global: {
|
||||
|
||||
@@ -23,7 +23,7 @@ const motion: SectionConfigOverrides = {
|
||||
"mqtt_off_delay",
|
||||
],
|
||||
fieldGroups: {
|
||||
sensitivity: ["enabled", "threshold", "contour_area"],
|
||||
sensitivity: ["threshold", "contour_area"],
|
||||
algorithm: ["improve_contrast", "delta_alpha", "frame_alpha"],
|
||||
},
|
||||
uiSchema: {
|
||||
|
||||
@@ -15,7 +15,7 @@ const record: SectionConfigOverrides = {
|
||||
"export",
|
||||
],
|
||||
fieldGroups: {
|
||||
retention: ["enabled", "continuous", "motion"],
|
||||
retention: ["continuous", "motion"],
|
||||
events: ["alerts", "detections"],
|
||||
},
|
||||
hiddenFields: ["enabled_in_config", "sync_recordings"],
|
||||
|
||||
@@ -18,6 +18,11 @@ const semanticSearch: SectionConfigOverrides = {
|
||||
advancedFields: ["reindex", "device"],
|
||||
restartRequired: ["enabled", "model", "model_size", "device"],
|
||||
hiddenFields: ["reindex"],
|
||||
uiSchema: {
|
||||
model: {
|
||||
"ui:widget": "semanticSearchModel",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const snapshots: SectionConfigOverrides = {
|
||||
"retain",
|
||||
],
|
||||
fieldGroups: {
|
||||
display: ["enabled", "bounding_box", "crop", "quality", "timestamp"],
|
||||
display: ["bounding_box", "crop", "quality", "timestamp"],
|
||||
},
|
||||
hiddenFields: ["enabled_in_config"],
|
||||
advancedFields: ["height", "quality", "retain"],
|
||||
|
||||
@@ -75,7 +75,9 @@ export default function CameraReviewStatusToggles({
|
||||
/>
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="detections-enabled">
|
||||
<Trans ns="views/settings">camera.review.detections</Trans>
|
||||
<Trans ns="views/settings">
|
||||
cameraReview.review.detections
|
||||
</Trans>
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -58,7 +58,7 @@ import type { ConfigSectionData, JsonObject } from "@/types/configForm";
|
||||
import { sanitizeSectionData } from "@/utils/configUtil";
|
||||
import type { SectionRendererProps } from "./registry";
|
||||
|
||||
const NOTIFICATION_SERVICE_WORKER = "/notification-worker.js";
|
||||
const NOTIFICATION_SERVICE_WORKER = "/notifications-worker.js";
|
||||
import {
|
||||
SettingsGroupCard,
|
||||
SPLIT_ROW_CLASS_NAME,
|
||||
@@ -126,6 +126,8 @@ export default function NotificationsSettingsExtras({
|
||||
.getRegistration(NOTIFICATION_SERVICE_WORKER)
|
||||
.then((worker) => {
|
||||
if (worker) {
|
||||
// Trigger a check for an updated service worker script
|
||||
worker.update().catch(() => {});
|
||||
setRegistration(worker);
|
||||
} else {
|
||||
setRegistration(null);
|
||||
@@ -633,7 +635,9 @@ export default function NotificationsSettingsExtras({
|
||||
Notification.requestPermission().then((permission) => {
|
||||
if (permission === "granted") {
|
||||
navigator.serviceWorker
|
||||
.register(NOTIFICATION_SERVICE_WORKER)
|
||||
.register(NOTIFICATION_SERVICE_WORKER, {
|
||||
updateViaCache: "none",
|
||||
})
|
||||
.then((workerRegistration) => {
|
||||
setRegistration(workerRegistration);
|
||||
|
||||
|
||||
@@ -28,12 +28,18 @@ import { useConfigOverride } from "@/hooks/use-config-override";
|
||||
import { useSectionSchema } from "@/hooks/use-config-schema";
|
||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LuChevronDown, LuChevronRight } from "react-icons/lu";
|
||||
import Heading from "@/components/ui/heading";
|
||||
import get from "lodash/get";
|
||||
import cloneDeep from "lodash/cloneDeep";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import merge from "lodash/merge";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
@@ -59,6 +65,7 @@ import {
|
||||
globalCameraDefaultSections,
|
||||
buildOverrides,
|
||||
buildConfigDataForPath,
|
||||
getBaseCameraSectionValue,
|
||||
sanitizeSectionData as sharedSanitizeSectionData,
|
||||
requiresRestartForOverrides as sharedRequiresRestartForOverrides,
|
||||
} from "@/utils/configUtil";
|
||||
@@ -126,16 +133,25 @@ export interface BaseSectionProps {
|
||||
onStatusChange?: (status: {
|
||||
hasChanges: boolean;
|
||||
isOverridden: boolean;
|
||||
overrideSource?: "global" | "profile";
|
||||
hasValidationErrors: boolean;
|
||||
}) => void;
|
||||
/** Pending form data keyed by "sectionKey" or "cameraName::sectionKey" */
|
||||
pendingDataBySection?: Record<string, unknown>;
|
||||
pendingDataBySection?: Record<string, ConfigSectionData>;
|
||||
/** Callback to update pending data for a section */
|
||||
onPendingDataChange?: (
|
||||
sectionKey: string,
|
||||
cameraName: string | undefined,
|
||||
data: ConfigSectionData | null,
|
||||
) => void;
|
||||
/** When set, editing this profile's overrides instead of the base config */
|
||||
profileName?: string;
|
||||
/** Display name for the profile (friendly name) */
|
||||
profileFriendlyName?: string;
|
||||
/** Border color class for profile override badge (e.g., "border-amber-500") */
|
||||
profileBorderColor?: string;
|
||||
/** Callback to delete the current profile's overrides for this section */
|
||||
onDeleteProfileSection?: () => void;
|
||||
}
|
||||
|
||||
export interface CreateSectionOptions {
|
||||
@@ -166,6 +182,10 @@ export function ConfigSection({
|
||||
onStatusChange,
|
||||
pendingDataBySection,
|
||||
onPendingDataChange,
|
||||
profileName,
|
||||
profileFriendlyName,
|
||||
profileBorderColor,
|
||||
onDeleteProfileSection,
|
||||
}: ConfigSectionProps) {
|
||||
// For replay level, treat as camera-level config access
|
||||
const effectiveLevel = level === "replay" ? "camera" : level;
|
||||
@@ -181,12 +201,17 @@ export function ConfigSection({
|
||||
const statusBar = useContext(StatusBarMessagesContext);
|
||||
|
||||
// Create a key for this section's pending data
|
||||
// When editing a profile, use "cameraName::profiles.profileName.sectionPath"
|
||||
const effectiveSectionPath = profileName
|
||||
? `profiles.${profileName}.${sectionPath}`
|
||||
: sectionPath;
|
||||
|
||||
const pendingDataKey = useMemo(
|
||||
() =>
|
||||
effectiveLevel === "camera" && cameraName
|
||||
? `${cameraName}::${sectionPath}`
|
||||
: sectionPath,
|
||||
[effectiveLevel, cameraName, sectionPath],
|
||||
? `${cameraName}::${effectiveSectionPath}`
|
||||
: effectiveSectionPath,
|
||||
[effectiveLevel, cameraName, effectiveSectionPath],
|
||||
);
|
||||
|
||||
// Use pending data from parent if available, otherwise use local state
|
||||
@@ -213,25 +238,29 @@ export function ConfigSection({
|
||||
const setPendingData = useCallback(
|
||||
(data: ConfigSectionData | null) => {
|
||||
if (onPendingDataChange) {
|
||||
onPendingDataChange(sectionPath, cameraName, data);
|
||||
onPendingDataChange(effectiveSectionPath, cameraName, data);
|
||||
} else {
|
||||
setLocalPendingData(data);
|
||||
}
|
||||
},
|
||||
[onPendingDataChange, sectionPath, cameraName],
|
||||
[onPendingDataChange, effectiveSectionPath, cameraName],
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [hasValidationErrors, setHasValidationErrors] = useState(false);
|
||||
const [extraHasChanges, setExtraHasChanges] = useState(false);
|
||||
const [formKey, setFormKey] = useState(0);
|
||||
const [isResetDialogOpen, setIsResetDialogOpen] = useState(false);
|
||||
const [isDeleteProfileDialogOpen, setIsDeleteProfileDialogOpen] =
|
||||
useState(false);
|
||||
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
|
||||
const isResettingRef = useRef(false);
|
||||
const isInitializingRef = useRef(true);
|
||||
const lastPendingDataKeyRef = useRef<string | null>(null);
|
||||
|
||||
const updateTopic =
|
||||
effectiveLevel === "camera" && cameraName
|
||||
// Profile definitions don't hot-reload — only PUT /api/profile/set applies them
|
||||
const updateTopic = profileName
|
||||
? undefined
|
||||
: effectiveLevel === "camera" && cameraName
|
||||
? cameraUpdateTopicMap[sectionPath]
|
||||
? `config/cameras/${cameraName}/${cameraUpdateTopicMap[sectionPath]}`
|
||||
: undefined
|
||||
@@ -256,7 +285,7 @@ export function ConfigSection({
|
||||
[sectionPath, level, sectionSchema],
|
||||
);
|
||||
|
||||
// Get override status
|
||||
// Get override status (camera vs global)
|
||||
const { isOverridden, globalValue, cameraValue } = useConfigOverride({
|
||||
config,
|
||||
cameraName: effectiveLevel === "camera" ? cameraName : undefined,
|
||||
@@ -264,16 +293,46 @@ export function ConfigSection({
|
||||
compareFields: sectionConfig.overrideFields,
|
||||
});
|
||||
|
||||
// Check if the active profile overrides the base config for this section
|
||||
const profileOverridesSection = useMemo(() => {
|
||||
if (!profileName || !cameraName || !config) return false;
|
||||
const profileData = config.cameras?.[cameraName]?.profiles?.[profileName];
|
||||
return !!profileData?.[sectionPath as keyof typeof profileData];
|
||||
}, [profileName, cameraName, config, sectionPath]);
|
||||
|
||||
const overrideSource: "global" | "profile" | undefined =
|
||||
profileOverridesSection ? "profile" : isOverridden ? "global" : undefined;
|
||||
|
||||
// Get current form data
|
||||
// When a profile is active the top-level camera sections contain the
|
||||
// effective (profile-merged) values. For the base-config view we read
|
||||
// from `base_config` (original values before the profile was applied).
|
||||
// When editing a profile, we merge the base value with profile overrides.
|
||||
const rawSectionValue = useMemo(() => {
|
||||
if (!config) return undefined;
|
||||
|
||||
if (effectiveLevel === "camera" && cameraName) {
|
||||
return get(config.cameras?.[cameraName], sectionPath);
|
||||
// Base value: prefer base_config (pre-profile) over effective value
|
||||
const baseValue = getBaseCameraSectionValue(
|
||||
config,
|
||||
cameraName,
|
||||
sectionPath,
|
||||
);
|
||||
if (profileName) {
|
||||
const profileOverrides = get(
|
||||
config.cameras?.[cameraName],
|
||||
`profiles.${profileName}.${sectionPath}`,
|
||||
);
|
||||
if (profileOverrides && typeof profileOverrides === "object") {
|
||||
return merge(cloneDeep(baseValue ?? {}), cloneDeep(profileOverrides));
|
||||
}
|
||||
return baseValue;
|
||||
}
|
||||
return baseValue;
|
||||
}
|
||||
|
||||
return get(config, sectionPath);
|
||||
}, [config, cameraName, sectionPath, effectiveLevel]);
|
||||
}, [config, cameraName, sectionPath, effectiveLevel, profileName]);
|
||||
|
||||
const rawFormData = useMemo(() => {
|
||||
if (!config) return {};
|
||||
@@ -285,10 +344,20 @@ export function ConfigSection({
|
||||
return rawSectionValue;
|
||||
}, [config, rawSectionValue]);
|
||||
|
||||
// When editing a profile, hide fields that require a restart since they
|
||||
// cannot take effect via profile switching alone.
|
||||
const effectiveHiddenFields = useMemo(() => {
|
||||
if (!profileName || !sectionConfig.restartRequired?.length) {
|
||||
return sectionConfig.hiddenFields;
|
||||
}
|
||||
const base = sectionConfig.hiddenFields ?? [];
|
||||
return [...new Set([...base, ...sectionConfig.restartRequired])];
|
||||
}, [profileName, sectionConfig.hiddenFields, sectionConfig.restartRequired]);
|
||||
|
||||
const sanitizeSectionData = useCallback(
|
||||
(data: ConfigSectionData) =>
|
||||
sharedSanitizeSectionData(data, sectionConfig.hiddenFields),
|
||||
[sectionConfig.hiddenFields],
|
||||
sharedSanitizeSectionData(data, effectiveHiddenFields),
|
||||
[effectiveHiddenFields],
|
||||
);
|
||||
|
||||
const formData = useMemo(() => {
|
||||
@@ -386,8 +455,20 @@ export function ConfigSection({
|
||||
}, [formData, pendingData, extraHasChanges]);
|
||||
|
||||
useEffect(() => {
|
||||
onStatusChange?.({ hasChanges, isOverridden, hasValidationErrors });
|
||||
}, [hasChanges, isOverridden, hasValidationErrors, onStatusChange]);
|
||||
onStatusChange?.({
|
||||
hasChanges,
|
||||
isOverridden: profileOverridesSection || isOverridden,
|
||||
overrideSource,
|
||||
hasValidationErrors,
|
||||
});
|
||||
}, [
|
||||
hasChanges,
|
||||
isOverridden,
|
||||
profileOverridesSection,
|
||||
overrideSource,
|
||||
hasValidationErrors,
|
||||
onStatusChange,
|
||||
]);
|
||||
|
||||
// Handle form data change
|
||||
const handleChange = useCallback(
|
||||
@@ -499,8 +580,8 @@ export function ConfigSection({
|
||||
try {
|
||||
const basePath =
|
||||
effectiveLevel === "camera" && cameraName
|
||||
? `cameras.${cameraName}.${sectionPath}`
|
||||
: sectionPath;
|
||||
? `cameras.${cameraName}.${effectiveSectionPath}`
|
||||
: effectiveSectionPath;
|
||||
const rawData = sanitizeSectionData(rawFormData);
|
||||
const overrides = buildOverrides(
|
||||
pendingData,
|
||||
@@ -522,9 +603,11 @@ export function ConfigSection({
|
||||
return;
|
||||
}
|
||||
|
||||
const needsRestart = skipSave
|
||||
? false
|
||||
: requiresRestartForOverrides(sanitizedOverrides);
|
||||
// Profile definition edits never require restart
|
||||
const needsRestart =
|
||||
skipSave || profileName
|
||||
? false
|
||||
: requiresRestartForOverrides(sanitizedOverrides);
|
||||
|
||||
const configData = buildConfigDataForPath(basePath, sanitizedOverrides);
|
||||
await axios.put("config/set", {
|
||||
@@ -619,6 +702,8 @@ export function ConfigSection({
|
||||
}
|
||||
}, [
|
||||
sectionPath,
|
||||
effectiveSectionPath,
|
||||
profileName,
|
||||
pendingData,
|
||||
effectiveLevel,
|
||||
cameraName,
|
||||
@@ -642,8 +727,8 @@ export function ConfigSection({
|
||||
try {
|
||||
const basePath =
|
||||
effectiveLevel === "camera" && cameraName
|
||||
? `cameras.${cameraName}.${sectionPath}`
|
||||
: sectionPath;
|
||||
? `cameras.${cameraName}.${effectiveSectionPath}`
|
||||
: effectiveSectionPath;
|
||||
|
||||
const configData = buildConfigDataForPath(basePath, "");
|
||||
|
||||
@@ -675,7 +760,7 @@ export function ConfigSection({
|
||||
);
|
||||
}
|
||||
}, [
|
||||
sectionPath,
|
||||
effectiveSectionPath,
|
||||
effectiveLevel,
|
||||
cameraName,
|
||||
requiresRestart,
|
||||
@@ -784,7 +869,7 @@ export function ConfigSection({
|
||||
onValidationChange={setHasValidationErrors}
|
||||
fieldOrder={sectionConfig.fieldOrder}
|
||||
fieldGroups={sectionConfig.fieldGroups}
|
||||
hiddenFields={sectionConfig.hiddenFields}
|
||||
hiddenFields={effectiveHiddenFields}
|
||||
advancedFields={sectionConfig.advancedFields}
|
||||
liveValidate={sectionConfig.liveValidate}
|
||||
uiSchema={sectionConfig.uiSchema}
|
||||
@@ -823,7 +908,7 @@ export function ConfigSection({
|
||||
renderers: wrappedRenderers,
|
||||
sectionDocs: sectionConfig.sectionDocs,
|
||||
fieldDocs: sectionConfig.fieldDocs,
|
||||
hiddenFields: sectionConfig.hiddenFields,
|
||||
hiddenFields: effectiveHiddenFields,
|
||||
restartRequired: sectionConfig.restartRequired,
|
||||
requiresRestart,
|
||||
}}
|
||||
@@ -851,11 +936,12 @@ export function ConfigSection({
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full items-center gap-2 md:w-auto">
|
||||
<div className="flex w-full flex-col gap-2 sm:flex-row sm:items-center md:w-auto">
|
||||
{((effectiveLevel === "camera" && isOverridden) ||
|
||||
effectiveLevel === "global") &&
|
||||
!hasChanges &&
|
||||
!skipSave && (
|
||||
!skipSave &&
|
||||
!profileName && (
|
||||
<Button
|
||||
onClick={() => setIsResetDialogOpen(true)}
|
||||
variant="outline"
|
||||
@@ -873,6 +959,23 @@ export function ConfigSection({
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
{profileName &&
|
||||
profileOverridesSection &&
|
||||
!hasChanges &&
|
||||
!skipSave &&
|
||||
onDeleteProfileSection && (
|
||||
<Button
|
||||
onClick={() => setIsDeleteProfileDialogOpen(true)}
|
||||
variant="outline"
|
||||
disabled={isSaving || disabled}
|
||||
className="flex flex-1 gap-2"
|
||||
>
|
||||
{t("profiles.removeOverride", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Remove Profile Override",
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
{hasChanges && (
|
||||
<Button
|
||||
onClick={handleReset}
|
||||
@@ -944,6 +1047,47 @@ export function ConfigSection({
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog
|
||||
open={isDeleteProfileDialogOpen}
|
||||
onOpenChange={setIsDeleteProfileDialogOpen}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("profiles.deleteSection", { ns: "views/settings" })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("profiles.deleteSectionConfirm", {
|
||||
ns: "views/settings",
|
||||
profile: profileFriendlyName ?? profileName,
|
||||
section: t(`${sectionPath}.label`, {
|
||||
ns:
|
||||
effectiveLevel === "camera"
|
||||
? "config/cameras"
|
||||
: "config/global",
|
||||
defaultValue: sectionPath,
|
||||
}),
|
||||
camera: cameraName ?? "",
|
||||
})}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("button.cancel", { ns: "common" })}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
onClick={() => {
|
||||
onDeleteProfileSection?.();
|
||||
setIsDeleteProfileDialogOpen(false);
|
||||
}}
|
||||
>
|
||||
{t("button.delete", { ns: "common" })}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -963,17 +1107,36 @@ export function ConfigSection({
|
||||
<Heading as="h4">{title}</Heading>
|
||||
{showOverrideIndicator &&
|
||||
effectiveLevel === "camera" &&
|
||||
isOverridden && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{t("button.overridden", {
|
||||
ns: "common",
|
||||
defaultValue: "Overridden",
|
||||
})}
|
||||
</Badge>
|
||||
(profileOverridesSection || isOverridden) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{overrideSource === "profile"
|
||||
? t("button.overriddenBaseConfig", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Overridden (Base Config)",
|
||||
})
|
||||
: t("button.overriddenGlobal", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Overridden (Global)",
|
||||
})}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{overrideSource === "profile"
|
||||
? t("button.overriddenBaseConfigTooltip", {
|
||||
ns: "views/settings",
|
||||
profile: profileFriendlyName ?? profileName,
|
||||
})
|
||||
: t("button.overriddenGlobalTooltip", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{hasChanges && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{t("modified", {
|
||||
{t("button.modified", {
|
||||
ns: "common",
|
||||
defaultValue: "Modified",
|
||||
})}
|
||||
@@ -1007,23 +1170,50 @@ export function ConfigSection({
|
||||
<Heading as="h4">{title}</Heading>
|
||||
{showOverrideIndicator &&
|
||||
effectiveLevel === "camera" &&
|
||||
isOverridden && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-default border-2 border-selected text-xs text-primary-variant"
|
||||
>
|
||||
{t("button.overridden", {
|
||||
ns: "common",
|
||||
defaultValue: "Overridden",
|
||||
})}
|
||||
</Badge>
|
||||
(profileOverridesSection || isOverridden) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cn(
|
||||
"cursor-default border-2 text-center text-xs text-primary-variant",
|
||||
overrideSource === "profile" && profileBorderColor
|
||||
? profileBorderColor
|
||||
: "border-selected",
|
||||
)}
|
||||
>
|
||||
{overrideSource === "profile"
|
||||
? t("button.overriddenBaseConfig", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Overridden (Base Config)",
|
||||
})
|
||||
: t("button.overriddenGlobal", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Overridden (Global)",
|
||||
})}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{overrideSource === "profile"
|
||||
? t("button.overriddenBaseConfigTooltip", {
|
||||
ns: "views/settings",
|
||||
profile: profileFriendlyName ?? profileName,
|
||||
})
|
||||
: t("button.overriddenGlobalTooltip", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{hasChanges && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-default bg-danger text-xs text-white hover:bg-danger"
|
||||
>
|
||||
{t("modified", { ns: "common", defaultValue: "Modified" })}
|
||||
{t("button.modified", {
|
||||
ns: "common",
|
||||
defaultValue: "Modified",
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -23,10 +23,12 @@ import { AudioLabelSwitchesWidget } from "./widgets/AudioLabelSwitchesWidget";
|
||||
import { ZoneSwitchesWidget } from "./widgets/ZoneSwitchesWidget";
|
||||
import { ArrayAsTextWidget } from "./widgets/ArrayAsTextWidget";
|
||||
import { FfmpegArgsWidget } from "./widgets/FfmpegArgsWidget";
|
||||
import { GenAIRolesWidget } from "./widgets/GenAIRolesWidget";
|
||||
import { InputRolesWidget } from "./widgets/InputRolesWidget";
|
||||
import { TimezoneSelectWidget } from "./widgets/TimezoneSelectWidget";
|
||||
import { CameraPathWidget } from "./widgets/CameraPathWidget";
|
||||
import { OptionalFieldWidget } from "./widgets/OptionalFieldWidget";
|
||||
import { SemanticSearchModelWidget } from "./widgets/SemanticSearchModelWidget";
|
||||
|
||||
import { FieldTemplate } from "./templates/FieldTemplate";
|
||||
import { ObjectFieldTemplate } from "./templates/ObjectFieldTemplate";
|
||||
@@ -60,6 +62,7 @@ export const frigateTheme: FrigateTheme = {
|
||||
ArrayAsTextWidget: ArrayAsTextWidget,
|
||||
FfmpegArgsWidget: FfmpegArgsWidget,
|
||||
CameraPathWidget: CameraPathWidget,
|
||||
genaiRoles: GenAIRolesWidget,
|
||||
inputRoles: InputRolesWidget,
|
||||
// Custom widgets
|
||||
switch: SwitchWidget,
|
||||
@@ -75,6 +78,7 @@ export const frigateTheme: FrigateTheme = {
|
||||
zoneNames: ZoneSwitchesWidget,
|
||||
timezoneSelect: TimezoneSelectWidget,
|
||||
optionalField: OptionalFieldWidget,
|
||||
semanticSearchModel: SemanticSearchModelWidget,
|
||||
},
|
||||
templates: {
|
||||
FieldTemplate: FieldTemplate as React.ComponentType<FieldTemplateProps>,
|
||||
|
||||
@@ -7,7 +7,11 @@ import type {
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { LuCircleAlert } from "react-icons/lu";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildTranslationPath, humanizeKey } from "../utils";
|
||||
import {
|
||||
buildTranslationPath,
|
||||
resolveConfigTranslation,
|
||||
humanizeKey,
|
||||
} from "../utils";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
|
||||
type ErrorSchemaNode = RJSFSchema & {
|
||||
@@ -114,22 +118,15 @@ const resolveErrorFieldLabel = ({
|
||||
);
|
||||
|
||||
if (effectiveNamespace && translationPath) {
|
||||
const prefixedTranslationKey =
|
||||
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
? `${sectionI18nPrefix}.${translationPath}.label`
|
||||
: undefined;
|
||||
const translationKey = `${translationPath}.label`;
|
||||
|
||||
if (
|
||||
prefixedTranslationKey &&
|
||||
i18n.exists(prefixedTranslationKey, { ns: effectiveNamespace })
|
||||
) {
|
||||
return t(prefixedTranslationKey, { ns: effectiveNamespace });
|
||||
}
|
||||
|
||||
if (i18n.exists(translationKey, { ns: effectiveNamespace })) {
|
||||
return t(translationKey, { ns: effectiveNamespace });
|
||||
}
|
||||
const translated = resolveConfigTranslation(
|
||||
i18n,
|
||||
t,
|
||||
translationPath,
|
||||
"label",
|
||||
sectionI18nPrefix,
|
||||
effectiveNamespace,
|
||||
);
|
||||
if (translated) return translated;
|
||||
}
|
||||
|
||||
const schemaNode = resolveSchemaNodeForPath(schema, segments);
|
||||
|
||||
@@ -20,6 +20,7 @@ import { requiresRestartForFieldPath } from "@/utils/configUtil";
|
||||
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
|
||||
import {
|
||||
buildTranslationPath,
|
||||
resolveConfigTranslation,
|
||||
getFilterObjectLabel,
|
||||
hasOverrideAtPath,
|
||||
humanizeKey,
|
||||
@@ -219,20 +220,16 @@ export function FieldTemplate(props: FieldTemplateProps) {
|
||||
// Try to get translated label, falling back to schema title, then RJSF label
|
||||
let finalLabel = label;
|
||||
if (effectiveNamespace && translationPath) {
|
||||
// Prefer camera-scoped translations when a section prefix is provided
|
||||
const prefixedTranslationKey =
|
||||
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
? `${sectionI18nPrefix}.${translationPath}.label`
|
||||
: undefined;
|
||||
const translationKey = `${translationPath}.label`;
|
||||
|
||||
if (
|
||||
prefixedTranslationKey &&
|
||||
i18n.exists(prefixedTranslationKey, { ns: effectiveNamespace })
|
||||
) {
|
||||
finalLabel = t(prefixedTranslationKey, { ns: effectiveNamespace });
|
||||
} else if (i18n.exists(translationKey, { ns: effectiveNamespace })) {
|
||||
finalLabel = t(translationKey, { ns: effectiveNamespace });
|
||||
const translatedLabel = resolveConfigTranslation(
|
||||
i18n,
|
||||
t,
|
||||
translationPath,
|
||||
"label",
|
||||
sectionI18nPrefix,
|
||||
effectiveNamespace,
|
||||
);
|
||||
if (translatedLabel) {
|
||||
finalLabel = translatedLabel;
|
||||
} else if (schemaTitle) {
|
||||
finalLabel = schemaTitle;
|
||||
} else if (translatedFilterObjectLabel) {
|
||||
@@ -330,18 +327,16 @@ export function FieldTemplate(props: FieldTemplateProps) {
|
||||
// Try to get translated description, falling back to schema description
|
||||
let finalDescription = description || "";
|
||||
if (effectiveNamespace && translationPath) {
|
||||
const prefixedDescriptionKey =
|
||||
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
? `${sectionI18nPrefix}.${translationPath}.description`
|
||||
: undefined;
|
||||
const descriptionKey = `${translationPath}.description`;
|
||||
if (
|
||||
prefixedDescriptionKey &&
|
||||
i18n.exists(prefixedDescriptionKey, { ns: effectiveNamespace })
|
||||
) {
|
||||
finalDescription = t(prefixedDescriptionKey, { ns: effectiveNamespace });
|
||||
} else if (i18n.exists(descriptionKey, { ns: effectiveNamespace })) {
|
||||
finalDescription = t(descriptionKey, { ns: effectiveNamespace });
|
||||
const translatedDescription = resolveConfigTranslation(
|
||||
i18n,
|
||||
t,
|
||||
translationPath,
|
||||
"description",
|
||||
sectionI18nPrefix,
|
||||
effectiveNamespace,
|
||||
);
|
||||
if (translatedDescription) {
|
||||
finalDescription = translatedDescription;
|
||||
} else if (schemaDescription) {
|
||||
finalDescription = schemaDescription;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { requiresRestartForFieldPath } from "@/utils/configUtil";
|
||||
import { ConfigFormContext } from "@/types/configForm";
|
||||
import {
|
||||
buildTranslationPath,
|
||||
resolveConfigTranslation,
|
||||
getDomainFromNamespace,
|
||||
getFilterObjectLabel,
|
||||
humanizeKey,
|
||||
@@ -263,16 +264,14 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
|
||||
let inferredLabel: string | undefined;
|
||||
if (i18nNs && translationPath) {
|
||||
const prefixedLabelKey =
|
||||
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
? `${sectionI18nPrefix}.${translationPath}.label`
|
||||
: undefined;
|
||||
const labelKey = `${translationPath}.label`;
|
||||
if (prefixedLabelKey && i18n.exists(prefixedLabelKey, { ns: i18nNs })) {
|
||||
inferredLabel = t(prefixedLabelKey, { ns: i18nNs });
|
||||
} else if (i18n.exists(labelKey, { ns: i18nNs })) {
|
||||
inferredLabel = t(labelKey, { ns: i18nNs });
|
||||
}
|
||||
inferredLabel = resolveConfigTranslation(
|
||||
i18n,
|
||||
t,
|
||||
translationPath,
|
||||
"label",
|
||||
sectionI18nPrefix,
|
||||
i18nNs,
|
||||
);
|
||||
}
|
||||
if (!inferredLabel && translatedFilterLabel) {
|
||||
inferredLabel = translatedFilterLabel;
|
||||
@@ -286,19 +285,14 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
|
||||
let inferredDescription: string | undefined;
|
||||
if (i18nNs && translationPath) {
|
||||
const prefixedDescriptionKey =
|
||||
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
? `${sectionI18nPrefix}.${translationPath}.description`
|
||||
: undefined;
|
||||
const descriptionKey = `${translationPath}.description`;
|
||||
if (
|
||||
prefixedDescriptionKey &&
|
||||
i18n.exists(prefixedDescriptionKey, { ns: i18nNs })
|
||||
) {
|
||||
inferredDescription = t(prefixedDescriptionKey, { ns: i18nNs });
|
||||
} else if (i18n.exists(descriptionKey, { ns: i18nNs })) {
|
||||
inferredDescription = t(descriptionKey, { ns: i18nNs });
|
||||
}
|
||||
inferredDescription = resolveConfigTranslation(
|
||||
i18n,
|
||||
t,
|
||||
translationPath,
|
||||
"description",
|
||||
sectionI18nPrefix,
|
||||
i18nNs,
|
||||
);
|
||||
}
|
||||
const schemaDescription = schema?.description;
|
||||
const fallbackDescription =
|
||||
@@ -311,51 +305,54 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const grouped = new Set<string>();
|
||||
const groups = Object.entries(groupDefinitions)
|
||||
.map(([groupKey, fields]) => {
|
||||
const ordered = fields
|
||||
.map((field) => items.find((item) => item.name === field))
|
||||
.filter(Boolean) as (typeof properties)[number][];
|
||||
// Build a lookup: field name → group info
|
||||
const fieldToGroup = new Map<
|
||||
string,
|
||||
{ groupKey: string; label: string; items: (typeof properties)[number][] }
|
||||
>();
|
||||
const hasGroups = Object.keys(groupDefinitions).length > 0;
|
||||
|
||||
if (ordered.length === 0) {
|
||||
return null;
|
||||
}
|
||||
for (const [groupKey, fields] of Object.entries(groupDefinitions)) {
|
||||
const ordered = fields
|
||||
.map((field) => items.find((item) => item.name === field))
|
||||
.filter(Boolean) as (typeof properties)[number][];
|
||||
|
||||
ordered.forEach((item) => grouped.add(item.name));
|
||||
if (ordered.length === 0) continue;
|
||||
|
||||
const label = domain
|
||||
? t(`${sectionI18nPrefix}.${domain}.${groupKey}`, {
|
||||
ns: "config/groups",
|
||||
defaultValue: humanizeKey(groupKey),
|
||||
})
|
||||
: t(`groups.${groupKey}`, {
|
||||
defaultValue: humanizeKey(groupKey),
|
||||
});
|
||||
const label = domain
|
||||
? t(`${sectionI18nPrefix}.${domain}.${groupKey}`, {
|
||||
ns: "config/groups",
|
||||
defaultValue: humanizeKey(groupKey),
|
||||
})
|
||||
: t(`groups.${groupKey}`, {
|
||||
defaultValue: humanizeKey(groupKey),
|
||||
});
|
||||
|
||||
return {
|
||||
key: groupKey,
|
||||
label,
|
||||
items: ordered,
|
||||
};
|
||||
})
|
||||
.filter(Boolean) as Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
items: (typeof properties)[number][];
|
||||
}>;
|
||||
const groupInfo = { groupKey, label, items: ordered };
|
||||
for (const item of ordered) {
|
||||
fieldToGroup.set(item.name, groupInfo);
|
||||
}
|
||||
}
|
||||
|
||||
const ungrouped = items.filter((item) => !grouped.has(item.name));
|
||||
const isObjectLikeField = (item: (typeof properties)[number]) => {
|
||||
const fieldSchema = (item.content.props as RjsfElementProps)?.schema;
|
||||
return fieldSchema?.type === "object";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{groups.map((group) => (
|
||||
// Walk items in order (respects fieldOrder / ui:order).
|
||||
// When we hit the first field of a group, render the whole group block.
|
||||
// Skip subsequent fields that belong to an already-rendered group.
|
||||
const renderedGroups = new Set<string>();
|
||||
const elements: React.ReactNode[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
const group = fieldToGroup.get(item.name);
|
||||
if (group) {
|
||||
if (renderedGroups.has(group.groupKey)) continue;
|
||||
renderedGroups.add(group.groupKey);
|
||||
elements.push(
|
||||
<div
|
||||
key={group.key}
|
||||
key={group.groupKey}
|
||||
className="space-y-4 rounded-lg border border-border/70 bg-card/30 p-4"
|
||||
>
|
||||
<div className="text-md border-b border-border/60 pb-4 font-semibold text-primary-variant">
|
||||
@@ -366,25 +363,21 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
<div key={element.name}>{element.content}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>,
|
||||
);
|
||||
} else {
|
||||
elements.push(
|
||||
<div
|
||||
key={item.name}
|
||||
className={cn(hasGroups && !isObjectLikeField(item) && "px-4")}
|
||||
>
|
||||
{item.content}
|
||||
</div>,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
{ungrouped.length > 0 && (
|
||||
<div className={cn("space-y-6", groups.length > 0 && "pt-2")}>
|
||||
{ungrouped.map((element) => (
|
||||
<div
|
||||
key={element.name}
|
||||
className={cn(
|
||||
groups.length > 0 && !isObjectLikeField(element) && "px-4",
|
||||
)}
|
||||
>
|
||||
{element.content}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return <div className="space-y-6">{elements}</div>;
|
||||
};
|
||||
|
||||
// Root level renders children directly
|
||||
@@ -456,7 +449,7 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
<CollapsibleTrigger asChild>
|
||||
<CardHeader className="cursor-pointer p-4 transition-colors hover:bg-muted/50">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="min-w-0 pr-3">
|
||||
<CardTitle
|
||||
className={cn(
|
||||
"flex items-center text-sm",
|
||||
@@ -475,9 +468,9 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
|
||||
)}
|
||||
</div>
|
||||
{isOpen ? (
|
||||
<LuChevronDown className="h-4 w-4" />
|
||||
<LuChevronDown className="h-4 w-4 shrink-0" />
|
||||
) : (
|
||||
<LuChevronRight className="h-4 w-4" />
|
||||
<LuChevronRight className="h-4 w-4 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
@@ -124,6 +124,50 @@ export function buildTranslationPath(
|
||||
return stringSegments.join(".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a translated label or description for a config form field.
|
||||
*
|
||||
* Tries keys in priority order:
|
||||
* 1. Type-specific prefixed key (e.g. "detectors.edgetpu.device.label")
|
||||
* 2. Shared prefixed key with type stripped (e.g. "detectors.device.label")
|
||||
* 3. Unprefixed key (e.g. "device.label")
|
||||
*
|
||||
* @returns The translated string, or undefined if no key matched.
|
||||
*/
|
||||
export function resolveConfigTranslation(
|
||||
i18n: { exists: (key: string, opts?: Record<string, unknown>) => boolean },
|
||||
t: (key: string, opts?: Record<string, unknown>) => string,
|
||||
translationPath: string,
|
||||
suffix: "label" | "description",
|
||||
sectionI18nPrefix?: string,
|
||||
ns?: string,
|
||||
): string | undefined {
|
||||
const opts = ns ? { ns } : undefined;
|
||||
|
||||
if (
|
||||
sectionI18nPrefix &&
|
||||
!translationPath.startsWith(`${sectionI18nPrefix}.`)
|
||||
) {
|
||||
// 1. Type-specific prefixed key (e.g. detectors.edgetpu.device.label)
|
||||
const prefixed = `${sectionI18nPrefix}.${translationPath}.${suffix}`;
|
||||
if (i18n.exists(prefixed, opts)) return t(prefixed, opts);
|
||||
|
||||
// 2. Shared prefixed key — strip leading type segment
|
||||
// e.g. detectors.edgetpu.model.path → detectors.model.path
|
||||
const dot = translationPath.indexOf(".");
|
||||
if (dot !== -1) {
|
||||
const shared = `${sectionI18nPrefix}.${translationPath.substring(dot + 1)}.${suffix}`;
|
||||
if (i18n.exists(shared, opts)) return t(shared, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Unprefixed key
|
||||
const base = `${translationPath}.${suffix}`;
|
||||
if (i18n.exists(base, opts)) return t(base, opts);
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the filter object label from a path containing "filters" segment.
|
||||
* Returns the segment immediately after "filters".
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
export {
|
||||
buildTranslationPath,
|
||||
resolveConfigTranslation,
|
||||
getFilterObjectLabel,
|
||||
humanizeKey,
|
||||
getDomainFromNamespace,
|
||||
|
||||
@@ -7,41 +7,35 @@ import type { FormContext } from "./SwitchesWidget";
|
||||
import { getTranslatedLabel } from "@/utils/i18n";
|
||||
import { JsonObject } from "@/types/configForm";
|
||||
|
||||
function extractListenLabels(value: unknown): string[] {
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
const listenValue = (value as JsonObject).listen;
|
||||
if (Array.isArray(listenValue)) {
|
||||
return listenValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function getEnabledAudioLabels(context: FormContext): string[] {
|
||||
let cameraLabels: string[] = [];
|
||||
let globalLabels: string[] = [];
|
||||
let formDataLabels: string[] = [];
|
||||
|
||||
if (context) {
|
||||
// context.cameraValue and context.globalValue should be the entire audio section
|
||||
if (
|
||||
context.cameraValue &&
|
||||
typeof context.cameraValue === "object" &&
|
||||
!Array.isArray(context.cameraValue)
|
||||
) {
|
||||
const listenValue = (context.cameraValue as JsonObject).listen;
|
||||
if (Array.isArray(listenValue)) {
|
||||
cameraLabels = listenValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
cameraLabels = extractListenLabels(context.cameraValue);
|
||||
globalLabels = extractListenLabels(context.globalValue);
|
||||
|
||||
if (
|
||||
context.globalValue &&
|
||||
typeof context.globalValue === "object" &&
|
||||
!Array.isArray(context.globalValue)
|
||||
) {
|
||||
const globalListenValue = (context.globalValue as JsonObject).listen;
|
||||
if (Array.isArray(globalListenValue)) {
|
||||
globalLabels = globalListenValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
// Include labels from the current form data so that labels added via
|
||||
// profile overrides (or user edits) are always visible as switches.
|
||||
formDataLabels = extractListenLabels(context.formData);
|
||||
}
|
||||
|
||||
const sourceLabels = cameraLabels.length > 0 ? cameraLabels : globalLabels;
|
||||
return [...sourceLabels].sort();
|
||||
return [...new Set([...sourceLabels, ...formDataLabels])].sort();
|
||||
}
|
||||
|
||||
function getAudioLabelDisplayName(label: string): string {
|
||||
|
||||
@@ -8,6 +8,11 @@ import { Input } from "@/components/ui/input";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getSizedFieldClassName } from "../utils";
|
||||
import {
|
||||
isMaskedPath,
|
||||
hasCredentials,
|
||||
maskCredentials,
|
||||
} from "@/utils/credentialMask";
|
||||
|
||||
type RawPathsResponse = {
|
||||
cameras?: Record<
|
||||
@@ -22,9 +27,6 @@ type RawPathsResponse = {
|
||||
>;
|
||||
};
|
||||
|
||||
const MASKED_AUTH_PATTERN = /:\/\/\*:\*@/i;
|
||||
const MASKED_QUERY_PATTERN = /(?:[?&])user=\*&password=\*/i;
|
||||
|
||||
const getInputIndexFromWidgetId = (id: string): number | undefined => {
|
||||
const match = id.match(/_inputs_(\d+)_path$/);
|
||||
if (!match) {
|
||||
@@ -35,44 +37,6 @@ const getInputIndexFromWidgetId = (id: string): number | undefined => {
|
||||
return Number.isNaN(index) ? undefined : index;
|
||||
};
|
||||
|
||||
const isMaskedPath = (value: string): boolean =>
|
||||
MASKED_AUTH_PATTERN.test(value) || MASKED_QUERY_PATTERN.test(value);
|
||||
|
||||
const hasCredentials = (value: string): boolean => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isMaskedPath(value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
if (parsed.username || parsed.password) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
parsed.searchParams.has("user") && parsed.searchParams.has("password")
|
||||
);
|
||||
} catch {
|
||||
return /:\/\/[^:@/\s]+:[^@/\s]+@/.test(value);
|
||||
}
|
||||
};
|
||||
|
||||
const maskCredentials = (value: string): string => {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const maskedAuth = value.replace(/:\/\/[^:@/\s]+:[^@/\s]*@/g, "://*:*@");
|
||||
|
||||
return maskedAuth
|
||||
.replace(/([?&]user=)[^&]*/gi, "$1*")
|
||||
.replace(/([?&]password=)[^&]*/gi, "$1*");
|
||||
};
|
||||
|
||||
export function CameraPathWidget(props: WidgetProps) {
|
||||
const {
|
||||
id,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { WidgetProps } from "@rjsf/utils";
|
||||
import useSWR from "swr";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import get from "lodash/get";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ConfigFormContext } from "@/types/configForm";
|
||||
import {
|
||||
@@ -22,7 +24,7 @@ type FfmpegPresetResponse = {
|
||||
};
|
||||
};
|
||||
|
||||
type FfmpegArgsMode = "preset" | "manual" | "inherit";
|
||||
type FfmpegArgsMode = "preset" | "manual" | "inherit" | "none";
|
||||
|
||||
type PresetField =
|
||||
| "hwaccel_args"
|
||||
@@ -60,8 +62,8 @@ const resolveMode = (
|
||||
defaultMode: FfmpegArgsMode,
|
||||
allowInherit: boolean,
|
||||
): FfmpegArgsMode => {
|
||||
if (allowInherit && (value === null || value === undefined)) {
|
||||
return "inherit";
|
||||
if (value === null || value === undefined) {
|
||||
return allowInherit ? "inherit" : "none";
|
||||
}
|
||||
|
||||
if (allowInherit && Array.isArray(value) && value.length === 0) {
|
||||
@@ -122,6 +124,19 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
const hideDescription = options?.hideDescription === true;
|
||||
const useSplitLayout = options?.splitLayout !== false;
|
||||
|
||||
// Detect camera-level top-level fields (not inside inputs array).
|
||||
// These should show "Use global setting" instead of "None".
|
||||
const isInputScoped = id.includes("_inputs_");
|
||||
const showUseGlobalSetting = isCameraLevel && !isInputScoped && !allowInherit;
|
||||
|
||||
// Extract the global value for this specific field to detect inheritance
|
||||
const globalFieldValue = useMemo(() => {
|
||||
if (!showUseGlobalSetting || !formContext?.globalValue || !presetField) {
|
||||
return undefined;
|
||||
}
|
||||
return get(formContext.globalValue as Record<string, unknown>, presetField);
|
||||
}, [showUseGlobalSetting, formContext?.globalValue, presetField]);
|
||||
|
||||
const { data } = useSWR<FfmpegPresetResponse>("ffmpeg/presets");
|
||||
|
||||
const presetOptions = useMemo(
|
||||
@@ -132,14 +147,48 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
const canUsePresets = presetOptions.length > 0;
|
||||
const defaultMode: FfmpegArgsMode = canUsePresets ? "preset" : "manual";
|
||||
|
||||
const detectedMode = useMemo(
|
||||
() => resolveMode(value, presetOptions, defaultMode, allowInherit),
|
||||
[value, presetOptions, defaultMode, allowInherit],
|
||||
);
|
||||
// Detect if this field's value is effectively inherited from the global
|
||||
// config (i.e. the camera does not override it).
|
||||
const isInheritedFromGlobal = useMemo(() => {
|
||||
if (!showUseGlobalSetting) return false;
|
||||
if (value === undefined || value === null) return true;
|
||||
if (globalFieldValue === undefined || globalFieldValue === null)
|
||||
return false;
|
||||
return isEqual(value, globalFieldValue);
|
||||
}, [showUseGlobalSetting, value, globalFieldValue]);
|
||||
|
||||
const detectedMode = useMemo(() => {
|
||||
if (showUseGlobalSetting && isInheritedFromGlobal) {
|
||||
return "inherit" as FfmpegArgsMode;
|
||||
}
|
||||
return resolveMode(value, presetOptions, defaultMode, allowInherit);
|
||||
}, [
|
||||
showUseGlobalSetting,
|
||||
isInheritedFromGlobal,
|
||||
value,
|
||||
presetOptions,
|
||||
defaultMode,
|
||||
allowInherit,
|
||||
]);
|
||||
|
||||
const [mode, setMode] = useState<FfmpegArgsMode>(detectedMode);
|
||||
|
||||
// Track whether the user has explicitly changed mode to prevent the
|
||||
// detected-mode sync from snapping back (e.g. when a user-selected
|
||||
// preset happens to match the global value).
|
||||
const userSetModeRef = useRef(false);
|
||||
|
||||
const formIsClean = !formContext?.hasChanges;
|
||||
|
||||
// Reset tracking when the widget identity changes (camera switch)
|
||||
// or when the form returns to a clean state (after a successful save).
|
||||
useEffect(() => {
|
||||
userSetModeRef.current = false;
|
||||
}, [id, formIsClean]);
|
||||
|
||||
useEffect(() => {
|
||||
if (userSetModeRef.current) return;
|
||||
|
||||
if (!canUsePresets && detectedMode === "preset") {
|
||||
setMode("manual");
|
||||
return;
|
||||
@@ -150,6 +199,7 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(nextMode: FfmpegArgsMode) => {
|
||||
userSetModeRef.current = true;
|
||||
setMode(nextMode);
|
||||
|
||||
if (nextMode === "inherit") {
|
||||
@@ -157,6 +207,11 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextMode === "none") {
|
||||
onChange(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextMode === "preset") {
|
||||
const currentValue = typeof value === "string" ? value : undefined;
|
||||
const presetValue =
|
||||
@@ -203,7 +258,6 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const isInputScoped = id.includes("_inputs_");
|
||||
const prefix = isInputScoped ? "ffmpeg.inputs" : "ffmpeg";
|
||||
|
||||
if (presetField === "hwaccel_args") {
|
||||
@@ -227,7 +281,7 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [id, presetField]);
|
||||
}, [isInputScoped, presetField]);
|
||||
|
||||
const translatedDescription =
|
||||
fallbackDescriptionKey &&
|
||||
@@ -247,7 +301,25 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
onValueChange={(next) => handleModeChange(next as FfmpegArgsMode)}
|
||||
className="gap-3"
|
||||
>
|
||||
{allowInherit ? (
|
||||
{showUseGlobalSetting ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="inherit"
|
||||
id={`${id}-inherit`}
|
||||
disabled={disabled || readonly}
|
||||
className={
|
||||
mode === "inherit"
|
||||
? "bg-selected from-selected/50 to-selected/90 text-selected"
|
||||
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
|
||||
}
|
||||
/>
|
||||
<label htmlFor={`${id}-inherit`} className="cursor-pointer text-sm">
|
||||
{t("configForm.ffmpegArgs.useGlobalSetting", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</label>
|
||||
</div>
|
||||
) : allowInherit ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="inherit"
|
||||
@@ -263,7 +335,23 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
{t("configForm.ffmpegArgs.inherit", { ns: "views/settings" })}
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
) : (
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="none"
|
||||
id={`${id}-none`}
|
||||
disabled={disabled || readonly}
|
||||
className={
|
||||
mode === "none"
|
||||
? "bg-selected from-selected/50 to-selected/90 text-selected"
|
||||
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
|
||||
}
|
||||
/>
|
||||
<label htmlFor={`${id}-none`} className="cursor-pointer text-sm">
|
||||
{t("configForm.ffmpegArgs.none", { ns: "views/settings" })}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="preset"
|
||||
@@ -296,7 +384,8 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
{mode === "inherit" ? null : mode === "preset" && canUsePresets ? (
|
||||
{mode === "inherit" || mode === "none" ? null : mode === "preset" &&
|
||||
canUsePresets ? (
|
||||
<Select
|
||||
value={presetValue}
|
||||
onValueChange={handlePresetChange}
|
||||
@@ -316,7 +405,10 @@ export function FfmpegArgsWidget(props: WidgetProps) {
|
||||
<SelectContent>
|
||||
{presetOptions.map((preset) => (
|
||||
<SelectItem key={preset} value={preset}>
|
||||
{preset}
|
||||
{t(`configForm.ffmpegArgs.presetLabels.${preset}`, {
|
||||
ns: "views/settings",
|
||||
defaultValue: preset,
|
||||
})}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { WidgetProps } from "@rjsf/utils";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
|
||||
const GENAI_ROLES = ["embeddings", "vision", "tools"] as const;
|
||||
|
||||
function normalizeValue(value: unknown): string[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((item): item is string => typeof item === "string");
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return [value.trim()];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function getProviderKey(widgetId: string): string | undefined {
|
||||
const prefix = "root_";
|
||||
const suffix = "_roles";
|
||||
|
||||
if (!widgetId.startsWith(prefix) || !widgetId.endsWith(suffix)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return widgetId.slice(prefix.length, -suffix.length) || undefined;
|
||||
}
|
||||
|
||||
export function GenAIRolesWidget(props: WidgetProps) {
|
||||
const { id, value, disabled, readonly, onChange, registry } = props;
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
|
||||
const formContext = registry?.formContext as ConfigFormContext | undefined;
|
||||
const selectedRoles = useMemo(() => normalizeValue(value), [value]);
|
||||
const providerKey = useMemo(() => getProviderKey(id), [id]);
|
||||
|
||||
// Compute occupied roles directly from formData. The computation is
|
||||
// trivially cheap (iterate providers × 3 roles max) so we skip an
|
||||
// intermediate memoization layer whose formData dependency would
|
||||
// never produce a cache hit (new object reference on every change).
|
||||
const occupiedRoles = useMemo(() => {
|
||||
const occupied = new Set<string>();
|
||||
const fd = formContext?.formData;
|
||||
|
||||
if (!fd || typeof fd !== "object") return occupied;
|
||||
|
||||
for (const [provider, config] of Object.entries(
|
||||
fd as Record<string, unknown>,
|
||||
)) {
|
||||
if (provider === providerKey) continue;
|
||||
if (!config || typeof config !== "object" || Array.isArray(config))
|
||||
continue;
|
||||
|
||||
for (const role of normalizeValue(
|
||||
(config as Record<string, unknown>).roles,
|
||||
)) {
|
||||
occupied.add(role);
|
||||
}
|
||||
}
|
||||
|
||||
return occupied;
|
||||
}, [formContext?.formData, providerKey]);
|
||||
|
||||
const toggleRole = (role: string, enabled: boolean) => {
|
||||
if (enabled) {
|
||||
if (!selectedRoles.includes(role)) {
|
||||
onChange([...selectedRoles, role]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
onChange(selectedRoles.filter((item) => item !== role));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-secondary-highlight bg-background_alt p-2 pr-0 md:max-w-md">
|
||||
<div className="grid gap-2">
|
||||
{GENAI_ROLES.map((role) => {
|
||||
const checked = selectedRoles.includes(role);
|
||||
const roleDisabled = !checked && occupiedRoles.has(role);
|
||||
const label = t(`configForm.genaiRoles.options.${role}`, {
|
||||
ns: "views/settings",
|
||||
defaultValue: role,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
key={role}
|
||||
className="flex items-center justify-between rounded-md px-3 py-0"
|
||||
>
|
||||
<label htmlFor={`${id}-${role}`} className="text-sm">
|
||||
{label}
|
||||
</label>
|
||||
<Switch
|
||||
id={`${id}-${role}`}
|
||||
checked={checked}
|
||||
disabled={disabled || readonly || roleDisabled}
|
||||
onCheckedChange={(enabled) => toggleRole(role, !!enabled)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -40,43 +40,42 @@ function getLabelmapLabels(context: FormContext): string[] {
|
||||
return [...labels];
|
||||
}
|
||||
|
||||
// Extract track labels from an objects section value.
|
||||
function extractTrackLabels(value: unknown): string[] {
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
const trackValue = (value as JsonObject).track;
|
||||
if (Array.isArray(trackValue)) {
|
||||
return trackValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// Build the list of labels for switches (labelmap + configured track list).
|
||||
function getObjectLabels(context: FormContext): string[] {
|
||||
const labelmapLabels = getLabelmapLabels(context);
|
||||
let cameraLabels: string[] = [];
|
||||
let globalLabels: string[] = [];
|
||||
let formDataLabels: string[] = [];
|
||||
|
||||
if (context) {
|
||||
// context.cameraValue and context.globalValue should be the entire objects section
|
||||
if (
|
||||
context.cameraValue &&
|
||||
typeof context.cameraValue === "object" &&
|
||||
!Array.isArray(context.cameraValue)
|
||||
) {
|
||||
const trackValue = (context.cameraValue as JsonObject).track;
|
||||
if (Array.isArray(trackValue)) {
|
||||
cameraLabels = trackValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
cameraLabels = extractTrackLabels(context.cameraValue);
|
||||
globalLabels = extractTrackLabels(context.globalValue);
|
||||
|
||||
if (
|
||||
context.globalValue &&
|
||||
typeof context.globalValue === "object" &&
|
||||
!Array.isArray(context.globalValue)
|
||||
) {
|
||||
const globalTrackValue = (context.globalValue as JsonObject).track;
|
||||
if (Array.isArray(globalTrackValue)) {
|
||||
globalLabels = globalTrackValue.filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
);
|
||||
}
|
||||
}
|
||||
// Include labels from the current form data so that labels added via
|
||||
// profile overrides (or user edits) are always visible as switches.
|
||||
formDataLabels = extractTrackLabels(context.formData);
|
||||
}
|
||||
|
||||
const sourceLabels = cameraLabels.length > 0 ? cameraLabels : globalLabels;
|
||||
const combinedLabels = new Set<string>([...labelmapLabels, ...sourceLabels]);
|
||||
const combinedLabels = new Set<string>([
|
||||
...labelmapLabels,
|
||||
...sourceLabels,
|
||||
...formDataLabels,
|
||||
]);
|
||||
return [...combinedLabels].sort();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Combobox widget for semantic_search.model field.
|
||||
// Shows built-in model enum values and GenAI providers with the embeddings role.
|
||||
import { useState, useMemo } from "react";
|
||||
import type { WidgetProps } from "@rjsf/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Check, ChevronsUpDown } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
import { getSizedFieldClassName } from "../utils";
|
||||
|
||||
interface ProviderOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function SemanticSearchModelWidget(props: WidgetProps) {
|
||||
const { id, value, disabled, readonly, onChange, schema, registry, options } =
|
||||
props;
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const formContext = registry?.formContext as ConfigFormContext | undefined;
|
||||
const fieldClassName = getSizedFieldClassName(options, "sm");
|
||||
|
||||
// Built-in model options from schema.examples (populated by transformer
|
||||
// collapsing the anyOf enum+string union)
|
||||
const builtInModels: ProviderOption[] = useMemo(() => {
|
||||
const examples = (schema as Record<string, unknown>).examples;
|
||||
if (!Array.isArray(examples)) return [];
|
||||
return examples
|
||||
.filter((v): v is string => typeof v === "string")
|
||||
.map((v) => ({ value: v, label: v }));
|
||||
}, [schema]);
|
||||
|
||||
// GenAI providers that have the "embeddings" role
|
||||
const embeddingsProviders: ProviderOption[] = useMemo(() => {
|
||||
const genai = (
|
||||
formContext?.fullConfig as Record<string, unknown> | undefined
|
||||
)?.genai;
|
||||
if (!genai || typeof genai !== "object" || Array.isArray(genai)) return [];
|
||||
|
||||
const providers: ProviderOption[] = [];
|
||||
for (const [key, config] of Object.entries(
|
||||
genai as Record<string, unknown>,
|
||||
)) {
|
||||
if (!config || typeof config !== "object" || Array.isArray(config))
|
||||
continue;
|
||||
const roles = (config as Record<string, unknown>).roles;
|
||||
if (Array.isArray(roles) && roles.includes("embeddings")) {
|
||||
providers.push({ value: key, label: key });
|
||||
}
|
||||
}
|
||||
return providers;
|
||||
}, [formContext?.fullConfig]);
|
||||
|
||||
const currentLabel =
|
||||
builtInModels.find((m) => m.value === value)?.label ??
|
||||
embeddingsProviders.find((p) => p.value === value)?.label ??
|
||||
(typeof value === "string" && value ? value : undefined);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
id={id}
|
||||
type="button"
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
disabled={disabled || readonly}
|
||||
className={cn(
|
||||
"justify-between font-normal",
|
||||
!currentLabel && "text-muted-foreground",
|
||||
fieldClassName,
|
||||
)}
|
||||
>
|
||||
{currentLabel ??
|
||||
t("configForm.semanticSearchModel.placeholder", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Select model…",
|
||||
})}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[--radix-popover-trigger-width] p-0">
|
||||
<Command>
|
||||
<CommandList>
|
||||
{builtInModels.length > 0 && (
|
||||
<CommandGroup
|
||||
heading={t("configForm.semanticSearchModel.builtIn", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "Built-in Models",
|
||||
})}
|
||||
>
|
||||
{builtInModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.value}
|
||||
value={model.value}
|
||||
onSelect={() => {
|
||||
onChange(model.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.value ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
{model.label}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
{embeddingsProviders.length > 0 && (
|
||||
<CommandGroup
|
||||
heading={t("configForm.semanticSearchModel.genaiProviders", {
|
||||
ns: "views/settings",
|
||||
defaultValue: "GenAI Providers",
|
||||
})}
|
||||
>
|
||||
{embeddingsProviders.map((provider) => (
|
||||
<CommandItem
|
||||
key={provider.value}
|
||||
value={provider.value}
|
||||
onSelect={() => {
|
||||
onChange(provider.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === provider.value ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
{provider.label}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type FormContext = Pick<
|
||||
| "globalValue"
|
||||
| "fullCameraConfig"
|
||||
| "fullConfig"
|
||||
| "formData"
|
||||
| "t"
|
||||
| "level"
|
||||
> & {
|
||||
|
||||
@@ -77,6 +77,7 @@ import { useStreamingSettings } from "@/context/streaming-settings-provider";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { CameraNameLabel } from "../camera/FriendlyNameLabel";
|
||||
import { useAllowedCameras } from "@/hooks/use-allowed-cameras";
|
||||
import { useHasFullCameraAccess } from "@/hooks/use-has-full-camera-access";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { useUserPersistedOverlayState } from "@/hooks/use-overlay-state";
|
||||
|
||||
@@ -677,7 +678,7 @@ export function CameraGroupEdit({
|
||||
);
|
||||
|
||||
const allowedCameras = useAllowedCameras();
|
||||
const isAdmin = useIsAdmin();
|
||||
const hasFullCameraAccess = useHasFullCameraAccess();
|
||||
|
||||
const [openCamera, setOpenCamera] = useState<string | null>();
|
||||
|
||||
@@ -866,8 +867,7 @@ export function CameraGroupEdit({
|
||||
<FormDescription>{t("group.cameras.desc")}</FormDescription>
|
||||
<FormMessage />
|
||||
{[
|
||||
...(birdseyeConfig?.enabled &&
|
||||
(isAdmin || "birdseye" in allowedCameras)
|
||||
...(birdseyeConfig?.enabled && hasFullCameraAccess
|
||||
? ["birdseye"]
|
||||
: []),
|
||||
...Object.keys(config?.cameras ?? {})
|
||||
|
||||
@@ -11,7 +11,7 @@ import useSWR from "swr";
|
||||
|
||||
type ThresholdBarGraphProps = {
|
||||
graphId: string;
|
||||
name: string;
|
||||
name?: string;
|
||||
unit: string;
|
||||
threshold: Threshold;
|
||||
updateTimes: number[];
|
||||
@@ -25,6 +25,7 @@ export function ThresholdBarGraph({
|
||||
updateTimes,
|
||||
data,
|
||||
}: ThresholdBarGraphProps) {
|
||||
const displayName = name || data[0]?.name || "";
|
||||
const { data: config } = useSWR<FrigateConfig>("config", {
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
@@ -186,7 +187,7 @@ export function ThresholdBarGraph({
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="text-xs text-secondary-foreground">{name}</div>
|
||||
<div className="text-xs text-secondary-foreground">{displayName}</div>
|
||||
<div className="text-xs text-primary">
|
||||
{lastValue}
|
||||
{unit}
|
||||
|
||||
@@ -126,19 +126,21 @@ export default function AccountSettings({ className }: AccountSettingsProps) {
|
||||
|
||||
<DropdownMenuSeparator className={isDesktop ? "my-2" : "my-2"} />
|
||||
|
||||
{profile?.username && profile.username !== "anonymous" && (
|
||||
<MenuItem
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2",
|
||||
isDesktop ? "cursor-pointer" : "p-2 text-sm",
|
||||
)}
|
||||
aria-label={t("menu.user.setPassword", { ns: "common" })}
|
||||
onClick={() => setPasswordDialogOpen(true)}
|
||||
>
|
||||
<LuSquarePen className="mr-2 size-4" />
|
||||
<span>{t("menu.user.setPassword", { ns: "common" })}</span>
|
||||
</MenuItem>
|
||||
)}
|
||||
{config?.auth?.enabled !== false &&
|
||||
profile?.username &&
|
||||
profile.username !== "anonymous" && (
|
||||
<MenuItem
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2",
|
||||
isDesktop ? "cursor-pointer" : "p-2 text-sm",
|
||||
)}
|
||||
aria-label={t("menu.user.setPassword", { ns: "common" })}
|
||||
onClick={() => setPasswordDialogOpen(true)}
|
||||
>
|
||||
<LuSquarePen className="mr-2 size-4" />
|
||||
<span>{t("menu.user.setPassword", { ns: "common" })}</span>
|
||||
</MenuItem>
|
||||
)}
|
||||
|
||||
<MenuItem
|
||||
className={cn(
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
LuActivity,
|
||||
LuGithub,
|
||||
LuLanguages,
|
||||
LuLayers,
|
||||
LuLifeBuoy,
|
||||
LuList,
|
||||
LuLogOut,
|
||||
@@ -69,6 +70,9 @@ import SetPasswordDialog from "../overlay/SetPasswordDialog";
|
||||
import { toast } from "sonner";
|
||||
import axios from "axios";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import type { ProfilesApiResponse } from "@/types/profile";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { supportedLanguageKeys } from "@/lib/const";
|
||||
|
||||
@@ -84,6 +88,8 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
const { data: profile } = useSWR("profile");
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const { data: profilesData, mutate: updateProfiles } =
|
||||
useSWR<ProfilesApiResponse>("profiles");
|
||||
const logoutUrl = config?.proxy?.logout_url || "/api/logout";
|
||||
|
||||
// languages
|
||||
@@ -105,6 +111,41 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
|
||||
});
|
||||
}, [t]);
|
||||
|
||||
// profiles
|
||||
|
||||
const allProfileNames = useMemo(
|
||||
() => profilesData?.profiles?.map((p) => p.name) ?? [],
|
||||
[profilesData],
|
||||
);
|
||||
|
||||
const profileFriendlyNames = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
profilesData?.profiles?.forEach((p) => map.set(p.name, p.friendly_name));
|
||||
return map;
|
||||
}, [profilesData]);
|
||||
|
||||
const hasProfiles = allProfileNames.length > 0;
|
||||
|
||||
const handleActivateProfile = async (profileName: string | null) => {
|
||||
try {
|
||||
await axios.put("camera/*/set/profile", { value: profileName ?? "none" });
|
||||
await updateProfiles();
|
||||
toast.success(
|
||||
profileName
|
||||
? t("profiles.activated", {
|
||||
ns: "views/settings",
|
||||
profile: profileFriendlyNames.get(profileName) ?? profileName,
|
||||
})
|
||||
: t("profiles.deactivated", { ns: "views/settings" }),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
} catch {
|
||||
toast.error(t("profiles.activateFailed", { ns: "views/settings" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// settings
|
||||
|
||||
const { language, setLanguage } = useLanguage();
|
||||
@@ -225,20 +266,24 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
|
||||
<DropdownMenuSeparator
|
||||
className={isDesktop ? "mt-3" : "mt-1"}
|
||||
/>
|
||||
{profile?.username && profile.username !== "anonymous" && (
|
||||
<MenuItem
|
||||
className={
|
||||
isDesktop
|
||||
? "cursor-pointer"
|
||||
: "flex items-center p-2 text-sm"
|
||||
}
|
||||
aria-label={t("menu.user.setPassword", { ns: "common" })}
|
||||
onClick={() => setPasswordDialogOpen(true)}
|
||||
>
|
||||
<LuSquarePen className="mr-2 size-4" />
|
||||
<span>{t("menu.user.setPassword", { ns: "common" })}</span>
|
||||
</MenuItem>
|
||||
)}
|
||||
{config?.auth?.enabled !== false &&
|
||||
profile?.username &&
|
||||
profile.username !== "anonymous" && (
|
||||
<MenuItem
|
||||
className={
|
||||
isDesktop
|
||||
? "cursor-pointer"
|
||||
: "flex items-center p-2 text-sm"
|
||||
}
|
||||
aria-label={t("menu.user.setPassword", { ns: "common" })}
|
||||
onClick={() => setPasswordDialogOpen(true)}
|
||||
>
|
||||
<LuSquarePen className="mr-2 size-4" />
|
||||
<span>
|
||||
{t("menu.user.setPassword", { ns: "common" })}
|
||||
</span>
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem
|
||||
className={
|
||||
isDesktop
|
||||
@@ -285,6 +330,118 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
|
||||
<span>{t("menu.systemLogs")}</span>
|
||||
</MenuItem>
|
||||
</Link>
|
||||
{hasProfiles && (
|
||||
<SubItem>
|
||||
<SubItemTrigger
|
||||
className={
|
||||
isDesktop
|
||||
? "cursor-pointer"
|
||||
: "flex items-center p-2 text-sm"
|
||||
}
|
||||
>
|
||||
<LuLayers className="mr-2 size-4" />
|
||||
<span>{t("menu.profiles")}</span>
|
||||
</SubItemTrigger>
|
||||
<Portal>
|
||||
<SubItemContent
|
||||
className={
|
||||
isDesktop ? "" : "w-[92%] rounded-lg md:rounded-2xl"
|
||||
}
|
||||
>
|
||||
{!isDesktop && (
|
||||
<>
|
||||
<DialogTitle className="sr-only">
|
||||
{t("menu.profiles")}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
{t("menu.profiles")}
|
||||
</DialogDescription>
|
||||
</>
|
||||
)}
|
||||
<span tabIndex={0} className="sr-only" />
|
||||
<MenuItem
|
||||
className={
|
||||
isDesktop
|
||||
? "cursor-pointer"
|
||||
: "flex items-center p-2 text-sm"
|
||||
}
|
||||
aria-label={t("profiles.baseConfig", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
onClick={() => handleActivateProfile(null)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="ml-6 mr-2">
|
||||
{t("profiles.baseConfig", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</span>
|
||||
{!profilesData?.active_profile && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-xs text-primary-variant"
|
||||
>
|
||||
{t("profiles.active", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</MenuItem>
|
||||
{allProfileNames.map((profileName) => {
|
||||
const color = getProfileColor(
|
||||
profileName,
|
||||
allProfileNames,
|
||||
);
|
||||
const isActive =
|
||||
profilesData?.active_profile === profileName;
|
||||
return (
|
||||
<MenuItem
|
||||
key={profileName}
|
||||
className={
|
||||
isDesktop
|
||||
? "cursor-pointer"
|
||||
: "flex items-center p-2 text-sm"
|
||||
}
|
||||
aria-label={
|
||||
profileFriendlyNames.get(profileName) ??
|
||||
profileName
|
||||
}
|
||||
onClick={() =>
|
||||
handleActivateProfile(profileName)
|
||||
}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"ml-2 size-2 shrink-0 rounded-full",
|
||||
color.dot,
|
||||
)}
|
||||
/>
|
||||
<span>
|
||||
{profileFriendlyNames.get(profileName) ??
|
||||
profileName}
|
||||
</span>
|
||||
</div>
|
||||
{isActive && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-xs text-primary-variant"
|
||||
>
|
||||
{t("profiles.active", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</SubItemContent>
|
||||
</Portal>
|
||||
</SubItem>
|
||||
)}
|
||||
</DropdownMenuGroup>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -159,25 +159,24 @@ export default function SearchResultActions({
|
||||
<MenuItem aria-label={t("itemMenu.downloadSnapshot.aria")}>
|
||||
<a
|
||||
className="flex items-center"
|
||||
href={`${baseUrl}api/events/${searchResult.id}/snapshot.jpg`}
|
||||
href={`${baseUrl}api/events/${searchResult.id}/snapshot.jpg?crop=0&bbox=1×tamp=0`}
|
||||
download={`${searchResult.camera}_${searchResult.label}.jpg`}
|
||||
>
|
||||
<span>{t("itemMenu.downloadSnapshot.label")}</span>
|
||||
</a>
|
||||
</MenuItem>
|
||||
)}
|
||||
{searchResult.has_snapshot &&
|
||||
config?.cameras[searchResult.camera].snapshots.clean_copy && (
|
||||
<MenuItem aria-label={t("itemMenu.downloadCleanSnapshot.aria")}>
|
||||
<a
|
||||
className="flex items-center"
|
||||
href={`${baseUrl}api/events/${searchResult.id}/snapshot-clean.webp`}
|
||||
download={`${searchResult.camera}_${searchResult.label}-clean.webp`}
|
||||
>
|
||||
<span>{t("itemMenu.downloadCleanSnapshot.label")}</span>
|
||||
</a>
|
||||
</MenuItem>
|
||||
)}
|
||||
{searchResult.has_snapshot && (
|
||||
<MenuItem aria-label={t("itemMenu.downloadCleanSnapshot.aria")}>
|
||||
<a
|
||||
className="flex items-center"
|
||||
href={`${baseUrl}api/events/${searchResult.id}/snapshot-clean.webp`}
|
||||
download={`${searchResult.camera}_${searchResult.label}-clean.webp`}
|
||||
>
|
||||
<span>{t("itemMenu.downloadCleanSnapshot.label")}</span>
|
||||
</a>
|
||||
</MenuItem>
|
||||
)}
|
||||
{searchResult.data.type == "object" && (
|
||||
<MenuItem
|
||||
aria-label={t("itemMenu.viewTrackingDetails.aria")}
|
||||
|
||||
@@ -159,7 +159,9 @@ export default function CameraInfoDialog({
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground">
|
||||
<div className="ml-2 mt-1">Audio:</div>
|
||||
<div className="ml-2 mt-1">
|
||||
{t("cameras.info.audio")}
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
{t("cameras.info.codec")}{" "}
|
||||
<span className="text-primary">
|
||||
|
||||
@@ -34,7 +34,11 @@ type ClassificationSelectionDialogProps = {
|
||||
classes: string[];
|
||||
modelName: string;
|
||||
image: string;
|
||||
onRefresh: () => void;
|
||||
onRefresh?: () => void;
|
||||
onCategorize?: (category: string) => void;
|
||||
excludeCategory?: string;
|
||||
dialogLabel?: string;
|
||||
tooltipLabel?: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
export default function ClassificationSelectionDialog({
|
||||
@@ -43,12 +47,21 @@ export default function ClassificationSelectionDialog({
|
||||
modelName,
|
||||
image,
|
||||
onRefresh,
|
||||
onCategorize,
|
||||
excludeCategory,
|
||||
dialogLabel,
|
||||
tooltipLabel,
|
||||
children,
|
||||
}: ClassificationSelectionDialogProps) {
|
||||
const { t } = useTranslation(["views/classificationModel"]);
|
||||
|
||||
const onCategorizeImage = useCallback(
|
||||
(category: string) => {
|
||||
if (onCategorize) {
|
||||
onCategorize(category);
|
||||
return;
|
||||
}
|
||||
|
||||
axios
|
||||
.post(`/classification/${modelName}/dataset/categorize`, {
|
||||
category,
|
||||
@@ -59,7 +72,7 @@ export default function ClassificationSelectionDialog({
|
||||
toast.success(t("toast.success.categorizedImage"), {
|
||||
position: "top-center",
|
||||
});
|
||||
onRefresh();
|
||||
onRefresh?.();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -72,7 +85,13 @@ export default function ClassificationSelectionDialog({
|
||||
});
|
||||
});
|
||||
},
|
||||
[modelName, image, onRefresh, t],
|
||||
[modelName, image, onRefresh, onCategorize, t],
|
||||
);
|
||||
|
||||
const filteredClasses = useMemo(
|
||||
() =>
|
||||
excludeCategory ? classes.filter((c) => c !== excludeCategory) : classes,
|
||||
[classes, excludeCategory],
|
||||
);
|
||||
|
||||
const isChildButton = useMemo(
|
||||
@@ -111,6 +130,7 @@ export default function ClassificationSelectionDialog({
|
||||
</SelectorTrigger>
|
||||
<SelectorContent
|
||||
className={cn("", isMobile && "mx-1 gap-2 rounded-t-2xl px-4")}
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
{isMobile && (
|
||||
<DrawerHeader className="sr-only">
|
||||
@@ -118,24 +138,32 @@ export default function ClassificationSelectionDialog({
|
||||
<DrawerDescription>Details</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
)}
|
||||
<DropdownMenuLabel>{t("categorizeImageAs")}</DropdownMenuLabel>
|
||||
<DropdownMenuLabel>
|
||||
{dialogLabel ?? t("categorizeImageAs")}
|
||||
</DropdownMenuLabel>
|
||||
<div
|
||||
className={cn(
|
||||
"flex max-h-[40dvh] flex-col overflow-y-auto",
|
||||
isMobile && "gap-2 pb-4",
|
||||
)}
|
||||
>
|
||||
{classes.sort().map((category) => (
|
||||
<SelectorItem
|
||||
key={category}
|
||||
className="flex cursor-pointer gap-2 smart-capitalize"
|
||||
onClick={() => onCategorizeImage(category)}
|
||||
>
|
||||
{category === "none"
|
||||
? t("details.none")
|
||||
: category.replaceAll("_", " ")}
|
||||
</SelectorItem>
|
||||
))}
|
||||
{filteredClasses
|
||||
.sort((a, b) => {
|
||||
if (a === "none") return 1;
|
||||
if (b === "none") return -1;
|
||||
return a.localeCompare(b);
|
||||
})
|
||||
.map((category) => (
|
||||
<SelectorItem
|
||||
key={category}
|
||||
className="flex cursor-pointer gap-2 smart-capitalize"
|
||||
onClick={() => onCategorizeImage(category)}
|
||||
>
|
||||
{category === "none"
|
||||
? t("details.none")
|
||||
: category.replaceAll("_", " ")}
|
||||
</SelectorItem>
|
||||
))}
|
||||
<Separator />
|
||||
<SelectorItem
|
||||
className="flex cursor-pointer gap-2 smart-capitalize"
|
||||
@@ -146,7 +174,7 @@ export default function ClassificationSelectionDialog({
|
||||
</div>
|
||||
</SelectorContent>
|
||||
</Selector>
|
||||
<TooltipContent>{t("categorizeImage")}</TooltipContent>
|
||||
<TooltipContent>{tooltipLabel ?? t("categorizeImage")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -60,7 +60,7 @@ export default function DeleteRoleDialog({
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
<Trans
|
||||
ns={"views/settings"}
|
||||
ns="views/settings"
|
||||
values={{ role }}
|
||||
components={{ strong: <span className="font-medium" /> }}
|
||||
>
|
||||
|
||||
@@ -35,7 +35,7 @@ export default function DeleteTriggerDialog({
|
||||
<DialogTitle>{t("triggers.dialog.deleteTrigger.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
<Trans
|
||||
ns={"views/settings"}
|
||||
ns="views/settings"
|
||||
values={{ triggerName }}
|
||||
components={{ strong: <span className="font-medium" /> }}
|
||||
>
|
||||
|
||||
@@ -90,7 +90,7 @@ export default function EditRoleCamerasDialog({
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
<Trans
|
||||
ns={"views/settings"}
|
||||
ns="views/settings"
|
||||
values={{ role }}
|
||||
components={{ strong: <span className="font-medium" /> }}
|
||||
>
|
||||
|
||||
@@ -30,17 +30,29 @@ import { Button } from "../ui/button";
|
||||
type FaceSelectionDialogProps = {
|
||||
className?: string;
|
||||
faceNames: string[];
|
||||
excludeName?: string;
|
||||
dialogLabel?: string;
|
||||
tooltipLabel?: string;
|
||||
onTrainAttempt: (name: string) => void;
|
||||
children: ReactNode;
|
||||
};
|
||||
export default function FaceSelectionDialog({
|
||||
className,
|
||||
faceNames,
|
||||
excludeName,
|
||||
dialogLabel,
|
||||
tooltipLabel,
|
||||
onTrainAttempt,
|
||||
children,
|
||||
}: FaceSelectionDialogProps) {
|
||||
const { t } = useTranslation(["views/faceLibrary"]);
|
||||
|
||||
const filteredNames = useMemo(
|
||||
() =>
|
||||
excludeName ? faceNames.filter((n) => n !== excludeName) : faceNames,
|
||||
[faceNames, excludeName],
|
||||
);
|
||||
|
||||
const isChildButton = useMemo(
|
||||
() => React.isValidElement(children) && children.type === Button,
|
||||
[children],
|
||||
@@ -79,6 +91,7 @@ export default function FaceSelectionDialog({
|
||||
</SelectorTrigger>
|
||||
<SelectorContent
|
||||
className={cn("", isMobile && "mx-1 gap-2 rounded-t-2xl px-4")}
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
{isMobile && (
|
||||
<DrawerHeader className="sr-only">
|
||||
@@ -86,14 +99,16 @@ export default function FaceSelectionDialog({
|
||||
<DrawerDescription>Details</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
)}
|
||||
<DropdownMenuLabel>{t("trainFaceAs")}</DropdownMenuLabel>
|
||||
<DropdownMenuLabel>
|
||||
{dialogLabel ?? t("trainFaceAs")}
|
||||
</DropdownMenuLabel>
|
||||
<div
|
||||
className={cn(
|
||||
"flex max-h-[40dvh] flex-col overflow-y-auto overflow-x-hidden",
|
||||
isMobile && "gap-2 pb-4",
|
||||
)}
|
||||
>
|
||||
{faceNames.sort().map((faceName) => (
|
||||
{filteredNames.sort().map((faceName) => (
|
||||
<SelectorItem
|
||||
key={faceName}
|
||||
className="flex cursor-pointer gap-2 smart-capitalize"
|
||||
@@ -112,7 +127,7 @@ export default function FaceSelectionDialog({
|
||||
</div>
|
||||
</SelectorContent>
|
||||
</Selector>
|
||||
<TooltipContent>{t("trainFace")}</TooltipContent>
|
||||
<TooltipContent>{tooltipLabel ?? t("trainFace")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function MobileTimelineDrawer({
|
||||
setDrawer(false);
|
||||
}}
|
||||
>
|
||||
{t("timeline")}
|
||||
{t("timeline.label")}
|
||||
</div>
|
||||
<div
|
||||
className={`mx-4 w-full py-2 text-center smart-capitalize ${selected == "events" ? "rounded-lg bg-secondary" : ""}`}
|
||||
|
||||
@@ -85,7 +85,7 @@ export default function DetailActionsMenu({
|
||||
<DropdownMenuItem>
|
||||
<a
|
||||
className="w-full"
|
||||
href={`${baseUrl}api/events/${search.id}/snapshot.jpg?bbox=1`}
|
||||
href={`${baseUrl}api/events/${search.id}/snapshot.jpg?crop=0&bbox=1×tamp=0`}
|
||||
download={`${search.camera}_${search.label}.jpg`}
|
||||
>
|
||||
<div className="flex cursor-pointer items-center gap-2">
|
||||
@@ -94,20 +94,19 @@ export default function DetailActionsMenu({
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{search.has_snapshot &&
|
||||
config?.cameras[search.camera].snapshots.clean_copy && (
|
||||
<DropdownMenuItem>
|
||||
<a
|
||||
className="w-full"
|
||||
href={`${baseUrl}api/events/${search.id}/snapshot-clean.webp`}
|
||||
download={`${search.camera}_${search.label}-clean.webp`}
|
||||
>
|
||||
<div className="flex cursor-pointer items-center gap-2">
|
||||
<span>{t("itemMenu.downloadCleanSnapshot.label")}</span>
|
||||
</div>
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{search.has_snapshot && (
|
||||
<DropdownMenuItem>
|
||||
<a
|
||||
className="w-full"
|
||||
href={`${baseUrl}api/events/${search.id}/snapshot-clean.webp`}
|
||||
download={`${search.camera}_${search.label}-clean.webp`}
|
||||
>
|
||||
<div className="flex cursor-pointer items-center gap-2">
|
||||
<span>{t("itemMenu.downloadCleanSnapshot.label")}</span>
|
||||
</div>
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{search.has_clip && (
|
||||
<DropdownMenuItem>
|
||||
<a
|
||||
|
||||
@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";
|
||||
export type SaveAllPreviewItem = {
|
||||
scope: "global" | "camera";
|
||||
cameraName?: string;
|
||||
profileName?: string;
|
||||
fieldPath: string;
|
||||
value: unknown;
|
||||
};
|
||||
@@ -114,6 +115,18 @@ export default function SaveAllPreviewPopover({
|
||||
})}
|
||||
</span>
|
||||
<span className="truncate">{scopeLabel}</span>
|
||||
{item.profileName && (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
{t("saveAllPreview.profile.label", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</span>
|
||||
<span className="truncate font-medium">
|
||||
{item.profileName}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span className="text-muted-foreground">
|
||||
{t("saveAllPreview.field.label", {
|
||||
ns: "views/settings",
|
||||
|
||||
@@ -1839,7 +1839,7 @@ export function ObjectSnapshotTab({
|
||||
<img
|
||||
ref={imgRef}
|
||||
className="mx-auto max-h-[60dvh] rounded-lg bg-background object-contain"
|
||||
src={`${baseUrl}api/events/${search?.id}/snapshot.jpg`}
|
||||
src={`${baseUrl}api/events/${search?.id}/snapshot.jpg?crop=0&bbox=1×tamp=0`}
|
||||
alt={`${search?.label}`}
|
||||
loading={isSafari ? "eager" : "lazy"}
|
||||
onLoad={() => {
|
||||
|
||||
@@ -41,6 +41,7 @@ import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator
|
||||
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { VideoResolutionType } from "@/types/live";
|
||||
import { VodManifest } from "@/types/playback";
|
||||
|
||||
type TrackingDetailsProps = {
|
||||
className?: string;
|
||||
@@ -133,19 +134,64 @@ export function TrackingDetails({
|
||||
},
|
||||
);
|
||||
|
||||
// Fetch the VOD manifest JSON to get the actual clipFrom after keyframe
|
||||
// snapping. The backend may snap clipFrom backwards to a keyframe, making
|
||||
// the video start earlier than the requested time.
|
||||
const vodManifestUrl = useMemo(() => {
|
||||
if (!event.camera) return null;
|
||||
const startTime =
|
||||
event.start_time + annotationOffset / 1000 - REVIEW_PADDING;
|
||||
const endTime =
|
||||
(event.end_time ?? Date.now() / 1000) +
|
||||
annotationOffset / 1000 +
|
||||
REVIEW_PADDING;
|
||||
return `vod/clip/${event.camera}/start/${startTime}/end/${endTime}`;
|
||||
}, [event, annotationOffset]);
|
||||
|
||||
const { data: vodManifest } = useSWR<VodManifest>(vodManifestUrl, null, {
|
||||
revalidateOnFocus: false,
|
||||
revalidateOnReconnect: false,
|
||||
dedupingInterval: 30000,
|
||||
});
|
||||
|
||||
// Derive the actual video start time from the VOD manifest's first clip.
|
||||
// Without this correction the timeline-to-player-time mapping is off by
|
||||
// the keyframe preroll amount.
|
||||
const actualVideoStart = useMemo(() => {
|
||||
const videoStartTime = eventStartRecord - REVIEW_PADDING;
|
||||
|
||||
if (!vodManifest?.sequences?.[0]?.clips?.[0] || !recordings?.length) {
|
||||
return videoStartTime;
|
||||
}
|
||||
|
||||
const firstClip = vodManifest.sequences[0].clips[0];
|
||||
|
||||
// Guard: clipFrom is only expected when the first recording starts before
|
||||
// the requested start. If this doesn't hold, fall back.
|
||||
if (recordings[0].start_time >= videoStartTime) {
|
||||
return recordings[0].start_time;
|
||||
}
|
||||
|
||||
if (firstClip.clipFrom !== undefined) {
|
||||
// clipFrom is in milliseconds from the start of the first recording
|
||||
return recordings[0].start_time + firstClip.clipFrom / 1000;
|
||||
}
|
||||
|
||||
// clipFrom absent means the full recording is included (keyframe probe failed)
|
||||
return recordings[0].start_time;
|
||||
}, [vodManifest, recordings, eventStartRecord]);
|
||||
|
||||
// Convert a timeline timestamp to actual video player time, accounting for
|
||||
// motion-only recording gaps. Uses the same algorithm as DynamicVideoController.
|
||||
const timestampToVideoTime = useCallback(
|
||||
(timestamp: number): number => {
|
||||
if (!recordings || recordings.length === 0) {
|
||||
// Fallback to simple calculation if no recordings data
|
||||
return timestamp - (eventStartRecord - REVIEW_PADDING);
|
||||
return timestamp - actualVideoStart;
|
||||
}
|
||||
|
||||
const videoStartTime = eventStartRecord - REVIEW_PADDING;
|
||||
|
||||
// If timestamp is before video start, return 0
|
||||
if (timestamp < videoStartTime) return 0;
|
||||
// If timestamp is before actual video start, return 0
|
||||
if (timestamp < actualVideoStart) return 0;
|
||||
|
||||
// Check if timestamp is before the first recording or after the last
|
||||
if (
|
||||
@@ -159,10 +205,10 @@ export function TrackingDetails({
|
||||
// Calculate the inpoint offset - the HLS video may start partway through the first segment
|
||||
let inpointOffset = 0;
|
||||
if (
|
||||
videoStartTime > recordings[0].start_time &&
|
||||
videoStartTime < recordings[0].end_time
|
||||
actualVideoStart > recordings[0].start_time &&
|
||||
actualVideoStart < recordings[0].end_time
|
||||
) {
|
||||
inpointOffset = videoStartTime - recordings[0].start_time;
|
||||
inpointOffset = actualVideoStart - recordings[0].start_time;
|
||||
}
|
||||
|
||||
let seekSeconds = 0;
|
||||
@@ -180,7 +226,7 @@ export function TrackingDetails({
|
||||
if (segment === recordings[0]) {
|
||||
// For the first segment, account for the inpoint offset
|
||||
seekSeconds +=
|
||||
timestamp - Math.max(segment.start_time, videoStartTime);
|
||||
timestamp - Math.max(segment.start_time, actualVideoStart);
|
||||
} else {
|
||||
seekSeconds += timestamp - segment.start_time;
|
||||
}
|
||||
@@ -190,7 +236,7 @@ export function TrackingDetails({
|
||||
|
||||
return seekSeconds;
|
||||
},
|
||||
[recordings, eventStartRecord],
|
||||
[recordings, actualVideoStart],
|
||||
);
|
||||
|
||||
// Convert video player time back to timeline timestamp, accounting for
|
||||
@@ -199,19 +245,16 @@ export function TrackingDetails({
|
||||
(playerTime: number): number => {
|
||||
if (!recordings || recordings.length === 0) {
|
||||
// Fallback to simple calculation if no recordings data
|
||||
const videoStartTime = eventStartRecord - REVIEW_PADDING;
|
||||
return playerTime + videoStartTime;
|
||||
return playerTime + actualVideoStart;
|
||||
}
|
||||
|
||||
const videoStartTime = eventStartRecord - REVIEW_PADDING;
|
||||
|
||||
// Calculate the inpoint offset - the video may start partway through the first segment
|
||||
let inpointOffset = 0;
|
||||
if (
|
||||
videoStartTime > recordings[0].start_time &&
|
||||
videoStartTime < recordings[0].end_time
|
||||
actualVideoStart > recordings[0].start_time &&
|
||||
actualVideoStart < recordings[0].end_time
|
||||
) {
|
||||
inpointOffset = videoStartTime - recordings[0].start_time;
|
||||
inpointOffset = actualVideoStart - recordings[0].start_time;
|
||||
}
|
||||
|
||||
let timestamp = 0;
|
||||
@@ -228,7 +271,7 @@ export function TrackingDetails({
|
||||
if (segment === recordings[0]) {
|
||||
// For the first segment, add the inpoint offset
|
||||
timestamp =
|
||||
Math.max(segment.start_time, videoStartTime) +
|
||||
Math.max(segment.start_time, actualVideoStart) +
|
||||
(playerTime - totalTime);
|
||||
} else {
|
||||
timestamp = segment.start_time + (playerTime - totalTime);
|
||||
@@ -241,7 +284,7 @@ export function TrackingDetails({
|
||||
|
||||
return timestamp;
|
||||
},
|
||||
[recordings, eventStartRecord],
|
||||
[recordings, actualVideoStart],
|
||||
);
|
||||
|
||||
eventSequence?.map((event) => {
|
||||
@@ -1080,7 +1123,7 @@ function LifecycleIconRow({
|
||||
<div className="ml-3 flex-shrink-0 px-1 text-right text-xs text-primary-variant">
|
||||
<div className="flex flex-row items-center gap-3">
|
||||
<div className="whitespace-nowrap">{formattedEventTimestamp}</div>
|
||||
{isAdmin && config?.plus?.enabled && item.data.box && (
|
||||
{isAdmin && (config?.plus?.enabled || item.data.box) && (
|
||||
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DropdownMenuTrigger>
|
||||
<div className="rounded p-1 pr-2" role="button">
|
||||
|
||||
@@ -107,7 +107,7 @@ export function FrigatePlusDialog({
|
||||
<img
|
||||
ref={imgRef}
|
||||
className="mx-auto max-h-[60dvh] rounded-lg bg-black object-contain"
|
||||
src={`${baseUrl}api/events/${upload.id}/snapshot.jpg`}
|
||||
src={`${baseUrl}api/events/${upload.id}/snapshot.jpg?crop=0&bbox=1×tamp=0`}
|
||||
alt={`${upload.label}`}
|
||||
loading={isSafari ? "eager" : "lazy"}
|
||||
onLoad={onImgLoad}
|
||||
|
||||
@@ -357,7 +357,7 @@ export default function HlsVideoPlayer({
|
||||
{transformedOverlay}
|
||||
{isDetailMode &&
|
||||
camera &&
|
||||
currentTime &&
|
||||
currentTime != null &&
|
||||
loadedMetadata &&
|
||||
videoDimensions.width > 0 &&
|
||||
videoDimensions.height > 0 && (
|
||||
|
||||
@@ -494,7 +494,7 @@ export default function CameraEditForm({
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="font-medium">
|
||||
{t("cameraWizard.step2.streamTitle", {
|
||||
{t("cameraWizard.step3.streamTitle", {
|
||||
number: index + 1,
|
||||
})}
|
||||
</h4>
|
||||
|
||||
@@ -20,7 +20,10 @@ import type {
|
||||
CameraConfigData,
|
||||
ConfigSetBody,
|
||||
} from "@/types/cameraWizard";
|
||||
import { processCameraName } from "@/utils/cameraUtil";
|
||||
import {
|
||||
processCameraName,
|
||||
calculateDetectDimensions,
|
||||
} from "@/utils/cameraUtil";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type WizardState = {
|
||||
@@ -203,6 +206,25 @@ export default function CameraWizardDialog({
|
||||
},
|
||||
};
|
||||
|
||||
// Calculate detect dimensions from the detect stream's probed resolution
|
||||
const detectStream = wizardData.streams.find((stream) =>
|
||||
stream.roles.includes("detect"),
|
||||
);
|
||||
if (detectStream?.testResult?.resolution) {
|
||||
const [streamWidth, streamHeight] = detectStream.testResult.resolution
|
||||
.split("x")
|
||||
.map(Number);
|
||||
if (streamWidth > 0 && streamHeight > 0) {
|
||||
const detectDimensions = calculateDetectDimensions(
|
||||
streamWidth,
|
||||
streamHeight,
|
||||
);
|
||||
if (detectDimensions) {
|
||||
configData.cameras[finalCameraName].detect = detectDimensions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add live.streams configuration for go2rtc streams
|
||||
if (wizardData.streams && wizardData.streams.length > 0) {
|
||||
configData.cameras[finalCameraName].live = {
|
||||
@@ -316,8 +338,8 @@ export default function CameraWizardDialog({
|
||||
}
|
||||
} else {
|
||||
toast.success(
|
||||
t("camera.cameraConfig.toast.success", {
|
||||
cameraName: wizardData.cameraName,
|
||||
t("cameraWizard.save.success", {
|
||||
cameraName: friendlyName || finalCameraName,
|
||||
}),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
|
||||
@@ -44,6 +44,7 @@ type MotionMaskEditPaneProps = {
|
||||
onCancel?: () => void;
|
||||
snapPoints: boolean;
|
||||
setSnapPoints: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
editingProfile?: string | null;
|
||||
};
|
||||
|
||||
export default function MotionMaskEditPane({
|
||||
@@ -58,6 +59,7 @@ export default function MotionMaskEditPane({
|
||||
onCancel,
|
||||
snapPoints,
|
||||
setSnapPoints,
|
||||
editingProfile,
|
||||
}: MotionMaskEditPaneProps) {
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
@@ -192,16 +194,28 @@ export default function MotionMaskEditPane({
|
||||
coordinates: coordinates,
|
||||
};
|
||||
|
||||
// Build config path based on profile mode
|
||||
const motionMaskPath = editingProfile
|
||||
? {
|
||||
profiles: {
|
||||
[editingProfile]: {
|
||||
motion: { mask: { [maskId]: maskConfig } },
|
||||
},
|
||||
},
|
||||
}
|
||||
: { motion: { mask: { [maskId]: maskConfig } } };
|
||||
|
||||
// If renaming, we need to delete the old mask first
|
||||
if (renamingMask) {
|
||||
const deleteQueryPath = editingProfile
|
||||
? `cameras.${polygon.camera}.profiles.${editingProfile}.motion.mask.${polygon.name}`
|
||||
: `cameras.${polygon.camera}.motion.mask.${polygon.name}`;
|
||||
|
||||
try {
|
||||
await axios.put(
|
||||
`config/set?cameras.${polygon.camera}.motion.mask.${polygon.name}`,
|
||||
{
|
||||
requires_restart: 0,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
await axios.put(`config/set?${deleteQueryPath}`, {
|
||||
requires_restart: 0,
|
||||
});
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
@@ -210,22 +224,20 @@ export default function MotionMaskEditPane({
|
||||
}
|
||||
}
|
||||
|
||||
const updateTopic = editingProfile
|
||||
? undefined
|
||||
: `config/cameras/${polygon.camera}/motion`;
|
||||
|
||||
// Save the new/updated mask using JSON body
|
||||
axios
|
||||
.put("config/set", {
|
||||
config_data: {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
motion: {
|
||||
mask: {
|
||||
[maskId]: maskConfig,
|
||||
},
|
||||
},
|
||||
},
|
||||
[polygon.camera]: motionMaskPath,
|
||||
},
|
||||
},
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/motion`,
|
||||
update_topic: updateTopic,
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.status === 200) {
|
||||
@@ -238,8 +250,10 @@ export default function MotionMaskEditPane({
|
||||
},
|
||||
);
|
||||
updateConfig();
|
||||
// Publish the enabled state through websocket
|
||||
sendMotionMaskState(enabled ? "ON" : "OFF");
|
||||
// Only publish WS state for base config
|
||||
if (!editingProfile) {
|
||||
sendMotionMaskState(enabled ? "ON" : "OFF");
|
||||
}
|
||||
} else {
|
||||
toast.error(
|
||||
t("toast.save.error.title", {
|
||||
@@ -277,6 +291,7 @@ export default function MotionMaskEditPane({
|
||||
cameraConfig,
|
||||
t,
|
||||
sendMotionMaskState,
|
||||
editingProfile,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ type ObjectMaskEditPaneProps = {
|
||||
onCancel?: () => void;
|
||||
snapPoints: boolean;
|
||||
setSnapPoints: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
editingProfile?: string | null;
|
||||
};
|
||||
|
||||
export default function ObjectMaskEditPane({
|
||||
@@ -65,6 +66,7 @@ export default function ObjectMaskEditPane({
|
||||
onCancel,
|
||||
snapPoints,
|
||||
setSnapPoints,
|
||||
editingProfile,
|
||||
}: ObjectMaskEditPaneProps) {
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
const { data: config, mutate: updateConfig } =
|
||||
@@ -190,14 +192,22 @@ export default function ObjectMaskEditPane({
|
||||
// Determine if old mask was global or per-object
|
||||
const wasGlobal =
|
||||
polygon.objects.length === 0 || polygon.objects[0] === "all_labels";
|
||||
const oldPath = wasGlobal
|
||||
? `cameras.${polygon.camera}.objects.mask.${polygon.name}`
|
||||
: `cameras.${polygon.camera}.objects.filters.${polygon.objects[0]}.mask.${polygon.name}`;
|
||||
|
||||
let oldPath: string;
|
||||
if (editingProfile) {
|
||||
oldPath = wasGlobal
|
||||
? `cameras.${polygon.camera}.profiles.${editingProfile}.objects.mask.${polygon.name}`
|
||||
: `cameras.${polygon.camera}.profiles.${editingProfile}.objects.filters.${polygon.objects[0]}.mask.${polygon.name}`;
|
||||
} else {
|
||||
oldPath = wasGlobal
|
||||
? `cameras.${polygon.camera}.objects.mask.${polygon.name}`
|
||||
: `cameras.${polygon.camera}.objects.filters.${polygon.objects[0]}.mask.${polygon.name}`;
|
||||
}
|
||||
|
||||
await axios.put(`config/set?${oldPath}`, {
|
||||
requires_restart: 0,
|
||||
});
|
||||
} catch (error) {
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
@@ -206,45 +216,32 @@ export default function ObjectMaskEditPane({
|
||||
}
|
||||
}
|
||||
|
||||
// Build the config structure based on whether it's global or per-object
|
||||
let configBody;
|
||||
if (globalMask) {
|
||||
configBody = {
|
||||
config_data: {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
objects: {
|
||||
mask: {
|
||||
[maskId]: maskConfig,
|
||||
},
|
||||
},
|
||||
},
|
||||
// Build config path based on profile mode
|
||||
const objectsSection = globalMask
|
||||
? { objects: { mask: { [maskId]: maskConfig } } }
|
||||
: {
|
||||
objects: {
|
||||
filters: { [form_objects]: { mask: { [maskId]: maskConfig } } },
|
||||
},
|
||||
};
|
||||
|
||||
const cameraData = editingProfile
|
||||
? { profiles: { [editingProfile]: objectsSection } }
|
||||
: objectsSection;
|
||||
|
||||
const updateTopic = editingProfile
|
||||
? undefined
|
||||
: `config/cameras/${polygon.camera}/objects`;
|
||||
|
||||
const configBody = {
|
||||
config_data: {
|
||||
cameras: {
|
||||
[polygon.camera]: cameraData,
|
||||
},
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/objects`,
|
||||
};
|
||||
} else {
|
||||
configBody = {
|
||||
config_data: {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
objects: {
|
||||
filters: {
|
||||
[form_objects]: {
|
||||
mask: {
|
||||
[maskId]: maskConfig,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/objects`,
|
||||
};
|
||||
}
|
||||
},
|
||||
requires_restart: 0,
|
||||
update_topic: updateTopic,
|
||||
};
|
||||
|
||||
axios
|
||||
.put("config/set", configBody)
|
||||
@@ -259,8 +256,10 @@ export default function ObjectMaskEditPane({
|
||||
},
|
||||
);
|
||||
updateConfig();
|
||||
// Publish the enabled state through websocket
|
||||
sendObjectMaskState(enabled ? "ON" : "OFF");
|
||||
// Only publish WS state for base config
|
||||
if (!editingProfile) {
|
||||
sendObjectMaskState(enabled ? "ON" : "OFF");
|
||||
}
|
||||
} else {
|
||||
toast.error(
|
||||
t("toast.save.error.title", {
|
||||
@@ -301,6 +300,7 @@ export default function ObjectMaskEditPane({
|
||||
cameraConfig,
|
||||
t,
|
||||
sendObjectMaskState,
|
||||
editingProfile,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ import { Trans, useTranslation } from "react-i18next";
|
||||
import ActivityIndicator from "../indicators/activity-indicator";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useMotionMaskState, useObjectMaskState, useZoneState } from "@/api/ws";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
|
||||
type PolygonItemProps = {
|
||||
polygon: Polygon;
|
||||
@@ -48,6 +49,8 @@ type PolygonItemProps = {
|
||||
setIsLoading: (loading: boolean) => void;
|
||||
loadingPolygonIndex: number | undefined;
|
||||
setLoadingPolygonIndex: (index: number | undefined) => void;
|
||||
editingProfile?: string | null;
|
||||
allProfileNames?: string[];
|
||||
};
|
||||
|
||||
export default function PolygonItem({
|
||||
@@ -62,6 +65,8 @@ export default function PolygonItem({
|
||||
setIsLoading,
|
||||
loadingPolygonIndex,
|
||||
setLoadingPolygonIndex,
|
||||
editingProfile,
|
||||
allProfileNames,
|
||||
}: PolygonItemProps) {
|
||||
const { t } = useTranslation("views/settings");
|
||||
const { data: config, mutate: updateConfig } =
|
||||
@@ -107,6 +112,8 @@ export default function PolygonItem({
|
||||
|
||||
const PolygonItemIcon = polygon ? polygonTypeIcons[polygon.type] : undefined;
|
||||
|
||||
const isBasePolygon = !!editingProfile && polygon.polygonSource === "base";
|
||||
|
||||
const saveToConfig = useCallback(
|
||||
async (polygon: Polygon) => {
|
||||
if (!polygon || !cameraConfig) {
|
||||
@@ -122,25 +129,36 @@ export default function PolygonItem({
|
||||
? "objects"
|
||||
: polygon.type;
|
||||
|
||||
const updateTopic = editingProfile
|
||||
? undefined
|
||||
: `config/cameras/${polygon.camera}/${updateTopicType}`;
|
||||
|
||||
setIsLoading(true);
|
||||
setLoadingPolygonIndex(index);
|
||||
|
||||
if (polygon.type === "zone") {
|
||||
// Zones use query string format
|
||||
const { alertQueries, detectionQueries } = reviewQueries(
|
||||
polygon.name,
|
||||
false,
|
||||
false,
|
||||
polygon.camera,
|
||||
cameraConfig?.review.alerts.required_zones || [],
|
||||
cameraConfig?.review.detections.required_zones || [],
|
||||
);
|
||||
const url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}`;
|
||||
let url: string;
|
||||
|
||||
if (editingProfile) {
|
||||
// Profile mode: just delete the profile zone
|
||||
url = `cameras.${polygon.camera}.profiles.${editingProfile}.zones.${polygon.name}`;
|
||||
} else {
|
||||
// Base mode: handle review queries
|
||||
const { alertQueries, detectionQueries } = reviewQueries(
|
||||
polygon.name,
|
||||
false,
|
||||
false,
|
||||
polygon.camera,
|
||||
cameraConfig?.review.alerts.required_zones || [],
|
||||
cameraConfig?.review.detections.required_zones || [],
|
||||
);
|
||||
url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}`;
|
||||
}
|
||||
|
||||
await axios
|
||||
.put(`config/set?${url}`, {
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/${updateTopicType}`,
|
||||
update_topic: updateTopic,
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.status === 200) {
|
||||
@@ -178,64 +196,34 @@ export default function PolygonItem({
|
||||
}
|
||||
|
||||
// Motion masks and object masks use JSON body format
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let configUpdate: any = {};
|
||||
|
||||
if (polygon.type === "motion_mask") {
|
||||
// Delete mask from motion.mask dict by setting it to undefined
|
||||
configUpdate = {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
motion: {
|
||||
mask: {
|
||||
[polygon.name]: null, // Setting to null will delete the key
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (polygon.type === "object_mask") {
|
||||
// Determine if this is a global mask or object-specific mask
|
||||
const isGlobalMask = !polygon.objects.length;
|
||||
|
||||
if (isGlobalMask) {
|
||||
configUpdate = {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
objects: {
|
||||
mask: {
|
||||
[polygon.name]: null, // Setting to null will delete the key
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
configUpdate = {
|
||||
cameras: {
|
||||
[polygon.camera]: {
|
||||
const deleteSection =
|
||||
polygon.type === "motion_mask"
|
||||
? { motion: { mask: { [polygon.name]: null } } }
|
||||
: !polygon.objects.length
|
||||
? { objects: { mask: { [polygon.name]: null } } }
|
||||
: {
|
||||
objects: {
|
||||
filters: {
|
||||
[polygon.objects[0]]: {
|
||||
mask: {
|
||||
[polygon.name]: null, // Setting to null will delete the key
|
||||
},
|
||||
mask: { [polygon.name]: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const configUpdate = {
|
||||
cameras: {
|
||||
[polygon.camera]: editingProfile
|
||||
? { profiles: { [editingProfile]: deleteSection } }
|
||||
: deleteSection,
|
||||
},
|
||||
};
|
||||
|
||||
await axios
|
||||
.put("config/set", {
|
||||
config_data: configUpdate,
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/${updateTopicType}`,
|
||||
update_topic: updateTopic,
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.status === 200) {
|
||||
@@ -278,6 +266,7 @@ export default function PolygonItem({
|
||||
setIsLoading,
|
||||
index,
|
||||
setLoadingPolygonIndex,
|
||||
editingProfile,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -289,14 +278,19 @@ export default function PolygonItem({
|
||||
const handleToggleEnabled = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
// Prevent toggling if disabled in config
|
||||
if (polygon.enabled_in_config === false) {
|
||||
// Prevent toggling if disabled in config or if this is a base polygon in profile mode
|
||||
if (polygon.enabled_in_config === false || isBasePolygon) {
|
||||
return;
|
||||
}
|
||||
if (!polygon) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't toggle via WS in profile mode
|
||||
if (editingProfile) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isEnabled = isPolygonEnabled;
|
||||
const nextState = isEnabled ? "OFF" : "ON";
|
||||
|
||||
@@ -320,6 +314,8 @@ export default function PolygonItem({
|
||||
sendZoneState,
|
||||
sendMotionMaskState,
|
||||
sendObjectMaskState,
|
||||
isBasePolygon,
|
||||
editingProfile,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -358,7 +354,12 @@ export default function PolygonItem({
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleToggleEnabled}
|
||||
disabled={isLoading || polygon.enabled_in_config === false}
|
||||
disabled={
|
||||
isLoading ||
|
||||
polygon.enabled_in_config === false ||
|
||||
isBasePolygon ||
|
||||
!!editingProfile
|
||||
}
|
||||
className="mr-2 shrink-0 cursor-pointer border-none bg-transparent p-0 transition-opacity hover:opacity-70 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<PolygonItemIcon
|
||||
@@ -384,15 +385,37 @@ export default function PolygonItem({
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
{editingProfile &&
|
||||
(polygon.polygonSource === "profile" ||
|
||||
polygon.polygonSource === "override") &&
|
||||
allProfileNames && (
|
||||
<span
|
||||
className={cn(
|
||||
"mr-1.5 inline-block h-2 w-2 shrink-0 rounded-full",
|
||||
getProfileColor(editingProfile, allProfileNames).dot,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<p
|
||||
className={cn(
|
||||
"cursor-default",
|
||||
!isPolygonEnabled && "opacity-60",
|
||||
polygon.enabled_in_config === false && "line-through",
|
||||
isBasePolygon && "opacity-50",
|
||||
)}
|
||||
>
|
||||
{polygon.friendly_name ?? polygon.name}
|
||||
{!isPolygonEnabled && " (disabled)"}
|
||||
{isBasePolygon && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">
|
||||
{t("masksAndZones.profileBase", { ns: "views/settings" })}
|
||||
</span>
|
||||
)}
|
||||
{polygon.polygonSource === "override" && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">
|
||||
{t("masksAndZones.profileOverride", { ns: "views/settings" })}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<AlertDialog
|
||||
@@ -459,7 +482,7 @@ export default function PolygonItem({
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
aria-label={t("button.delete", { ns: "common" })}
|
||||
disabled={isLoading}
|
||||
disabled={isLoading || isBasePolygon}
|
||||
onClick={() => setDeleteDialogOpen(true)}
|
||||
>
|
||||
{t("button.delete", { ns: "common" })}
|
||||
@@ -531,9 +554,12 @@ export default function PolygonItem({
|
||||
"size-[15px] cursor-pointer",
|
||||
hoveredPolygonIndex === index &&
|
||||
"fill-primary-variant text-primary-variant",
|
||||
isLoading && "cursor-not-allowed opacity-50",
|
||||
(isLoading || isBasePolygon) &&
|
||||
"cursor-not-allowed opacity-50",
|
||||
)}
|
||||
onClick={() => !isLoading && setDeleteDialogOpen(true)}
|
||||
onClick={() =>
|
||||
!isLoading && !isBasePolygon && setDeleteDialogOpen(true)
|
||||
}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Check, ChevronDown } from "lucide-react";
|
||||
import { LuLayers } from "react-icons/lu";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type ProfileSectionDropdownProps = {
|
||||
allProfileNames: string[];
|
||||
profileFriendlyNames: Map<string, string>;
|
||||
editingProfile: string | null;
|
||||
hasProfileData: (profileName: string) => boolean;
|
||||
onSelectProfile: (profileName: string | null) => void;
|
||||
/** When true, show only an icon as the trigger (for mobile) */
|
||||
iconOnly?: boolean;
|
||||
};
|
||||
|
||||
export function ProfileSectionDropdown({
|
||||
allProfileNames,
|
||||
profileFriendlyNames,
|
||||
editingProfile,
|
||||
hasProfileData,
|
||||
onSelectProfile,
|
||||
iconOnly = false,
|
||||
}: ProfileSectionDropdownProps) {
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
|
||||
const activeColor = editingProfile
|
||||
? getProfileColor(editingProfile, allProfileNames)
|
||||
: null;
|
||||
|
||||
const editingFriendlyName = editingProfile
|
||||
? (profileFriendlyNames.get(editingProfile) ?? editingProfile)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
{iconOnly ? (
|
||||
<Button variant="outline" size="sm">
|
||||
<LuLayers className="size-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline" className="h-9 gap-2 font-normal">
|
||||
{editingProfile ? (
|
||||
<>
|
||||
<span
|
||||
className={cn(
|
||||
"h-2 w-2 shrink-0 rounded-full",
|
||||
activeColor?.dot,
|
||||
)}
|
||||
/>
|
||||
{editingFriendlyName}
|
||||
</>
|
||||
) : (
|
||||
t("profiles.baseConfig", { ns: "views/settings" })
|
||||
)}
|
||||
<ChevronDown className="h-3 w-3 opacity-50" />
|
||||
</Button>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="min-w-[180px]">
|
||||
<DropdownMenuItem onClick={() => onSelectProfile(null)}>
|
||||
<div className="flex w-full items-center gap-2">
|
||||
{editingProfile === null && (
|
||||
<Check className="h-3.5 w-3.5 shrink-0" />
|
||||
)}
|
||||
<span className={editingProfile === null ? "" : "pl-[22px]"}>
|
||||
{t("profiles.baseConfig", { ns: "views/settings" })}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
|
||||
{allProfileNames.length > 0 && <DropdownMenuSeparator />}
|
||||
|
||||
{allProfileNames.map((profile) => {
|
||||
const color = getProfileColor(profile, allProfileNames);
|
||||
const hasData = hasProfileData(profile);
|
||||
const isActive = editingProfile === profile;
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={profile}
|
||||
className="group flex items-start justify-between gap-2"
|
||||
onClick={() => onSelectProfile(profile)}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<div className="flex w-full flex-row items-center justify-start gap-2">
|
||||
{isActive && <Check className="h-3.5 w-3.5 shrink-0" />}
|
||||
<span
|
||||
className={cn(
|
||||
"h-2 w-2 shrink-0 rounded-full",
|
||||
color.dot,
|
||||
!isActive && "ml-[22px]",
|
||||
)}
|
||||
/>
|
||||
<span>{profileFriendlyNames.get(profile) ?? profile}</span>
|
||||
</div>
|
||||
{!hasData && (
|
||||
<span className="ml-[22px] text-xs text-muted-foreground">
|
||||
{t("profiles.noOverrides", { ns: "views/settings" })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -50,6 +50,7 @@ type ZoneEditPaneProps = {
|
||||
setActiveLine: React.Dispatch<React.SetStateAction<number | undefined>>;
|
||||
snapPoints: boolean;
|
||||
setSnapPoints: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
editingProfile?: string | null;
|
||||
};
|
||||
|
||||
export default function ZoneEditPane({
|
||||
@@ -65,6 +66,7 @@ export default function ZoneEditPane({
|
||||
setActiveLine,
|
||||
snapPoints,
|
||||
setSnapPoints,
|
||||
editingProfile,
|
||||
}: ZoneEditPaneProps) {
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
@@ -101,15 +103,23 @@ export default function ZoneEditPane({
|
||||
}, [polygon, config]);
|
||||
|
||||
const [lineA, lineB, lineC, lineD] = useMemo(() => {
|
||||
const distances =
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.distances;
|
||||
if (!polygon?.camera || !polygon?.name || !config) {
|
||||
return [undefined, undefined, undefined, undefined];
|
||||
}
|
||||
|
||||
// Check profile zone first, then base
|
||||
const profileZone = editingProfile
|
||||
? config.cameras[polygon.camera]?.profiles?.[editingProfile]?.zones?.[
|
||||
polygon.name
|
||||
]
|
||||
: undefined;
|
||||
const baseZone = config.cameras[polygon.camera]?.zones[polygon.name];
|
||||
const distances = profileZone?.distances ?? baseZone?.distances;
|
||||
|
||||
return Array.isArray(distances)
|
||||
? distances.map((value) => parseFloat(value) || 0)
|
||||
: [undefined, undefined, undefined, undefined];
|
||||
}, [polygon, config]);
|
||||
}, [polygon, config, editingProfile]);
|
||||
|
||||
const formSchema = z
|
||||
.object({
|
||||
@@ -272,6 +282,17 @@ export default function ZoneEditPane({
|
||||
},
|
||||
);
|
||||
|
||||
// Resolve zone data: profile zone takes priority over base
|
||||
const resolvedZoneData = useMemo(() => {
|
||||
if (!polygon?.camera || !polygon?.name || !config) return undefined;
|
||||
const cam = config.cameras[polygon.camera];
|
||||
if (!cam) return undefined;
|
||||
const profileZone = editingProfile
|
||||
? cam.profiles?.[editingProfile]?.zones?.[polygon.name]
|
||||
: undefined;
|
||||
return profileZone ?? cam.zones[polygon.name];
|
||||
}, [polygon, config, editingProfile]);
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
mode: "onBlur",
|
||||
@@ -279,20 +300,11 @@ export default function ZoneEditPane({
|
||||
name: polygon?.name ?? "",
|
||||
friendly_name: polygon?.friendly_name ?? polygon?.name ?? "",
|
||||
enabled:
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.enabled !==
|
||||
undefined
|
||||
? config?.cameras[polygon.camera]?.zones[polygon.name]?.enabled
|
||||
resolvedZoneData?.enabled !== undefined
|
||||
? resolvedZoneData.enabled
|
||||
: (polygon?.enabled ?? true),
|
||||
inertia:
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.inertia,
|
||||
loitering_time:
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.loitering_time,
|
||||
inertia: resolvedZoneData?.inertia,
|
||||
loitering_time: resolvedZoneData?.loitering_time,
|
||||
isFinished: polygon?.isFinished ?? false,
|
||||
objects: polygon?.objects ?? [],
|
||||
speedEstimation: !!(lineA || lineB || lineC || lineD),
|
||||
@@ -300,10 +312,7 @@ export default function ZoneEditPane({
|
||||
lineB,
|
||||
lineC,
|
||||
lineD,
|
||||
speed_threshold:
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.speed_threshold,
|
||||
speed_threshold: resolvedZoneData?.speed_threshold,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -341,6 +350,16 @@ export default function ZoneEditPane({
|
||||
if (!scaledWidth || !scaledHeight || !polygon) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine config path prefix based on profile mode
|
||||
const pathPrefix = editingProfile
|
||||
? `cameras.${polygon.camera}.profiles.${editingProfile}.zones.${zoneName}`
|
||||
: `cameras.${polygon.camera}.zones.${zoneName}`;
|
||||
|
||||
const oldPathPrefix = editingProfile
|
||||
? `cameras.${polygon.camera}.profiles.${editingProfile}.zones.${polygon.name}`
|
||||
: `cameras.${polygon.camera}.zones.${polygon.name}`;
|
||||
|
||||
let mutatedConfig = config;
|
||||
let alertQueries = "";
|
||||
let detectionQueries = "";
|
||||
@@ -349,55 +368,74 @@ export default function ZoneEditPane({
|
||||
|
||||
if (renamingZone) {
|
||||
// rename - delete old zone and replace with new
|
||||
const zoneInAlerts =
|
||||
cameraConfig?.review.alerts.required_zones.includes(polygon.name) ??
|
||||
false;
|
||||
const zoneInDetections =
|
||||
cameraConfig?.review.detections.required_zones.includes(
|
||||
let renameAlertQueries = "";
|
||||
let renameDetectionQueries = "";
|
||||
|
||||
// Only handle review queries for base config (not profiles)
|
||||
if (!editingProfile) {
|
||||
const zoneInAlerts =
|
||||
cameraConfig?.review.alerts.required_zones.includes(polygon.name) ??
|
||||
false;
|
||||
const zoneInDetections =
|
||||
cameraConfig?.review.detections.required_zones.includes(
|
||||
polygon.name,
|
||||
) ?? false;
|
||||
|
||||
({
|
||||
alertQueries: renameAlertQueries,
|
||||
detectionQueries: renameDetectionQueries,
|
||||
} = reviewQueries(
|
||||
polygon.name,
|
||||
) ?? false;
|
||||
false,
|
||||
false,
|
||||
polygon.camera,
|
||||
cameraConfig?.review.alerts.required_zones || [],
|
||||
cameraConfig?.review.detections.required_zones || [],
|
||||
));
|
||||
|
||||
const {
|
||||
alertQueries: renameAlertQueries,
|
||||
detectionQueries: renameDetectionQueries,
|
||||
} = reviewQueries(
|
||||
polygon.name,
|
||||
false,
|
||||
false,
|
||||
polygon.camera,
|
||||
cameraConfig?.review.alerts.required_zones || [],
|
||||
cameraConfig?.review.detections.required_zones || [],
|
||||
);
|
||||
try {
|
||||
await axios.put(
|
||||
`config/set?${oldPathPrefix}${renameAlertQueries}${renameDetectionQueries}`,
|
||||
{
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/zones`,
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
await axios.put(
|
||||
`config/set?cameras.${polygon.camera}.zones.${polygon.name}${renameAlertQueries}${renameDetectionQueries}`,
|
||||
{
|
||||
// Wait for the config to be updated
|
||||
mutatedConfig = await updateConfig();
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// make sure new zone name is readded to review
|
||||
({ alertQueries, detectionQueries } = reviewQueries(
|
||||
zoneName,
|
||||
zoneInAlerts,
|
||||
zoneInDetections,
|
||||
polygon.camera,
|
||||
mutatedConfig?.cameras[polygon.camera]?.review.alerts
|
||||
.required_zones || [],
|
||||
mutatedConfig?.cameras[polygon.camera]?.review.detections
|
||||
.required_zones || [],
|
||||
));
|
||||
} else {
|
||||
// Profile mode: just delete the old profile zone path
|
||||
try {
|
||||
await axios.put(`config/set?${oldPathPrefix}`, {
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/zones`,
|
||||
},
|
||||
);
|
||||
|
||||
// Wait for the config to be updated
|
||||
mutatedConfig = await updateConfig();
|
||||
} catch (error) {
|
||||
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
return;
|
||||
});
|
||||
mutatedConfig = await updateConfig();
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.noMessage", { ns: "common" }), {
|
||||
position: "top-center",
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// make sure new zone name is readded to review
|
||||
({ alertQueries, detectionQueries } = reviewQueries(
|
||||
zoneName,
|
||||
zoneInAlerts,
|
||||
zoneInDetections,
|
||||
polygon.camera,
|
||||
mutatedConfig?.cameras[polygon.camera]?.review.alerts
|
||||
.required_zones || [],
|
||||
mutatedConfig?.cameras[polygon.camera]?.review.detections
|
||||
.required_zones || [],
|
||||
));
|
||||
}
|
||||
|
||||
const coordinates = flattenPoints(
|
||||
@@ -405,10 +443,7 @@ export default function ZoneEditPane({
|
||||
).join(",");
|
||||
|
||||
let objectQueries = objects
|
||||
.map(
|
||||
(object) =>
|
||||
`&cameras.${polygon?.camera}.zones.${zoneName}.objects=${object}`,
|
||||
)
|
||||
.map((object) => `&${pathPrefix}.objects=${object}`)
|
||||
.join("");
|
||||
|
||||
const same_objects =
|
||||
@@ -419,55 +454,55 @@ export default function ZoneEditPane({
|
||||
|
||||
// deleting objects
|
||||
if (!objectQueries && !same_objects && !renamingZone) {
|
||||
objectQueries = `&cameras.${polygon?.camera}.zones.${zoneName}.objects`;
|
||||
objectQueries = `&${pathPrefix}.objects`;
|
||||
}
|
||||
|
||||
let inertiaQuery = "";
|
||||
if (inertia) {
|
||||
inertiaQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.inertia=${inertia}`;
|
||||
inertiaQuery = `&${pathPrefix}.inertia=${inertia}`;
|
||||
}
|
||||
|
||||
let loiteringTimeQuery = "";
|
||||
if (loitering_time >= 0) {
|
||||
loiteringTimeQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.loitering_time=${loitering_time}`;
|
||||
loiteringTimeQuery = `&${pathPrefix}.loitering_time=${loitering_time}`;
|
||||
}
|
||||
|
||||
let distancesQuery = "";
|
||||
const distances = [lineA, lineB, lineC, lineD].filter(Boolean).join(",");
|
||||
if (speedEstimation) {
|
||||
distancesQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.distances=${distances}`;
|
||||
distancesQuery = `&${pathPrefix}.distances=${distances}`;
|
||||
} else {
|
||||
if (distances != "") {
|
||||
distancesQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.distances`;
|
||||
distancesQuery = `&${pathPrefix}.distances`;
|
||||
}
|
||||
}
|
||||
|
||||
let speedThresholdQuery = "";
|
||||
if (speed_threshold >= 0 && speedEstimation) {
|
||||
speedThresholdQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.speed_threshold=${speed_threshold}`;
|
||||
speedThresholdQuery = `&${pathPrefix}.speed_threshold=${speed_threshold}`;
|
||||
} else {
|
||||
if (
|
||||
polygon?.camera &&
|
||||
polygon?.name &&
|
||||
config?.cameras[polygon.camera]?.zones[polygon.name]?.speed_threshold
|
||||
) {
|
||||
speedThresholdQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.speed_threshold`;
|
||||
if (resolvedZoneData?.speed_threshold) {
|
||||
speedThresholdQuery = `&${pathPrefix}.speed_threshold`;
|
||||
}
|
||||
}
|
||||
|
||||
let friendlyNameQuery = "";
|
||||
if (friendly_name && friendly_name !== zoneName) {
|
||||
friendlyNameQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.friendly_name=${encodeURIComponent(friendly_name)}`;
|
||||
friendlyNameQuery = `&${pathPrefix}.friendly_name=${encodeURIComponent(friendly_name)}`;
|
||||
}
|
||||
|
||||
const enabledQuery = `&cameras.${polygon?.camera}.zones.${zoneName}.enabled=${enabled ? "True" : "False"}`;
|
||||
const enabledQuery = `&${pathPrefix}.enabled=${enabled ? "True" : "False"}`;
|
||||
|
||||
const updateTopic = editingProfile
|
||||
? undefined
|
||||
: `config/cameras/${polygon.camera}/zones`;
|
||||
|
||||
axios
|
||||
.put(
|
||||
`config/set?cameras.${polygon?.camera}.zones.${zoneName}.coordinates=${coordinates}${enabledQuery}${inertiaQuery}${loiteringTimeQuery}${speedThresholdQuery}${distancesQuery}${objectQueries}${friendlyNameQuery}${alertQueries}${detectionQueries}`,
|
||||
`config/set?${pathPrefix}.coordinates=${coordinates}${enabledQuery}${inertiaQuery}${loiteringTimeQuery}${speedThresholdQuery}${distancesQuery}${objectQueries}${friendlyNameQuery}${alertQueries}${detectionQueries}`,
|
||||
{
|
||||
requires_restart: 0,
|
||||
update_topic: `config/cameras/${polygon.camera}/zones`,
|
||||
update_topic: updateTopic,
|
||||
},
|
||||
)
|
||||
.then((res) => {
|
||||
@@ -481,8 +516,10 @@ export default function ZoneEditPane({
|
||||
},
|
||||
);
|
||||
updateConfig();
|
||||
// Publish the enabled state through websocket
|
||||
sendZoneState(enabled ? "ON" : "OFF");
|
||||
// Only publish WS state for base config (not profiles)
|
||||
if (!editingProfile) {
|
||||
sendZoneState(enabled ? "ON" : "OFF");
|
||||
}
|
||||
} else {
|
||||
toast.error(
|
||||
t("toast.save.error.title", {
|
||||
@@ -524,6 +561,8 @@ export default function ZoneEditPane({
|
||||
cameraConfig,
|
||||
t,
|
||||
sendZoneState,
|
||||
editingProfile,
|
||||
resolvedZoneData,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -746,7 +785,7 @@ export default function ZoneEditPane({
|
||||
</div>
|
||||
<FormDescription>
|
||||
{t("masksAndZones.zones.speedEstimation.desc")}
|
||||
<div className="mt-2 flex items-center text-primary">
|
||||
<span className="mt-2 flex items-center text-primary">
|
||||
<Link
|
||||
to={getLocaleDocUrl(
|
||||
"configuration/zones#speed-estimation",
|
||||
@@ -758,7 +797,7 @@ export default function ZoneEditPane({
|
||||
{t("readTheDocumentation", { ns: "common" })}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</span>
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
|
||||
@@ -136,7 +136,7 @@ export default function EventMenu({
|
||||
download
|
||||
href={
|
||||
event.has_snapshot
|
||||
? `${apiHost}api/events/${event.id}/snapshot.jpg`
|
||||
? `${apiHost}api/events/${event.id}/snapshot.jpg?crop=0&bbox=1×tamp=0`
|
||||
: `${apiHost}api/events/${event.id}/thumbnail.webp`
|
||||
}
|
||||
>
|
||||
|
||||
@@ -18,18 +18,25 @@ export default function useCameraLiveMode(
|
||||
|
||||
const streamNames = new Set<string>();
|
||||
cameras.forEach((camera) => {
|
||||
const isRestreamed = Object.keys(config.go2rtc.streams || {}).includes(
|
||||
Object.values(camera.live.streams)[0],
|
||||
);
|
||||
if (activeStreams && activeStreams[camera.name]) {
|
||||
const selectedStreamName = activeStreams[camera.name];
|
||||
const isRestreamed = Object.keys(config.go2rtc.streams || {}).includes(
|
||||
selectedStreamName,
|
||||
);
|
||||
|
||||
if (isRestreamed) {
|
||||
if (activeStreams && activeStreams[camera.name]) {
|
||||
streamNames.add(activeStreams[camera.name]);
|
||||
} else {
|
||||
Object.values(camera.live.streams).forEach((streamName) => {
|
||||
streamNames.add(streamName);
|
||||
});
|
||||
if (isRestreamed) {
|
||||
streamNames.add(selectedStreamName);
|
||||
}
|
||||
} else {
|
||||
Object.values(camera.live.streams).forEach((streamName) => {
|
||||
const isRestreamed = Object.keys(
|
||||
config.go2rtc.streams || {},
|
||||
).includes(streamName);
|
||||
|
||||
if (isRestreamed) {
|
||||
streamNames.add(streamName);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -66,11 +73,11 @@ export default function useCameraLiveMode(
|
||||
} = {};
|
||||
|
||||
cameras.forEach((camera) => {
|
||||
const selectedStreamName =
|
||||
activeStreams?.[camera.name] ?? Object.values(camera.live.streams)[0];
|
||||
const isRestreamed =
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(
|
||||
Object.values(camera.live.streams)[0],
|
||||
);
|
||||
Object.keys(config.go2rtc.streams || {}).includes(selectedStreamName);
|
||||
|
||||
newIsRestreamedStates[camera.name] = isRestreamed ?? false;
|
||||
|
||||
@@ -101,14 +108,21 @@ export default function useCameraLiveMode(
|
||||
setPreferredLiveModes(newPreferredLiveModes);
|
||||
setIsRestreamedStates(newIsRestreamedStates);
|
||||
setSupportsAudioOutputStates(newSupportsAudioOutputStates);
|
||||
}, [cameras, config, windowVisible, streamMetadata]);
|
||||
}, [activeStreams, cameras, config, windowVisible, streamMetadata]);
|
||||
|
||||
const resetPreferredLiveMode = useCallback(
|
||||
(cameraName: string) => {
|
||||
const mseSupported =
|
||||
"MediaSource" in window || "ManagedMediaSource" in window;
|
||||
const cameraConfig = cameras.find((camera) => camera.name === cameraName);
|
||||
const selectedStreamName =
|
||||
activeStreams?.[cameraName] ??
|
||||
(cameraConfig
|
||||
? Object.values(cameraConfig.live.streams)[0]
|
||||
: cameraName);
|
||||
const isRestreamed =
|
||||
config && Object.keys(config.go2rtc.streams || {}).includes(cameraName);
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(selectedStreamName);
|
||||
|
||||
setPreferredLiveModes((prevModes) => {
|
||||
const newModes = { ...prevModes };
|
||||
@@ -122,7 +136,7 @@ export default function useCameraLiveMode(
|
||||
return newModes;
|
||||
});
|
||||
},
|
||||
[config],
|
||||
[activeStreams, cameras, config],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -6,6 +6,7 @@ import set from "lodash/set";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { JsonObject, JsonValue } from "@/types/configForm";
|
||||
import { isJsonObject } from "@/lib/utils";
|
||||
import { getBaseCameraSectionValue } from "@/utils/configUtil";
|
||||
|
||||
const INTERNAL_FIELD_SUFFIXES = ["enabled_in_config", "raw_mask"];
|
||||
|
||||
@@ -144,7 +145,13 @@ export function useConfigOverride({
|
||||
};
|
||||
}
|
||||
|
||||
const cameraValue = get(cameraConfig, sectionPath);
|
||||
// Prefer the base (pre-profile) value so that override detection and
|
||||
// widget context reflect the camera's own config, not profile effects.
|
||||
const cameraValue = getBaseCameraSectionValue(
|
||||
config,
|
||||
cameraName,
|
||||
sectionPath,
|
||||
);
|
||||
|
||||
const normalizedGlobalValue = normalizeConfigValue(globalValue);
|
||||
const normalizedCameraValue = normalizeConfigValue(cameraValue);
|
||||
@@ -256,7 +263,9 @@ export function useAllCameraOverrides(
|
||||
|
||||
for (const { key, compareFields } of sectionsToCheck) {
|
||||
const globalValue = normalizeConfigValue(get(config, key));
|
||||
const cameraValue = normalizeConfigValue(get(cameraConfig, key));
|
||||
const cameraValue = normalizeConfigValue(
|
||||
getBaseCameraSectionValue(config, cameraName, key),
|
||||
);
|
||||
|
||||
const comparisonGlobal = compareFields
|
||||
? pickFields(globalValue, compareFields)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useAllowedCameras } from "@/hooks/use-allowed-cameras";
|
||||
import useSWR from "swr";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
|
||||
/**
|
||||
* Returns true if the current user has access to all cameras.
|
||||
* This is used to determine birdseye access — users who can see
|
||||
* all cameras should also be able to see the birdseye view.
|
||||
*/
|
||||
export function useHasFullCameraAccess() {
|
||||
const allowedCameras = useAllowedCameras();
|
||||
const { data: config } = useSWR<FrigateConfig>("config", {
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
|
||||
if (!config?.cameras) return false;
|
||||
|
||||
const enabledCameraNames = Object.entries(config.cameras)
|
||||
.filter(([, cam]) => cam.enabled_in_config)
|
||||
.map(([name]) => name);
|
||||
|
||||
return (
|
||||
enabledCameraNames.length > 0 &&
|
||||
enabledCameraNames.every((name) => allowedCameras.includes(name))
|
||||
);
|
||||
}
|
||||
@@ -98,8 +98,8 @@ function normalizeNullableSchema(schema: RJSFSchema): RJSFSchema {
|
||||
: ["null"];
|
||||
const { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schemaObj;
|
||||
const merged: Record<string, unknown> = {
|
||||
...rest,
|
||||
...normalizedNonNullObj,
|
||||
...rest,
|
||||
type: mergedType,
|
||||
};
|
||||
// When unwrapping a nullable enum, add null to the enum list so
|
||||
@@ -110,6 +110,39 @@ function normalizeNullableSchema(schema: RJSFSchema): RJSFSchema {
|
||||
return merged as RJSFSchema;
|
||||
}
|
||||
|
||||
// Handle anyOf where a plain string branch subsumes a string-enum branch
|
||||
// (e.g. Union[StrEnum, str] or Union[StrEnum, str, None]).
|
||||
// Collapse to a single string type with enum values preserved as `examples`.
|
||||
const stringBranches = anyOf.filter(
|
||||
(item) =>
|
||||
isSchemaObject(item) &&
|
||||
(item as Record<string, unknown>).type === "string",
|
||||
);
|
||||
const enumBranch = stringBranches.find((item) =>
|
||||
Array.isArray((item as Record<string, unknown>).enum),
|
||||
);
|
||||
const plainStringBranch = stringBranches.find(
|
||||
(item) => !Array.isArray((item as Record<string, unknown>).enum),
|
||||
);
|
||||
|
||||
if (
|
||||
enumBranch &&
|
||||
plainStringBranch &&
|
||||
anyOf.length === stringBranches.length + (hasNull ? 1 : 0)
|
||||
) {
|
||||
const enumValues = (enumBranch as Record<string, unknown>).enum as
|
||||
| unknown[]
|
||||
| undefined;
|
||||
const { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schemaObj;
|
||||
return {
|
||||
...rest,
|
||||
type: hasNull ? ["string", "null"] : "string",
|
||||
...(enumValues && enumValues.length > 0
|
||||
? { examples: enumValues }
|
||||
: {}),
|
||||
} as RJSFSchema;
|
||||
}
|
||||
|
||||
return {
|
||||
...schemaObj,
|
||||
anyOf: anyOf
|
||||
@@ -142,8 +175,8 @@ function normalizeNullableSchema(schema: RJSFSchema): RJSFSchema {
|
||||
: ["null"];
|
||||
const { anyOf: _anyOf, oneOf: _oneOf, ...rest } = schemaObj;
|
||||
const merged: Record<string, unknown> = {
|
||||
...rest,
|
||||
...normalizedNonNullObj,
|
||||
...rest,
|
||||
type: mergedType,
|
||||
};
|
||||
// When unwrapping a nullable oneOf enum, add null to the enum list.
|
||||
@@ -538,6 +571,67 @@ function generateUiSchema(
|
||||
return uiSchema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes hidden field properties from the JSON schema itself so RJSF won't
|
||||
* validate them. The existing ui:widget=hidden approach only hides rendering
|
||||
* but still validates — fields with server-only values (e.g. raw_coordinates
|
||||
* serialized as null) cause spurious validation errors.
|
||||
*
|
||||
* Supports dotted paths ("mask"), nested paths ("genai.enabled_in_config"),
|
||||
* and wildcard segments ("filters.*.mask") where `*` matches
|
||||
* additionalProperties.
|
||||
*/
|
||||
function stripHiddenFieldsFromSchema(
|
||||
schema: RJSFSchema,
|
||||
hiddenFields: string[],
|
||||
): void {
|
||||
for (const pattern of hiddenFields) {
|
||||
if (!pattern) continue;
|
||||
const segments = pattern.split(".");
|
||||
removePropertyBySegments(schema, segments);
|
||||
}
|
||||
}
|
||||
|
||||
function removePropertyBySegments(
|
||||
schema: RJSFSchema,
|
||||
segments: string[],
|
||||
): void {
|
||||
if (segments.length === 0 || !isSchemaObject(schema)) return;
|
||||
|
||||
const [head, ...rest] = segments;
|
||||
const props = schema.properties as Record<string, RJSFSchema> | undefined;
|
||||
|
||||
if (rest.length === 0) {
|
||||
// Terminal segment — delete the property
|
||||
if (head === "*") {
|
||||
// Wildcard at leaf: strip from additionalProperties
|
||||
if (isSchemaObject(schema.additionalProperties)) {
|
||||
// Nothing to delete — "*" as the last segment means "every dynamic key".
|
||||
// The parent's additionalProperties schema IS the dynamic value, not a
|
||||
// container. In practice hidden-field patterns always have a named leaf
|
||||
// after the wildcard (e.g. "filters.*.mask"), so this branch is a no-op.
|
||||
}
|
||||
} else if (props && head in props) {
|
||||
delete props[head];
|
||||
if (Array.isArray(schema.required)) {
|
||||
schema.required = (schema.required as string[]).filter(
|
||||
(r) => r !== head,
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (head === "*") {
|
||||
// Wildcard segment — descend into additionalProperties
|
||||
if (isSchemaObject(schema.additionalProperties)) {
|
||||
removePropertyBySegments(schema.additionalProperties as RJSFSchema, rest);
|
||||
}
|
||||
} else if (props && head in props && isSchemaObject(props[head])) {
|
||||
removePropertyBySegments(props[head], rest);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a Pydantic JSON Schema to RJSF format
|
||||
* Resolves references and generates appropriate uiSchema
|
||||
@@ -550,6 +644,11 @@ export function transformSchema(
|
||||
const cleanSchema = resolveAndCleanSchema(rawSchema);
|
||||
const normalizedSchema = normalizeNullableSchema(cleanSchema);
|
||||
|
||||
// Remove hidden fields from schema so RJSF won't validate them
|
||||
if (options.hiddenFields && options.hiddenFields.length > 0) {
|
||||
stripHiddenFieldsFromSchema(normalizedSchema, options.hiddenFields);
|
||||
}
|
||||
|
||||
// Generate uiSchema
|
||||
const uiSchema = generateUiSchema(normalizedSchema, options);
|
||||
|
||||
|
||||
@@ -220,7 +220,7 @@ function Exports() {
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("deleteExport")}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("deleteExport.label")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("deleteExport.desc", { exportName: deleteClip?.exportName })}
|
||||
</AlertDialogDescription>
|
||||
|
||||
@@ -266,6 +266,34 @@ export default function FaceLibrary() {
|
||||
[setPageToggle, refreshFaces, t],
|
||||
);
|
||||
|
||||
const onReclassify = useCallback(
|
||||
(image: string, newName: string) => {
|
||||
axios
|
||||
.post(`/faces/${pageToggle}/reclassify`, {
|
||||
id: image,
|
||||
new_name: newName,
|
||||
})
|
||||
.then((resp) => {
|
||||
if (resp.status == 200) {
|
||||
toast.success(t("toast.success.reclassifiedFace"), {
|
||||
position: "top-center",
|
||||
});
|
||||
refreshFaces();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
const errorMessage =
|
||||
error.response?.data?.message ||
|
||||
error.response?.data?.detail ||
|
||||
"Unknown error";
|
||||
toast.error(t("toast.error.reclassifyFailed", { errorMessage }), {
|
||||
position: "top-center",
|
||||
});
|
||||
});
|
||||
},
|
||||
[pageToggle, refreshFaces, t],
|
||||
);
|
||||
|
||||
// keyboard
|
||||
|
||||
const contentRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -452,10 +480,12 @@ export default function FaceLibrary() {
|
||||
<FaceGrid
|
||||
contentRef={contentRef}
|
||||
faceImages={faceImages}
|
||||
faceNames={faces}
|
||||
pageToggle={pageToggle}
|
||||
selectedFaces={selectedFaces}
|
||||
onClickFaces={onClickFaces}
|
||||
onDelete={onDelete}
|
||||
onReclassify={onReclassify}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
@@ -598,10 +628,10 @@ function LibrarySelector({
|
||||
{Object.values(faces).map((face) => (
|
||||
<DropdownMenuItem
|
||||
key={face}
|
||||
className="group flex items-center justify-between"
|
||||
className="group flex items-center justify-between p-0"
|
||||
>
|
||||
<div
|
||||
className="flex-grow cursor-pointer"
|
||||
className="flex-grow cursor-pointer px-2 py-1.5"
|
||||
onClick={() => setPageToggle(face)}
|
||||
>
|
||||
{face}
|
||||
@@ -609,7 +639,7 @@ function LibrarySelector({
|
||||
({faceData?.[face].length})
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-0.5">
|
||||
<div className="flex gap-0.5 px-2">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
@@ -983,18 +1013,22 @@ function FaceAttemptGroup({
|
||||
type FaceGridProps = {
|
||||
contentRef: MutableRefObject<HTMLDivElement | null>;
|
||||
faceImages: string[];
|
||||
faceNames: string[];
|
||||
pageToggle: string;
|
||||
selectedFaces: string[];
|
||||
onClickFaces: (images: string[], ctrl: boolean) => void;
|
||||
onDelete: (name: string, ids: string[]) => void;
|
||||
onReclassify: (image: string, newName: string) => void;
|
||||
};
|
||||
function FaceGrid({
|
||||
contentRef,
|
||||
faceImages,
|
||||
faceNames,
|
||||
pageToggle,
|
||||
selectedFaces,
|
||||
onClickFaces,
|
||||
onDelete,
|
||||
onReclassify,
|
||||
}: FaceGridProps) {
|
||||
const { t } = useTranslation(["views/faceLibrary"]);
|
||||
|
||||
@@ -1032,6 +1066,17 @@ function FaceGrid({
|
||||
i18nLibrary="views/faceLibrary"
|
||||
onClick={(data, meta) => onClickFaces([data.filename], meta)}
|
||||
>
|
||||
<FaceSelectionDialog
|
||||
faceNames={faceNames}
|
||||
excludeName={pageToggle}
|
||||
dialogLabel={t("reclassifyFaceAs")}
|
||||
tooltipLabel={t("reclassifyFace")}
|
||||
onTrainAttempt={(newName) => onReclassify(image, newName)}
|
||||
>
|
||||
<BlurredIconButton>
|
||||
<AddFaceIcon className="size-5" />
|
||||
</BlurredIconButton>
|
||||
</FaceSelectionDialog>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<LuTrash2
|
||||
|
||||
@@ -11,12 +11,12 @@ import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import useSWR from "swr";
|
||||
import { useAllowedCameras } from "@/hooks/use-allowed-cameras";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { useHasFullCameraAccess } from "@/hooks/use-has-full-camera-access";
|
||||
|
||||
function Live() {
|
||||
const { t } = useTranslation(["views/live"]);
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const isAdmin = useIsAdmin();
|
||||
const hasFullCameraAccess = useHasFullCameraAccess();
|
||||
|
||||
// selection
|
||||
|
||||
@@ -81,7 +81,7 @@ function Live() {
|
||||
camera: `${cameraGroup[0].toUpperCase()}${cameraGroup.substring(1)}`,
|
||||
});
|
||||
} else {
|
||||
document.title = t("documentTitle", { ns: "views/live" });
|
||||
document.title = t("documentTitle.default", { ns: "views/live" });
|
||||
}
|
||||
}, [cameraGroup, selectedCameraName, t]);
|
||||
|
||||
@@ -90,8 +90,8 @@ function Live() {
|
||||
const allowedCameras = useAllowedCameras();
|
||||
|
||||
const includesBirdseye = useMemo(() => {
|
||||
// Restricted users should never have access to birdseye
|
||||
if (!isAdmin) {
|
||||
// Users without access to all cameras should not have access to birdseye
|
||||
if (!hasFullCameraAccess) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ function Live() {
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}, [config, cameraGroup, isAdmin]);
|
||||
}, [config, cameraGroup, hasFullCameraAccess]);
|
||||
|
||||
const cameras = useMemo(() => {
|
||||
if (!config) {
|
||||
@@ -151,7 +151,9 @@ function Live() {
|
||||
|
||||
return (
|
||||
<div className="size-full" ref={mainRef}>
|
||||
{selectedCameraName === "birdseye" ? (
|
||||
{selectedCameraName === "birdseye" &&
|
||||
hasFullCameraAccess &&
|
||||
config?.birdseye?.enabled ? (
|
||||
<LiveBirdseyeView
|
||||
supportsFullscreen={supportsFullScreen}
|
||||
fullscreen={fullscreen}
|
||||
|
||||
+424
-40
@@ -28,7 +28,11 @@ import useOptimisticState from "@/hooks/use-optimistic-state";
|
||||
import { isMobile } from "react-device-detect";
|
||||
import { FaVideo } from "react-icons/fa";
|
||||
import { CameraConfig, FrigateConfig } from "@/types/frigateConfig";
|
||||
import type { ConfigSectionData } from "@/types/configForm";
|
||||
import type {
|
||||
ConfigSectionData,
|
||||
JsonObject,
|
||||
JsonValue,
|
||||
} from "@/types/configForm";
|
||||
import useSWR from "swr";
|
||||
import FilterSwitch from "@/components/filter/FilterSwitch";
|
||||
import { ZoneMaskFilterButton } from "@/components/filter/ZoneMaskFilter";
|
||||
@@ -39,9 +43,11 @@ import MasksAndZonesView from "@/views/settings/MasksAndZonesView";
|
||||
import UsersView from "@/views/settings/UsersView";
|
||||
import RolesView from "@/views/settings/RolesView";
|
||||
import UiSettingsView from "@/views/settings/UiSettingsView";
|
||||
import ProfilesView from "@/views/settings/ProfilesView";
|
||||
import FrigatePlusSettingsView from "@/views/settings/FrigatePlusSettingsView";
|
||||
import MediaSyncSettingsView from "@/views/settings/MediaSyncSettingsView";
|
||||
import RegionGridSettingsView from "@/views/settings/RegionGridSettingsView";
|
||||
import Go2RtcStreamsSettingsView from "@/views/settings/Go2RtcStreamsSettingsView";
|
||||
import SystemDetectionModelSettingsView from "@/views/settings/SystemDetectionModelSettingsView";
|
||||
import {
|
||||
SingleSectionPage,
|
||||
@@ -87,8 +93,13 @@ import { mutate } from "swr";
|
||||
import { RJSFSchema } from "@rjsf/utils";
|
||||
import {
|
||||
buildConfigDataForPath,
|
||||
parseProfileFromSectionPath,
|
||||
prepareSectionSavePayload,
|
||||
PROFILE_ELIGIBLE_SECTIONS,
|
||||
} from "@/utils/configUtil";
|
||||
import type { ProfileState, ProfilesApiResponse } from "@/types/profile";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
import { ProfileSectionDropdown } from "@/components/settings/ProfileSectionDropdown";
|
||||
import ActivityIndicator from "@/components/indicators/activity-indicator";
|
||||
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
|
||||
import SaveAllPreviewPopover, {
|
||||
@@ -97,7 +108,8 @@ import SaveAllPreviewPopover, {
|
||||
import { useRestart } from "@/api/ws";
|
||||
|
||||
const allSettingsViews = [
|
||||
"profileSettings",
|
||||
"uiSettings",
|
||||
"profiles",
|
||||
"globalDetect",
|
||||
"globalRecording",
|
||||
"globalSnapshots",
|
||||
@@ -121,6 +133,7 @@ const allSettingsViews = [
|
||||
"systemDetectorHardware",
|
||||
"systemDetectionModel",
|
||||
"systemMqtt",
|
||||
"systemGo2rtcStreams",
|
||||
"integrationSemanticSearch",
|
||||
"integrationGenerativeAi",
|
||||
"integrationFaceRecognition",
|
||||
@@ -178,15 +191,15 @@ const parsePendingDataKey = (pendingDataKey: string) => {
|
||||
};
|
||||
|
||||
const flattenOverrides = (
|
||||
value: unknown,
|
||||
value: JsonValue | undefined,
|
||||
path: string[] = [],
|
||||
): Array<{ path: string; value: unknown }> => {
|
||||
): Array<{ path: string; value: JsonValue }> => {
|
||||
if (value === undefined) return [];
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
return [{ path: path.join("."), value }];
|
||||
}
|
||||
|
||||
const entries = Object.entries(value as Record<string, unknown>);
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 0) {
|
||||
return [{ path: path.join("."), value: {} }];
|
||||
}
|
||||
@@ -308,7 +321,7 @@ const CameraTimestampStyleSettingsPage = createSectionPage(
|
||||
const settingsGroups = [
|
||||
{
|
||||
label: "general",
|
||||
items: [{ key: "profileSettings", component: UiSettingsView }],
|
||||
items: [{ key: "uiSettings", component: UiSettingsView }],
|
||||
},
|
||||
{
|
||||
label: "globalConfig",
|
||||
@@ -334,6 +347,7 @@ const settingsGroups = [
|
||||
{
|
||||
label: "cameras",
|
||||
items: [
|
||||
{ key: "profiles", component: ProfilesView },
|
||||
{ key: "cameraManagement", component: CameraManagementView },
|
||||
{ key: "cameraDetect", component: CameraDetectSettingsPage },
|
||||
{ key: "cameraObjects", component: CameraObjectsSettingsPage },
|
||||
@@ -402,6 +416,10 @@ const settingsGroups = [
|
||||
{
|
||||
label: "system",
|
||||
items: [
|
||||
{
|
||||
key: "systemGo2rtcStreams",
|
||||
component: Go2RtcStreamsSettingsView,
|
||||
},
|
||||
{
|
||||
key: "systemDetectorHardware",
|
||||
component: SystemDetectorHardwareSettingsPage,
|
||||
@@ -479,7 +497,7 @@ const CAMERA_SELECT_BUTTON_PAGES = [
|
||||
"regionGrid",
|
||||
];
|
||||
|
||||
const ALLOWED_VIEWS_FOR_VIEWER = ["profileSettings", "notifications"];
|
||||
const ALLOWED_VIEWS_FOR_VIEWER = ["uiSettings", "notifications"];
|
||||
|
||||
// keys for camera sections
|
||||
const CAMERA_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
@@ -503,6 +521,28 @@ const CAMERA_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
timestamp_style: "cameraTimestampStyle",
|
||||
};
|
||||
|
||||
// Reverse mapping: page key → config section key
|
||||
const REVERSE_CAMERA_SECTION_MAPPING: Record<string, string> =
|
||||
Object.fromEntries(
|
||||
Object.entries(CAMERA_SECTION_MAPPING).map(([section, page]) => [
|
||||
page,
|
||||
section,
|
||||
]),
|
||||
);
|
||||
// masksAndZones is a composite page, not in CAMERA_SECTION_MAPPING
|
||||
REVERSE_CAMERA_SECTION_MAPPING["masksAndZones"] = "masksAndZones";
|
||||
|
||||
// Pages where the profile dropdown should appear
|
||||
const PROFILE_DROPDOWN_PAGES = new Set(
|
||||
Object.entries(REVERSE_CAMERA_SECTION_MAPPING)
|
||||
.filter(
|
||||
([, sectionKey]) =>
|
||||
PROFILE_ELIGIBLE_SECTIONS.has(sectionKey) ||
|
||||
sectionKey === "masksAndZones",
|
||||
)
|
||||
.map(([pageKey]) => pageKey),
|
||||
);
|
||||
|
||||
// keys for global sections
|
||||
const GLOBAL_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
detect: "globalDetect",
|
||||
@@ -528,6 +568,7 @@ const ENRICHMENTS_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
};
|
||||
|
||||
const SYSTEM_SECTION_MAPPING: Record<string, SettingsType> = {
|
||||
go2rtc_streams: "systemGo2rtcStreams",
|
||||
database: "systemDatabase",
|
||||
mqtt: "systemMqtt",
|
||||
tls: "systemTls",
|
||||
@@ -594,7 +635,7 @@ function MobileMenuItem({
|
||||
|
||||
export default function Settings() {
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
const [page, setPage] = useState<SettingsType>("profileSettings");
|
||||
const [page, setPage] = useState<SettingsType>("uiSettings");
|
||||
const [pageToggle, setPageToggle] = useOptimisticState(page, setPage, 100);
|
||||
const [contentMobileOpen, setContentMobileOpen] = useState(false);
|
||||
const [sectionStatusByKey, setSectionStatusByKey] = useState<
|
||||
@@ -602,6 +643,7 @@ export default function Settings() {
|
||||
>({});
|
||||
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const { data: profilesData } = useSWR<ProfilesApiResponse>("profiles");
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
@@ -618,9 +660,28 @@ export default function Settings() {
|
||||
|
||||
// Store pending form data keyed by "sectionKey" or "cameraName::sectionKey"
|
||||
const [pendingDataBySection, setPendingDataBySection] = useState<
|
||||
Record<string, unknown>
|
||||
Record<string, ConfigSectionData>
|
||||
>({});
|
||||
|
||||
// Profile editing state
|
||||
const [editingProfile, setEditingProfile] = useState<
|
||||
Record<string, string | null>
|
||||
>({});
|
||||
const [profilesUIEnabled, setProfilesUIEnabled] = useState(false);
|
||||
|
||||
const allProfileNames = useMemo(() => {
|
||||
if (!config?.profiles) return [];
|
||||
return Object.keys(config.profiles).sort();
|
||||
}, [config]);
|
||||
|
||||
const profileFriendlyNames = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
if (profilesData?.profiles) {
|
||||
profilesData.profiles.forEach((p) => map.set(p.name, p.friendly_name));
|
||||
}
|
||||
return map;
|
||||
}, [profilesData]);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const cameras = useMemo(() => {
|
||||
@@ -692,11 +753,22 @@ export default function Settings() {
|
||||
|
||||
const { scope, cameraName, sectionPath } =
|
||||
parsePendingDataKey(pendingDataKey);
|
||||
const { isProfile, profileName, actualSection } =
|
||||
parseProfileFromSectionPath(sectionPath);
|
||||
const flattened = flattenOverrides(payload.sanitizedOverrides);
|
||||
const displaySection = isProfile ? actualSection : sectionPath;
|
||||
|
||||
flattened.forEach(({ path, value }) => {
|
||||
const fieldPath = path ? `${sectionPath}.${path}` : sectionPath;
|
||||
items.push({ scope, cameraName, fieldPath, value });
|
||||
const fieldPath = path ? `${displaySection}.${path}` : displaySection;
|
||||
items.push({
|
||||
scope,
|
||||
cameraName,
|
||||
profileName: isProfile
|
||||
? (profileFriendlyNames.get(profileName!) ?? profileName)
|
||||
: undefined,
|
||||
fieldPath,
|
||||
value,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -710,7 +782,7 @@ export default function Settings() {
|
||||
if (cameraCompare !== 0) return cameraCompare;
|
||||
return left.fieldPath.localeCompare(right.fieldPath);
|
||||
});
|
||||
}, [config, fullSchema, pendingDataBySection]);
|
||||
}, [config, fullSchema, pendingDataBySection, profileFriendlyNames]);
|
||||
|
||||
// Map a pendingDataKey to SettingsType menu key for clearing section status
|
||||
const pendingKeyToMenuKey = useCallback(
|
||||
@@ -726,15 +798,20 @@ export default function Settings() {
|
||||
level = "global";
|
||||
}
|
||||
|
||||
// For profile keys like "profiles.armed.detect", extract the actual section
|
||||
const { actualSection } = parseProfileFromSectionPath(sectionPath);
|
||||
|
||||
if (level === "camera") {
|
||||
return CAMERA_SECTION_MAPPING[sectionPath] as SettingsType | undefined;
|
||||
return CAMERA_SECTION_MAPPING[actualSection] as
|
||||
| SettingsType
|
||||
| undefined;
|
||||
}
|
||||
return (
|
||||
(GLOBAL_SECTION_MAPPING[sectionPath] as SettingsType | undefined) ??
|
||||
(ENRICHMENTS_SECTION_MAPPING[sectionPath] as
|
||||
(GLOBAL_SECTION_MAPPING[actualSection] as SettingsType | undefined) ??
|
||||
(ENRICHMENTS_SECTION_MAPPING[actualSection] as
|
||||
| SettingsType
|
||||
| undefined) ??
|
||||
(SYSTEM_SECTION_MAPPING[sectionPath] as SettingsType | undefined)
|
||||
(SYSTEM_SECTION_MAPPING[actualSection] as SettingsType | undefined)
|
||||
);
|
||||
},
|
||||
[],
|
||||
@@ -759,6 +836,7 @@ export default function Settings() {
|
||||
|
||||
for (const key of pendingKeys) {
|
||||
const pendingData = pendingDataBySection[key];
|
||||
|
||||
try {
|
||||
const payload = prepareSectionSavePayload({
|
||||
pendingDataKey: key,
|
||||
@@ -884,6 +962,7 @@ export default function Settings() {
|
||||
|
||||
setPendingDataBySection({});
|
||||
setUnsavedChanges(false);
|
||||
setEditingProfile({});
|
||||
|
||||
setSectionStatusByKey((prev) => {
|
||||
const updated = { ...prev };
|
||||
@@ -940,7 +1019,7 @@ export default function Settings() {
|
||||
!isAdmin &&
|
||||
!ALLOWED_VIEWS_FOR_VIEWER.includes(page as SettingsType)
|
||||
) {
|
||||
setPageToggle("profileSettings");
|
||||
setPageToggle("uiSettings");
|
||||
} else {
|
||||
setPageToggle(page as SettingsType);
|
||||
}
|
||||
@@ -970,6 +1049,210 @@ export default function Settings() {
|
||||
}
|
||||
}, [t, contentMobileOpen]);
|
||||
|
||||
// Profile state handlers
|
||||
const handleSelectProfile = useCallback(
|
||||
(camera: string, _section: string, profile: string | null) => {
|
||||
setEditingProfile((prev) => {
|
||||
if (profile === null) {
|
||||
const { [camera]: _, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
return { ...prev, [camera]: profile };
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleDeleteProfileSection = useCallback(
|
||||
async (camera: string, section: string, profile: string) => {
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
cameras: {
|
||||
[camera]: {
|
||||
profiles: {
|
||||
[profile]: {
|
||||
[section]: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await mutate("config");
|
||||
// Switch back to base config
|
||||
handleSelectProfile(camera, section, null);
|
||||
toast.success(
|
||||
t("profiles.deleteSectionSuccess", {
|
||||
ns: "views/settings",
|
||||
section: t(`configForm.sections.${section}`, {
|
||||
ns: "views/settings",
|
||||
defaultValue: section,
|
||||
}),
|
||||
profile: profileFriendlyNames.get(profile) ?? profile,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.title", { ns: "common" }));
|
||||
}
|
||||
},
|
||||
[handleSelectProfile, profileFriendlyNames, t],
|
||||
);
|
||||
|
||||
const profileState: ProfileState = useMemo(
|
||||
() => ({
|
||||
editingProfile,
|
||||
allProfileNames,
|
||||
profileFriendlyNames,
|
||||
onSelectProfile: handleSelectProfile,
|
||||
onDeleteProfileSection: handleDeleteProfileSection,
|
||||
}),
|
||||
[
|
||||
editingProfile,
|
||||
allProfileNames,
|
||||
profileFriendlyNames,
|
||||
handleSelectProfile,
|
||||
handleDeleteProfileSection,
|
||||
],
|
||||
);
|
||||
|
||||
// Header profile dropdown: derive section key from current page
|
||||
const currentSectionKey = useMemo(
|
||||
() => REVERSE_CAMERA_SECTION_MAPPING[pageToggle] ?? null,
|
||||
[pageToggle],
|
||||
);
|
||||
|
||||
const headerEditingProfile = useMemo(() => {
|
||||
if (!selectedCamera || !currentSectionKey) return null;
|
||||
return editingProfile[selectedCamera] ?? null;
|
||||
}, [selectedCamera, currentSectionKey, editingProfile]);
|
||||
|
||||
const showProfileDropdown =
|
||||
PROFILE_DROPDOWN_PAGES.has(pageToggle) &&
|
||||
!!selectedCamera &&
|
||||
(allProfileNames.length > 0 || profilesUIEnabled);
|
||||
|
||||
const headerHasProfileData = useCallback(
|
||||
(profileName: string): boolean => {
|
||||
if (!config || !selectedCamera || !currentSectionKey) return false;
|
||||
const profileData =
|
||||
config.cameras[selectedCamera]?.profiles?.[profileName];
|
||||
if (!profileData) return false;
|
||||
|
||||
if (currentSectionKey === "masksAndZones") {
|
||||
const hasZones =
|
||||
profileData.zones && Object.keys(profileData.zones).length > 0;
|
||||
const hasMotionMasks =
|
||||
profileData.motion?.mask &&
|
||||
Object.keys(profileData.motion.mask).length > 0;
|
||||
const hasObjectMasks =
|
||||
(profileData.objects?.mask &&
|
||||
Object.keys(profileData.objects.mask).length > 0) ||
|
||||
(profileData.objects?.filters &&
|
||||
Object.values(profileData.objects.filters).some(
|
||||
(f) => f.mask && Object.keys(f.mask).length > 0,
|
||||
));
|
||||
return !!(hasZones || hasMotionMasks || hasObjectMasks);
|
||||
}
|
||||
|
||||
return !!profileData[currentSectionKey as keyof typeof profileData];
|
||||
},
|
||||
[config, selectedCamera, currentSectionKey],
|
||||
);
|
||||
|
||||
const handleDeleteProfileForCurrentSection = useCallback(
|
||||
async (profileName: string) => {
|
||||
if (!selectedCamera || !currentSectionKey) return;
|
||||
|
||||
if (currentSectionKey === "masksAndZones") {
|
||||
try {
|
||||
const profileData =
|
||||
config?.cameras?.[selectedCamera]?.profiles?.[profileName];
|
||||
if (!profileData) return;
|
||||
|
||||
// Build a targeted delete payload that only removes mask-related
|
||||
// sub-keys, not the entire motion/objects sections
|
||||
const deletePayload: JsonObject = {};
|
||||
|
||||
if (profileData.zones !== undefined) {
|
||||
deletePayload.zones = "";
|
||||
}
|
||||
|
||||
if (profileData.motion?.mask !== undefined) {
|
||||
deletePayload.motion = { mask: "" };
|
||||
}
|
||||
|
||||
if (profileData.objects) {
|
||||
const objDelete: JsonObject = {};
|
||||
if (profileData.objects.mask !== undefined) {
|
||||
objDelete.mask = "";
|
||||
}
|
||||
if (profileData.objects.filters) {
|
||||
const filtersDelete: JsonObject = {};
|
||||
for (const [filterName, filterVal] of Object.entries(
|
||||
profileData.objects.filters,
|
||||
)) {
|
||||
if (filterVal.mask !== undefined) {
|
||||
filtersDelete[filterName] = { mask: "" };
|
||||
}
|
||||
}
|
||||
if (Object.keys(filtersDelete).length > 0) {
|
||||
objDelete.filters = filtersDelete;
|
||||
}
|
||||
}
|
||||
if (Object.keys(objDelete).length > 0) {
|
||||
deletePayload.objects = objDelete;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(deletePayload).length === 0) return;
|
||||
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
cameras: {
|
||||
[selectedCamera]: {
|
||||
profiles: {
|
||||
[profileName]: deletePayload,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await mutate("config");
|
||||
handleSelectProfile(selectedCamera, "masksAndZones", null);
|
||||
toast.success(
|
||||
t("profiles.deleteSectionSuccess", {
|
||||
ns: "views/settings",
|
||||
section: t("configForm.sections.masksAndZones", {
|
||||
ns: "views/settings",
|
||||
}),
|
||||
profile: profileFriendlyNames.get(profileName) ?? profileName,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
toast.error(t("toast.save.error.title", { ns: "common" }));
|
||||
}
|
||||
} else {
|
||||
await handleDeleteProfileSection(
|
||||
selectedCamera,
|
||||
currentSectionKey,
|
||||
profileName,
|
||||
);
|
||||
}
|
||||
},
|
||||
[
|
||||
selectedCamera,
|
||||
currentSectionKey,
|
||||
config,
|
||||
handleSelectProfile,
|
||||
handleDeleteProfileSection,
|
||||
profileFriendlyNames,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSectionStatusChange = useCallback(
|
||||
(sectionKey: string, level: "global" | "camera", status: SectionStatus) => {
|
||||
// Map section keys to menu keys based on level
|
||||
@@ -1016,24 +1299,64 @@ export default function Settings() {
|
||||
[],
|
||||
);
|
||||
|
||||
// The active profile being edited for the selected camera
|
||||
const activeEditingProfile = selectedCamera
|
||||
? (editingProfile[selectedCamera] ?? null)
|
||||
: null;
|
||||
|
||||
// Profile color for the active editing profile
|
||||
const activeProfileColor = useMemo(
|
||||
() =>
|
||||
activeEditingProfile
|
||||
? getProfileColor(activeEditingProfile, allProfileNames)
|
||||
: undefined,
|
||||
[activeEditingProfile, allProfileNames],
|
||||
);
|
||||
|
||||
// Initialize override status for all camera sections
|
||||
useEffect(() => {
|
||||
if (!selectedCamera || !cameraOverrides) return;
|
||||
|
||||
const overrideMap: Partial<
|
||||
Record<SettingsType, Pick<SectionStatus, "hasChanges" | "isOverridden">>
|
||||
Record<
|
||||
SettingsType,
|
||||
Pick<SectionStatus, "hasChanges" | "isOverridden" | "overrideSource">
|
||||
>
|
||||
> = {};
|
||||
|
||||
// Build a set of menu keys that have pending changes for this camera
|
||||
const pendingMenuKeys = new Set<string>();
|
||||
const cameraPrefix = `${selectedCamera}::`;
|
||||
for (const key of Object.keys(pendingDataBySection)) {
|
||||
if (key.startsWith(cameraPrefix)) {
|
||||
const menuKey = pendingKeyToMenuKey(key);
|
||||
if (menuKey) pendingMenuKeys.add(menuKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Get profile data if a profile is being edited
|
||||
const profileData = activeEditingProfile
|
||||
? config?.cameras?.[selectedCamera]?.profiles?.[activeEditingProfile]
|
||||
: undefined;
|
||||
|
||||
// Set override status for all camera sections using the shared mapping
|
||||
Object.entries(CAMERA_SECTION_MAPPING).forEach(
|
||||
([sectionKey, settingsKey]) => {
|
||||
const isOverridden = cameraOverrides.includes(sectionKey);
|
||||
// Check if there are pending changes for this camera and section
|
||||
const pendingDataKey = `${selectedCamera}::${sectionKey}`;
|
||||
const hasChanges = pendingDataKey in pendingDataBySection;
|
||||
const globalOverridden = cameraOverrides.includes(sectionKey);
|
||||
|
||||
// Check if the active profile overrides this section
|
||||
const profileOverrides = profileData
|
||||
? !!profileData[sectionKey as keyof typeof profileData]
|
||||
: false;
|
||||
|
||||
overrideMap[settingsKey] = {
|
||||
hasChanges,
|
||||
isOverridden,
|
||||
hasChanges: pendingMenuKeys.has(settingsKey),
|
||||
isOverridden: profileOverrides || globalOverridden,
|
||||
overrideSource: profileOverrides
|
||||
? "profile"
|
||||
: globalOverridden
|
||||
? "global"
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
);
|
||||
@@ -1046,12 +1369,20 @@ export default function Settings() {
|
||||
merged[key as SettingsType] = {
|
||||
hasChanges: status.hasChanges,
|
||||
isOverridden: status.isOverridden,
|
||||
overrideSource: status.overrideSource,
|
||||
hasValidationErrors: existingStatus?.hasValidationErrors ?? false,
|
||||
};
|
||||
});
|
||||
return merged;
|
||||
});
|
||||
}, [selectedCamera, cameraOverrides, pendingDataBySection]);
|
||||
}, [
|
||||
selectedCamera,
|
||||
cameraOverrides,
|
||||
pendingDataBySection,
|
||||
pendingKeyToMenuKey,
|
||||
activeEditingProfile,
|
||||
config,
|
||||
]);
|
||||
|
||||
const renderMenuItemLabel = useCallback(
|
||||
(key: SettingsType) => {
|
||||
@@ -1060,13 +1391,22 @@ export default function Settings() {
|
||||
CAMERA_SECTION_KEYS.has(key) && status?.isOverridden;
|
||||
const showUnsavedDot = status?.hasChanges;
|
||||
|
||||
const dotColor =
|
||||
status?.overrideSource === "profile" && activeProfileColor
|
||||
? activeProfileColor.dot
|
||||
: "bg-selected";
|
||||
|
||||
return (
|
||||
<div className="flex w-full items-center justify-between pr-4 md:pr-0">
|
||||
<div>{t("menu." + key)}</div>
|
||||
<div className="flex w-full min-w-0 items-center justify-between pr-4 md:pr-0">
|
||||
<div className="min-w-0 flex-1 whitespace-normal break-words">
|
||||
{t("menu." + key)}
|
||||
</div>
|
||||
{(showOverrideDot || showUnsavedDot) && (
|
||||
<div className="ml-2 flex items-center gap-2">
|
||||
<div className="ml-2 flex shrink-0 items-center gap-2">
|
||||
{showOverrideDot && (
|
||||
<span className="inline-block size-2 rounded-full bg-selected" />
|
||||
<span
|
||||
className={cn("inline-block size-2 rounded-full", dotColor)}
|
||||
/>
|
||||
)}
|
||||
{showUnsavedDot && (
|
||||
<span className="inline-block size-2 rounded-full bg-danger" />
|
||||
@@ -1076,7 +1416,7 @@ export default function Settings() {
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[sectionStatusByKey, t],
|
||||
[sectionStatusByKey, t, activeProfileColor],
|
||||
);
|
||||
|
||||
if (isMobile) {
|
||||
@@ -1101,7 +1441,7 @@ export default function Settings() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-row text-center">
|
||||
<div className="flex flex-row items-center">
|
||||
<h2 className="ml-2 text-lg">
|
||||
{t("menu.settings", { ns: "common" })}
|
||||
</h2>
|
||||
@@ -1134,7 +1474,7 @@ export default function Settings() {
|
||||
key as SettingsType,
|
||||
)
|
||||
) {
|
||||
setPageToggle("profileSettings");
|
||||
setPageToggle("uiSettings");
|
||||
} else {
|
||||
setPageToggle(key as SettingsType);
|
||||
}
|
||||
@@ -1217,6 +1557,22 @@ export default function Settings() {
|
||||
updateZoneMaskFilter={setFilterZoneMask}
|
||||
/>
|
||||
)}
|
||||
{showProfileDropdown && currentSectionKey && (
|
||||
<ProfileSectionDropdown
|
||||
allProfileNames={allProfileNames}
|
||||
profileFriendlyNames={profileFriendlyNames}
|
||||
editingProfile={headerEditingProfile}
|
||||
hasProfileData={headerHasProfileData}
|
||||
onSelectProfile={(profile) =>
|
||||
handleSelectProfile(
|
||||
selectedCamera,
|
||||
currentSectionKey,
|
||||
profile,
|
||||
)
|
||||
}
|
||||
iconOnly
|
||||
/>
|
||||
)}
|
||||
<CameraSelectButton
|
||||
allCameras={cameras}
|
||||
selectedCamera={selectedCamera}
|
||||
@@ -1244,6 +1600,12 @@ export default function Settings() {
|
||||
onSectionStatusChange={handleSectionStatusChange}
|
||||
pendingDataBySection={pendingDataBySection}
|
||||
onPendingDataChange={handlePendingDataChange}
|
||||
profileState={profileState}
|
||||
onDeleteProfileSection={
|
||||
handleDeleteProfileForCurrentSection
|
||||
}
|
||||
profilesUIEnabled={profilesUIEnabled}
|
||||
setProfilesUIEnabled={setProfilesUIEnabled}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
@@ -1288,10 +1650,12 @@ export default function Settings() {
|
||||
<div className="flex h-full flex-col">
|
||||
<Toaster position="top-center" />
|
||||
<div className="flex min-h-16 items-center justify-between border-b border-secondary p-3">
|
||||
<Heading as="h3" className="mb-0">
|
||||
{t("menu.settings", { ns: "common" })}
|
||||
</Heading>
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="mr-2 flex w-full items-center justify-between gap-3">
|
||||
<Heading as="h3" className="mb-0">
|
||||
{t("menu.settings", { ns: "common" })}
|
||||
</Heading>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasPendingChanges && (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -1327,7 +1691,7 @@ export default function Settings() {
|
||||
>
|
||||
{isSavingAll ? (
|
||||
<>
|
||||
<ActivityIndicator className="mr-2" />
|
||||
<ActivityIndicator className="mr-2 size-4" />
|
||||
{t("button.savingAll", { ns: "common" })}
|
||||
</>
|
||||
) : (
|
||||
@@ -1344,6 +1708,21 @@ export default function Settings() {
|
||||
updateZoneMaskFilter={setFilterZoneMask}
|
||||
/>
|
||||
)}
|
||||
{showProfileDropdown && currentSectionKey && (
|
||||
<ProfileSectionDropdown
|
||||
allProfileNames={allProfileNames}
|
||||
profileFriendlyNames={profileFriendlyNames}
|
||||
editingProfile={headerEditingProfile}
|
||||
hasProfileData={headerHasProfileData}
|
||||
onSelectProfile={(profile) =>
|
||||
handleSelectProfile(
|
||||
selectedCamera,
|
||||
currentSectionKey,
|
||||
profile,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<CameraSelectButton
|
||||
allCameras={cameras}
|
||||
selectedCamera={selectedCamera}
|
||||
@@ -1370,7 +1749,7 @@ export default function Settings() {
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
className="ml-0"
|
||||
className="ml-0 h-auto min-h-8 py-1.5"
|
||||
isActive={pageToggle === filteredItems[0].key}
|
||||
onClick={() => {
|
||||
if (
|
||||
@@ -1379,7 +1758,7 @@ export default function Settings() {
|
||||
filteredItems[0].key as SettingsType,
|
||||
)
|
||||
) {
|
||||
setPageToggle("profileSettings");
|
||||
setPageToggle("uiSettings");
|
||||
} else {
|
||||
setPageToggle(
|
||||
filteredItems[0].key as SettingsType,
|
||||
@@ -1411,6 +1790,7 @@ export default function Settings() {
|
||||
{filteredItems.map((item) => (
|
||||
<SidebarMenuSubItem key={item.key}>
|
||||
<SidebarMenuSubButton
|
||||
className="h-auto w-full py-1.5"
|
||||
isActive={pageToggle === item.key}
|
||||
onClick={() => {
|
||||
if (
|
||||
@@ -1419,7 +1799,7 @@ export default function Settings() {
|
||||
item.key as SettingsType,
|
||||
)
|
||||
) {
|
||||
setPageToggle("profileSettings");
|
||||
setPageToggle("uiSettings");
|
||||
} else {
|
||||
setPageToggle(item.key as SettingsType);
|
||||
}
|
||||
@@ -1459,6 +1839,10 @@ export default function Settings() {
|
||||
onSectionStatusChange={handleSectionStatusChange}
|
||||
pendingDataBySection={pendingDataBySection}
|
||||
onPendingDataChange={handlePendingDataChange}
|
||||
profileState={profileState}
|
||||
onDeleteProfileSection={handleDeleteProfileForCurrentSection}
|
||||
profilesUIEnabled={profilesUIEnabled}
|
||||
setProfilesUIEnabled={setProfilesUIEnabled}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -162,6 +162,10 @@ export type CameraConfigData = {
|
||||
input_args?: string;
|
||||
}[];
|
||||
};
|
||||
detect?: {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
live?: {
|
||||
streams: Record<string, string>;
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ export type Polygon = {
|
||||
friendly_name?: string;
|
||||
enabled?: boolean;
|
||||
enabled_in_config?: boolean;
|
||||
polygonSource?: "base" | "profile" | "override";
|
||||
};
|
||||
|
||||
export type ZoneFormValuesType = {
|
||||
|
||||
@@ -23,7 +23,7 @@ export type ConfigFormContext = {
|
||||
extraHasChanges?: boolean;
|
||||
setExtraHasChanges?: (hasChanges: boolean) => void;
|
||||
formData?: JsonObject;
|
||||
pendingDataBySection?: Record<string, unknown>;
|
||||
pendingDataBySection?: Record<string, ConfigSectionData>;
|
||||
onPendingDataChange?: (
|
||||
sectionKey: string,
|
||||
cameraName: string | undefined,
|
||||
|
||||
@@ -72,6 +72,10 @@ export interface CameraConfig {
|
||||
};
|
||||
enabled: boolean;
|
||||
enabled_in_config: boolean;
|
||||
face_recognition: {
|
||||
enabled: boolean;
|
||||
min_area: number;
|
||||
};
|
||||
ffmpeg: {
|
||||
global_args: string[];
|
||||
hwaccel_args: string;
|
||||
@@ -99,6 +103,12 @@ export interface CameraConfig {
|
||||
quality: number;
|
||||
streams: { [key: string]: string };
|
||||
};
|
||||
lpr: {
|
||||
enabled: boolean;
|
||||
expire_time: number;
|
||||
min_area: number;
|
||||
enhancement: number;
|
||||
};
|
||||
motion: {
|
||||
contour_area: number;
|
||||
delta_alpha: number;
|
||||
@@ -263,7 +273,6 @@ export interface CameraConfig {
|
||||
};
|
||||
snapshots: {
|
||||
bounding_box: boolean;
|
||||
clean_copy: boolean;
|
||||
crop: boolean;
|
||||
enabled: boolean;
|
||||
height: number | null;
|
||||
@@ -305,8 +314,31 @@ export interface CameraConfig {
|
||||
friendly_name?: string;
|
||||
};
|
||||
};
|
||||
profiles?: Record<string, CameraProfileConfig>;
|
||||
/** Pre-profile base section configs, present only when a profile is active */
|
||||
base_config?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export type CameraProfileConfig = {
|
||||
enabled?: boolean;
|
||||
audio?: Partial<CameraConfig["audio"]>;
|
||||
birdseye?: Partial<CameraConfig["birdseye"]>;
|
||||
detect?: Partial<CameraConfig["detect"]>;
|
||||
face_recognition?: Partial<CameraConfig["face_recognition"]>;
|
||||
lpr?: Partial<CameraConfig["lpr"]>;
|
||||
motion?: Partial<CameraConfig["motion"]>;
|
||||
notifications?: Partial<CameraConfig["notifications"]>;
|
||||
objects?: Partial<CameraConfig["objects"]>;
|
||||
record?: Partial<CameraConfig["record"]>;
|
||||
review?: Partial<CameraConfig["review"]>;
|
||||
snapshots?: Partial<CameraConfig["snapshots"]>;
|
||||
zones?: Partial<CameraConfig["zones"]>;
|
||||
};
|
||||
|
||||
export type ProfileDefinitionConfig = {
|
||||
friendly_name: string;
|
||||
};
|
||||
|
||||
export type CameraGroupConfig = {
|
||||
cameras: string[];
|
||||
icon: IconName;
|
||||
@@ -369,6 +401,7 @@ export interface FrigateConfig {
|
||||
};
|
||||
|
||||
auth: {
|
||||
enabled: boolean;
|
||||
roles: {
|
||||
[roleName: string]: string[];
|
||||
};
|
||||
@@ -453,7 +486,7 @@ export interface FrigateConfig {
|
||||
};
|
||||
|
||||
go2rtc: {
|
||||
streams: string[];
|
||||
streams: Record<string, string | string[]>;
|
||||
webrtc: {
|
||||
candidates: string[];
|
||||
};
|
||||
@@ -461,6 +494,8 @@ export interface FrigateConfig {
|
||||
|
||||
camera_groups: { [groupName: string]: CameraGroupConfig };
|
||||
|
||||
profiles: { [profileName: string]: ProfileDefinitionConfig };
|
||||
|
||||
lpr: {
|
||||
enabled: boolean;
|
||||
};
|
||||
@@ -580,7 +615,6 @@ export interface FrigateConfig {
|
||||
|
||||
snapshots: {
|
||||
bounding_box: boolean;
|
||||
clean_copy: boolean;
|
||||
crop: boolean;
|
||||
enabled: boolean;
|
||||
height: number | null;
|
||||
|
||||
@@ -24,8 +24,8 @@ export const EmbeddingThreshold = {
|
||||
} as Threshold;
|
||||
|
||||
export const GenAIThreshold = {
|
||||
warning: 30000,
|
||||
error: 60000,
|
||||
warning: 60,
|
||||
error: 120,
|
||||
} as Threshold;
|
||||
|
||||
export const DetectorTempThreshold = {
|
||||
|
||||
@@ -11,3 +11,7 @@ export type PreviewPlayback = {
|
||||
preview: Preview | undefined;
|
||||
timeRange: TimeRange;
|
||||
};
|
||||
|
||||
export type VodManifest = {
|
||||
sequences: { clips: { clipFrom?: number }[] }[];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
export type ProfileColor = {
|
||||
bg: string;
|
||||
text: string;
|
||||
dot: string;
|
||||
border: string;
|
||||
bgMuted: string;
|
||||
};
|
||||
|
||||
export type ProfileInfo = {
|
||||
name: string;
|
||||
friendly_name: string;
|
||||
};
|
||||
|
||||
export type ProfilesApiResponse = {
|
||||
profiles: ProfileInfo[];
|
||||
active_profile: string | null;
|
||||
};
|
||||
|
||||
export type ProfileState = {
|
||||
editingProfile: Record<string, string | null>;
|
||||
allProfileNames: string[];
|
||||
profileFriendlyNames: Map<string, string>;
|
||||
onSelectProfile: (
|
||||
camera: string,
|
||||
section: string,
|
||||
profile: string | null,
|
||||
) => void;
|
||||
onDeleteProfileSection: (
|
||||
camera: string,
|
||||
section: string,
|
||||
profile: string,
|
||||
) => void;
|
||||
};
|
||||
@@ -115,6 +115,51 @@ export type CameraAudioFeatures = {
|
||||
* @param requireSecureContext - If true, two-way audio requires secure context (default: true)
|
||||
* @returns CameraAudioFeatures object with detected capabilities
|
||||
*/
|
||||
/**
|
||||
* Calculates optimal detect dimensions from stream resolution.
|
||||
*
|
||||
* Scales dimensions to an efficient size for object detection while
|
||||
* preserving the stream's aspect ratio. Does not upscale.
|
||||
*
|
||||
* @param streamWidth - Native stream width in pixels
|
||||
* @param streamHeight - Native stream height in pixels
|
||||
* @returns Detect dimensions with even values, or null if inputs are invalid
|
||||
*/
|
||||
|
||||
// Target size for the smaller dimension (width or height) for detect streams
|
||||
export const DETECT_TARGET_PX = 720;
|
||||
|
||||
export function calculateDetectDimensions(
|
||||
streamWidth: number,
|
||||
streamHeight: number,
|
||||
): { width: number; height: number } | null {
|
||||
if (
|
||||
!Number.isFinite(streamWidth) ||
|
||||
!Number.isFinite(streamHeight) ||
|
||||
streamWidth <= 0 ||
|
||||
streamHeight <= 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const smallerDim = Math.min(streamWidth, streamHeight);
|
||||
const target = Math.min(DETECT_TARGET_PX, smallerDim);
|
||||
const scale = target / smallerDim;
|
||||
|
||||
let width = Math.round(streamWidth * scale);
|
||||
let height = Math.round(streamHeight * scale);
|
||||
|
||||
// Round down to even numbers (required for video processing)
|
||||
width = width - (width % 2);
|
||||
height = height - (height % 2);
|
||||
|
||||
if (width < 2 || height < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
export function detectCameraAudioFeatures(
|
||||
metadata: LiveStreamMetadata | null | undefined,
|
||||
requireSecureContext: boolean = true,
|
||||
|
||||
+148
-21
@@ -6,6 +6,7 @@
|
||||
|
||||
import get from "lodash/get";
|
||||
import cloneDeep from "lodash/cloneDeep";
|
||||
import merge from "lodash/merge";
|
||||
import unset from "lodash/unset";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import mergeWith from "lodash/mergeWith";
|
||||
@@ -68,6 +69,63 @@ export const globalCameraDefaultSections = new Set([
|
||||
"ffmpeg",
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Profile helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the base (pre-profile) value for a camera section.
|
||||
*
|
||||
* When a profile is active the API populates `base_config` with original
|
||||
* section values. This helper returns that value when available, falling
|
||||
* back to the top-level (effective) value otherwise.
|
||||
*/
|
||||
export function getBaseCameraSectionValue(
|
||||
config: FrigateConfig | undefined,
|
||||
cameraName: string | undefined,
|
||||
sectionPath: string,
|
||||
): unknown {
|
||||
if (!config || !cameraName) return undefined;
|
||||
const cam = config.cameras?.[cameraName];
|
||||
if (!cam) return undefined;
|
||||
const base = cam.base_config?.[sectionPath];
|
||||
return base !== undefined ? base : get(cam, sectionPath);
|
||||
}
|
||||
|
||||
/** Sections that can appear inside a camera profile definition. */
|
||||
export const PROFILE_ELIGIBLE_SECTIONS = new Set([
|
||||
"audio",
|
||||
"birdseye",
|
||||
"detect",
|
||||
"face_recognition",
|
||||
"lpr",
|
||||
"motion",
|
||||
"notifications",
|
||||
"objects",
|
||||
"record",
|
||||
"review",
|
||||
"snapshots",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Parse a section path that may encode a profile reference.
|
||||
*
|
||||
* Examples:
|
||||
* "detect" → { isProfile: false, actualSection: "detect" }
|
||||
* "profiles.armed.detect" → { isProfile: true, profileName: "armed", actualSection: "detect" }
|
||||
*/
|
||||
export function parseProfileFromSectionPath(sectionPath: string): {
|
||||
isProfile: boolean;
|
||||
profileName?: string;
|
||||
actualSection: string;
|
||||
} {
|
||||
const match = sectionPath.match(/^profiles\.([^.]+)\.(.+)$/);
|
||||
if (match) {
|
||||
return { isProfile: true, profileName: match[1], actualSection: match[2] };
|
||||
}
|
||||
return { isProfile: false, actualSection: sectionPath };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// buildOverrides — pure recursive diff of current vs stored config & defaults
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -168,6 +226,26 @@ export function buildOverrides(
|
||||
// Normalize raw config data (strip internal fields) and remove any paths
|
||||
// listed in `hiddenFields` so they are not included in override computation.
|
||||
|
||||
// lodash `unset` treats `*` as a literal key. This helper expands wildcard
|
||||
// segments so that e.g. `"filters.*.mask"` unsets `filters.<each key>.mask`.
|
||||
function unsetWithWildcard(obj: Record<string, unknown>, path: string): void {
|
||||
if (!path.includes("*")) {
|
||||
unset(obj, path);
|
||||
return;
|
||||
}
|
||||
const segments = path.split(".");
|
||||
const starIndex = segments.indexOf("*");
|
||||
const prefix = segments.slice(0, starIndex).join(".");
|
||||
const suffix = segments.slice(starIndex + 1).join(".");
|
||||
const parent = prefix ? get(obj, prefix) : obj;
|
||||
if (parent && typeof parent === "object") {
|
||||
for (const key of Object.keys(parent as Record<string, unknown>)) {
|
||||
const fullPath = suffix ? `${key}.${suffix}` : key;
|
||||
unsetWithWildcard(parent as Record<string, unknown>, fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizeSectionData(
|
||||
data: ConfigSectionData,
|
||||
hiddenFields?: string[],
|
||||
@@ -179,7 +257,7 @@ export function sanitizeSectionData(
|
||||
const cleaned = cloneDeep(normalized) as ConfigSectionData;
|
||||
hiddenFields.forEach((path) => {
|
||||
if (!path) return;
|
||||
unset(cleaned, path);
|
||||
unsetWithWildcard(cleaned as Record<string, unknown>, path);
|
||||
});
|
||||
return cleaned;
|
||||
}
|
||||
@@ -315,7 +393,7 @@ export function requiresRestartForFieldPath(
|
||||
|
||||
export interface SectionSavePayload {
|
||||
basePath: string;
|
||||
sanitizedOverrides: Record<string, unknown>;
|
||||
sanitizedOverrides: JsonObject;
|
||||
updateTopic: string | undefined;
|
||||
needsRestart: boolean;
|
||||
pendingDataKey: string;
|
||||
@@ -421,23 +499,57 @@ export function prepareSectionSavePayload(opts: {
|
||||
level = "global";
|
||||
}
|
||||
|
||||
// Resolve section config
|
||||
const sectionConfig = getSectionConfig(sectionPath, level);
|
||||
// Detect profile-encoded section paths (e.g., "profiles.armed.detect")
|
||||
const profileInfo = parseProfileFromSectionPath(sectionPath);
|
||||
const schemaSection = profileInfo.actualSection;
|
||||
|
||||
// Resolve section schema
|
||||
const sectionSchema = extractSectionSchema(fullSchema, sectionPath, level);
|
||||
// Resolve section config using the actual section name (not the profile path)
|
||||
const sectionConfig = getSectionConfig(schemaSection, level);
|
||||
|
||||
// Resolve section schema using the actual section name
|
||||
const sectionSchema = extractSectionSchema(fullSchema, schemaSection, level);
|
||||
if (!sectionSchema) return null;
|
||||
|
||||
const modifiedSchema = modifySchemaForSection(
|
||||
sectionPath,
|
||||
schemaSection,
|
||||
level,
|
||||
sectionSchema,
|
||||
);
|
||||
|
||||
// Compute rawFormData (the current stored value for this section)
|
||||
// For profiles, merge base camera config with profile overrides (matching
|
||||
// what BaseSection displays in the form) so the diff only contains actual
|
||||
// user changes, not every field from the merged view.
|
||||
let rawSectionValue: unknown;
|
||||
if (level === "camera" && cameraName) {
|
||||
rawSectionValue = get(config.cameras?.[cameraName], sectionPath);
|
||||
if (profileInfo.isProfile) {
|
||||
const baseValue = getBaseCameraSectionValue(
|
||||
config,
|
||||
cameraName,
|
||||
profileInfo.actualSection,
|
||||
);
|
||||
const profileOverrides = get(config.cameras?.[cameraName], sectionPath);
|
||||
if (
|
||||
profileOverrides &&
|
||||
typeof profileOverrides === "object" &&
|
||||
baseValue &&
|
||||
typeof baseValue === "object"
|
||||
) {
|
||||
rawSectionValue = merge(
|
||||
cloneDeep(baseValue),
|
||||
cloneDeep(profileOverrides),
|
||||
);
|
||||
} else {
|
||||
rawSectionValue = baseValue;
|
||||
}
|
||||
} else {
|
||||
// Use base (pre-profile) value so the diff matches what the form shows
|
||||
rawSectionValue = getBaseCameraSectionValue(
|
||||
config,
|
||||
cameraName,
|
||||
sectionPath,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
rawSectionValue = get(config, sectionPath);
|
||||
}
|
||||
@@ -446,10 +558,21 @@ export function prepareSectionSavePayload(opts: {
|
||||
? {}
|
||||
: rawSectionValue;
|
||||
|
||||
// For profile sections, also hide restart-required fields to match
|
||||
// effectiveHiddenFields in BaseSection (prevents spurious deletion markers
|
||||
// for fields that are hidden from the form during profile editing).
|
||||
let hiddenFieldsForSanitize = sectionConfig.hiddenFields;
|
||||
if (profileInfo.isProfile && sectionConfig.restartRequired?.length) {
|
||||
const base = sectionConfig.hiddenFields ?? [];
|
||||
hiddenFieldsForSanitize = [
|
||||
...new Set([...base, ...sectionConfig.restartRequired]),
|
||||
];
|
||||
}
|
||||
|
||||
// Sanitize raw form data
|
||||
const rawData = sanitizeSectionData(
|
||||
rawFormData as ConfigSectionData,
|
||||
sectionConfig.hiddenFields,
|
||||
hiddenFieldsForSanitize,
|
||||
);
|
||||
|
||||
// Compute schema defaults
|
||||
@@ -457,7 +580,7 @@ export function prepareSectionSavePayload(opts: {
|
||||
? applySchemaDefaults(modifiedSchema, {})
|
||||
: {};
|
||||
const effectiveDefaults = getEffectiveDefaultsForSection(
|
||||
sectionPath,
|
||||
schemaSection,
|
||||
level,
|
||||
modifiedSchema ?? undefined,
|
||||
schemaDefaults,
|
||||
@@ -466,7 +589,7 @@ export function prepareSectionSavePayload(opts: {
|
||||
// Build overrides
|
||||
const overrides = buildOverrides(pendingData, rawData, effectiveDefaults);
|
||||
const sanitizedOverrides = sanitizeOverridesForSection(
|
||||
sectionPath,
|
||||
schemaSection,
|
||||
level,
|
||||
overrides,
|
||||
);
|
||||
@@ -474,7 +597,7 @@ export function prepareSectionSavePayload(opts: {
|
||||
if (
|
||||
!sanitizedOverrides ||
|
||||
typeof sanitizedOverrides !== "object" ||
|
||||
Object.keys(sanitizedOverrides as Record<string, unknown>).length === 0
|
||||
Object.keys(sanitizedOverrides as JsonObject).length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -485,9 +608,11 @@ export function prepareSectionSavePayload(opts: {
|
||||
? `cameras.${cameraName}.${sectionPath}`
|
||||
: sectionPath;
|
||||
|
||||
// Compute updateTopic
|
||||
// Compute updateTopic — profile definitions don't trigger hot-reload
|
||||
let updateTopic: string | undefined;
|
||||
if (level === "camera" && cameraName) {
|
||||
if (profileInfo.isProfile) {
|
||||
updateTopic = undefined;
|
||||
} else if (level === "camera" && cameraName) {
|
||||
const topic = cameraUpdateTopicMap[sectionPath];
|
||||
updateTopic = topic ? `config/cameras/${cameraName}/${topic}` : undefined;
|
||||
} else if (globalCameraDefaultSections.has(sectionPath)) {
|
||||
@@ -497,16 +622,18 @@ export function prepareSectionSavePayload(opts: {
|
||||
updateTopic = `config/${sectionPath}`;
|
||||
}
|
||||
|
||||
// Restart detection
|
||||
const needsRestart = requiresRestartForOverrides(
|
||||
sanitizedOverrides,
|
||||
sectionConfig.restartRequired,
|
||||
true,
|
||||
);
|
||||
// Restart detection — profile definitions never need restart
|
||||
const needsRestart = profileInfo.isProfile
|
||||
? false
|
||||
: requiresRestartForOverrides(
|
||||
sanitizedOverrides,
|
||||
sectionConfig.restartRequired,
|
||||
true,
|
||||
);
|
||||
|
||||
return {
|
||||
basePath,
|
||||
sanitizedOverrides: sanitizedOverrides as Record<string, unknown>,
|
||||
sanitizedOverrides: sanitizedOverrides as JsonObject,
|
||||
updateTopic,
|
||||
needsRestart,
|
||||
pendingDataKey,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
const MASKED_AUTH_PATTERN = /:\/\/\*:\*@/i;
|
||||
const MASKED_QUERY_PATTERN = /(?:[?&])user=\*&password=\*/i;
|
||||
|
||||
export const isMaskedPath = (value: string): boolean =>
|
||||
MASKED_AUTH_PATTERN.test(value) || MASKED_QUERY_PATTERN.test(value);
|
||||
|
||||
export const hasCredentials = (value: string): boolean => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isMaskedPath(value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
if (parsed.username || parsed.password) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
parsed.searchParams.has("user") && parsed.searchParams.has("password")
|
||||
);
|
||||
} catch {
|
||||
return /:\/\/[^:@/\s]+:[^@/\s]+@/.test(value);
|
||||
}
|
||||
};
|
||||
|
||||
export const maskCredentials = (value: string): string => {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const maskedAuth = value.replace(/:\/\/[^:@/\s]+:[^@/\s]*@/g, "://*:*@");
|
||||
|
||||
return maskedAuth
|
||||
.replace(/([?&]user=)[^&]*/gi, "$1*")
|
||||
.replace(/([?&]password=)[^&]*/gi, "$1*");
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
export type FfmpegVideoOption = "copy" | "h264" | "h265" | "exclude";
|
||||
export type FfmpegAudioOption =
|
||||
| "copy"
|
||||
| "aac"
|
||||
| "opus"
|
||||
| "pcmu"
|
||||
| "pcma"
|
||||
| "pcm"
|
||||
| "mp3"
|
||||
| "exclude";
|
||||
export type FfmpegHardwareOption = "none" | "auto";
|
||||
|
||||
export type ParsedFfmpegUrl = {
|
||||
isFfmpeg: boolean;
|
||||
baseUrl: string;
|
||||
video: FfmpegVideoOption;
|
||||
audio: FfmpegAudioOption;
|
||||
hardware: FfmpegHardwareOption;
|
||||
extraFragments: string[];
|
||||
};
|
||||
|
||||
const VIDEO_VALUES = new Set(["copy", "h264", "h265"]);
|
||||
const AUDIO_VALUES = new Set([
|
||||
"copy",
|
||||
"aac",
|
||||
"opus",
|
||||
"pcmu",
|
||||
"pcma",
|
||||
"pcm",
|
||||
"mp3",
|
||||
]);
|
||||
const HARDWARE_SPECIFIC = new Set([
|
||||
"vaapi",
|
||||
"cuda",
|
||||
"v4l2m2m",
|
||||
"dxva2",
|
||||
"videotoolbox",
|
||||
]);
|
||||
|
||||
export function parseFfmpegUrl(url: string): ParsedFfmpegUrl {
|
||||
if (!url.startsWith("ffmpeg:")) {
|
||||
return {
|
||||
isFfmpeg: false,
|
||||
baseUrl: url,
|
||||
video: "copy",
|
||||
audio: "copy",
|
||||
hardware: "none",
|
||||
extraFragments: [],
|
||||
};
|
||||
}
|
||||
|
||||
const withoutPrefix = url.slice(7);
|
||||
const parts = withoutPrefix.split("#");
|
||||
const baseUrl = parts[0];
|
||||
const fragments = parts.slice(1);
|
||||
|
||||
let video: FfmpegVideoOption | null = null;
|
||||
let audio: FfmpegAudioOption | null = null;
|
||||
let hardware: FfmpegHardwareOption = "none";
|
||||
const extraFragments: string[] = [];
|
||||
|
||||
for (const frag of fragments) {
|
||||
if (frag.startsWith("video=")) {
|
||||
const val = frag.slice(6);
|
||||
if (VIDEO_VALUES.has(val)) {
|
||||
video = val as FfmpegVideoOption;
|
||||
} else {
|
||||
extraFragments.push(frag);
|
||||
}
|
||||
} else if (frag.startsWith("audio=")) {
|
||||
const val = frag.slice(6);
|
||||
if (AUDIO_VALUES.has(val)) {
|
||||
audio = val as FfmpegAudioOption;
|
||||
} else {
|
||||
extraFragments.push(frag);
|
||||
}
|
||||
} else if (frag === "hardware") {
|
||||
hardware = "auto";
|
||||
} else if (frag.startsWith("hardware=")) {
|
||||
const val = frag.slice(9);
|
||||
if (HARDWARE_SPECIFIC.has(val)) {
|
||||
hardware = "auto";
|
||||
} else {
|
||||
extraFragments.push(frag);
|
||||
}
|
||||
} else {
|
||||
extraFragments.push(frag);
|
||||
}
|
||||
}
|
||||
|
||||
const hasAnyKnownFragment = video !== null || audio !== null;
|
||||
|
||||
return {
|
||||
isFfmpeg: true,
|
||||
baseUrl,
|
||||
video: video ?? (hasAnyKnownFragment ? "exclude" : "copy"),
|
||||
audio: audio ?? (hasAnyKnownFragment ? "exclude" : "copy"),
|
||||
hardware,
|
||||
extraFragments,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildFfmpegUrl(parsed: ParsedFfmpegUrl): string {
|
||||
let url = `ffmpeg:${parsed.baseUrl}`;
|
||||
|
||||
if (parsed.video !== "exclude") {
|
||||
url += `#video=${parsed.video}`;
|
||||
}
|
||||
if (parsed.audio !== "exclude") {
|
||||
url += `#audio=${parsed.audio}`;
|
||||
}
|
||||
if (parsed.hardware === "auto") {
|
||||
url += "#hardware";
|
||||
}
|
||||
for (const frag of parsed.extraFragments) {
|
||||
url += `#${frag}`;
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
export function toggleFfmpegMode(url: string, enable: boolean): string {
|
||||
if (enable) {
|
||||
if (url.startsWith("ffmpeg:")) {
|
||||
return url;
|
||||
}
|
||||
return `ffmpeg:${url}#video=copy#audio=copy`;
|
||||
}
|
||||
|
||||
if (!url.startsWith("ffmpeg:")) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const withoutPrefix = url.slice(7);
|
||||
const baseUrl = withoutPrefix.split("#")[0];
|
||||
return baseUrl;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { TFunction } from "i18next";
|
||||
|
||||
export const calculatePasswordStrength = (password: string): number => {
|
||||
if (!password) return 0;
|
||||
|
||||
@@ -16,13 +18,18 @@ export const getPasswordRequirements = (password: string) => ({
|
||||
|
||||
export const getPasswordStrengthLabel = (
|
||||
password: string,
|
||||
t: (key: string) => string,
|
||||
t: TFunction,
|
||||
): string => {
|
||||
const strength = calculatePasswordStrength(password);
|
||||
|
||||
if (!password) return "";
|
||||
if (strength < 1) return t("users.dialog.form.password.strength.weak");
|
||||
return t("users.dialog.form.password.strength.veryStrong");
|
||||
if (strength < 1)
|
||||
return t("users.dialog.form.password.strength.weak", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
return t("users.dialog.form.password.strength.veryStrong", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
};
|
||||
|
||||
export const getPasswordStrengthColor = (password: string): string => {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { ProfileColor } from "@/types/profile";
|
||||
|
||||
const PROFILE_COLORS: ProfileColor[] = [
|
||||
{
|
||||
bg: "bg-pink-400",
|
||||
text: "text-pink-400",
|
||||
dot: "bg-pink-400",
|
||||
border: "border-pink-400",
|
||||
bgMuted: "bg-pink-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-violet-500",
|
||||
text: "text-violet-500",
|
||||
dot: "bg-violet-500",
|
||||
border: "border-violet-500",
|
||||
bgMuted: "bg-violet-500/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-lime-500",
|
||||
text: "text-lime-500",
|
||||
dot: "bg-lime-500",
|
||||
border: "border-lime-500",
|
||||
bgMuted: "bg-lime-500/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-teal-400",
|
||||
text: "text-teal-400",
|
||||
dot: "bg-teal-400",
|
||||
border: "border-teal-400",
|
||||
bgMuted: "bg-teal-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-sky-400",
|
||||
text: "text-sky-400",
|
||||
dot: "bg-sky-400",
|
||||
border: "border-sky-400",
|
||||
bgMuted: "bg-sky-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-emerald-400",
|
||||
text: "text-emerald-400",
|
||||
dot: "bg-emerald-400",
|
||||
border: "border-emerald-400",
|
||||
bgMuted: "bg-emerald-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-indigo-400",
|
||||
text: "text-indigo-400",
|
||||
dot: "bg-indigo-400",
|
||||
border: "border-indigo-400",
|
||||
bgMuted: "bg-indigo-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-rose-400",
|
||||
text: "text-rose-400",
|
||||
dot: "bg-rose-400",
|
||||
border: "border-rose-400",
|
||||
bgMuted: "bg-rose-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-cyan-300",
|
||||
text: "text-cyan-300",
|
||||
dot: "bg-cyan-300",
|
||||
border: "border-cyan-300",
|
||||
bgMuted: "bg-cyan-300/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-purple-400",
|
||||
text: "text-purple-400",
|
||||
dot: "bg-purple-400",
|
||||
border: "border-purple-400",
|
||||
bgMuted: "bg-purple-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-green-400",
|
||||
text: "text-green-400",
|
||||
dot: "bg-green-400",
|
||||
border: "border-green-400",
|
||||
bgMuted: "bg-green-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-amber-400",
|
||||
text: "text-amber-400",
|
||||
dot: "bg-amber-400",
|
||||
border: "border-amber-400",
|
||||
bgMuted: "bg-amber-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-slate-400",
|
||||
text: "text-slate-400",
|
||||
dot: "bg-slate-400",
|
||||
border: "border-slate-400",
|
||||
bgMuted: "bg-slate-400/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-orange-300",
|
||||
text: "text-orange-300",
|
||||
dot: "bg-orange-300",
|
||||
border: "border-orange-300",
|
||||
bgMuted: "bg-orange-300/20",
|
||||
},
|
||||
{
|
||||
bg: "bg-blue-300",
|
||||
text: "text-blue-300",
|
||||
dot: "bg-blue-300",
|
||||
border: "border-blue-300",
|
||||
bgMuted: "bg-blue-300/20",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Get a deterministic color for a profile name.
|
||||
*
|
||||
* Colors are assigned based on sorted position among all profile names,
|
||||
* so the same profile always gets the same color regardless of context.
|
||||
*/
|
||||
export function getProfileColor(
|
||||
profileName: string,
|
||||
allProfileNames: string[],
|
||||
): ProfileColor {
|
||||
const sorted = [...allProfileNames].sort();
|
||||
const index = sorted.indexOf(profileName);
|
||||
return PROFILE_COLORS[(index >= 0 ? index : 0) % PROFILE_COLORS.length];
|
||||
}
|
||||
@@ -342,7 +342,7 @@ function ModelCard({ config, onClick, onUpdate, onDelete }: ModelCardProps) {
|
||||
{config.name}
|
||||
</div>
|
||||
<div className="absolute bottom-2 right-2 z-40">
|
||||
<DropdownMenu>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<BlurredIconButton>
|
||||
<FiMoreVertical className="size-5 text-white" />
|
||||
|
||||
@@ -304,6 +304,37 @@ export default function ModelTrainingView({ model }: ModelTrainingViewProps) {
|
||||
[pageToggle, model, refreshTrain, refreshDataset, t],
|
||||
);
|
||||
|
||||
const onReclassify = useCallback(
|
||||
(image: string, newCategory: string) => {
|
||||
axios
|
||||
.post(
|
||||
`/classification/${model.name}/dataset/${pageToggle}/reclassify`,
|
||||
{
|
||||
id: image,
|
||||
new_category: newCategory,
|
||||
},
|
||||
)
|
||||
.then((resp) => {
|
||||
if (resp.status == 200) {
|
||||
toast.success(t("toast.success.reclassifiedImage"), {
|
||||
position: "top-center",
|
||||
});
|
||||
refreshDataset();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
const errorMessage =
|
||||
error.response?.data?.message ||
|
||||
error.response?.data?.detail ||
|
||||
"Unknown error";
|
||||
toast.error(t("toast.error.reclassifyFailed", { errorMessage }), {
|
||||
position: "top-center",
|
||||
});
|
||||
});
|
||||
},
|
||||
[pageToggle, model, refreshDataset, t],
|
||||
);
|
||||
|
||||
// keyboard
|
||||
|
||||
const contentRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -535,10 +566,12 @@ export default function ModelTrainingView({ model }: ModelTrainingViewProps) {
|
||||
contentRef={contentRef}
|
||||
modelName={model.name}
|
||||
categoryName={pageToggle}
|
||||
classes={Object.keys(dataset || {})}
|
||||
images={dataset?.[pageToggle] || []}
|
||||
selectedImages={selectedImages}
|
||||
onClickImages={onClickImages}
|
||||
onDelete={onDelete}
|
||||
onReclassify={onReclassify}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -700,66 +733,72 @@ function LibrarySelector({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{Object.keys(dataset).map((id) => (
|
||||
<DropdownMenuItem
|
||||
key={id}
|
||||
className="group flex items-center justify-between"
|
||||
>
|
||||
<div
|
||||
className="flex-grow cursor-pointer capitalize"
|
||||
onClick={() => setPageToggle(id)}
|
||||
{Object.keys(dataset)
|
||||
.sort((a, b) => {
|
||||
if (a === "none") return 1;
|
||||
if (b === "none") return -1;
|
||||
return a.localeCompare(b);
|
||||
})
|
||||
.map((id) => (
|
||||
<DropdownMenuItem
|
||||
key={id}
|
||||
className="group flex items-center justify-between p-0"
|
||||
>
|
||||
{id === "none" ? t("details.none") : id.replaceAll("_", " ")}
|
||||
<span className="ml-2 text-muted-foreground">
|
||||
({dataset?.[id].length})
|
||||
</span>
|
||||
</div>
|
||||
{id != "none" && (
|
||||
<div className="flex gap-0.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 lg:opacity-0 lg:transition-opacity lg:group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRenameClass(id);
|
||||
}}
|
||||
>
|
||||
<LuPencil className="size-4 text-primary" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>
|
||||
{t("button.renameCategory")}
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 lg:opacity-0 lg:transition-opacity lg:group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setConfirmDelete(id);
|
||||
}}
|
||||
>
|
||||
<LuTrash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>
|
||||
{t("button.deleteCategory")}
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
<div
|
||||
className="flex-grow cursor-pointer px-2 py-1.5 capitalize"
|
||||
onClick={() => setPageToggle(id)}
|
||||
>
|
||||
{id === "none" ? t("details.none") : id.replaceAll("_", " ")}
|
||||
<span className="ml-2 text-muted-foreground">
|
||||
({dataset?.[id].length})
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{id != "none" && (
|
||||
<div className="flex gap-0.5 px-2">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 lg:opacity-0 lg:transition-opacity lg:group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRenameClass(id);
|
||||
}}
|
||||
>
|
||||
<LuPencil className="size-4 text-primary" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>
|
||||
{t("button.renameCategory")}
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 lg:opacity-0 lg:transition-opacity lg:group-hover:opacity-100"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setConfirmDelete(id);
|
||||
}}
|
||||
>
|
||||
<LuTrash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>
|
||||
{t("button.deleteCategory")}
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
@@ -770,19 +809,23 @@ type DatasetGridProps = {
|
||||
contentRef: MutableRefObject<HTMLDivElement | null>;
|
||||
modelName: string;
|
||||
categoryName: string;
|
||||
classes: string[];
|
||||
images: string[];
|
||||
selectedImages: string[];
|
||||
onClickImages: (images: string[], ctrl: boolean) => void;
|
||||
onDelete: (ids: string[]) => void;
|
||||
onReclassify: (image: string, newCategory: string) => void;
|
||||
};
|
||||
function DatasetGrid({
|
||||
contentRef,
|
||||
modelName,
|
||||
categoryName,
|
||||
classes,
|
||||
images,
|
||||
selectedImages,
|
||||
onClickImages,
|
||||
onDelete,
|
||||
onReclassify,
|
||||
}: DatasetGridProps) {
|
||||
const { t } = useTranslation(["views/classificationModel"]);
|
||||
|
||||
@@ -810,10 +853,23 @@ function DatasetGrid({
|
||||
i18nLibrary="views/classificationModel"
|
||||
onClick={(data, _) => onClickImages([data.filename], true)}
|
||||
>
|
||||
<ClassificationSelectionDialog
|
||||
classes={classes}
|
||||
modelName={modelName}
|
||||
image={image}
|
||||
excludeCategory={categoryName}
|
||||
dialogLabel={t("reclassifyImageAs")}
|
||||
tooltipLabel={t("reclassifyImage")}
|
||||
onCategorize={(newCat) => onReclassify(image, newCat)}
|
||||
>
|
||||
<BlurredIconButton>
|
||||
<TbCategoryPlus className="size-5" />
|
||||
</BlurredIconButton>
|
||||
</ClassificationSelectionDialog>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<LuTrash2
|
||||
className="size-5 cursor-pointer text-primary-variant hover:text-danger"
|
||||
className="size-5 cursor-pointer text-gray-200 hover:text-danger"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete([image]);
|
||||
|
||||
@@ -570,9 +570,10 @@ export default function LiveDashboardView({
|
||||
toggleStats={() => toggleStats(camera.name)}
|
||||
volumeState={volumeStates[camera.name] ?? 1}
|
||||
setVolumeState={(value) =>
|
||||
setVolumeStates({
|
||||
setVolumeStates((prev) => ({
|
||||
...prev,
|
||||
[camera.name]: value,
|
||||
})
|
||||
}))
|
||||
}
|
||||
muteAll={muteAll}
|
||||
unmuteAll={unmuteAll}
|
||||
|
||||
@@ -372,24 +372,25 @@ export default function MotionSearchROICanvas({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Vertex points */}
|
||||
{scaledPoints.map((point, index) => (
|
||||
<Circle
|
||||
key={index}
|
||||
name={`point-${index}`}
|
||||
x={point[0]}
|
||||
y={point[1]}
|
||||
radius={vertexRadius}
|
||||
fill={polygonColorString}
|
||||
stroke="white"
|
||||
strokeWidth={2}
|
||||
draggable={!isDrawing && isInteractive}
|
||||
onDragMove={(e) => handlePointDragMove(e, index)}
|
||||
onMouseOver={(e) => handleMouseOverPoint(e, index)}
|
||||
onMouseOut={(e) => handleMouseOutPoint(e, index)}
|
||||
onContextMenu={(e) => handleContextMenu(e, index)}
|
||||
/>
|
||||
))}
|
||||
{/* Vertex points (only shown in interactive/dialog mode) */}
|
||||
{isInteractive &&
|
||||
scaledPoints.map((point, index) => (
|
||||
<Circle
|
||||
key={index}
|
||||
name={`point-${index}`}
|
||||
x={point[0]}
|
||||
y={point[1]}
|
||||
radius={vertexRadius}
|
||||
fill={polygonColorString}
|
||||
stroke="white"
|
||||
strokeWidth={2}
|
||||
draggable={!isDrawing}
|
||||
onDragMove={(e) => handlePointDragMove(e, index)}
|
||||
onMouseOver={(e) => handleMouseOverPoint(e, index)}
|
||||
onMouseOut={(e) => handleMouseOutPoint(e, index)}
|
||||
onContextMenu={(e) => handleContextMenu(e, index)}
|
||||
/>
|
||||
))}
|
||||
</Layer>
|
||||
</Stage>
|
||||
)}
|
||||
|
||||
@@ -752,7 +752,7 @@ export function RecordingView({
|
||||
value="timeline"
|
||||
aria-label={t("timeline.aria")}
|
||||
>
|
||||
<div className="">{t("timeline")}</div>
|
||||
<div className="">{t("timeline.label")}</div>
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem
|
||||
className={`${timelineType == "events" ? "" : "text-muted-foreground"}`}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import axios from "axios";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { IoIosWarning } from "react-icons/io";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Link } from "react-router-dom";
|
||||
import { LuExternalLink } from "react-icons/lu";
|
||||
@@ -197,15 +196,6 @@ export default function FrigatePlusSettingsView({
|
||||
document.title = t("documentTitle.frigatePlus");
|
||||
}, [t]);
|
||||
|
||||
const needCleanSnapshots = () => {
|
||||
if (!config) {
|
||||
return false;
|
||||
}
|
||||
return Object.values(config.cameras).some(
|
||||
(camera) => camera.snapshots.enabled && !camera.snapshots.clean_copy,
|
||||
);
|
||||
};
|
||||
|
||||
if (!config) {
|
||||
return <ActivityIndicator />;
|
||||
}
|
||||
@@ -415,11 +405,6 @@ export default function FrigatePlusSettingsView({
|
||||
"frigatePlus.snapshotConfig.table.snapshots",
|
||||
)}
|
||||
</th>
|
||||
<th className="px-4 py-2 text-center">
|
||||
<Trans ns="views/settings">
|
||||
frigatePlus.snapshotConfig.table.cleanCopySnapshots
|
||||
</Trans>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -439,32 +424,12 @@ export default function FrigatePlusSettingsView({
|
||||
<XCircle className="mx-auto size-5 text-danger" />
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{camera.snapshots?.enabled &&
|
||||
camera.snapshots?.clean_copy ? (
|
||||
<CheckCircle2 className="mx-auto size-5 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="mx-auto size-5 text-danger" />
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{needCleanSnapshots() && (
|
||||
<div className="rounded-lg border border-secondary-foreground bg-secondary p-4 text-sm text-danger">
|
||||
<div className="flex items-center gap-2">
|
||||
<IoIosWarning className="mr-2 size-5 text-danger" />
|
||||
<div className="max-w-[85%] text-sm">
|
||||
<Trans ns="views/settings">
|
||||
frigatePlus.snapshotConfig.cleanCopyWarning
|
||||
</Trans>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
|
||||
@@ -22,6 +22,7 @@ export default function MediaSyncSettingsView() {
|
||||
]);
|
||||
const [dryRun, setDryRun] = useState(true);
|
||||
const [force, setForce] = useState(false);
|
||||
const [verbose, setVerbose] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const MEDIA_TYPES = [
|
||||
@@ -67,6 +68,7 @@ export default function MediaSyncSettingsView() {
|
||||
dry_run: dryRun,
|
||||
media_types: selectedMediaTypes,
|
||||
force: force,
|
||||
verbose: verbose,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
@@ -94,7 +96,7 @@ export default function MediaSyncSettingsView() {
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [selectedMediaTypes, dryRun, force, t]);
|
||||
}, [selectedMediaTypes, dryRun, force, verbose, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -205,6 +207,25 @@ export default function MediaSyncSettingsView() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-row items-center justify-between gap-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="verbose" className="cursor-pointer">
|
||||
{t("maintenance.sync.verbose")}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("maintenance.sync.verboseDesc")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="verbose"
|
||||
checked={verbose}
|
||||
onCheckedChange={setVerbose}
|
||||
disabled={isJobRunning}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
|
||||
@@ -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("camera/*/set/profile", {
|
||||
value: profile ?? "none",
|
||||
});
|
||||
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("camera/*/set/profile", { value: "none" });
|
||||
}
|
||||
|
||||
// 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 flex-col gap-3 rounded-lg border border-border/70 bg-card/30 p-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
{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 flex-wrap items-center gap-y-2 px-4 py-3 hover:bg-secondary/30">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
{isExpanded ? (
|
||||
<LuChevronDown className="size-4 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<LuChevronRight className="size-4 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"size-2.5 shrink-0 rounded-full",
|
||||
color.dot,
|
||||
)}
|
||||
/>
|
||||
<span className="truncate font-medium">
|
||||
{profileFriendlyNames?.get(profile) ?? profile}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 shrink-0 text-muted-foreground hover:text-primary"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRenameProfile(profile);
|
||||
setRenameValue(
|
||||
profileFriendlyNames?.get(profile) ?? profile,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Pencil className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-3">
|
||||
{isActive && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-xs text-primary-variant"
|
||||
>
|
||||
{t("profiles.active", { ns: "views/settings" })}
|
||||
</Badge>
|
||||
)}
|
||||
<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 shrink-0 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 className="gap-2 md:gap-0">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
@@ -96,57 +131,124 @@ export function SingleSectionPage({
|
||||
|
||||
return (
|
||||
<div className="flex size-full flex-col lg:pr-2">
|
||||
<div className="mb-5 flex items-center justify-between gap-4">
|
||||
<div className="flex flex-col">
|
||||
<Heading as="h4">
|
||||
{t(`${sectionKey}.label`, { ns: sectionNamespace })}
|
||||
</Heading>
|
||||
{i18n.exists(`${sectionKey}.description`, {
|
||||
ns: sectionNamespace,
|
||||
}) && (
|
||||
<div className="my-1 text-sm text-muted-foreground">
|
||||
{t(`${sectionKey}.description`, { ns: sectionNamespace })}
|
||||
</div>
|
||||
)}
|
||||
{sectionDocsUrl && (
|
||||
<div className="flex items-center text-sm text-primary-variant">
|
||||
<Link
|
||||
to={sectionDocsUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline"
|
||||
>
|
||||
{t("readTheDocumentation", { ns: "common" })}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-2 md:flex-row md:items-center">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<div className="mb-5 flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex flex-col">
|
||||
<Heading as="h4">
|
||||
{t(`${sectionKey}.label`, { ns: sectionNamespace })}
|
||||
</Heading>
|
||||
{i18n.exists(`${sectionKey}.description`, {
|
||||
ns: sectionNamespace,
|
||||
}) && (
|
||||
<div className="my-1 text-sm text-muted-foreground">
|
||||
{t(`${sectionKey}.description`, { ns: sectionNamespace })}
|
||||
</div>
|
||||
)}
|
||||
{sectionDocsUrl && (
|
||||
<div className="flex items-center text-sm text-primary-variant">
|
||||
<Link
|
||||
to={sectionDocsUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline"
|
||||
>
|
||||
{t("readTheDocumentation", { ns: "common" })}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Desktop: badge inline next to title */}
|
||||
<div className="hidden shrink-0 sm:flex sm:flex-wrap sm:items-center sm:gap-2">
|
||||
{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
|
||||
variant="secondary"
|
||||
className="cursor-default bg-danger text-xs text-white hover:bg-danger"
|
||||
>
|
||||
{t("modified", { ns: "common", defaultValue: "Modified" })}
|
||||
{t("button.modified", {
|
||||
ns: "common",
|
||||
defaultValue: "Modified",
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* Mobile: badge below title/description */}
|
||||
<div className="flex flex-wrap items-center gap-2 sm:hidden">
|
||||
{level === "camera" &&
|
||||
showOverrideIndicator &&
|
||||
sectionStatus.isOverridden && (
|
||||
<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>
|
||||
)}
|
||||
{sectionStatus.hasChanges && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-default bg-danger text-xs text-white hover:bg-danger"
|
||||
>
|
||||
{t("button.modified", { ns: "common", defaultValue: "Modified" })}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ConfigSectionTemplate
|
||||
sectionKey={sectionKey}
|
||||
@@ -160,6 +262,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>
|
||||
);
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -107,7 +107,10 @@ export default function EnrichmentMetrics({
|
||||
};
|
||||
}
|
||||
|
||||
series[key].data.push({ x: statsIdx + 1, y: stat });
|
||||
series[key].data.push({
|
||||
x: statsIdx + 1,
|
||||
y: rawKey.includes("description_speed") ? stat / 1000 : stat,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,6 +118,7 @@ export default function EnrichmentMetrics({
|
||||
const grouped: {
|
||||
[category: string]: {
|
||||
categoryName: string;
|
||||
unit: string;
|
||||
speedSeries?: {
|
||||
name: string;
|
||||
metrics: Threshold;
|
||||
@@ -154,6 +158,7 @@ export default function EnrichmentMetrics({
|
||||
if (!(categoryKey in grouped)) {
|
||||
grouped[categoryKey] = {
|
||||
categoryName,
|
||||
unit: categoryKey.includes("description") ? "s" : "ms",
|
||||
speedSeries: undefined,
|
||||
eventsSeries: undefined,
|
||||
};
|
||||
@@ -196,7 +201,7 @@ export default function EnrichmentMetrics({
|
||||
key={`${group.categoryName}-speed`}
|
||||
graphId={`${group.categoryName}-inference`}
|
||||
name={t("enrichments.averageInf")}
|
||||
unit="ms"
|
||||
unit={group.unit}
|
||||
threshold={group.speedSeries.metrics}
|
||||
updateTimes={updateTimes}
|
||||
data={[group.speedSeries]}
|
||||
|
||||
@@ -548,7 +548,10 @@ export default function GeneralMetrics({
|
||||
Object.entries(stats.processes).forEach(([key, procStats]) => {
|
||||
if (procStats.pid.toString() in stats.cpu_usages) {
|
||||
if (!(key in series)) {
|
||||
series[key] = { name: key, data: [] };
|
||||
series[key] = {
|
||||
name: t(`general.otherProcesses.series.${key}`),
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
const data = stats.cpu_usages[procStats.pid.toString()]?.cpu;
|
||||
@@ -563,7 +566,7 @@ export default function GeneralMetrics({
|
||||
});
|
||||
});
|
||||
return Object.keys(series).length > 0 ? Object.values(series) : [];
|
||||
}, [statsHistory]);
|
||||
}, [statsHistory, t]);
|
||||
|
||||
const otherProcessMemSeries = useMemo(() => {
|
||||
if (!statsHistory) {
|
||||
@@ -582,7 +585,10 @@ export default function GeneralMetrics({
|
||||
Object.entries(stats.processes).forEach(([key, procStats]) => {
|
||||
if (procStats.pid.toString() in stats.cpu_usages) {
|
||||
if (!(key in series)) {
|
||||
series[key] = { name: key, data: [] };
|
||||
series[key] = {
|
||||
name: t(`general.otherProcesses.series.${key}`),
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
const data = stats.cpu_usages[procStats.pid.toString()]?.mem;
|
||||
@@ -597,7 +603,7 @@ export default function GeneralMetrics({
|
||||
});
|
||||
});
|
||||
return Object.values(series);
|
||||
}, [statsHistory]);
|
||||
}, [statsHistory, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -964,11 +970,10 @@ export default function GeneralMetrics({
|
||||
<div className="mb-5">
|
||||
{t("general.otherProcesses.processCpuUsage")}
|
||||
</div>
|
||||
{otherProcessCpuSeries.map((series) => (
|
||||
{otherProcessCpuSeries.map((series, index) => (
|
||||
<ThresholdBarGraph
|
||||
key={series.name}
|
||||
graphId={`${series.name}-cpu`}
|
||||
name={t(`general.otherProcesses.series.${series.name}`)}
|
||||
key={`other-process-cpu-${index}`}
|
||||
graphId={`other-process-cpu-${index}`}
|
||||
unit="%"
|
||||
threshold={DetectorCpuThreshold}
|
||||
updateTimes={updateTimes}
|
||||
@@ -984,12 +989,11 @@ export default function GeneralMetrics({
|
||||
<div className="mb-5">
|
||||
{t("general.otherProcesses.processMemoryUsage")}
|
||||
</div>
|
||||
{otherProcessMemSeries.map((series) => (
|
||||
{otherProcessMemSeries.map((series, index) => (
|
||||
<ThresholdBarGraph
|
||||
key={series.name}
|
||||
graphId={`${series.name}-mem`}
|
||||
key={`other-process-mem-${index}`}
|
||||
graphId={`other-process-mem-${index}`}
|
||||
unit="%"
|
||||
name={series.name.replaceAll("_", " ")}
|
||||
threshold={DetectorMemThreshold}
|
||||
updateTimes={updateTimes}
|
||||
data={[series]}
|
||||
|
||||
Reference in New Issue
Block a user