Merge remote-tracking branch 'upstream/dev' into feature/share-review-timestamp

This commit is contained in:
0x464e
2026-04-05 14:06:59 +03:00
433 changed files with 19470 additions and 3221 deletions
+1 -2
View File
@@ -116,8 +116,7 @@ export default function Statusbar() {
case "amd-vaapi":
gpuTitle = "AMD GPU";
break;
case "intel-vaapi":
case "intel-qsv":
case "intel-gpu":
gpuTitle = "Intel GPU";
break;
case "rockchip":
+2 -1
View File
@@ -8,6 +8,7 @@ import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { useTranslation } from "react-i18next";
import { useTimeFormat } from "@/hooks/use-date-utils";
const GRAPH_COLORS = ["#3b82f6", "#ef4444"]; // RMS, dBFS
@@ -72,7 +73,7 @@ export function AudioLevelGraph({ cameraName }: AudioLevelGraphProps) {
return [last.rms, last.dBFS];
}, [audioData]);
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const formatString = useMemo(
() =>
t(`time.formattedTimestampHourMinuteSecond.${timeFormat}`, {
@@ -7,6 +7,7 @@ import { useTranslation } from "react-i18next";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { useDateLocale } from "@/hooks/use-date-locale";
import { useTimeFormat } from "@/hooks/use-date-utils";
import { useMemo } from "react";
type DownloadVideoButtonProps = {
@@ -26,7 +27,7 @@ export function DownloadVideoButton({
const { data: config } = useSWR<FrigateConfig>("config");
const locale = useDateLocale();
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
return t(`time.formattedTimestampFilename.${timeFormat}`, { ns: "common" });
}, [t, timeFormat]);
+3 -2
View File
@@ -1,5 +1,5 @@
import { baseUrl } from "@/api/baseUrl";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { FrigateConfig } from "@/types/frigateConfig";
import { REVIEW_PADDING, ReviewSegment } from "@/types/review";
import { getIconForLabel } from "@/utils/iconUtil";
@@ -55,9 +55,10 @@ export default function ReviewCard({
const { t } = useTranslation(["components/dialog"]);
const { data: config } = useSWR<FrigateConfig>("config");
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
const is24Hour = use24HourTime(config);
const formattedDate = useFormattedTimestamp(
event.start_time,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestampHourMinute.24hour", { ns: "common" })
: t("time.formattedTimestampHourMinute.12hour", { ns: "common" }),
config?.ui.timezone,
@@ -1,7 +1,7 @@
import TimeAgo from "../dynamic/TimeAgo";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { SearchResult } from "@/types/search";
import ActivityIndicator from "../indicators/activity-indicator";
import SearchResultActions from "../menu/SearchResultActions";
@@ -29,9 +29,10 @@ export default function SearchThumbnailFooter({
const { data: config } = useSWR<FrigateConfig>("config");
// date
const is24Hour = use24HourTime(config);
const formattedDate = useFormattedTimestamp(
searchResult.start_time,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestampMonthDayHourMinute.24hour", { ns: "common" })
: t("time.formattedTimestampMonthDayHourMinute.12hour", { ns: "common" }),
config?.ui.timezone,
+46 -32
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from "react";
import { useState, useEffect, useRef, useCallback } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useTranslation } from "react-i18next";
@@ -6,6 +6,7 @@ import copy from "copy-to-clipboard";
import { toast } from "sonner";
import { FaCopy, FaPencilAlt } from "react-icons/fa";
import { FaArrowUpLong } from "react-icons/fa6";
import { LuCheck } from "react-icons/lu";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
@@ -50,13 +51,17 @@ export function MessageBubble({
}
}, [isEditing]);
const handleCopy = () => {
const [copied, setCopied] = useState(false);
const handleCopy = useCallback(() => {
const text = content?.trim() || "";
if (!text) return;
if (copy(text)) {
setCopied(true);
toast.success(t("button.copiedToClipboard", { ns: "common" }));
setTimeout(() => setCopied(false), 2000);
}
};
}, [content, t]);
const handleEditClick = () => {
setDraftContent(content);
@@ -93,7 +98,7 @@ export function MessageBubble({
value={draftContent}
onChange={(e) => setDraftContent(e.target.value)}
onKeyDown={handleEditKeyDown}
className="min-h-[80px] w-full resize-y rounded-lg bg-primary px-3 py-2 text-primary-foreground placeholder:text-primary-foreground/60"
className="min-h-[80px] w-full resize-y rounded-2xl bg-primary px-4 py-3 text-primary-foreground placeholder:text-primary-foreground/60"
placeholder={t("placeholder")}
rows={3}
/>
@@ -124,44 +129,49 @@ export function MessageBubble({
return (
<div
className={cn(
"flex flex-col gap-1",
"flex max-w-[85%] flex-col gap-1",
isUser ? "items-end self-end" : "items-start self-start",
)}
>
<div
className={cn(
"rounded-lg px-3 py-2",
"rounded-2xl px-4 py-3",
isUser ? "bg-primary text-primary-foreground" : "bg-muted",
)}
>
{isUser ? (
content
) : (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ node: _n, ...props }) => (
<table
className="my-2 w-full border-collapse border border-border"
{...props}
/>
),
th: ({ node: _n, ...props }) => (
<th
className="border border-border bg-muted/50 px-2 py-1 text-left text-sm font-medium"
{...props}
/>
),
td: ({ node: _n, ...props }) => (
<td
className="border border-border px-2 py-1 text-sm"
{...props}
/>
),
}}
>
{content}
</ReactMarkdown>
<>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ node: _n, ...props }) => (
<table
className="my-2 w-full border-collapse border border-border"
{...props}
/>
),
th: ({ node: _n, ...props }) => (
<th
className="border border-border bg-muted/50 px-2 py-1 text-left text-sm font-medium"
{...props}
/>
),
td: ({ node: _n, ...props }) => (
<td
className="border border-border px-2 py-1 text-sm"
{...props}
/>
),
}}
>
{content}
</ReactMarkdown>
{!isComplete && (
<span className="ml-1 inline-block h-4 w-0.5 animate-pulse bg-foreground align-middle" />
)}
</>
)}
</div>
<div className="flex items-center gap-0.5">
@@ -194,7 +204,11 @@ export function MessageBubble({
disabled={!content?.trim()}
aria-label={t("button.copy", { ns: "common" })}
>
<FaCopy className="size-3" />
{copied ? (
<LuCheck className="size-3" />
) : (
<FaCopy className="size-3" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
@@ -22,6 +22,14 @@ export function ChatStartingState({ onSendMessage }: ChatStartingStateProps) {
label: t("starting_requests.show_camera_status"),
prompt: t("starting_requests_prompts.show_camera_status"),
},
{
label: t("starting_requests.recap"),
prompt: t("starting_requests_prompts.recap"),
},
{
label: t("starting_requests.watch_camera"),
prompt: t("starting_requests_prompts.watch_camera"),
},
];
const handleRequestClick = (prompt: string) => {
@@ -67,7 +75,7 @@ export function ChatStartingState({ onSendMessage }: ChatStartingStateProps) {
</div>
</div>
<div className="flex w-full max-w-2xl flex-row items-center gap-2 rounded-xl bg-secondary p-4">
<div className="flex w-full max-w-2xl flex-row items-center gap-2 rounded-xl bg-secondary p-3">
<Input
className="h-12 w-full flex-1 border-transparent bg-transparent text-base shadow-none focus-visible:ring-0 dark:bg-transparent"
placeholder={t("placeholder")}
+4 -4
View File
@@ -7,7 +7,7 @@ import {
} from "@/components/ui/collapsible";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ChevronDown, ChevronRight } from "lucide-react";
import { LuChevronDown, LuChevronRight } from "react-icons/lu";
type ToolCallBubbleProps = {
name: string;
@@ -34,7 +34,7 @@ export function ToolCallBubble({
return (
<div
className={cn(
"rounded-lg px-3 py-2",
"rounded-2xl px-3 py-2",
isLeft
? "self-start bg-muted"
: "self-end bg-primary text-primary-foreground",
@@ -51,9 +51,9 @@ export function ToolCallBubble({
)}
>
{open ? (
<ChevronDown size={12} className="shrink-0" />
<LuChevronDown className="size-3 shrink-0" />
) : (
<ChevronRight size={12} className="shrink-0" />
<LuChevronRight className="size-3 shrink-0" />
)}
<span className="break-words font-medium">
{isLeft ? t("call") : t("result")} {normalizedName}
+103
View File
@@ -0,0 +1,103 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { LuChevronsUpDown } from "react-icons/lu";
import type { ToolCall } from "@/types/chat";
type ToolCallsGroupProps = {
toolCalls: ToolCall[];
};
function normalizeName(name: string): string {
return name
.replace(/_/g, " ")
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
export function ToolCallsGroup({ toolCalls }: ToolCallsGroupProps) {
const grouped = useMemo(() => {
const map = new Map<string, ToolCall[]>();
for (const tc of toolCalls) {
const existing = map.get(tc.name);
if (existing) {
existing.push(tc);
} else {
map.set(tc.name, [tc]);
}
}
return map;
}, [toolCalls]);
if (toolCalls.length === 0) return null;
return (
<div className="flex flex-col items-start gap-2">
{[...grouped.entries()].map(([name, calls]) => (
<ToolCallRow key={name} name={name} calls={calls} />
))}
</div>
);
}
type ToolCallRowProps = {
name: string;
calls: ToolCall[];
};
function ToolCallRow({ name, calls }: ToolCallRowProps) {
const { t } = useTranslation(["views/chat"]);
const [open, setOpen] = useState(false);
const displayName = normalizeName(name);
const label =
calls.length > 1 ? `${displayName} (\u00d7${calls.length})` : displayName;
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger className="flex items-center gap-3 rounded-xl bg-muted px-4 py-3 text-sm text-secondary-foreground transition-colors hover:bg-muted/80">
<span className="font-medium">{label}</span>
<LuChevronsUpDown className="size-4 shrink-0 text-muted-foreground" />
</CollapsibleTrigger>
<CollapsibleContent>
<div className="mt-1 space-y-3 rounded-xl bg-muted/40 px-4 py-3">
{calls.map((tc, idx) => (
<div
key={idx}
className={
calls.length > 1
? "space-y-1 border-l-2 border-border pl-3"
: "space-y-1"
}
>
{tc.arguments && Object.keys(tc.arguments).length > 0 && (
<div className="text-xs">
<div className="font-medium text-muted-foreground">
{t("arguments")}
</div>
<pre className="scrollbar-container mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-words rounded bg-background/50 p-2 text-[10px]">
{JSON.stringify(tc.arguments, null, 2)}
</pre>
</div>
)}
{tc.response && tc.response !== "" && (
<div className="text-xs">
<div className="font-medium text-muted-foreground">
{t("response")}
</div>
<pre className="scrollbar-container mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-words rounded bg-background/50 p-2 text-[10px]">
{tc.response}
</pre>
</div>
)}
</div>
))}
</div>
</CollapsibleContent>
</Collapsible>
);
}
@@ -0,0 +1,48 @@
import { useTranslation } from "react-i18next";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { LuInfo, LuTriangleAlert, LuCircleAlert } from "react-icons/lu";
import type { MessageSeverity } from "./section-configs/types";
const severityVariantMap: Record<
MessageSeverity,
"info" | "warning" | "destructive"
> = {
info: "info",
warning: "warning",
error: "destructive",
};
function SeverityIcon({ severity }: { severity: string }) {
switch (severity) {
case "info":
return <LuInfo className="size-4" />;
case "warning":
return <LuTriangleAlert className="size-4" />;
case "error":
return <LuCircleAlert className="size-4" />;
default:
return <LuInfo className="size-4" />;
}
}
type ConfigFieldMessageProps = {
messageKey: string;
severity: string;
};
export function ConfigFieldMessage({
messageKey,
severity,
}: ConfigFieldMessageProps) {
const { t } = useTranslation("views/settings");
return (
<Alert
variant={severityVariantMap[severity as MessageSeverity] ?? "info"}
className="flex items-center [&>svg+div]:translate-y-0 [&>svg]:static [&>svg~*]:pl-2"
>
<SeverityIcon severity={severity} />
<AlertDescription>{t(messageKey)}</AlertDescription>
</Alert>
);
}
@@ -0,0 +1,52 @@
import { useTranslation } from "react-i18next";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { LuInfo, LuTriangleAlert, LuCircleAlert } from "react-icons/lu";
import type {
ConditionalMessage,
MessageSeverity,
} from "./section-configs/types";
const severityVariantMap: Record<
MessageSeverity,
"info" | "warning" | "destructive"
> = {
info: "info",
warning: "warning",
error: "destructive",
};
function SeverityIcon({ severity }: { severity: MessageSeverity }) {
switch (severity) {
case "info":
return <LuInfo className="size-4" />;
case "warning":
return <LuTriangleAlert className="size-4" />;
case "error":
return <LuCircleAlert className="size-4" />;
}
}
type ConfigMessageBannerProps = {
messages: ConditionalMessage[];
};
export function ConfigMessageBanner({ messages }: ConfigMessageBannerProps) {
const { t } = useTranslation("views/settings");
if (messages.length === 0) return null;
return (
<div className="max-w-5xl space-y-2">
{messages.map((msg) => (
<Alert
key={msg.key}
variant={severityVariantMap[msg.severity]}
className="flex items-center [&>svg+div]:translate-y-0 [&>svg]:static [&>svg~*]:pl-2"
>
<SeverityIcon severity={msg.severity} />
<AlertDescription>{t(msg.messageKey)}</AlertDescription>
</Alert>
))}
</div>
);
}
@@ -3,6 +3,21 @@ import type { SectionConfigOverrides } from "./types";
const audio: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/audio_detectors",
messages: [
{
key: "no-audio-role",
messageKey: "configMessages.audio.noAudioRole",
severity: "warning",
condition: (ctx) => {
if (ctx.level === "camera" && ctx.fullCameraConfig) {
return !ctx.fullCameraConfig.ffmpeg?.inputs?.some((input) =>
input.roles?.includes("audio"),
);
}
return false;
},
},
],
restartRequired: [],
fieldOrder: [
"enabled",
@@ -19,6 +34,16 @@ const audio: SectionConfigOverrides = {
hiddenFields: ["enabled_in_config"],
advancedFields: ["min_volume", "max_not_heard", "num_threads"],
uiSchema: {
filters: {
"ui:options": {
expandable: false,
},
},
"filters.*": {
"ui:options": {
additionalPropertyKeyReadonly: true,
},
},
listen: {
"ui:widget": "audioLabels",
},
@@ -3,6 +3,19 @@ import type { SectionConfigOverrides } from "./types";
const audioTranscription: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/audio_detectors#audio-transcription",
messages: [
{
key: "audio-detection-disabled",
messageKey: "configMessages.audioTranscription.audioDetectionDisabled",
severity: "warning",
condition: (ctx) => {
if (ctx.level === "camera" && ctx.fullCameraConfig) {
return ctx.fullCameraConfig.audio.enabled === false;
}
return false;
},
},
],
restartRequired: [],
fieldOrder: ["enabled", "language", "device", "model_size"],
hiddenFields: ["enabled_in_config", "live_enabled"],
@@ -3,6 +3,20 @@ import type { SectionConfigOverrides } from "./types";
const birdseye: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/birdseye",
messages: [
{
key: "objects-mode-detect-disabled",
messageKey: "configMessages.birdseye.objectsModeDetectDisabled",
severity: "info",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
return (
ctx.formData?.mode === "objects" &&
ctx.fullCameraConfig.detect?.enabled === false
);
},
},
],
restartRequired: [],
fieldOrder: ["enabled", "mode", "order"],
hiddenFields: [],
@@ -3,6 +3,21 @@ import type { SectionConfigOverrides } from "./types";
const detect: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/camera_specific",
fieldMessages: [
{
key: "fps-greater-than-five",
field: "fps",
messageKey: "configMessages.detect.fpsGreaterThanFive",
severity: "info",
position: "after",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
const detectFps = ctx.formData?.fps as number | undefined;
const streamFps = ctx.fullCameraConfig.detect?.fps;
return detectFps != null && streamFps != null && detectFps > 5;
},
},
],
fieldOrder: [
"enabled",
"width",
@@ -16,7 +16,7 @@ const detectors: SectionConfigOverrides = {
uiSchema: {
"ui:field": "DetectorHardwareField",
"ui:options": {
multiInstanceTypes: ["cpu", "onnx", "openvino"],
multiInstanceTypes: ["cpu", "onnx", "openvino", "edgetpu"],
typeOrder: ["onnx", "openvino", "edgetpu"],
hiddenByType: {},
hiddenFields: detectorHiddenFields,
@@ -3,6 +3,26 @@ import type { SectionConfigOverrides } from "./types";
const faceRecognition: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/face_recognition",
messages: [
{
key: "global-disabled",
messageKey: "configMessages.faceRecognition.globalDisabled",
severity: "warning",
condition: (ctx) => {
if (ctx.level !== "camera") return false;
return ctx.fullConfig.face_recognition?.enabled === false;
},
},
{
key: "person-not-tracked",
messageKey: "configMessages.faceRecognition.personNotTracked",
severity: "info",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
return !ctx.fullCameraConfig.objects?.track?.includes("person");
},
},
],
restartRequired: [],
fieldOrder: ["enabled", "min_area"],
hiddenFields: [],
@@ -3,16 +3,9 @@ import type { SectionConfigOverrides } from "./types";
const genai: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/genai/config",
restartRequired: [
"*.provider",
"*.api_key",
"*.base_url",
"*.model",
"*.provider_options",
"*.runtime_options",
],
advancedFields: ["*.base_url", "*.provider_options", "*.runtime_options"],
hiddenFields: ["genai.enabled_in_config"],
restartRequired: [],
uiSchema: {
"ui:options": { disableNestedCard: true },
"*": {
@@ -37,20 +30,17 @@ const genai: SectionConfigOverrides = {
"ui:options": { size: "lg" },
},
"*.model": {
"ui:widget": "genaiModel",
"ui:options": { size: "xs" },
},
"*.provider": {
"ui:options": { size: "xs" },
},
"*.provider_options": {
additionalProperties: {
"ui:options": { size: "lg" },
},
"ui:field": "DictAsYamlField",
},
"*.runtime_options": {
additionalProperties: {
"ui:options": { size: "lg" },
},
"ui:field": "DictAsYamlField",
},
},
},
@@ -3,6 +3,28 @@ import type { SectionConfigOverrides } from "./types";
const lpr: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/license_plate_recognition",
messages: [
{
key: "global-disabled",
messageKey: "configMessages.lpr.globalDisabled",
severity: "warning",
condition: (ctx) => {
if (ctx.level !== "camera") return false;
return ctx.fullConfig.lpr?.enabled === false;
},
},
{
key: "vehicle-not-tracked",
messageKey: "configMessages.lpr.vehicleNotTracked",
severity: "info",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
if (ctx.fullCameraConfig.type === "lpr") return false;
const tracked = ctx.fullCameraConfig.objects?.track ?? [];
return !tracked.some((o) => ["car", "motorcycle"].includes(o));
},
},
],
fieldDocs: {
enhancement: "/configuration/license_plate_recognition#enhancement",
},
@@ -29,6 +29,11 @@ const objects: SectionConfigOverrides = {
],
advancedFields: ["genai"],
uiSchema: {
filters: {
"ui:options": {
expandable: false,
},
},
"filters.*.min_area": {
"ui:options": {
suppressMultiSchema: true,
@@ -3,20 +3,12 @@ import type { SectionConfigOverrides } from "./types";
const onvif: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/cameras#setting-up-camera-ptz-controls",
restartRequired: [
"host",
"port",
"user",
"password",
"tls_insecure",
"ignore_time_mismatch",
"autotracking.calibrate_on_startup",
],
fieldOrder: [
"host",
"port",
"user",
"password",
"profile",
"tls_insecure",
"ignore_time_mismatch",
"autotracking",
@@ -27,10 +19,14 @@ const onvif: SectionConfigOverrides = {
],
advancedFields: ["tls_insecure", "ignore_time_mismatch"],
overrideFields: [],
restartRequired: ["autotracking.calibrate_on_startup"],
uiSchema: {
host: {
"ui:options": { size: "sm" },
},
profile: {
"ui:widget": "onvifProfile",
},
autotracking: {
required_zones: {
"ui:widget": "zoneNames",
@@ -3,6 +3,19 @@ import type { SectionConfigOverrides } from "./types";
const record: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/record",
messages: [
{
key: "no-record-role",
messageKey: "configMessages.record.noRecordRole",
severity: "warning",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
return !ctx.fullCameraConfig.ffmpeg?.inputs?.some((i) =>
i.roles?.includes("record"),
);
},
},
],
restartRequired: [],
fieldOrder: [
"enabled",
@@ -23,7 +36,7 @@ const record: SectionConfigOverrides = {
uiSchema: {
export: {
hwaccel_args: {
"ui:options": { size: "lg" },
"ui:options": { suppressMultiSchema: true, size: "lg" },
},
},
},
@@ -3,14 +3,55 @@ import type { SectionConfigOverrides } from "./types";
const review: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/review",
messages: [
{
key: "record-disabled",
messageKey: "configMessages.review.recordDisabled",
severity: "warning",
condition: (ctx) => {
if (ctx.level === "camera" && ctx.fullCameraConfig) {
return ctx.fullCameraConfig.record.enabled === false;
}
return ctx.fullConfig.record?.enabled === false;
},
},
{
key: "detect-disabled",
messageKey: "configMessages.review.detectDisabled",
severity: "info",
condition: (ctx) => {
if (ctx.level === "camera" && ctx.fullCameraConfig) {
return ctx.fullCameraConfig.detect?.enabled === false;
}
return false;
},
},
],
fieldMessages: [
{
key: "detections-all-non-alert",
field: "detections.labels",
messageKey: "configMessages.review.allNonAlertDetections",
severity: "info",
position: "after",
condition: (ctx) => {
const labels = (
ctx.formData?.detections as Record<string, unknown> | undefined
)?.labels;
return !Array.isArray(labels) || labels.length === 0;
},
},
],
fieldDocs: {
"alerts.labels": "/configuration/review/#alerts-and-detections",
"detections.labels": "/configuration/review/#alerts-and-detections",
},
restartRequired: [],
fieldOrder: ["alerts", "detections", "genai"],
fieldOrder: ["alerts", "detections", "genai", "genai.enabled"],
fieldGroups: {},
hiddenFields: [
"enabled_in_config",
"alerts.labels",
"alerts.enabled_in_config",
"detections.labels",
"detections.enabled_in_config",
"genai.enabled_in_config",
],
@@ -18,20 +59,33 @@ const review: SectionConfigOverrides = {
uiSchema: {
alerts: {
"ui:before": { render: "CameraReviewStatusToggles" },
labels: {
"ui:widget": "reviewLabels",
"ui:options": {
suppressMultiSchema: true,
},
},
required_zones: {
"ui:widget": "hidden",
},
},
detections: {
labels: {
"ui:widget": "reviewLabels",
"ui:options": {
suppressMultiSchema: true,
},
},
required_zones: {
"ui:widget": "hidden",
},
},
genai: {
additional_concerns: {
"ui:widget": "textarea",
"ui:widget": "ArrayAsTextWidget",
"ui:options": {
size: "full",
multiline: true,
},
},
activity_context_prompt: {
@@ -3,6 +3,17 @@ import type { SectionConfigOverrides } from "./types";
const snapshots: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/snapshots",
messages: [
{
key: "detect-disabled",
messageKey: "configMessages.snapshots.detectDisabled",
severity: "info",
condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
return ctx.fullCameraConfig.detect?.enabled === false;
},
},
],
restartRequired: [],
fieldOrder: [
"enabled",
@@ -4,12 +4,13 @@ const timestampStyle: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/reference",
restartRequired: [],
fieldOrder: ["position", "format", "color", "thickness"],
fieldOrder: ["position", "format", "thickness", "color"],
hiddenFields: ["effect", "enabled_in_config"],
advancedFields: [],
uiSchema: {
position: {
"ui:size": "xs",
"ui:options": { enumI18nPrefix: "timestampPosition" },
},
format: {
"ui:size": "xs",
@@ -17,7 +18,7 @@ const timestampStyle: SectionConfigOverrides = {
},
},
global: {
restartRequired: ["position", "format", "color", "thickness", "effect"],
restartRequired: [],
},
camera: {
restartRequired: [],
@@ -1,5 +1,39 @@
import type { FrigateConfig, CameraConfig } from "@/types/frigateConfig";
import type { ConfigSectionData } from "@/types/configForm";
import type { SectionConfig } from "../sections/BaseSection";
/** Context provided to message condition functions */
export type MessageConditionContext = {
fullConfig: FrigateConfig;
fullCameraConfig?: CameraConfig;
level: "global" | "camera";
cameraName?: string;
formData: ConfigSectionData;
};
/** Severity levels for conditional messages */
export type MessageSeverity = "info" | "warning" | "error";
/** A conditional message definition */
export type ConditionalMessage = {
/** Unique key for React list rendering and deduplication */
key: string;
/** Translation key resolved via t() in the views/settings namespace */
messageKey: string;
/** Severity level controlling visual styling */
severity: MessageSeverity;
/** Function returning true when the message should be shown */
condition: (ctx: MessageConditionContext) => boolean;
};
/** Field-level conditional message, adds field targeting */
export type FieldConditionalMessage = ConditionalMessage & {
/** Dot-separated field path (e.g., "enabled", "alerts.labels") */
field: string;
/** Whether to render before or after the field (default: "before") */
position?: "before" | "after";
};
export type SectionConfigOverrides = {
base?: SectionConfig;
global?: Partial<SectionConfig>;
@@ -43,6 +43,7 @@ import {
SelectItem,
} from "@/components/ui/select";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { use24HourTime } from "@/hooks/use-date-utils";
import FilterSwitch from "@/components/filter/FilterSwitch";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Trans, useTranslation } from "react-i18next";
@@ -752,6 +753,7 @@ export function CameraNotificationSwitch({
};
const locale = useDateLocale();
const is24Hour = use24HourTime(config);
const formatSuspendedUntil = (timestamp: string) => {
if (timestamp === "0") return t("time.untilForRestart", { ns: "common" });
@@ -760,14 +762,13 @@ export function CameraNotificationSwitch({
time_style: "medium",
date_style: "medium",
timezone: config?.ui.timezone,
date_format:
config?.ui.time_format == "24hour"
? t("time.formattedTimestampMonthDayHourMinute.24hour", {
ns: "common",
})
: t("time.formattedTimestampMonthDayHourMinute.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestampMonthDayHourMinute.24hour", {
ns: "common",
})
: t("time.formattedTimestampMonthDayHourMinute.12hour", {
ns: "common",
}),
locale: locale,
});
return t("time.untilForTime", { ns: "common", time });
@@ -71,6 +71,13 @@ import {
} from "@/utils/configUtil";
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
import { useRestart } from "@/api/ws";
import type {
ConditionalMessage,
FieldConditionalMessage,
MessageConditionContext,
} from "../section-configs/types";
import { useConfigMessages } from "@/hooks/use-config-messages";
import { ConfigMessageBanner } from "../ConfigMessageBanner";
export interface SectionConfig {
/** Field ordering within the section */
@@ -100,6 +107,10 @@ export interface SectionConfig {
formData: unknown,
errors: FormValidation,
) => FormValidation;
/** Conditional messages displayed as banners above the section form */
messages?: ConditionalMessage[];
/** Conditional messages displayed inline with specific fields */
fieldMessages?: FieldConditionalMessage[];
}
export interface BaseSectionProps {
@@ -152,6 +163,10 @@ export interface BaseSectionProps {
profileBorderColor?: string;
/** Callback to delete the current profile's overrides for this section */
onDeleteProfileSection?: () => void;
/** Whether a SaveAll operation is in progress (disables individual Save) */
isSavingAll?: boolean;
/** Callback when this section's saving state changes */
onSavingChange?: (isSaving: boolean) => void;
}
export interface CreateSectionOptions {
@@ -186,6 +201,8 @@ export function ConfigSection({
profileFriendlyName,
profileBorderColor,
onDeleteProfileSection,
isSavingAll = false,
onSavingChange,
}: ConfigSectionProps) {
// For replay level, treat as camera-level config access
const effectiveLevel = level === "replay" ? "camera" : level;
@@ -246,6 +263,7 @@ export function ConfigSection({
[onPendingDataChange, effectiveSectionPath, cameraName],
);
const [isSaving, setIsSaving] = useState(false);
const [isResettingToDefault, setIsResettingToDefault] = useState(false);
const [hasValidationErrors, setHasValidationErrors] = useState(false);
const [extraHasChanges, setExtraHasChanges] = useState(false);
const [formKey, setFormKey] = useState(0);
@@ -529,6 +547,65 @@ export function ConfigSection({
const currentFormData = pendingData || formData;
const effectiveBaselineFormData = baselineSnapshot;
// Build context for conditional messages
const messageContext = useMemo<MessageConditionContext | undefined>(() => {
if (!config || !currentFormData) return undefined;
return {
fullConfig: config,
fullCameraConfig:
effectiveLevel === "camera" && cameraName
? config.cameras?.[cameraName]
: undefined,
level: effectiveLevel,
cameraName,
formData: currentFormData as ConfigSectionData,
};
}, [config, currentFormData, effectiveLevel, cameraName]);
const { activeMessages, activeFieldMessages } = useConfigMessages(
sectionConfig.messages,
sectionConfig.fieldMessages,
messageContext,
);
// Merge field-level conditional messages into uiSchema
const effectiveUiSchema = useMemo(() => {
if (activeFieldMessages.length === 0) return sectionConfig.uiSchema;
const merged = { ...(sectionConfig.uiSchema ?? {}) };
for (const msg of activeFieldMessages) {
const segments = msg.field.split(".");
// Navigate to the nested uiSchema node, shallow-cloning along the way
let node = merged;
for (let i = 0; i < segments.length - 1; i++) {
const seg = segments[i];
node[seg] = { ...(node[seg] as Record<string, unknown>) };
node = node[seg] as Record<string, unknown>;
}
const leafKey = segments[segments.length - 1];
const existing = node[leafKey] as Record<string, unknown> | undefined;
const existingMessages = ((existing?.["ui:messages"] as unknown[]) ??
[]) as Array<{
key: string;
messageKey: string;
severity: string;
position?: string;
}>;
node[leafKey] = {
...existing,
"ui:messages": [
...existingMessages,
{
key: msg.key,
messageKey: msg.messageKey,
severity: msg.severity,
position: msg.position ?? "before",
},
],
};
}
return merged;
}, [sectionConfig.uiSchema, activeFieldMessages]);
const currentOverrides = useMemo(() => {
if (!currentFormData || typeof currentFormData !== "object") {
return undefined;
@@ -577,6 +654,7 @@ export function ConfigSection({
if (!pendingData) return;
setIsSaving(true);
onSavingChange?.(true);
try {
const basePath =
effectiveLevel === "camera" && cameraName
@@ -659,8 +737,8 @@ export function ConfigSection({
);
}
await refreshConfig();
setPendingData(null);
refreshConfig();
onSave?.();
} catch (error) {
// Parse Pydantic validation errors from API response
@@ -699,6 +777,7 @@ export function ConfigSection({
}
} finally {
setIsSaving(false);
onSavingChange?.(false);
}
}, [
sectionPath,
@@ -718,12 +797,14 @@ export function ConfigSection({
setPendingData,
requiresRestartForOverrides,
skipSave,
onSavingChange,
]);
// Handle reset to global/defaults - removes camera-level override or resets global to defaults
const handleResetToGlobal = useCallback(async () => {
if (effectiveLevel === "camera" && !cameraName) return;
setIsResettingToDefault(true);
try {
const basePath =
effectiveLevel === "camera" && cameraName
@@ -758,6 +839,8 @@ export function ConfigSection({
defaultValue: "Failed to reset settings",
}),
);
} finally {
setIsResettingToDefault(false);
}
}, [
effectiveSectionPath,
@@ -861,6 +944,7 @@ export function ConfigSection({
const sectionContent = (
<div className="space-y-6">
<ConfigMessageBanner messages={activeMessages} />
<ConfigForm
key={formKey}
schema={modifiedSchema}
@@ -872,7 +956,7 @@ export function ConfigSection({
hiddenFields={effectiveHiddenFields}
advancedFields={sectionConfig.advancedFields}
liveValidate={sectionConfig.liveValidate}
uiSchema={sectionConfig.uiSchema}
uiSchema={effectiveUiSchema}
disabled={disabled || isSaving}
readonly={readonly}
showSubmit={false}
@@ -945,9 +1029,12 @@ export function ConfigSection({
<Button
onClick={() => setIsResetDialogOpen(true)}
variant="outline"
disabled={isSaving || disabled}
disabled={isSaving || isResettingToDefault || disabled}
className="flex flex-1 gap-2"
>
{isResettingToDefault && (
<ActivityIndicator className="h-4 w-4" />
)}
{effectiveLevel === "global"
? t("button.resetToDefault", {
ns: "common",
@@ -980,7 +1067,7 @@ export function ConfigSection({
<Button
onClick={handleReset}
variant="outline"
disabled={isSaving || disabled}
disabled={isSaving || isSavingAll || disabled}
className="flex min-w-36 flex-1 gap-2"
>
{t("button.undo", { ns: "common", defaultValue: "Undo" })}
@@ -990,7 +1077,11 @@ export function ConfigSection({
onClick={handleSave}
variant="select"
disabled={
!hasChanges || hasValidationErrors || isSaving || disabled
!hasChanges ||
hasValidationErrors ||
isSaving ||
isSavingAll ||
disabled
}
className="flex min-w-36 flex-1 gap-2"
>
@@ -60,7 +60,9 @@ export function AddPropertyButton({
className="gap-2"
>
<LuPlus className="h-4 w-4" />
{t("button.add", { ns: "common", defaultValue: "Add" })}
{typeof uiSchema?.["ui:options"]?.addButtonText === "string"
? uiSchema["ui:options"].addButtonText
: t("button.add", { ns: "common", defaultValue: "Add" })}
</Button>
);
}
@@ -374,6 +374,18 @@ export function DetectorHardwareField(props: FieldProps) {
[detectors],
);
const getExistingType = useCallback(
(excludeKey?: string): string | undefined => {
for (const [key, value] of Object.entries(detectors)) {
if (excludeKey && key === excludeKey) continue;
const type = getInstanceType(value);
if (type) return type;
}
return undefined;
},
[detectors],
);
const handleAdd = useCallback(() => {
if (!addType) {
setAddError(
@@ -400,6 +412,28 @@ export function DetectorHardwareField(props: FieldProps) {
return;
}
const existingType = getExistingType();
if (existingType && existingType !== addType) {
const canAddExisting =
multiInstanceSet.has(existingType) ||
!resolveDuplicateType(existingType);
setAddError(
canAddExisting
? t("configMessages.detectors.mixedTypesSuggestion", {
ns: "views/settings",
defaultValue:
"All detectors must use the same type. Remove existing detectors or select {{type}}.",
type: getTypeLabel(existingType),
})
: t("configMessages.detectors.mixedTypes", {
ns: "views/settings",
defaultValue:
"All detectors must use the same type. Remove existing detectors to use a different type.",
}),
);
return;
}
const baseKey = addType;
let nextKey = baseKey;
let index = 2;
@@ -427,8 +461,10 @@ export function DetectorHardwareField(props: FieldProps) {
configNamespace,
detectors,
getDetectorDefaults,
getExistingType,
getTypeLabel,
isSingleInstanceType,
multiInstanceSet,
resolveDuplicateType,
updateDetectors,
]);
@@ -523,6 +559,29 @@ export function DetectorHardwareField(props: FieldProps) {
return;
}
const existingType = getExistingType(key);
if (existingType && existingType !== nextType) {
const canAddExisting =
multiInstanceSet.has(existingType) ||
!resolveDuplicateType(existingType, key);
setTypeErrors((prev) => ({
...prev,
[key]: canAddExisting
? t("configMessages.detectors.mixedTypesSuggestion", {
ns: "views/settings",
defaultValue:
"All detectors must use the same type. Remove existing detectors or select {{type}}.",
type: getTypeLabel(existingType),
})
: t("configMessages.detectors.mixedTypes", {
ns: "views/settings",
defaultValue:
"All detectors must use the same type. Remove existing detectors to use a different type.",
}),
}));
return;
}
setTypeErrors((prev) => {
const { [key]: _, ...rest } = prev;
return rest;
@@ -538,8 +597,10 @@ export function DetectorHardwareField(props: FieldProps) {
[
detectors,
getDetectorDefaults,
getExistingType,
getTypeLabel,
isSingleInstanceType,
multiInstanceSet,
resolveDuplicateType,
t,
updateDetectors,
@@ -556,6 +617,10 @@ export function DetectorHardwareField(props: FieldProps) {
const nestedOverrides = {
"ui:options": {
disableNestedCard: true,
addButtonText: t("configForm.detectors.addCustomKey", {
ns: "views/settings",
defaultValue: "Add custom key",
}),
},
} as UiSchema;
@@ -567,7 +632,7 @@ export function DetectorHardwareField(props: FieldProps) {
);
return mergeUiSchema(withTypeHiddenAndOptions, nestedOverrides);
},
[globalHiddenFields, hiddenByType, uiSchema?.additionalProperties],
[globalHiddenFields, hiddenByType, t, uiSchema?.additionalProperties],
);
const renderInstanceForm = useCallback(
@@ -0,0 +1,122 @@
import type { FieldPathList, FieldProps } from "@rjsf/utils";
import yaml from "js-yaml";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
function formatYaml(value: unknown): string {
if (
value == null ||
(typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value as Record<string, unknown>).length === 0)
) {
return "";
}
try {
return yaml.dump(value, { indent: 2, lineWidth: -1 }).trimEnd();
} catch {
return "";
}
}
function parseYaml(text: string): {
value: Record<string, unknown> | undefined;
error: string | undefined;
} {
const trimmed = text.trim();
if (trimmed === "") {
return { value: {}, error: undefined };
}
try {
const parsed = yaml.load(trimmed);
if (
typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed)
) {
return { value: undefined, error: "Must be a YAML mapping" };
}
return { value: parsed as Record<string, unknown>, error: undefined };
} catch (e) {
const msg = e instanceof yaml.YAMLException ? e.reason : "Invalid YAML";
return { value: undefined, error: msg };
}
}
export function DictAsYamlField(props: FieldProps) {
const { formData, onChange, readonly, disabled, idSchema, schema } = props;
const emptyPath = useMemo(() => [] as FieldPathList, []);
const fieldPath =
(props as { fieldPathId?: { path?: FieldPathList } }).fieldPathId?.path ??
emptyPath;
const [text, setText] = useState(() => formatYaml(formData));
const [error, setError] = useState<string>();
const focusedRef = useRef(false);
useEffect(() => {
// Only sync from external formData changes, not our own onChange
if (!focusedRef.current) {
setText(formatYaml(formData));
setError(undefined);
}
}, [formData]);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
const raw = e.target.value;
setText(raw);
const { value, error: parseError } = parseYaml(raw);
setError(parseError);
if (value !== undefined) {
onChange(value, fieldPath);
}
},
[onChange, fieldPath],
);
const handleFocus = useCallback(() => {
focusedRef.current = true;
}, []);
const handleBlur = useCallback(
(_e: React.FocusEvent<HTMLTextAreaElement>) => {
focusedRef.current = false;
// Reformat on blur if valid
const { value } = parseYaml(text);
if (value !== undefined) {
setText(formatYaml(value));
}
},
[text],
);
const id = idSchema?.$id ?? props.name;
return (
<div className="flex flex-col gap-1.5">
{schema.title && (
<label htmlFor={id} className="text-sm font-medium">
{schema.title}
</label>
)}
<Textarea
id={id}
className={cn("font-mono text-sm", error && "border-destructive")}
value={text}
disabled={disabled || readonly}
placeholder={"key: value"}
rows={Math.max(3, text.split("\n").length + 1)}
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
/>
{error && <p className="text-xs text-destructive">{error}</p>}
{schema.description && (
<p className="text-xs text-muted-foreground">{schema.description}</p>
)}
</div>
);
}
@@ -20,15 +20,18 @@ import { TextareaWidget } from "./widgets/TextareaWidget";
import { SwitchesWidget } from "./widgets/SwitchesWidget";
import { ObjectLabelSwitchesWidget } from "./widgets/ObjectLabelSwitchesWidget";
import { AudioLabelSwitchesWidget } from "./widgets/AudioLabelSwitchesWidget";
import { ReviewLabelSwitchesWidget } from "./widgets/ReviewLabelSwitchesWidget";
import { ZoneSwitchesWidget } from "./widgets/ZoneSwitchesWidget";
import { ArrayAsTextWidget } from "./widgets/ArrayAsTextWidget";
import { FfmpegArgsWidget } from "./widgets/FfmpegArgsWidget";
import { GenAIModelWidget } from "./widgets/GenAIModelWidget";
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 { OnvifProfileWidget } from "./widgets/OnvifProfileWidget";
import { FieldTemplate } from "./templates/FieldTemplate";
import { ObjectFieldTemplate } from "./templates/ObjectFieldTemplate";
@@ -45,6 +48,7 @@ import { LayoutGridField } from "./fields/LayoutGridField";
import { DetectorHardwareField } from "./fields/DetectorHardwareField";
import { ReplaceRulesField } from "./fields/ReplaceRulesField";
import { CameraInputsField } from "./fields/CameraInputsField";
import { DictAsYamlField } from "./fields/DictAsYamlField";
export interface FrigateTheme {
widgets: RegistryWidgetsType;
@@ -62,6 +66,7 @@ export const frigateTheme: FrigateTheme = {
ArrayAsTextWidget: ArrayAsTextWidget,
FfmpegArgsWidget: FfmpegArgsWidget,
CameraPathWidget: CameraPathWidget,
genaiModel: GenAIModelWidget,
genaiRoles: GenAIRolesWidget,
inputRoles: InputRolesWidget,
// Custom widgets
@@ -75,10 +80,12 @@ export const frigateTheme: FrigateTheme = {
switches: SwitchesWidget,
objectLabels: ObjectLabelSwitchesWidget,
audioLabels: AudioLabelSwitchesWidget,
reviewLabels: ReviewLabelSwitchesWidget,
zoneNames: ZoneSwitchesWidget,
timezoneSelect: TimezoneSelectWidget,
optionalField: OptionalFieldWidget,
semanticSearchModel: SemanticSearchModelWidget,
onvifProfile: OnvifProfileWidget,
},
templates: {
FieldTemplate: FieldTemplate as React.ComponentType<FieldTemplateProps>,
@@ -97,5 +104,6 @@ export const frigateTheme: FrigateTheme = {
DetectorHardwareField: DetectorHardwareField,
ReplaceRulesField: ReplaceRulesField,
CameraInputsField: CameraInputsField,
DictAsYamlField: DictAsYamlField,
},
};
@@ -28,6 +28,7 @@ import {
} from "../utils";
import { normalizeOverridePath } from "../utils/overrides";
import get from "lodash/get";
import { ConfigFieldMessage } from "../../ConfigFieldMessage";
import isEqual from "lodash/isEqual";
import { SPLIT_ROW_CLASS_NAME } from "@/components/card/SettingsGroupCard";
@@ -382,6 +383,46 @@ export function FieldTemplate(props: FieldTemplateProps) {
const beforeContent = renderCustom(beforeSpec);
const afterContent = renderCustom(afterSpec);
// Render conditional field messages from ui:messages
const fieldMessageSpecs = uiSchema?.["ui:messages"] as
| Array<{
key: string;
messageKey: string;
severity: string;
position?: string;
}>
| undefined;
const beforeMessages = fieldMessageSpecs?.filter(
(m) => (m.position ?? "before") === "before",
);
const afterMessages = fieldMessageSpecs?.filter(
(m) => m.position === "after",
);
const beforeMessagesContent =
beforeMessages && beforeMessages.length > 0 ? (
<div className="space-y-2">
{beforeMessages.map((m) => (
<ConfigFieldMessage
key={m.key}
messageKey={m.messageKey}
severity={m.severity}
/>
))}
</div>
) : null;
const afterMessagesContent =
afterMessages && afterMessages.length > 0 ? (
<div className="space-y-2">
{afterMessages.map((m) => (
<ConfigFieldMessage
key={m.key}
messageKey={m.messageKey}
severity={m.severity}
/>
))}
</div>
) : null;
const WrapIfAdditionalTemplate = getTemplate(
"WrapIfAdditionalTemplate",
registry,
@@ -600,6 +641,7 @@ export function FieldTemplate(props: FieldTemplateProps) {
>
<div className="flex flex-col space-y-6">
{beforeContent}
{beforeMessagesContent}
<div className={cn("space-y-1")} data-field-id={translationPath}>
{renderStandardLabel()}
{renderFieldLayout()}
@@ -607,6 +649,7 @@ export function FieldTemplate(props: FieldTemplateProps) {
{errors}
{help}
</div>
{afterMessagesContent}
{afterContent}
</div>
</WrapIfAdditionalTemplate>
@@ -1,33 +1,101 @@
// Widget that displays an array as a concatenated text string
// Widget that displays an array as editable text.
// Single-line mode (default): space-separated in an Input.
// Multiline mode (options.multiline): one item per line in a Textarea.
import type { WidgetProps } from "@rjsf/utils";
import { Input } from "@/components/ui/input";
import { useCallback } from "react";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { getSizedFieldClassName } from "../utils";
import { useCallback, useEffect, useState } from "react";
function arrayToText(value: unknown, multiline: boolean): string {
const sep = multiline ? "\n" : " ";
if (Array.isArray(value) && value.length > 0) {
return value.join(sep);
}
if (typeof value === "string") {
return value;
}
return "";
}
function textToArray(text: string, multiline: boolean): string[] {
if (text.trim() === "") {
return [];
}
return multiline
? text.split("\n").filter((line) => line.trim() !== "")
: text.trim().split(/\s+/);
}
export function ArrayAsTextWidget(props: WidgetProps) {
const { value, onChange, disabled, readonly, placeholder } = props;
const {
id,
value,
disabled,
readonly,
onChange,
onBlur,
onFocus,
placeholder,
schema,
options,
} = props;
// Convert array or string to text
let textValue = "";
if (typeof value === "string" && value.length > 0) {
textValue = value;
} else if (Array.isArray(value) && value.length > 0) {
textValue = value.join(" ");
}
const multiline = !!(options.multiline as boolean);
const handleChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const newText = event.target.value;
// Convert space-separated string back to array
const newArray = newText.trim() ? newText.trim().split(/\s+/) : [];
onChange(newArray);
// Local state keeps raw text so newlines aren't stripped mid-typing
const [text, setText] = useState(() => arrayToText(value, multiline));
useEffect(() => {
setText(arrayToText(value, multiline));
}, [value, multiline]);
const fieldClassName = multiline
? getSizedFieldClassName(options, "md")
: undefined;
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const raw = e.target.value;
setText(raw);
onChange(textToArray(raw, multiline));
},
[onChange],
[onChange, multiline],
);
const handleBlur = useCallback(
(e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
// Clean up: strip empty entries and sync
const cleaned = textToArray(e.target.value, multiline);
onChange(cleaned);
setText(arrayToText(cleaned, multiline));
onBlur?.(id, e.target.value);
},
[id, onChange, onBlur, multiline],
);
if (multiline) {
return (
<Textarea
id={id}
className={cn("text-md", fieldClassName)}
value={text}
disabled={disabled || readonly}
rows={(options.rows as number) || 3}
onChange={handleInputChange}
onBlur={handleBlur}
onFocus={(e) => onFocus?.(id, e.target.value)}
aria-label={schema.title}
/>
);
}
return (
<Input
value={textValue}
onChange={handleChange}
value={text}
onChange={handleInputChange}
onBlur={handleBlur}
disabled={disabled}
readOnly={readonly}
placeholder={placeholder}
@@ -0,0 +1,125 @@
// Combobox widget for genai *.model fields.
// Fetches available models from the provider's backend and shows them in a dropdown.
import { useState, useMemo } from "react";
import type { WidgetProps } from "@rjsf/utils";
import { useTranslation } from "react-i18next";
import useSWR from "swr";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { getSizedFieldClassName } from "../utils";
/**
* Extract the provider config entry name from the RJSF widget id.
* Widget ids look like "root_myProvider_model".
*/
function getProviderKey(widgetId: string): string | undefined {
const prefix = "root_";
const suffix = "_model";
if (!widgetId.startsWith(prefix) || !widgetId.endsWith(suffix)) {
return undefined;
}
return widgetId.slice(prefix.length, -suffix.length) || undefined;
}
export function GenAIModelWidget(props: WidgetProps) {
const { id, value, disabled, readonly, onChange, options } = props;
const { t } = useTranslation(["views/settings"]);
const [open, setOpen] = useState(false);
const fieldClassName = getSizedFieldClassName(options, "sm");
const providerKey = useMemo(() => getProviderKey(id), [id]);
const { data: allModels } = useSWR<Record<string, string[]>>("genai/models", {
revalidateOnFocus: false,
});
const models = useMemo(() => {
if (!allModels || !providerKey) return [];
return allModels[providerKey] ?? [];
}, [allModels, providerKey]);
const currentLabel = 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.genaiModel.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>
<CommandInput
placeholder={t("configForm.genaiModel.search", {
ns: "views/settings",
defaultValue: "Search models…",
})}
/>
<CommandList>
{models.length > 0 ? (
<CommandGroup>
{models.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => {
onChange(model);
setOpen(false);
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0",
)}
/>
{model}
</CommandItem>
))}
</CommandGroup>
) : (
<div className="p-4 text-center text-sm text-muted-foreground">
{t("configForm.genaiModel.noModels", {
ns: "views/settings",
defaultValue: "No models available",
})}
</div>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
@@ -4,7 +4,7 @@ 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;
const GENAI_ROLES = ["embeddings", "descriptions", "chat"] as const;
function normalizeValue(value: unknown): string[] {
if (Array.isArray(value)) {
@@ -0,0 +1,84 @@
import type { WidgetProps } from "@rjsf/utils";
import useSWR from "swr";
import { useTranslation } from "react-i18next";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { ConfigFormContext } from "@/types/configForm";
import type { CameraPtzInfo } from "@/types/ptz";
import { getSizedFieldClassName } from "../utils";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { cn } from "@/lib/utils";
const AUTO_VALUE = "__auto__";
export function OnvifProfileWidget(props: WidgetProps) {
const { id, value, disabled, readonly, onChange, schema, options } = props;
const { t } = useTranslation(["views/settings"]);
const formContext = props.registry?.formContext as
| ConfigFormContext
| undefined;
const cameraName = formContext?.cameraName;
const isCameraLevel = formContext?.level === "camera";
const hasOnvifHost = !!formContext?.fullCameraConfig?.onvif?.host;
const { data: ptzInfo } = useSWR<CameraPtzInfo>(
isCameraLevel && cameraName && hasOnvifHost
? `${cameraName}/ptz/info`
: null,
{
// ONVIF may not be initialized yet when the settings page loads,
// so retry until profiles become available
refreshInterval: (data) =>
data?.profiles && data.profiles.length > 0 ? 0 : 5000,
},
);
const profiles = ptzInfo?.profiles ?? [];
const fieldClassName = getSizedFieldClassName(options, "md");
const hasProfiles = profiles.length > 0;
const waiting = isCameraLevel && !!cameraName && hasOnvifHost && !hasProfiles;
const selected = value ?? AUTO_VALUE;
if (waiting) {
return (
<div className={cn("flex items-center gap-2", fieldClassName)}>
<ActivityIndicator className="size-4" />
<span className="text-sm text-muted-foreground">
{t("onvif.profileLoading")}
</span>
</div>
);
}
return (
<Select
value={String(selected)}
onValueChange={(val) => {
onChange(val === AUTO_VALUE ? null : val);
}}
disabled={disabled || readonly}
>
<SelectTrigger id={id} className={cn("text-left", fieldClassName)}>
<SelectValue placeholder={schema.title || "Select..."} />
</SelectTrigger>
<SelectContent>
<SelectItem value={AUTO_VALUE}>{t("onvif.profileAuto")}</SelectItem>
{profiles.map((p) => (
<SelectItem key={p.token} value={p.token}>
{p.name !== p.token ? `${p.name} (${p.token})` : p.token}
</SelectItem>
))}
{!hasProfiles && value && value !== AUTO_VALUE && (
<SelectItem value={String(value)}>{String(value)}</SelectItem>
)}
</SelectContent>
</Select>
);
}
@@ -0,0 +1,84 @@
// Review Label Switches Widget - For selecting review alert/detection labels via switches.
// Combines object labels (from objects.track) and audio labels (from audio.listen)
// since review labels can include both types.
import type { WidgetProps } from "@rjsf/utils";
import { SwitchesWidget } from "./SwitchesWidget";
import type { FormContext } from "./SwitchesWidget";
import { getTranslatedLabel } from "@/utils/i18n";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { JsonObject } from "@/types/configForm";
function getReviewLabels(context: FormContext): string[] {
const labels = new Set<string>();
const fullConfig = context.fullConfig as FrigateConfig | undefined;
const fullCameraConfig = context.fullCameraConfig;
// Object labels from tracked objects (camera-level, falling back to global)
const trackLabels =
fullCameraConfig?.objects?.track ?? fullConfig?.objects?.track;
if (Array.isArray(trackLabels)) {
trackLabels.forEach((label: string) => labels.add(label));
}
// Audio labels from listen config, only if audio detection is enabled
const audioEnabled =
fullCameraConfig?.audio?.enabled_in_config ??
fullConfig?.audio?.enabled_in_config;
if (audioEnabled) {
const audioLabels =
fullCameraConfig?.audio?.listen ?? fullConfig?.audio?.listen;
if (Array.isArray(audioLabels)) {
audioLabels.forEach((label: string) => labels.add(label));
}
}
// Include any labels already in the review form data (alerts + detections)
// so that previously saved labels remain visible even if tracking config changed
if (context.formData && typeof context.formData === "object") {
const formData = context.formData as JsonObject;
for (const section of ["alerts", "detections"] as const) {
const sectionData = formData[section];
if (sectionData && typeof sectionData === "object") {
const sectionLabels = (sectionData as JsonObject).labels;
if (Array.isArray(sectionLabels)) {
sectionLabels.forEach((label) => {
if (typeof label === "string") {
labels.add(label);
}
});
}
}
}
}
return [...labels].sort();
}
function getReviewLabelDisplayName(
label: string,
context?: FormContext,
): string {
const fullCameraConfig = context?.fullCameraConfig;
const fullConfig = context?.fullConfig as FrigateConfig | undefined;
const audioLabels =
fullCameraConfig?.audio?.listen ?? fullConfig?.audio?.listen;
const isAudio = Array.isArray(audioLabels) && audioLabels.includes(label);
return getTranslatedLabel(label, isAudio ? "audio" : "object");
}
export function ReviewLabelSwitchesWidget(props: WidgetProps) {
return (
<SwitchesWidget
{...props}
options={{
...props.options,
getEntities: getReviewLabels,
getDisplayLabel: getReviewLabelDisplayName,
i18nKey: "reviewLabels",
allowCustomEntries: true,
listClassName:
"relative max-h-none overflow-visible md:max-h-64 md:overflow-y-auto md:overscroll-contain md:scrollbar-container",
}}
/>
);
}
@@ -1,5 +1,6 @@
// Select Widget - maps to shadcn/ui Select
import type { WidgetProps } from "@rjsf/utils";
import { useTranslation } from "react-i18next";
import {
Select,
SelectContent,
@@ -21,9 +22,18 @@ export function SelectWidget(props: WidgetProps) {
schema,
} = props;
const { t } = useTranslation(["views/settings"]);
const { enumOptions = [] } = options;
const enumI18nPrefix = options["enumI18nPrefix"] as string | undefined;
const fieldClassName = getSizedFieldClassName(options, "sm");
const getLabel = (option: { value: unknown; label: string }) => {
if (enumI18nPrefix) {
return t(`${enumI18nPrefix}.${option.value}`);
}
return option.label;
};
return (
<Select
value={value?.toString() ?? ""}
@@ -42,7 +52,7 @@ export function SelectWidget(props: WidgetProps) {
<SelectContent>
{enumOptions.map((option: { value: unknown; label: string }) => (
<SelectItem key={String(option.value)} value={String(option.value)}>
{option.label}
{getLabel(option)}
</SelectItem>
))}
</SelectContent>
@@ -1,6 +1,6 @@
// Generic Switches Widget - Reusable component for selecting from any list of entities
import { WidgetProps } from "@rjsf/utils";
import { useMemo, useState } from "react";
import { useCallback, useMemo, useState } from "react";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -43,6 +43,8 @@ export type SwitchesWidgetOptions = {
listClassName?: string;
/** Enable search input to filter the list */
enableSearch?: boolean;
/** Allow users to add custom entries not in the predefined list */
allowCustomEntries?: boolean;
};
function normalizeValue(value: unknown): string[] {
@@ -122,20 +124,46 @@ export function SwitchesWidget(props: WidgetProps) {
[props.options],
);
const allowCustomEntries = useMemo(
() => props.options?.allowCustomEntries as boolean | undefined,
[props.options],
);
const selectedEntities = useMemo(() => normalizeValue(value), [value]);
const [isOpen, setIsOpen] = useState(selectedEntities.length > 0);
const [searchTerm, setSearchTerm] = useState("");
const [customEntries, setCustomEntries] = useState<string[]>([]);
const [customInput, setCustomInput] = useState("");
const allEntities = useMemo(() => {
if (customEntries.length === 0) {
return availableEntities;
}
const merged = new Set([...availableEntities, ...customEntries]);
return [...merged].sort();
}, [availableEntities, customEntries]);
const filteredEntities = useMemo(() => {
if (!enableSearch || !searchTerm.trim()) {
return availableEntities;
return allEntities;
}
const term = searchTerm.toLowerCase();
return availableEntities.filter((entity) => {
return allEntities.filter((entity) => {
const displayLabel = getDisplayLabel(entity, context);
return displayLabel.toLowerCase().includes(term);
});
}, [availableEntities, searchTerm, enableSearch, getDisplayLabel, context]);
}, [allEntities, searchTerm, enableSearch, getDisplayLabel, context]);
const addCustomEntry = useCallback(() => {
const trimmed = customInput.trim().toLowerCase();
if (!trimmed || allEntities.includes(trimmed)) {
setCustomInput("");
return;
}
setCustomEntries((prev) => [...prev, trimmed]);
onChange([...selectedEntities, trimmed]);
setCustomInput("");
}, [customInput, allEntities, selectedEntities, onChange]);
const toggleEntity = (entity: string, enabled: boolean) => {
if (enabled) {
@@ -163,7 +191,7 @@ export function SwitchesWidget(props: WidgetProps) {
return (
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<div className="space-y-3">
<div className="space-y-2">
<CollapsibleTrigger asChild>
<Button
type="button"
@@ -180,8 +208,8 @@ export function SwitchesWidget(props: WidgetProps) {
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="rounded-lg bg-secondary p-2 pr-0 md:max-w-md">
{availableEntities.length === 0 ? (
<CollapsibleContent className="rounded-lg border border-input bg-secondary pb-1 pr-0 pt-2 md:max-w-md">
{allEntities.length === 0 && !allowCustomEntries ? (
<div className="text-sm text-muted-foreground">{emptyMessage}</div>
) : (
<>
@@ -223,6 +251,26 @@ export function SwitchesWidget(props: WidgetProps) {
);
})}
</div>
{allowCustomEntries && !disabled && !readonly && (
<div className="mx-2 mt-2 pb-1">
<Input
type="text"
placeholder={t?.("configForm.addCustomLabel", {
ns: "views/settings",
defaultValue: "Add custom label...",
})}
value={customInput}
onChange={(e) => setCustomInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addCustomEntry();
}
}}
onBlur={addCustomEntry}
/>
</div>
)}
</>
)}
</CollapsibleContent>
+28 -3
View File
@@ -2,12 +2,13 @@ import { useTheme } from "@/context/theme-provider";
import { useDateLocale } from "@/hooks/use-date-locale";
import { FrigateConfig } from "@/types/frigateConfig";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { useCallback, useEffect, useMemo } from "react";
import { useCallback, useEffect, useMemo, useRef } from "react";
import Chart from "react-apexcharts";
import { isMobileOnly } from "react-device-detect";
import { useTranslation } from "react-i18next";
import { MdCircle } from "react-icons/md";
import useSWR from "swr";
import { useTimeFormat } from "@/hooks/use-date-utils";
const GRAPH_COLORS = ["#5C7CFA", "#ED5CFA", "#FAD75C"];
@@ -17,6 +18,7 @@ type CameraLineGraphProps = {
dataLabels: string[];
updateTimes: number[];
data: ApexAxisChartSeries;
isActive?: boolean;
};
export function CameraLineGraph({
graphId,
@@ -24,6 +26,7 @@ export function CameraLineGraph({
dataLabels,
updateTimes,
data,
isActive = true,
}: CameraLineGraphProps) {
const { t } = useTranslation(["views/system", "common"]);
const { data: config } = useSWR<FrigateConfig>("config", {
@@ -46,7 +49,7 @@ export function CameraLineGraph({
const locale = useDateLocale();
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
return t(`time.formattedTimestampHourMinute.${timeFormat}`, {
ns: "common",
@@ -134,6 +137,16 @@ export function CameraLineGraph({
ApexCharts.exec(graphId, "updateOptions", options, true, true);
}, [graphId, options]);
const hasBeenActive = useRef(isActive);
useEffect(() => {
if (isActive && hasBeenActive.current === false) {
ApexCharts.exec(graphId, "updateSeries", data, true);
}
hasBeenActive.current = isActive;
// only replay animation on visibility change, not data updates
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive, graphId]);
return (
<div className="flex w-full flex-col">
{lastValues && (
@@ -166,6 +179,7 @@ type EventsPerSecondLineGraphProps = {
name: string;
updateTimes: number[];
data: ApexAxisChartSeries;
isActive?: boolean;
};
export function EventsPerSecondsLineGraph({
graphId,
@@ -173,6 +187,7 @@ export function EventsPerSecondsLineGraph({
name,
updateTimes,
data,
isActive = true,
}: EventsPerSecondLineGraphProps) {
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
@@ -189,7 +204,7 @@ export function EventsPerSecondsLineGraph({
const locale = useDateLocale();
const { t } = useTranslation(["common"]);
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
return t(`time.formattedTimestampHourMinute.${timeFormat}`, {
ns: "common",
@@ -277,6 +292,16 @@ export function EventsPerSecondsLineGraph({
ApexCharts.exec(graphId, "updateOptions", options, true, true);
}, [graphId, options]);
const hasBeenActive = useRef(isActive);
useEffect(() => {
if (isActive && hasBeenActive.current === false) {
ApexCharts.exec(graphId, "updateSeries", data, true);
}
hasBeenActive.current = isActive;
// only replay animation on visibility change, not data updates
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive, graphId]);
return (
<div className="flex w-full flex-col">
<div className="flex items-center gap-1">
+22 -7
View File
@@ -3,11 +3,12 @@ import { useDateLocale } from "@/hooks/use-date-locale";
import { FrigateConfig } from "@/types/frigateConfig";
import { Threshold } from "@/types/graph";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { useCallback, useEffect, useMemo } from "react";
import { useCallback, useEffect, useMemo, useRef } from "react";
import Chart from "react-apexcharts";
import { isMobileOnly } from "react-device-detect";
import { useTranslation } from "react-i18next";
import useSWR from "swr";
import { useTimeFormat } from "@/hooks/use-date-utils";
type ThresholdBarGraphProps = {
graphId: string;
@@ -16,6 +17,7 @@ type ThresholdBarGraphProps = {
threshold: Threshold;
updateTimes: number[];
data: ApexAxisChartSeries;
isActive?: boolean;
};
export function ThresholdBarGraph({
graphId,
@@ -24,6 +26,7 @@ export function ThresholdBarGraph({
threshold,
updateTimes,
data,
isActive = true,
}: ThresholdBarGraphProps) {
const displayName = name || data[0]?.name || "";
const { data: config } = useSWR<FrigateConfig>("config", {
@@ -51,7 +54,7 @@ export function ThresholdBarGraph({
const locale = useDateLocale();
const { t } = useTranslation(["common"]);
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
return t(`time.formattedTimestampHourMinute.${timeFormat}`, {
ns: "common",
@@ -173,17 +176,29 @@ export function ThresholdBarGraph({
return data;
}
const copiedData = [...data];
const dataPointCount = data[0].data.length;
const fakeData = [];
for (let i = data.length; i < 30; i++) {
for (let i = dataPointCount; i < 30; i++) {
fakeData.push({ x: i - 30, y: 0 });
}
// @ts-expect-error data types are not obvious
copiedData[0].data = [...fakeData, ...data[0].data];
return copiedData;
const paddedFirst = {
...data[0],
data: [...fakeData, ...data[0].data],
};
return [paddedFirst, ...data.slice(1)] as ApexAxisChartSeries;
}, [data]);
const hasBeenActive = useRef(isActive);
useEffect(() => {
if (isActive && hasBeenActive.current === false) {
ApexCharts.exec(graphId, "updateSeries", chartData, true);
}
hasBeenActive.current = isActive;
// only replay animation on visibility change, not data updates
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive, graphId]);
return (
<div className="flex w-full flex-col">
<div className="flex items-center gap-1">
+11 -15
View File
@@ -50,6 +50,7 @@ import {
import { toast } from "sonner";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { use24HourTime } from "@/hooks/use-date-utils";
import { MdImageSearch } from "react-icons/md";
import { useTranslation } from "react-i18next";
import { getTranslatedLabel } from "@/utils/i18n";
@@ -80,6 +81,8 @@ export default function InputWithTags({
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
const is24Hour = use24HourTime(config);
const resolvedTimeFormat = is24Hour ? "24hour" : ("12hour" as const);
const allAudioListenLabels = useMemo<Set<string>>(() => {
if (!config) {
@@ -431,12 +434,8 @@ export default function InputWithTags({
const [startTime, endTime] = (filterValues as string)
.replace("-", ",")
.split(",");
return `${
config?.ui.time_format === "24hour"
? startTime
: convertTo12Hour(startTime)
} - ${
config?.ui.time_format === "24hour" ? endTime : convertTo12Hour(endTime)
return `${is24Hour ? startTime : convertTo12Hour(startTime)} - ${
is24Hour ? endTime : convertTo12Hour(endTime)
}`;
} else if (filterType === "min_score" || filterType === "max_score") {
return Math.round(Number(filterValues) * 100).toString() + "%";
@@ -478,7 +477,7 @@ export default function InputWithTags({
(filterType === "time_range" &&
isValidTimeRange(
trimmedValue.replace("-", ","),
config?.ui.time_format,
resolvedTimeFormat,
)) ||
((filterType === "min_score" || filterType === "max_score") &&
!isNaN(Number(trimmedValue)) &&
@@ -495,7 +494,7 @@ export default function InputWithTags({
? trimmedValue
.replace("-", ",")
.split(",")
.map((time) => to24Hour(time.trim(), config?.ui.time_format))
.map((time) => to24Hour(time.trim(), resolvedTimeFormat))
.join(",")
: trimmedValue,
);
@@ -511,7 +510,7 @@ export default function InputWithTags({
setCurrentFilterType(null);
}
},
[allSuggestions, createFilter, config],
[allSuggestions, createFilter, resolvedTimeFormat],
);
const handleInputChange = useCallback(
@@ -598,7 +597,7 @@ export default function InputWithTags({
suggestion = suggestion
.replace("-", ",")
.split(",")
.map((time) => to24Hour(time.trim(), config?.ui.time_format))
.map((time) => to24Hour(time.trim(), resolvedTimeFormat))
.join(",");
}
createFilter(currentFilterType, suggestion);
@@ -627,7 +626,7 @@ export default function InputWithTags({
inputRef.current?.focus();
},
[createFilter, currentFilterType, allSuggestions, config],
[createFilter, currentFilterType, allSuggestions, resolvedTimeFormat],
);
const handleSearch = useCallback(
@@ -779,10 +778,7 @@ export default function InputWithTags({
</li>
<li>
{t("filter.tips.desc.step5", {
exampleTime:
config?.ui.time_format == "24hour"
? "15:00-16:00"
: "3:00PM-4:00PM",
exampleTime: is24Hour ? "15:00-16:00" : "3:00PM-4:00PM",
})}
</li>
<li>{t("filter.tips.desc.step6")}</li>
+10 -8
View File
@@ -46,6 +46,7 @@ import {
} from "@/api/ws";
import { useTranslation } from "react-i18next";
import { useDateLocale } from "@/hooks/use-date-locale";
import { use24HourTime } from "@/hooks/use-date-utils";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { CameraNameLabel } from "../camera/FriendlyNameLabel";
import { LiveStreamMetadata } from "@/types/live";
@@ -247,6 +248,8 @@ export default function LiveContextMenu({
const locale = useDateLocale();
const is24Hour = use24HourTime(config);
const formatSuspendedUntil = (timestamp: string) => {
// Some languages require a change in word order
if (timestamp === "0") return t("time.untilForRestart", { ns: "common" });
@@ -255,14 +258,13 @@ export default function LiveContextMenu({
time_style: "medium",
date_style: "medium",
timezone: config?.ui.timezone,
date_format:
config?.ui.time_format == "24hour"
? t("time.formattedTimestampMonthDayHourMinute.24hour", {
ns: "common",
})
: t("time.formattedTimestampMonthDayHourMinute.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestampMonthDayHourMinute.24hour", {
ns: "common",
})
: t("time.formattedTimestampMonthDayHourMinute.12hour", {
ns: "common",
}),
locale: locale,
});
return t("time.untilForTime", { ns: "common", time });
@@ -3,7 +3,7 @@ import { Button } from "../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { SelectSeparator } from "../ui/select";
import { TimeRange } from "@/types/timeline";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { getUTCOffset } from "@/utils/dateUtil";
import { TimezoneAwareCalendar } from "./ReviewActivityCalendar";
import { FaArrowRight, FaCalendarAlt } from "react-icons/fa";
@@ -69,16 +69,18 @@ export function CustomTimeSelector({
return time;
}, [range, latestTime, timezoneOffset, localTimeOffset]);
const is24Hour = use24HourTime(config);
const formattedStart = useFormattedTimestamp(
startTime,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestamp.24hour")
: t("time.formattedTimestamp.12hour"),
);
const formattedEnd = useFormattedTimestamp(
endTime,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestamp.24hour")
: t("time.formattedTimestamp.12hour"),
);
@@ -284,7 +284,9 @@ export default function PtzControlPanel({
<p>
{clickOverlay
? t("ptz.move.clickMove.disable")
: t("ptz.move.clickMove.enable")}
: ptz?.features?.includes("zoom-r")
? t("ptz.move.clickMove.enableWithZoom")
: t("ptz.move.clickMove.enable")}
</p>
</TooltipContent>
</Tooltip>
@@ -108,7 +108,7 @@ export function GenAISummaryDialog({
return (
<Overlay open={open} onOpenChange={setOpen}>
<Trigger asChild>
<div>{children}</div>
<div className="min-w-0">{children}</div>
</Trigger>
<Content
className={cn(
@@ -9,15 +9,16 @@ import { toast } from "sonner";
import { Trans, useTranslation } from "react-i18next";
import { LuExternalLink, LuInfo, LuMinus, LuPlus } from "react-icons/lu";
import { cn } from "@/lib/utils";
import {
ANNOTATION_OFFSET_MAX,
ANNOTATION_OFFSET_MIN,
ANNOTATION_OFFSET_STEP,
} from "@/lib/const";
import { isMobile } from "react-device-detect";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { Link } from "react-router-dom";
const OFFSET_MIN = -2500;
const OFFSET_MAX = 2500;
const OFFSET_STEP = 50;
type Props = {
className?: string;
};
@@ -43,7 +44,10 @@ export default function AnnotationOffsetSlider({ className }: Props) {
(delta: number) => {
setAnnotationOffset((prev) => {
const next = prev + delta;
return Math.max(OFFSET_MIN, Math.min(OFFSET_MAX, next));
return Math.max(
ANNOTATION_OFFSET_MIN,
Math.min(ANNOTATION_OFFSET_MAX, next),
);
});
},
[setAnnotationOffset],
@@ -114,17 +118,17 @@ export default function AnnotationOffsetSlider({ className }: Props) {
size="icon"
className="size-8 shrink-0"
aria-label="-50ms"
onClick={() => stepOffset(-OFFSET_STEP)}
disabled={annotationOffset <= OFFSET_MIN}
onClick={() => stepOffset(-ANNOTATION_OFFSET_STEP)}
disabled={annotationOffset <= ANNOTATION_OFFSET_MIN}
>
<LuMinus className="size-4" />
</Button>
<div className="w-full flex-1 landscape:flex">
<Slider
value={[annotationOffset]}
min={OFFSET_MIN}
max={OFFSET_MAX}
step={OFFSET_STEP}
min={ANNOTATION_OFFSET_MIN}
max={ANNOTATION_OFFSET_MAX}
step={ANNOTATION_OFFSET_STEP}
onValueChange={handleChange}
/>
</div>
@@ -134,8 +138,8 @@ export default function AnnotationOffsetSlider({ className }: Props) {
size="icon"
className="size-8 shrink-0"
aria-label="+50ms"
onClick={() => stepOffset(OFFSET_STEP)}
disabled={annotationOffset >= OFFSET_MAX}
onClick={() => stepOffset(ANNOTATION_OFFSET_STEP)}
disabled={annotationOffset >= ANNOTATION_OFFSET_MAX}
>
<LuPlus className="size-4" />
</Button>
@@ -13,10 +13,11 @@ import { Slider } from "@/components/ui/slider";
import { Trans, useTranslation } from "react-i18next";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { useIsAdmin } from "@/hooks/use-is-admin";
const OFFSET_MIN = -2500;
const OFFSET_MAX = 2500;
const OFFSET_STEP = 50;
import {
ANNOTATION_OFFSET_MAX,
ANNOTATION_OFFSET_MIN,
ANNOTATION_OFFSET_STEP,
} from "@/lib/const";
type AnnotationSettingsPaneProps = {
event: Event;
@@ -49,7 +50,10 @@ export function AnnotationSettingsPane({
(delta: number) => {
setAnnotationOffset((prev) => {
const next = prev + delta;
return Math.max(OFFSET_MIN, Math.min(OFFSET_MAX, next));
return Math.max(
ANNOTATION_OFFSET_MIN,
Math.min(ANNOTATION_OFFSET_MAX, next),
);
});
},
[setAnnotationOffset],
@@ -128,16 +132,16 @@ export function AnnotationSettingsPane({
size="icon"
className="size-8 shrink-0"
aria-label="-50ms"
onClick={() => stepOffset(-OFFSET_STEP)}
disabled={annotationOffset <= OFFSET_MIN}
onClick={() => stepOffset(-ANNOTATION_OFFSET_STEP)}
disabled={annotationOffset <= ANNOTATION_OFFSET_MIN}
>
<LuMinus className="size-4" />
</Button>
<Slider
value={[annotationOffset]}
min={OFFSET_MIN}
max={OFFSET_MAX}
step={OFFSET_STEP}
min={ANNOTATION_OFFSET_MIN}
max={ANNOTATION_OFFSET_MAX}
step={ANNOTATION_OFFSET_STEP}
onValueChange={handleSliderChange}
className="flex-1"
/>
@@ -147,8 +151,8 @@ export function AnnotationSettingsPane({
size="icon"
className="size-8 shrink-0"
aria-label="+50ms"
onClick={() => stepOffset(OFFSET_STEP)}
disabled={annotationOffset >= OFFSET_MAX}
onClick={() => stepOffset(ANNOTATION_OFFSET_STEP)}
disabled={annotationOffset >= ANNOTATION_OFFSET_MAX}
>
<LuPlus className="size-4" />
</Button>
@@ -2,7 +2,7 @@ import { isDesktop, isIOS, isMobile, isSafari } from "react-device-detect";
import { SearchResult } from "@/types/search";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { getIconForLabel } from "@/utils/iconUtil";
import { useApiHost } from "@/api";
import { Button } from "../../ui/button";
@@ -769,9 +769,10 @@ function ObjectDetailsTab({
setShowNavigationButtons,
]);
const is24Hour = use24HourTime(config);
const formattedDate = useFormattedTimestamp(
search?.start_time ?? 0,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestampMonthDayYearHourMinute.24hour", {
ns: "common",
})
@@ -7,6 +7,7 @@ import ActivityIndicator from "@/components/indicators/activity-indicator";
import { TrackingDetailsSequence } from "@/types/timeline";
import { FrigateConfig } from "@/types/frigateConfig";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { use24HourTime } from "@/hooks/use-date-utils";
import { getIconForLabel } from "@/utils/iconUtil";
import { LuCircle, LuFolderX } from "react-icons/lu";
import { cn } from "@/lib/utils";
@@ -428,17 +429,18 @@ export function TrackingDetails({
[annotationOffset, displaySource, timestampToVideoTime],
);
const is24Hour = use24HourTime(config);
const formattedStart = config
? formatUnixTimestampToDateTime(event.start_time ?? 0, {
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t("time.formattedTimestamp.24hour", {
ns: "common",
})
: t("time.formattedTimestamp.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestamp.24hour", {
ns: "common",
})
: t("time.formattedTimestamp.12hour", {
ns: "common",
}),
time_style: "medium",
date_style: "medium",
})
@@ -448,14 +450,13 @@ export function TrackingDetails({
config && event.end_time != null
? formatUnixTimestampToDateTime(event.end_time, {
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t("time.formattedTimestamp.24hour", {
ns: "common",
})
: t("time.formattedTimestamp.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestamp.24hour", {
ns: "common",
})
: t("time.formattedTimestamp.12hour", {
ns: "common",
}),
time_style: "medium",
date_style: "medium",
})
@@ -917,24 +918,25 @@ function LifecycleIconRow({
[effectiveTime, item.timestamp],
);
const is24Hour = use24HourTime(config);
const formattedEventTimestamp = useMemo(
() =>
config
? formatUnixTimestampToDateTime(item.timestamp ?? 0, {
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t("time.formattedTimestampHourMinuteSecond.24hour", {
ns: "common",
})
: t("time.formattedTimestampHourMinuteSecond.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestampHourMinuteSecond.24hour", {
ns: "common",
})
: t("time.formattedTimestampHourMinuteSecond.12hour", {
ns: "common",
}),
time_style: "medium",
date_style: "medium",
})
: "",
[config, item.timestamp, t],
[config, is24Hour, item.timestamp, t],
);
const ratio = useMemo(
+6 -2
View File
@@ -195,6 +195,7 @@ export default function LivePlayer({
}, [preferredLiveMode]);
const [key, setKey] = useState(0);
const prevStreamNameRef = useRef(streamName);
const resetPlayer = () => {
setLiveReady(false);
@@ -202,8 +203,11 @@ export default function LivePlayer({
};
useEffect(() => {
if (streamName) {
resetPlayer();
if (prevStreamNameRef.current !== streamName) {
prevStreamNameRef.current = streamName;
if (streamName) {
resetPlayer();
}
}
}, [streamName]);
+14 -8
View File
@@ -81,6 +81,7 @@ function MSEPlayer({
const wsRef = useRef<WebSocket | null>(null);
const reconnectTIDRef = useRef<number | null>(null);
const intentionalDisconnectRef = useRef<boolean>(false);
const onCloseRef = useRef<(() => void) | null>(null);
const ondataRef = useRef<((data: ArrayBufferLike) => void) | null>(null);
const onmessageRef = useRef<{
[key: string]: (msg: { value: string; type: string }) => void;
@@ -167,6 +168,8 @@ function MSEPlayer({
wsRef.current = new WebSocket(wsURL);
wsRef.current.binaryType = "arraybuffer";
wsRef.current.addEventListener("open", onOpen);
// Capture current onClose identity so removeEventListener can find it later
onCloseRef.current = onClose;
wsRef.current.addEventListener("close", onClose);
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -200,20 +203,23 @@ function MSEPlayer({
intentionalDisconnectRef.current = true;
setWsState(WebSocket.CLOSED);
// Remove event listeners to prevent them firing during close
// Remove event listeners to prevent them firing during close.
// Use onCloseRef to remove the exact function that was attached in onConnect,
// since onClose may have been recreated by React since then.
try {
ws.removeEventListener("open", onOpen);
ws.removeEventListener("close", onClose);
if (onCloseRef.current) {
ws.removeEventListener("close", onCloseRef.current);
onCloseRef.current = null;
}
} catch {
// Ignore errors removing listeners
}
// Only call close() if the socket is OPEN or CLOSING
// For CONNECTING or CLOSED sockets, just let it die
if (
currentReadyState === WebSocket.OPEN ||
currentReadyState === WebSocket.CLOSING
) {
// Close the socket in any non-CLOSED state, including CONNECTING.
// A CONNECTING socket that is not closed will complete its handshake
// and remain open, leaking a browser connection.
if (currentReadyState !== WebSocket.CLOSED) {
try {
ws.close();
} catch {
@@ -12,7 +12,7 @@ import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { isIOS, isMobile, isSafari } from "react-device-detect";
import Chip from "@/components/indicators/Chip";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import useImageLoaded from "@/hooks/use-image-loaded";
import { useSwipeable } from "react-swipeable";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
@@ -174,9 +174,10 @@ export default function PreviewThumbnailPlayer({
// date
const is24Hour = use24HourTime(config);
const formattedDate = useFormattedTimestamp(
review.start_time,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestampMonthDayHourMinute.24hour", { ns: "common" })
: t("time.formattedTimestampMonthDayHourMinute.12hour", { ns: "common" }),
config?.ui?.timezone,
@@ -74,9 +74,11 @@ export default function MotionMaskEditPane({
}
}, [polygons, activePolygonIndex]);
const maskCamera = polygon?.camera || "";
const maskName = polygon?.name || "";
const { send: sendMotionMaskState } = useMotionMaskState(
polygon?.camera || "",
polygon?.name || "",
maskCamera,
maskName,
);
const cameraConfig = useMemo(() => {
@@ -154,7 +156,7 @@ export default function MotionMaskEditPane({
message: t("masksAndZones.form.name.error.mustNotBeEmpty"),
}),
enabled: z.boolean(),
isFinished: z.boolean().refine(() => polygon?.isFinished === true, {
isFinished: z.boolean().refine((val) => val === true, {
message: t("masksAndZones.form.polygonDrawing.error.mustBeFinished"),
}),
});
@@ -170,6 +172,12 @@ export default function MotionMaskEditPane({
},
});
useEffect(() => {
if (polygon?.isFinished !== undefined) {
form.setValue("isFinished", polygon.isFinished, { shouldValidate: true });
}
}, [polygon?.isFinished, form]);
const saveToConfig = useCallback(
async ({
name: maskId,
@@ -250,8 +258,8 @@ export default function MotionMaskEditPane({
},
);
updateConfig();
// Only publish WS state for base config
if (!editingProfile) {
// Only publish WS state for base config when mask has a name
if (!editingProfile && maskName) {
sendMotionMaskState(enabled ? "ON" : "OFF");
}
} else {
@@ -291,6 +299,7 @@ export default function MotionMaskEditPane({
cameraConfig,
t,
sendMotionMaskState,
maskName,
editingProfile,
],
);
@@ -449,7 +458,7 @@ export default function MotionMaskEditPane({
<Button
variant="select"
aria-label={t("button.save", { ns: "common" })}
disabled={isLoading}
disabled={isLoading || !form.formState.isValid}
className="flex flex-1"
type="submit"
>
@@ -80,9 +80,10 @@ export default function ObjectMaskEditPane({
}
}, [polygons, activePolygonIndex]);
const maskName = polygon?.name || "";
const { send: sendObjectMaskState } = useObjectMaskState(
polygon?.camera || "",
polygon?.name || "",
maskName,
);
const cameraConfig = useMemo(() => {
@@ -143,7 +144,7 @@ export default function ObjectMaskEditPane({
}),
enabled: z.boolean(),
objects: z.string(),
isFinished: z.boolean().refine(() => polygon?.isFinished === true, {
isFinished: z.boolean().refine((val) => val === true, {
message: t("masksAndZones.form.polygonDrawing.error.mustBeFinished"),
}),
});
@@ -160,6 +161,12 @@ export default function ObjectMaskEditPane({
},
});
useEffect(() => {
if (polygon?.isFinished !== undefined) {
form.setValue("isFinished", polygon.isFinished, { shouldValidate: true });
}
}, [polygon?.isFinished, form]);
const saveToConfig = useCallback(
async ({
name: maskId,
@@ -256,8 +263,8 @@ export default function ObjectMaskEditPane({
},
);
updateConfig();
// Only publish WS state for base config
if (!editingProfile) {
// Only publish WS state for base config when mask has a name
if (!editingProfile && maskName) {
sendObjectMaskState(enabled ? "ON" : "OFF");
}
} else {
@@ -300,6 +307,7 @@ export default function ObjectMaskEditPane({
cameraConfig,
t,
sendObjectMaskState,
maskName,
editingProfile,
],
);
@@ -454,7 +462,7 @@ export default function ObjectMaskEditPane({
</Button>
<Button
variant="select"
disabled={isLoading}
disabled={isLoading || !form.formState.isValid}
className="flex flex-1"
aria-label={t("button.save", { ns: "common" })}
type="submit"
+89 -21
View File
@@ -30,7 +30,6 @@ import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { reviewQueries } from "@/utils/zoneEdutUtil";
import IconWrapper from "../ui/icon-wrapper";
import { buttonVariants } from "../ui/button";
import { Trans, useTranslation } from "react-i18next";
import ActivityIndicator from "../indicators/activity-indicator";
import { cn } from "@/lib/utils";
@@ -51,6 +50,7 @@ type PolygonItemProps = {
setLoadingPolygonIndex: (index: number | undefined) => void;
editingProfile?: string | null;
allProfileNames?: string[];
onDeleted?: () => void;
};
export default function PolygonItem({
@@ -67,6 +67,7 @@ export default function PolygonItem({
setLoadingPolygonIndex,
editingProfile,
allProfileNames,
onDeleted,
}: PolygonItemProps) {
const { t } = useTranslation("views/settings");
const { data: config, mutate: updateConfig } =
@@ -152,7 +153,19 @@ export default function PolygonItem({
cameraConfig?.review.alerts.required_zones || [],
cameraConfig?.review.detections.required_zones || [],
);
url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}`;
// Also delete from profiles that have overrides for this zone
let profileQueries = "";
if (allProfileNames && cameraConfig) {
for (const profileName of allProfileNames) {
if (
cameraConfig.profiles?.[profileName]?.zones?.[polygon.name] !==
undefined
) {
profileQueries += `&cameras.${polygon.camera}.profiles.${profileName}.zones.${polygon.name}`;
}
}
}
url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}${profileQueries}`;
}
await axios
@@ -169,6 +182,7 @@ export default function PolygonItem({
{ position: "top-center" },
);
updateConfig();
onDeleted?.();
} else {
toast.error(
t("toast.save.error.title", {
@@ -211,11 +225,41 @@ export default function PolygonItem({
},
};
let cameraUpdate: Record<string, unknown>;
if (editingProfile) {
cameraUpdate = { profiles: { [editingProfile]: deleteSection } };
} else {
// Base mode: also delete from profiles that have overrides for this mask
const profileDeletes: Record<string, unknown> = {};
if (allProfileNames && cameraConfig) {
for (const profileName of allProfileNames) {
const profileData = cameraConfig.profiles?.[profileName];
if (!profileData) continue;
const hasMask =
polygon.type === "motion_mask"
? profileData.motion?.mask?.[polygon.name] !== undefined
: polygon.type === "object_mask"
? profileData.objects?.mask?.[polygon.name] !== undefined ||
Object.values(profileData.objects?.filters || {}).some(
(f) => f?.mask?.[polygon.name] !== undefined,
)
: false;
if (hasMask) {
profileDeletes[profileName] = deleteSection;
}
}
}
cameraUpdate =
Object.keys(profileDeletes).length > 0
? { ...deleteSection, profiles: profileDeletes }
: deleteSection;
}
const configUpdate = {
cameras: {
[polygon.camera]: editingProfile
? { profiles: { [editingProfile]: deleteSection } }
: deleteSection,
[polygon.camera]: cameraUpdate,
},
};
@@ -234,6 +278,7 @@ export default function PolygonItem({
{ position: "top-center" },
);
updateConfig();
onDeleted?.();
} else {
toast.error(
t("toast.save.error.title", {
@@ -267,6 +312,8 @@ export default function PolygonItem({
index,
setLoadingPolygonIndex,
editingProfile,
allProfileNames,
onDeleted,
],
);
@@ -425,32 +472,51 @@ export default function PolygonItem({
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("masksAndZones.form.polygonDrawing.delete.title")}
{polygon.polygonSource === "override"
? t("masksAndZones.form.polygonDrawing.revertOverride.title")
: t("masksAndZones.form.polygonDrawing.delete.title")}
</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogDescription>
<Trans
ns="views/settings"
values={{
type: t(
`masksAndZones.form.polygonDrawing.type.${polygon.type}`,
{ ns: "views/settings" },
),
name: polygon.friendly_name ?? polygon.name,
}}
>
masksAndZones.form.polygonDrawing.delete.desc
</Trans>
{polygon.polygonSource === "override" ? (
<Trans
ns="views/settings"
values={{
type: t(
`masksAndZones.form.polygonDrawing.type.${polygon.type}`,
{ ns: "views/settings" },
),
name: polygon.friendly_name ?? polygon.name,
}}
>
masksAndZones.form.polygonDrawing.revertOverride.desc
</Trans>
) : (
<Trans
ns="views/settings"
values={{
type: t(
`masksAndZones.form.polygonDrawing.type.${polygon.type}`,
{ ns: "views/settings" },
),
name: polygon.friendly_name ?? polygon.name,
}}
>
masksAndZones.form.polygonDrawing.delete.desc
</Trans>
)}
</AlertDialogDescription>
<AlertDialogFooter>
<AlertDialogCancel>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className={buttonVariants({ variant: "destructive" })}
className="bg-destructive text-white hover:bg-destructive/90"
onClick={handleDelete}
>
{t("button.delete", { ns: "common" })}
{polygon.polygonSource === "override"
? t("masksAndZones.form.polygonDrawing.revertOverride.title")
: t("button.delete", { ns: "common" })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -563,7 +629,9 @@ export default function PolygonItem({
/>
</TooltipTrigger>
<TooltipContent>
{t("button.delete", { ns: "common" })}
{polygon.polygonSource === "override"
? t("masksAndZones.form.polygonDrawing.revertOverride.title")
: t("button.delete", { ns: "common" })}
</TooltipContent>
</Tooltip>
</div>
+28 -17
View File
@@ -91,10 +91,8 @@ export default function ZoneEditPane({
}
}, [polygons, activePolygonIndex]);
const { send: sendZoneState } = useZoneState(
polygon?.camera || "",
polygon?.name || "",
);
const zoneName = polygon?.name || "";
const { send: sendZoneState } = useZoneState(polygon?.camera || "", zoneName);
const cameraConfig = useMemo(() => {
if (polygon?.camera && config) {
@@ -210,7 +208,7 @@ export default function ZoneEditPane({
})
.optional()
.or(z.literal("")),
isFinished: z.boolean().refine(() => polygon?.isFinished === true, {
isFinished: z.boolean().refine((val) => val === true, {
message: t("masksAndZones.form.polygonDrawing.error.mustBeFinished"),
}),
objects: z.array(z.string()).optional(),
@@ -295,7 +293,7 @@ export default function ZoneEditPane({
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
mode: "onBlur",
mode: "onChange",
defaultValues: {
name: polygon?.name ?? "",
friendly_name: polygon?.friendly_name ?? polygon?.name ?? "",
@@ -303,8 +301,8 @@ export default function ZoneEditPane({
resolvedZoneData?.enabled !== undefined
? resolvedZoneData.enabled
: (polygon?.enabled ?? true),
inertia: resolvedZoneData?.inertia,
loitering_time: resolvedZoneData?.loitering_time,
inertia: resolvedZoneData?.inertia ?? 3,
loitering_time: resolvedZoneData?.loitering_time ?? 0,
isFinished: polygon?.isFinished ?? false,
objects: polygon?.objects ?? [],
speedEstimation: !!(lineA || lineB || lineC || lineD),
@@ -316,18 +314,31 @@ export default function ZoneEditPane({
},
});
const watchSpeedEstimation = form.watch("speedEstimation");
const watchLineA = form.watch("lineA");
const watchLineB = form.watch("lineB");
const watchLineC = form.watch("lineC");
const watchLineD = form.watch("lineD");
const canSave =
form.formState.isValid &&
(!watchSpeedEstimation ||
(!!watchLineA && !!watchLineB && !!watchLineC && !!watchLineD));
useEffect(() => {
if (
form.watch("speedEstimation") &&
polygon &&
polygon.points.length !== 4
) {
if (watchSpeedEstimation && polygon && polygon.points.length !== 4) {
toast.error(
t("masksAndZones.zones.speedThreshold.toast.error.pointLengthError"),
);
form.setValue("speedEstimation", false);
}
}, [polygon, form, t]);
}, [polygon, form, t, watchSpeedEstimation]);
useEffect(() => {
if (polygon?.isFinished !== undefined) {
form.setValue("isFinished", polygon.isFinished, { shouldValidate: true });
}
}, [polygon?.isFinished, form]);
const saveToConfig = useCallback(
async (
@@ -516,8 +527,8 @@ export default function ZoneEditPane({
},
);
updateConfig();
// Only publish WS state for base config (not profiles)
if (!editingProfile) {
// Only publish WS state for base config when zone has a name
if (!editingProfile && zoneName) {
sendZoneState(enabled ? "ON" : "OFF");
}
} else {
@@ -968,7 +979,7 @@ export default function ZoneEditPane({
</Button>
<Button
variant="select"
disabled={isLoading}
disabled={isLoading || !canSave}
className="flex flex-1"
aria-label={t("button.save", { ns: "common" })}
type="submit"
+14 -13
View File
@@ -8,6 +8,7 @@ import {
formatUnixTimestampToDateTime,
getDurationFromTimestamps,
} from "@/utils/dateUtil";
import { use24HourTime } from "@/hooks/use-date-utils";
import { useTranslation } from "react-i18next";
import AnnotationOffsetSlider from "@/components/overlay/detail/AnnotationOffsetSlider";
import { FrigateConfig } from "@/types/frigateConfig";
@@ -398,12 +399,12 @@ function ReviewGroup({
}
}, [isActive, alwaysExpandActive]);
const is24Hour = use24HourTime(config);
const displayTime = formatUnixTimestampToDateTime(start, {
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t("time.formattedTimestampHourMinuteSecond.24hour", { ns: "common" })
: t("time.formattedTimestampHourMinuteSecond.12hour", { ns: "common" }),
date_format: is24Hour
? t("time.formattedTimestampHourMinuteSecond.24hour", { ns: "common" })
: t("time.formattedTimestampHourMinuteSecond.12hour", { ns: "common" }),
time_style: "medium",
date_style: "medium",
});
@@ -524,7 +525,7 @@ function ReviewGroup({
}
}}
>
<span className="truncate hover:underline">
<span className="block truncate hover:underline">
{review.data.metadata.title}
</span>
</GenAISummaryDialog>
@@ -787,17 +788,17 @@ function LifecycleItem({
);
}, [config, item]);
const is24Hour = use24HourTime(config);
const formattedEventTimestamp = config
? formatUnixTimestampToDateTime(item?.timestamp ?? 0, {
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t("time.formattedTimestampHourMinuteSecond.24hour", {
ns: "common",
})
: t("time.formattedTimestampHourMinuteSecond.12hour", {
ns: "common",
}),
date_format: is24Hour
? t("time.formattedTimestampHourMinuteSecond.24hour", {
ns: "common",
})
: t("time.formattedTimestampHourMinuteSecond.12hour", {
ns: "common",
}),
time_style: "medium",
date_style: "medium",
})
@@ -1,4 +1,4 @@
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, useTimeFormat } from "@/hooks/use-date-utils";
import { FrigateConfig } from "@/types/frigateConfig";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
@@ -36,7 +36,7 @@ export function MinimapBounds({
}: MinimapSegmentProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const { t } = useTranslation(["common"]);
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const formatKey = dense
? `time.formattedTimestampHourMinute.${timeFormat}`
@@ -104,7 +104,7 @@ export function Timestamp({
const { t } = useTranslation(["common"]);
const { data: config } = useSWR<FrigateConfig>("config");
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = t(`time.formattedTimestampHourMinute.${timeFormat}`);
const formattedTimestamp = useFormattedTimestamp(
+3
View File
@@ -11,6 +11,9 @@ const alertVariants = cva(
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
warning:
"border-amber-500/50 bg-amber-50 text-amber-800 dark:bg-amber-950/20 dark:text-amber-400 dark:border-amber-500/30 [&>svg]:text-amber-600 dark:[&>svg]:text-amber-400",
info: "border-blue-500/50 bg-blue-50 text-blue-800 dark:bg-blue-950/20 dark:text-blue-400 dark:border-blue-500/30 [&>svg]:text-blue-600 dark:[&>svg]:text-blue-400",
},
},
defaultVariants: {
+27
View File
@@ -0,0 +1,27 @@
import { useMemo } from "react";
import type {
ConditionalMessage,
FieldConditionalMessage,
MessageConditionContext,
} from "@/components/config-form/section-configs/types";
export function useConfigMessages(
messages: ConditionalMessage[] | undefined,
fieldMessages: FieldConditionalMessage[] | undefined,
context: MessageConditionContext | undefined,
): {
activeMessages: ConditionalMessage[];
activeFieldMessages: FieldConditionalMessage[];
} {
const activeMessages = useMemo(() => {
if (!messages || !context) return [];
return messages.filter((msg) => msg.condition(context));
}, [messages, context]);
const activeFieldMessages = useMemo(() => {
if (!fieldMessages || !context) return [];
return fieldMessages.filter((msg) => msg.condition(context));
}, [fieldMessages, context]);
return { activeMessages, activeFieldMessages };
}
+12
View File
@@ -84,6 +84,18 @@ export function use24HourTime(config: FrigateConfig | undefined) {
}, [config, localeUses24HourTime]);
}
/**
* Returns the resolved time format key ("24hour" | "12hour") based on config
* and browser locale. Use this instead of checking config.ui.time_format directly
* to correctly handle the "browser" setting.
*/
export function useTimeFormat(
config: FrigateConfig | undefined,
): "24hour" | "12hour" {
const is24Hour = use24HourTime(config);
return is24Hour ? "24hour" : "12hour";
}
export function useFormattedHour(
config: FrigateConfig | undefined,
time: string, // hour is assumed to be in 24 hour format per the Date object
+2 -1
View File
@@ -4,6 +4,7 @@ import { FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { useDateLocale } from "./use-date-locale";
import { useTimeFormat } from "./use-date-utils";
import { useTranslation } from "react-i18next";
import useUserInteraction from "./use-user-interaction";
@@ -168,7 +169,7 @@ function useDraggableElement({
const { t } = useTranslation(["common"]);
const locale = useDateLocale();
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
const formatKey = `time.${
segmentDuration < 60 && !dense
+13 -2
View File
@@ -483,9 +483,20 @@ function generateUiSchema(
const schemaObj = schema as Record<string, unknown>;
// Set field ordering
// Set field ordering — supports dot notation (e.g. "genai.enabled")
if (fieldOrder && fieldOrder.length > 0) {
uiSchema["ui:order"] = [...fieldOrder, "*"];
const depth = currentPath.length;
const localOrder = fieldOrder
.map((f) => f.split("."))
.filter((segments) => {
if (segments.length !== depth + 1) return false;
return currentPath.every((p, i) => segments[i] === p);
})
.map((segments) => segments[depth]);
if (localOrder.length > 0) {
uiSchema["ui:order"] = [...localOrder, "*"];
}
}
if (!isSchemaObject(schemaObj.properties)) {
+4
View File
@@ -1,6 +1,10 @@
/** ONNX embedding models that require local model downloads. GenAI providers are not in this list. */
export const JINA_EMBEDDING_MODELS = ["jinav1", "jinav2"] as const;
export const ANNOTATION_OFFSET_MIN = -10000;
export const ANNOTATION_OFFSET_MAX = 5000;
export const ANNOTATION_OFFSET_STEP = 50;
export const supportedLanguageKeys = [
"en",
"es",
+97 -81
View File
@@ -1,12 +1,13 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FaArrowUpLong } from "react-icons/fa6";
import { LuCircleAlert } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { useState, useCallback } from "react";
import { useState, useCallback, useRef, useEffect } from "react";
import axios from "axios";
import { ChatEventThumbnailsRow } from "@/components/chat/ChatEventThumbnailsRow";
import { MessageBubble } from "@/components/chat/ChatMessage";
import { ToolCallBubble } from "@/components/chat/ToolCallBubble";
import { ToolCallsGroup } from "@/components/chat/ToolCallsGroup";
import { ChatStartingState } from "@/components/chat/ChatStartingState";
import type { ChatMessage } from "@/types/chat";
import {
@@ -20,6 +21,21 @@ export default function ChatPage() {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
document.title = t("documentTitle");
}, [t]);
// Auto-scroll to bottom when messages change, but only if near bottom
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const isNearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 150;
if (isNearBottom) {
el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
}
}, [messages]);
const submitConversation = useCallback(
async (messagesToSend: ChatMessage[]) => {
@@ -77,7 +93,7 @@ export default function ChatPage() {
);
return (
<div className="flex size-full justify-center p-2">
<div className="flex size-full justify-center p-2 md:p-4">
<div className="flex size-full flex-col xl:w-[50%] 3xl:w-[35%]">
{messages.length === 0 ? (
<ChatStartingState
@@ -87,83 +103,83 @@ export default function ChatPage() {
}}
/>
) : (
<div className="scrollbar-container flex min-h-0 w-full flex-1 flex-col gap-2 overflow-y-auto">
{messages.map((msg, i) => {
const isStreamingPlaceholder =
i === messages.length - 1 &&
msg.role === "assistant" &&
isLoading &&
!msg.content?.trim() &&
!(msg.toolCalls && msg.toolCalls.length > 0);
if (isStreamingPlaceholder) {
return <div key={i} />;
}
return (
<div key={i} className="flex flex-col gap-2">
{msg.role === "assistant" && msg.toolCalls && (
<>
{msg.toolCalls.map((tc, tcIdx) => (
<div key={tcIdx} className="flex flex-col gap-2">
<ToolCallBubble
name={tc.name}
arguments={tc.arguments}
side="left"
/>
{tc.response && (
<ToolCallBubble
name={tc.name}
response={tc.response}
side="right"
/>
)}
</div>
))}
</>
)}
<MessageBubble
role={msg.role}
content={msg.content}
messageIndex={i}
onEditSubmit={
msg.role === "user" ? handleEditSubmit : undefined
}
isComplete={
msg.role === "user" ||
!isLoading ||
i < messages.length - 1
}
/>
{msg.role === "assistant" &&
(() => {
const isComplete = !isLoading || i < messages.length - 1;
if (!isComplete) return null;
const events = getEventIdsFromSearchObjectsToolCalls(
msg.toolCalls,
);
return <ChatEventThumbnailsRow events={events} />;
})()}
</div>
);
})}
{(() => {
const lastMsg = messages[messages.length - 1];
const showProcessing =
isLoading &&
lastMsg?.role === "assistant" &&
!lastMsg.content?.trim() &&
!(lastMsg.toolCalls && lastMsg.toolCalls.length > 0);
return showProcessing ? (
<div className="self-start rounded-lg bg-muted px-3 py-2 text-muted-foreground">
{t("processing")}
</div>
) : null;
})()}
{error && (
<p className="self-start text-sm text-destructive" role="alert">
{error}
</p>
)}
</div>
<>
<div
ref={scrollRef}
className="scrollbar-container flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto"
>
{messages.map((msg, i) => {
const isLastAssistant =
i === messages.length - 1 && msg.role === "assistant";
const isComplete =
msg.role === "user" || !isLoading || !isLastAssistant;
const hasToolCalls = msg.toolCalls && msg.toolCalls.length > 0;
const hasContent = !!msg.content?.trim();
const showProcessing =
isLastAssistant && isLoading && !hasContent;
// Hide empty placeholder only when there are no tool calls yet
if (
isLastAssistant &&
isLoading &&
!hasContent &&
!hasToolCalls
)
return (
<div
key={i}
className="flex items-center gap-2 self-start rounded-2xl bg-muted px-5 py-4"
>
<span className="size-2.5 animate-bounce rounded-full bg-muted-foreground/60 [animation-delay:-0.32s]" />
<span className="size-2.5 animate-bounce rounded-full bg-muted-foreground/60 [animation-delay:-0.16s]" />
<span className="size-2.5 animate-bounce rounded-full bg-muted-foreground/60" />
</div>
);
return (
<div key={i} className="flex flex-col gap-2">
{msg.role === "assistant" && hasToolCalls && (
<ToolCallsGroup toolCalls={msg.toolCalls!} />
)}
{showProcessing ? (
<div className="flex items-center gap-2 self-start rounded-2xl bg-muted px-5 py-4">
<span className="size-2 animate-bounce rounded-full bg-muted-foreground/60 [animation-delay:-0.3s]" />
<span className="size-2 animate-bounce rounded-full bg-muted-foreground/60 [animation-delay:-0.15s]" />
<span className="size-2 animate-bounce rounded-full bg-muted-foreground/60" />
</div>
) : (
<MessageBubble
role={msg.role}
content={msg.content}
messageIndex={i}
onEditSubmit={
msg.role === "user" ? handleEditSubmit : undefined
}
isComplete={isComplete}
/>
)}
{msg.role === "assistant" &&
isComplete &&
(() => {
const events = getEventIdsFromSearchObjectsToolCalls(
msg.toolCalls,
);
return <ChatEventThumbnailsRow events={events} />;
})()}
</div>
);
})}
{error && (
<p
className="flex items-center gap-1.5 self-start text-sm text-destructive"
role="alert"
>
<LuCircleAlert className="size-3.5 shrink-0" />
{error}
</p>
)}
</div>
</>
)}
{messages.length > 0 && (
<ChatEntry
@@ -202,7 +218,7 @@ function ChatEntry({
};
return (
<div className="flex w-full flex-col items-center justify-center rounded-xl bg-secondary p-2">
<div className="mt-2 flex w-full flex-col items-center justify-center rounded-xl bg-secondary p-3">
<div className="flex w-full flex-row items-center gap-2">
<Input
className="w-full flex-1 border-transparent bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent"
+21 -4
View File
@@ -724,6 +724,7 @@ export default function Settings() {
// Save All state
const [isSavingAll, setIsSavingAll] = useState(false);
const [isAnySectionSaving, setIsAnySectionSaving] = useState(false);
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
const { send: sendRestart } = useRestart();
const { data: fullSchema } = useSWR<RJSFSchema>("config/schema.json");
@@ -1299,6 +1300,10 @@ export default function Settings() {
[],
);
const handleSectionSavingChange = useCallback((saving: boolean) => {
setIsAnySectionSaving(saving);
}, []);
// The active profile being edited for the selected camera
const activeEditingProfile = selectedCamera
? (editingProfile[selectedCamera] ?? null)
@@ -1508,7 +1513,7 @@ export default function Settings() {
onClick={handleUndoAll}
variant="outline"
size="sm"
disabled={isSavingAll}
disabled={isSavingAll || isAnySectionSaving}
className="flex w-full items-center justify-center gap-2"
>
{t("button.undoAll", {
@@ -1520,7 +1525,11 @@ export default function Settings() {
onClick={handleSaveAll}
variant="select"
size="sm"
disabled={isSavingAll || hasPendingValidationErrors}
disabled={
isSavingAll ||
isAnySectionSaving ||
hasPendingValidationErrors
}
className="flex w-full items-center justify-center gap-2"
>
{isSavingAll ? (
@@ -1606,6 +1615,8 @@ export default function Settings() {
}
profilesUIEnabled={profilesUIEnabled}
setProfilesUIEnabled={setProfilesUIEnabled}
isSavingAll={isSavingAll}
onSectionSavingChange={handleSectionSavingChange}
/>
);
})()}
@@ -1674,7 +1685,7 @@ export default function Settings() {
onClick={handleUndoAll}
variant="outline"
size="sm"
disabled={isSavingAll}
disabled={isSavingAll || isAnySectionSaving}
className="flex items-center justify-center gap-2"
>
{t("button.undoAll", {
@@ -1686,7 +1697,11 @@ export default function Settings() {
variant="select"
size="sm"
onClick={handleSaveAll}
disabled={isSavingAll || hasPendingValidationErrors}
disabled={
isSavingAll ||
isAnySectionSaving ||
hasPendingValidationErrors
}
className="flex items-center justify-center gap-2"
>
{isSavingAll ? (
@@ -1843,6 +1858,8 @@ export default function Settings() {
onDeleteProfileSection={handleDeleteProfileForCurrentSection}
profilesUIEnabled={profilesUIEnabled}
setProfilesUIEnabled={setProfilesUIEnabled}
isSavingAll={isSavingAll}
onSectionSavingChange={handleSectionSavingChange}
/>
);
})()}
+41 -18
View File
@@ -1,6 +1,6 @@
import useSWR from "swr";
import { FrigateStats } from "@/types/stats";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import TimeAgo from "@/components/dynamic/TimeAgo";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { isDesktop, isMobile } from "react-device-detect";
@@ -49,7 +49,17 @@ function System() {
setPage,
100,
);
const [lastUpdated, setLastUpdated] = useState<number>(Date.now() / 1000);
const [lastUpdated, setLastUpdated] = useState<number>(
Math.floor(Date.now() / 1000),
);
// Track which tabs have been visited so we can keep them mounted after first visit.
// Using a ref updated during render avoids extra render cycles from state/effects.
const visitedTabsRef = useRef(new Set<string>());
if (page) {
visitedTabsRef.current.add(page);
}
const visitedTabs = visitedTabsRef.current;
useEffect(() => {
if (pageToggle) {
@@ -116,24 +126,37 @@ function System() {
</div>
)}
</div>
{page == "general" && (
<GeneralMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
/>
{visitedTabs.has("general") && (
<div className={page == "general" ? "contents" : "hidden"}>
<GeneralMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
isActive={page == "general"}
/>
</div>
)}
{page == "enrichments" && (
<EnrichmentMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
/>
{metrics.includes("enrichments") && visitedTabs.has("enrichments") && (
<div className={page == "enrichments" ? "contents" : "hidden"}>
<EnrichmentMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
isActive={page == "enrichments"}
/>
</div>
)}
{page == "storage" && <StorageMetrics setLastUpdated={setLastUpdated} />}
{page == "cameras" && (
<CameraMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
/>
{visitedTabs.has("storage") && (
<div className={page == "storage" ? "contents" : "hidden"}>
<StorageMetrics setLastUpdated={setLastUpdated} />
</div>
)}
{visitedTabs.has("cameras") && (
<div className={page == "cameras" ? "contents" : "hidden"}>
<CameraMetrics
lastUpdated={lastUpdated}
setLastUpdated={setLastUpdated}
isActive={page == "cameras"}
/>
</div>
)}
</div>
);
+1
View File
@@ -14,6 +14,7 @@ export type ProfileInfo = {
export type ProfilesApiResponse = {
profiles: ProfileInfo[];
active_profile: string | null;
last_activated: Record<string, number>;
};
export type ProfileState = {
+6
View File
@@ -7,8 +7,14 @@ type PtzFeature =
| "pt-r-fov"
| "focus";
export type OnvifProfile = {
name: string;
token: string;
};
export type CameraPtzInfo = {
name: string;
features: PtzFeature[];
presets: string[];
profiles: OnvifProfile[];
};
+9
View File
@@ -28,6 +28,9 @@ export type CameraStats = {
expected_fps: number;
reconnects_last_hour: number;
stalls_last_hour: number;
ffmpeg_cpu?: string;
capture_cpu?: string;
detect_cpu?: string;
};
export type CpuStats = {
@@ -42,6 +45,8 @@ export type DetectorStats = {
inference_speed: number;
pid: number;
temperature?: number;
cpu?: string;
mem?: string;
};
export type EmbeddingsStats = {
@@ -53,6 +58,8 @@ export type EmbeddingsStats = {
export type ExtraProcessStats = {
pid: number;
cpu?: string;
mem?: string;
};
export type GpuStats = {
@@ -60,8 +67,10 @@ export type GpuStats = {
mem: string;
enc?: string;
dec?: string;
compute?: string;
pstate?: string;
temp?: number;
clients?: { [pid: string]: string };
};
export type NpuStats = {
+5 -2
View File
@@ -649,8 +649,11 @@ const mergeSectionConfig = (
return srcValue ?? objValue;
}
if (key === "uiSchema" && srcValue !== undefined) {
return srcValue;
if (key === "uiSchema") {
if (objValue && srcValue) {
return merge({}, objValue, srcValue);
}
return srcValue ?? objValue;
}
return undefined;
@@ -601,7 +601,9 @@ function LibrarySelector({
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
const [renameClass, setRenameClass] = useState<string | null>(null);
const pageTitle = useMemo(() => {
if (pageToggle != "train") {
if (pageToggle == "none") {
return t("details.none");
} else if (pageToggle != "train") {
return pageToggle;
}
+3 -2
View File
@@ -19,7 +19,7 @@ import { useResizeObserver } from "@/hooks/resize-observer";
import { Skeleton } from "@/components/ui/skeleton";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import TimeAgo from "@/components/dynamic/TimeAgo";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { FrigateConfig } from "@/types/frigateConfig";
const MOTION_HEATMAP_GRID_SIZE = 16;
@@ -165,9 +165,10 @@ function MotionPreviewClip({
const [fallbackFrameIndex, setFallbackFrameIndex] = useState(0);
const [fallbackFramesReady, setFallbackFramesReady] = useState(false);
const is24Hour = use24HourTime(config);
const formattedDate = useFormattedTimestamp(
range.start_time,
config?.ui.time_format == "24hour"
is24Hour
? t("time.formattedTimestampMonthDayHourMinute.24hour", {
ns: "common",
})
+141 -31
View File
@@ -122,6 +122,11 @@ import {
SnapshotResult,
} from "@/utils/snapshotUtil";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Stage, Layer, Rect } from "react-konva";
import type { KonvaEventObject } from "konva/lib/Node";
/** Pixel threshold to distinguish drag from click. */
const DRAG_MIN_PX = 15;
type LiveCameraViewProps = {
config?: FrigateConfig;
@@ -213,45 +218,112 @@ export default function LiveCameraView({
};
}, [audioTranscriptionState, sendTranscription]);
// click overlay for ptzs
// click-to-move / drag-to-zoom overlay for PTZ cameras
const [clickOverlay, setClickOverlay] = useState(false);
const clickOverlayRef = useRef<HTMLDivElement>(null);
const { send: sendPtz } = usePtzCommand(camera.name);
const handleOverlayClick = useCallback(
(
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>,
) => {
if (!clickOverlay) {
return;
}
// drag rectangle state in stage-local coordinates
const [ptzRect, setPtzRect] = useState<{
x: number;
y: number;
width: number;
height: number;
} | null>(null);
const [isPtzDrawing, setIsPtzDrawing] = useState(false);
// raw origin to determine drag direction (not min/max corrected)
const ptzOriginRef = useRef<{ x: number; y: number } | null>(null);
let clientX;
let clientY;
if ("TouchEvent" in window && e.nativeEvent instanceof TouchEvent) {
clientX = e.nativeEvent.touches[0].clientX;
clientY = e.nativeEvent.touches[0].clientY;
} else if (e.nativeEvent instanceof MouseEvent) {
clientX = e.nativeEvent.clientX;
clientY = e.nativeEvent.clientY;
}
const [overlaySize] = useResizeObserver(clickOverlayRef);
if (clickOverlayRef.current && clientX && clientY) {
const rect = clickOverlayRef.current.getBoundingClientRect();
const normalizedX = (clientX - rect.left) / rect.width;
const normalizedY = (clientY - rect.top) / rect.height;
const pan = (normalizedX - 0.5) * 2;
const tilt = (0.5 - normalizedY) * 2;
sendPtz(`move_relative_${pan}_${tilt}`);
const onPtzStageDown = useCallback(
(e: KonvaEventObject<MouseEvent> | KonvaEventObject<TouchEvent>) => {
const pos = e.target.getStage()?.getPointerPosition();
if (pos) {
setIsPtzDrawing(true);
ptzOriginRef.current = { x: pos.x, y: pos.y };
setPtzRect({ x: pos.x, y: pos.y, width: 0, height: 0 });
}
},
[clickOverlayRef, clickOverlay, sendPtz],
[],
);
const onPtzStageMove = useCallback(
(e: KonvaEventObject<MouseEvent> | KonvaEventObject<TouchEvent>) => {
if (!isPtzDrawing || !ptzRect) return;
const pos = e.target.getStage()?.getPointerPosition();
if (pos) {
setPtzRect({
...ptzRect,
width: pos.x - ptzRect.x,
height: pos.y - ptzRect.y,
});
}
},
[isPtzDrawing, ptzRect],
);
const onPtzStageUp = useCallback(() => {
setIsPtzDrawing(false);
if (!ptzRect || !ptzOriginRef.current || overlaySize.width === 0) {
setPtzRect(null);
ptzOriginRef.current = null;
return;
}
const endX = ptzRect.x + ptzRect.width;
const endY = ptzRect.y + ptzRect.height;
const distX = Math.abs(ptzRect.width);
const distY = Math.abs(ptzRect.height);
if (distX < DRAG_MIN_PX && distY < DRAG_MIN_PX) {
// click — pan/tilt to point without zoom
const normX = endX / overlaySize.width;
const normY = endY / overlaySize.height;
const pan = (normX - 0.5) * 2;
const tilt = (0.5 - normY) * 2;
sendPtz(`move_relative_${pan}_${tilt}`);
} else {
// drag — pan/tilt to box center, zoom based on box size
const origin = ptzOriginRef.current;
const n0x = Math.min(origin.x, endX) / overlaySize.width;
const n0y = Math.min(origin.y, endY) / overlaySize.height;
const n1x = Math.max(origin.x, endX) / overlaySize.width;
const n1y = Math.max(origin.y, endY) / overlaySize.height;
let boxW = n1x - n0x;
let boxH = n1y - n0y;
// correct box to match camera aspect ratio so zoom is uniform
const frameAR = overlaySize.width / overlaySize.height;
const boxAR = boxW / boxH;
if (boxAR > frameAR) {
boxH = boxW / frameAR;
} else {
boxW = boxH * frameAR;
}
const centerX = (n0x + n1x) / 2;
const centerY = (n0y + n1y) / 2;
const pan = (centerX - 0.5) * 2;
const tilt = (0.5 - centerY) * 2;
// zoom magnitude from box size (small box = more zoom)
let zoom = Math.max(0.01, Math.min(1, Math.max(boxW, boxH)));
// drag direction: top-left → bottom-right = zoom in, reverse = zoom out
const zoomIn = endX > origin.x && endY > origin.y;
if (!zoomIn) zoom = -zoom;
sendPtz(`move_relative_${pan}_${tilt}_${zoom}`);
}
setPtzRect(null);
ptzOriginRef.current = null;
}, [ptzRect, overlaySize, sendPtz]);
// pip state
useEffect(() => {
@@ -440,7 +512,8 @@ export default function LiveCameraView({
<TransformWrapper
minScale={1.0}
wheel={{ smoothStep: 0.005 }}
disabled={debug}
disabled={debug || clickOverlay}
panning={{ disabled: clickOverlay }}
>
<Toaster position="top-center" closeButton={true} />
<div
@@ -634,13 +707,50 @@ export default function LiveCameraView({
}}
>
<div
className={`flex flex-col items-center justify-center ${growClassName}`}
className={cn(
"flex flex-col items-center justify-center",
growClassName,
)}
ref={clickOverlayRef}
onClick={handleOverlayClick}
style={{
aspectRatio: constrainedAspectRatio,
}}
>
{clickOverlay && overlaySize.width > 0 && (
<div
className="absolute z-40 cursor-crosshair"
style={{
width: overlaySize.width,
height: overlaySize.height,
}}
>
<Stage
width={overlaySize.width}
height={overlaySize.height}
onMouseDown={onPtzStageDown}
onMouseMove={onPtzStageMove}
onMouseUp={onPtzStageUp}
onTouchStart={onPtzStageDown}
onTouchMove={onPtzStageMove}
onTouchEnd={onPtzStageUp}
>
<Layer>
{ptzRect && (
<Rect
x={ptzRect.x}
y={ptzRect.y}
width={ptzRect.width}
height={ptzRect.height}
stroke="white"
strokeWidth={2}
dash={[6, 4]}
opacity={0.8}
/>
)}
</Layer>
</Stage>
</div>
)}
<LivePlayer
key={camera.name}
className={`${fullscreen ? "*:rounded-none" : ""}`}
@@ -43,8 +43,9 @@ import { TimezoneAwareCalendar } from "@/components/overlay/ReviewActivityCalend
import { useApiHost } from "@/api";
import { useResizeObserver } from "@/hooks/resize-observer";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import { getUTCOffset } from "@/utils/dateUtil";
import useSWR from "swr";
import { cn } from "@/lib/utils";
import MotionSearchROICanvas from "./MotionSearchROICanvas";
import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
@@ -452,7 +453,6 @@ export default function MotionSearchDialog({
range={searchRange}
setRange={setSearchRange}
defaultRange={defaultRange}
timeFormat={config.ui?.time_format}
timezone={timezone}
/>
@@ -476,7 +476,6 @@ type SearchRangeSelectorProps = {
range?: TimeRange;
setRange: React.Dispatch<React.SetStateAction<TimeRange | undefined>>;
defaultRange: TimeRange;
timeFormat?: "browser" | "12hour" | "24hour";
timezone?: string;
};
@@ -484,7 +483,6 @@ function SearchRangeSelector({
range,
setRange,
defaultRange,
timeFormat,
timezone,
}: SearchRangeSelectorProps) {
const { t } = useTranslation(["views/motionSearch", "common"]);
@@ -527,15 +525,18 @@ function SearchRangeSelector({
return time;
}, [range, defaultRange, timezoneOffset, localTimeOffset]);
const { data: config } = useSWR<FrigateConfig>("config");
const is24Hour = use24HourTime(config);
const formattedStart = useFormattedTimestamp(
startTime,
timeFormat === "24hour"
is24Hour
? t("time.formattedTimestamp.24hour", { ns: "common" })
: t("time.formattedTimestamp.12hour", { ns: "common" }),
);
const formattedEnd = useFormattedTimestamp(
endTime,
timeFormat === "24hour"
is24Hour
? t("time.formattedTimestamp.24hour", { ns: "common" })
: t("time.formattedTimestamp.12hour", { ns: "common" }),
);
@@ -51,7 +51,7 @@ import {
RecordingSegment,
} from "@/types/record";
import { VideoResolutionType } from "@/types/live";
import { useFormattedTimestamp } from "@/hooks/use-date-utils";
import { useFormattedTimestamp, use24HourTime } from "@/hooks/use-date-utils";
import MotionSearchROICanvas from "./MotionSearchROICanvas";
import MotionSearchDialog from "./MotionSearchDialog";
import { IoMdArrowRoundBack } from "react-icons/io";
@@ -94,12 +94,13 @@ export default function MotionSearchView({
]);
const navigate = useNavigate();
const is24Hour = use24HourTime(config);
const resultTimestampFormat = useMemo(
() =>
config.ui?.time_format === "24hour"
is24Hour
? t("time.formattedTimestamp.24hour", { ns: "common" })
: t("time.formattedTimestamp.12hour", { ns: "common" }),
[config.ui?.time_format, t],
[is24Hour, t],
);
// Refs
+4 -4
View File
@@ -31,6 +31,7 @@ import Chip from "@/components/indicators/Chip";
import { TooltipPortal } from "@radix-ui/react-tooltip";
import SearchActionGroup from "@/components/filter/SearchActionGroup";
import { Trans, useTranslation } from "react-i18next";
import { use24HourTime } from "@/hooks/use-date-utils";
import { useNavigate } from "react-router-dom";
import { useAllowedCameras } from "@/hooks/use-allowed-cameras";
@@ -77,6 +78,7 @@ export default function SearchView({
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
const is24Hour = use24HourTime(config);
const navigate = useNavigate();
const { data: exploreEvents } = useSWR<SearchResult[]>(
@@ -191,10 +193,7 @@ export default function SearchView({
sub_labels: allSubLabels,
...(hasCustomClassificationModels && { attributes: allAttributes }),
search_type: ["thumbnail", "description"] as SearchSource[],
time_range:
config?.ui.time_format == "24hour"
? ["00:00-23:59"]
: ["12:00AM-11:59PM"],
time_range: is24Hour ? ["00:00-23:59"] : ["12:00AM-11:59PM"],
before: [formatDateToLocaleString()],
after: [formatDateToLocaleString(-5)],
min_score: ["50"],
@@ -209,6 +208,7 @@ export default function SearchView({
}),
[
config,
is24Hour,
allLabels,
allZones,
allSubLabels,
+64 -36
View File
@@ -201,6 +201,16 @@ export default function MasksAndZonesView({
setUnsavedChanges(false);
}, [editingPolygons, setUnsavedChanges]);
const handlePolygonDeleted = useCallback(() => {
// Temporarily clear the edit pane guard so the useEffect that
// rebuilds editingPolygons from config will run when the fresh
// config arrives via updateConfig(). This handles all cases:
// base deletes, profile override deletes (which revert to base),
// and profile-only deletes.
setEditPane(undefined);
setActivePolygonIndex(undefined);
}, [setEditPane, setActivePolygonIndex]);
useEffect(() => {
if (isLoading) {
return;
@@ -806,20 +816,25 @@ export default function MasksAndZonesView({
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.zones.add")}
onClick={() => {
setEditPane("zone");
handleNewPolygon("zone");
}}
>
<LuPlus />
</Button>
<span className="inline-flex">
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.zones.add")}
disabled={!!currentEditingProfile}
onClick={() => {
setEditPane("zone");
handleNewPolygon("zone");
}}
>
<LuPlus />
</Button>
</span>
</TooltipTrigger>
<TooltipContent>
{t("masksAndZones.zones.add")}
{currentEditingProfile
? t("masksAndZones.addDisabledProfile")
: t("masksAndZones.zones.add")}
</TooltipContent>
</Tooltip>
</div>
@@ -843,6 +858,7 @@ export default function MasksAndZonesView({
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
onDeleted={handlePolygonDeleted}
/>
))}
</div>
@@ -880,20 +896,25 @@ export default function MasksAndZonesView({
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.motionMasks.add")}
onClick={() => {
setEditPane("motion_mask");
handleNewPolygon("motion_mask");
}}
>
<LuPlus />
</Button>
<span className="inline-flex">
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.motionMasks.add")}
disabled={!!currentEditingProfile}
onClick={() => {
setEditPane("motion_mask");
handleNewPolygon("motion_mask");
}}
>
<LuPlus />
</Button>
</span>
</TooltipTrigger>
<TooltipContent>
{t("masksAndZones.motionMasks.add")}
{currentEditingProfile
? t("masksAndZones.addDisabledProfile")
: t("masksAndZones.motionMasks.add")}
</TooltipContent>
</Tooltip>
</div>
@@ -919,6 +940,7 @@ export default function MasksAndZonesView({
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
onDeleted={handlePolygonDeleted}
/>
))}
</div>
@@ -956,20 +978,25 @@ export default function MasksAndZonesView({
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.objectMasks.add")}
onClick={() => {
setEditPane("object_mask");
handleNewPolygon("object_mask");
}}
>
<LuPlus />
</Button>
<span className="inline-flex">
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
aria-label={t("masksAndZones.objectMasks.add")}
disabled={!!currentEditingProfile}
onClick={() => {
setEditPane("object_mask");
handleNewPolygon("object_mask");
}}
>
<LuPlus />
</Button>
</span>
</TooltipTrigger>
<TooltipContent>
{t("masksAndZones.objectMasks.add")}
{currentEditingProfile
? t("masksAndZones.addDisabledProfile")
: t("masksAndZones.objectMasks.add")}
</TooltipContent>
</Tooltip>
</div>
@@ -995,6 +1022,7 @@ export default function MasksAndZonesView({
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
onDeleted={handlePolygonDeleted}
/>
))}
</div>
+14
View File
@@ -542,6 +542,20 @@ export default function ProfilesView({
<CollapsibleContent>
{cameras.length > 0 ? (
<div className="mx-4 mb-3 ml-11 border-l border-border/50 pl-4">
<div className="flex items-baseline gap-3 border-b border-border/30 pb-1.5">
<span className="min-w-[120px] shrink-0 text-xs font-semibold uppercase text-muted-foreground">
{t("profiles.columnCamera", {
ns: "views/settings",
defaultValue: "Camera",
})}
</span>
<span className="text-xs font-semibold uppercase text-muted-foreground">
{t("profiles.columnOverrides", {
ns: "views/settings",
defaultValue: "Profile Overrides",
})}
</span>
</div>
{cameras.map((camera) => {
const sections = cameraData[camera];
return (
+12 -3
View File
@@ -39,6 +39,10 @@ export type SettingsPageProps = {
onDeleteProfileSection?: (profileName: string) => void;
profilesUIEnabled?: boolean;
setProfilesUIEnabled?: React.Dispatch<React.SetStateAction<boolean>>;
/** Whether a SaveAll operation is in progress */
isSavingAll?: boolean;
/** Callback when a section's saving state changes */
onSectionSavingChange?: (isSaving: boolean) => void;
};
export type SectionStatus = {
@@ -73,6 +77,8 @@ export function SingleSectionPage({
onPendingDataChange,
profileState,
onDeleteProfileSection,
isSavingAll,
onSectionSavingChange,
}: SingleSectionPageProps) {
const sectionNamespace =
level === "camera" ? "config/cameras" : "config/global";
@@ -95,9 +101,10 @@ export function SingleSectionPage({
? getLocaleDocUrl(resolvedSectionConfig.sectionDocs)
: undefined;
const currentEditingProfile = selectedCamera
? (profileState?.editingProfile[selectedCamera] ?? null)
: null;
const currentEditingProfile =
level === "camera" && selectedCamera
? (profileState?.editingProfile[selectedCamera] ?? null)
: null;
const profileColor = useMemo(
() =>
@@ -273,6 +280,8 @@ export function SingleSectionPage({
onDeleteProfileSection={
currentEditingProfile ? handleDeleteProfileSection : undefined
}
isSavingAll={isSavingAll}
onSavingChange={onSectionSavingChange}
/>
</div>
);
+28 -28
View File
@@ -39,6 +39,7 @@ import { Trigger, TriggerAction, TriggerType } from "@/types/trigger";
import { useSearchEffect } from "@/hooks/use-overlay-state";
import { cn } from "@/lib/utils";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import { use24HourTime } from "@/hooks/use-date-utils";
import { Link } from "react-router-dom";
import { useTriggers } from "@/api/ws";
import { useCameraFriendlyName } from "@/hooks/use-camera-friendly-name";
@@ -89,6 +90,7 @@ export default function TriggerView({
const { t } = useTranslation("views/settings");
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");
const is24Hour = use24HourTime(config);
const { data: trigger_status, mutate } = useSWR(
config?.cameras[selectedCamera]?.semantic_search?.triggers &&
Object.keys(config.cameras[selectedCamera].semantic_search.triggers)
@@ -581,20 +583,19 @@ export default function TriggerView({
?.last_triggered,
{
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t(
"time.formattedTimestamp2.24hour",
{
ns: "common",
},
)
: t(
"time.formattedTimestamp2.12hour",
{
ns: "common",
},
),
date_format: is24Hour
? t(
"time.formattedTimestamp2.24hour",
{
ns: "common",
},
)
: t(
"time.formattedTimestamp2.12hour",
{
ns: "common",
},
),
time_style: "medium",
date_style: "medium",
},
@@ -742,20 +743,19 @@ export default function TriggerView({
?.last_triggered,
{
timezone: config.ui.timezone,
date_format:
config.ui.time_format == "24hour"
? t(
"time.formattedTimestamp2.24hour",
{
ns: "common",
},
)
: t(
"time.formattedTimestamp2.12hour",
{
ns: "common",
},
),
date_format: is24Hour
? t(
"time.formattedTimestamp2.24hour",
{
ns: "common",
},
)
: t(
"time.formattedTimestamp2.12hour",
{
ns: "common",
},
),
time_style: "medium",
date_style: "medium",
},
+43 -13
View File
@@ -5,7 +5,14 @@ import { ConnectionQualityIndicator } from "@/components/camera/ConnectionQualit
import { Skeleton } from "@/components/ui/skeleton";
import { FrigateConfig } from "@/types/frigateConfig";
import { FrigateStats } from "@/types/stats";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Fragment,
startTransition,
useCallback,
useEffect,
useMemo,
useState,
} from "react";
import { MdInfo } from "react-icons/md";
import {
Tooltip,
@@ -20,10 +27,12 @@ import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
type CameraMetricsProps = {
lastUpdated: number;
setLastUpdated: (last: number) => void;
isActive: boolean;
};
export default function CameraMetrics({
lastUpdated,
setLastUpdated,
isActive,
}: CameraMetricsProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const { t } = useTranslation(["views/system"]);
@@ -39,11 +48,11 @@ export default function CameraMetrics({
// stats
const { data: initialStats } = useSWR<FrigateStats[]>(
const { data: initialStats, mutate: refreshStats } = useSWR<FrigateStats[]>(
[
"stats/history",
{
keys: "cpu_usages,cameras,camera_fps,detection_fps,skipped_fps,service",
keys: "cameras.camera_fps,cameras.detection_fps,cameras.skipped_fps,cameras.ffmpeg_cpu,cameras.capture_cpu,cameras.detect_cpu,cameras.connection_quality,cameras.expected_fps,cameras.reconnects_last_hour,cameras.stalls_last_hour,camera_fps,detection_fps,skipped_fps,service.last_updated",
},
],
{
@@ -60,19 +69,38 @@ export default function CameraMetrics({
}
if (statsHistory.length == 0) {
setStatsHistory(initialStats);
startTransition(() => setStatsHistory(initialStats));
return;
}
if (!updatedStats) {
if (!isActive || !updatedStats) {
return;
}
if (updatedStats.service.last_updated > lastUpdated) {
setStatsHistory([...statsHistory.slice(1), updatedStats]);
setLastUpdated(Date.now() / 1000);
setLastUpdated(updatedStats.service.last_updated);
}
}, [initialStats, updatedStats, statsHistory, lastUpdated, setLastUpdated]);
}, [
initialStats,
updatedStats,
statsHistory,
lastUpdated,
setLastUpdated,
isActive,
]);
useEffect(() => {
if (isActive && statsHistory.length > 0) {
refreshStats().then((freshStats) => {
if (freshStats && freshStats.length > 0) {
setStatsHistory(freshStats);
}
});
}
// only re-fetch when tab becomes active, not on data changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive]);
// timestamps
@@ -168,15 +196,15 @@ export default function CameraMetrics({
series[key]["ffmpeg"].data.push({
x: statsIdx,
y: stats.cpu_usages[camStats.ffmpeg_pid.toString()]?.cpu ?? 0.0,
y: camStats.ffmpeg_cpu ?? "0",
});
series[key]["capture"].data.push({
x: statsIdx,
y: stats.cpu_usages[camStats.capture_pid?.toString()]?.cpu ?? 0,
y: camStats.capture_cpu ?? "0",
});
series[key]["detect"].data.push({
x: statsIdx,
y: stats.cpu_usages[camStats.pid?.toString()]?.cpu,
y: camStats.detect_cpu ?? "0",
});
});
});
@@ -261,6 +289,7 @@ export default function CameraMetrics({
dataLabels={["camera", "detect", "skipped"]}
updateTimes={updateTimes}
data={overallFpsSeries}
isActive={isActive}
/>
</div>
) : (
@@ -272,10 +301,9 @@ export default function CameraMetrics({
Object.values(config.cameras).map((camera) => {
if (camera.enabled) {
return (
<>
<Fragment key={camera.name}>
{probeCameraName == camera.name && (
<CameraInfoDialog
key={camera.name}
camera={camera}
showCameraInfoDialog={showCameraInfoDialog}
setShowCameraInfoDialog={setShowCameraInfoDialog}
@@ -345,6 +373,7 @@ export default function CameraMetrics({
data={Object.values(
cameraCpuSeries[camera.name] || {},
)}
isActive={isActive}
/>
</div>
) : (
@@ -363,6 +392,7 @@ export default function CameraMetrics({
data={Object.values(
cameraFpsSeries[camera.name] || {},
)}
isActive={isActive}
/>
</div>
) : (
@@ -370,7 +400,7 @@ export default function CameraMetrics({
)}
</div>
</div>
</>
</Fragment>
);
}
+36 -7
View File
@@ -1,6 +1,12 @@
import useSWR from "swr";
import { FrigateStats } from "@/types/stats";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
startTransition,
useCallback,
useEffect,
useMemo,
useState,
} from "react";
import { useFrigateStats } from "@/api/ws";
import { EmbeddingThreshold, GenAIThreshold, Threshold } from "@/types/graph";
import { Skeleton } from "@/components/ui/skeleton";
@@ -12,16 +18,18 @@ import { EventsPerSecondsLineGraph } from "@/components/graph/LineGraph";
type EnrichmentMetricsProps = {
lastUpdated: number;
setLastUpdated: (last: number) => void;
isActive: boolean;
};
export default function EnrichmentMetrics({
lastUpdated,
setLastUpdated,
isActive,
}: EnrichmentMetricsProps) {
// stats
const { t } = useTranslation(["views/system"]);
const { data: initialStats } = useSWR<FrigateStats[]>(
["stats/history", { keys: "embeddings,service" }],
const { data: initialStats, mutate: refreshStats } = useSWR<FrigateStats[]>(
["stats/history", { keys: "embeddings,service.last_updated" }],
{
revalidateOnFocus: false,
},
@@ -36,19 +44,38 @@ export default function EnrichmentMetrics({
}
if (statsHistory.length == 0) {
setStatsHistory(initialStats);
startTransition(() => setStatsHistory(initialStats));
return;
}
if (!updatedStats) {
if (!isActive || !updatedStats) {
return;
}
if (updatedStats.service.last_updated > lastUpdated) {
setStatsHistory([...statsHistory.slice(1), updatedStats]);
setLastUpdated(Date.now() / 1000);
setLastUpdated(updatedStats.service.last_updated);
}
}, [initialStats, updatedStats, statsHistory, lastUpdated, setLastUpdated]);
}, [
initialStats,
updatedStats,
statsHistory,
lastUpdated,
setLastUpdated,
isActive,
]);
useEffect(() => {
if (isActive && statsHistory.length > 0) {
refreshStats().then((freshStats) => {
if (freshStats && freshStats.length > 0) {
setStatsHistory(freshStats);
}
});
}
// only re-fetch when tab becomes active, not on data changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive]);
const getThreshold = useCallback((key: string) => {
if (key.includes("description")) {
@@ -205,6 +232,7 @@ export default function EnrichmentMetrics({
threshold={group.speedSeries.metrics}
updateTimes={updateTimes}
data={[group.speedSeries]}
isActive={isActive}
/>
)}
{group.eventsSeries && (
@@ -215,6 +243,7 @@ export default function EnrichmentMetrics({
name={t("enrichments.infPerSecond")}
updateTimes={updateTimes}
data={[group.eventsSeries]}
isActive={isActive}
/>
)}
</div>
+141 -50
View File
@@ -1,6 +1,6 @@
import useSWR from "swr";
import { FrigateStats, GpuInfo } from "@/types/stats";
import { useEffect, useMemo, useState } from "react";
import { startTransition, useEffect, useMemo, useState } from "react";
import { useFrigateStats } from "@/api/ws";
import {
DetectorCpuThreshold,
@@ -26,10 +26,12 @@ import { CiCircleAlert } from "react-icons/ci";
type GeneralMetricsProps = {
lastUpdated: number;
setLastUpdated: (last: number) => void;
isActive: boolean;
};
export default function GeneralMetrics({
lastUpdated,
setLastUpdated,
isActive,
}: GeneralMetricsProps) {
// extra info
const { t } = useTranslation(["views/system"]);
@@ -37,10 +39,12 @@ export default function GeneralMetrics({
// stats
const { data: initialStats } = useSWR<FrigateStats[]>(
const { data: initialStats, mutate: refreshStats } = useSWR<FrigateStats[]>(
[
"stats/history",
{ keys: "cpu_usages,detectors,gpu_usages,npu_usages,processes,service" },
{
keys: "detectors.inference_speed,detectors.temperature,detectors.cpu,detectors.mem,gpu_usages,npu_usages,processes.cpu,processes.mem,service.last_updated",
},
],
{
revalidateOnFocus: false,
@@ -56,19 +60,38 @@ export default function GeneralMetrics({
}
if (statsHistory.length == 0) {
setStatsHistory(initialStats);
startTransition(() => setStatsHistory(initialStats));
return;
}
if (!updatedStats) {
if (!isActive || !updatedStats) {
return;
}
if (updatedStats.service.last_updated > lastUpdated) {
setStatsHistory([...statsHistory.slice(1), updatedStats]);
setLastUpdated(Date.now() / 1000);
setLastUpdated(updatedStats.service.last_updated);
}
}, [initialStats, updatedStats, statsHistory, lastUpdated, setLastUpdated]);
}, [
initialStats,
updatedStats,
statsHistory,
lastUpdated,
setLastUpdated,
isActive,
]);
useEffect(() => {
if (isActive && statsHistory.length > 0) {
refreshStats().then((freshStats) => {
if (freshStats && freshStats.length > 0) {
setStatsHistory(freshStats);
}
});
}
// only re-fetch when tab becomes active, not on data changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isActive]);
const [canGetGpuInfo, gpuType] = useMemo<[boolean, GpuInfo]>(() => {
let vaCount = 0;
@@ -76,7 +99,7 @@ export default function GeneralMetrics({
statsHistory.length > 0 &&
Object.keys(statsHistory[0]?.gpu_usages ?? {}).forEach((key) => {
if (key == "amd-vaapi" || key == "intel-vaapi" || key == "intel-qsv") {
if (key == "amd-vaapi" || key == "intel-gpu") {
vaCount += 1;
}
@@ -181,7 +204,7 @@ export default function GeneralMetrics({
series[key] = { name: key, data: [] };
}
const data = stats.cpu_usages[detStats.pid.toString()]?.cpu;
const data = detStats.cpu;
if (data != undefined) {
series[key].data.push({
@@ -213,10 +236,12 @@ export default function GeneralMetrics({
series[key] = { name: key, data: [] };
}
series[key].data.push({
x: statsIdx + 1,
y: stats.cpu_usages[detStats.pid.toString()].mem,
});
if (detStats.mem != undefined) {
series[key].data.push({
x: statsIdx + 1,
y: detStats.mem,
});
}
});
});
return Object.values(series);
@@ -265,7 +290,7 @@ export default function GeneralMetrics({
if (
Object.keys(statsHistory?.at(0)?.gpu_usages ?? {}).length == 1 &&
Object.keys(statsHistory?.at(0)?.gpu_usages ?? {})[0].includes("intel")
Object.keys(statsHistory?.at(0)?.gpu_usages ?? {})[0] === "intel-gpu"
) {
// intel gpu stats do not support memory
return undefined;
@@ -334,6 +359,43 @@ export default function GeneralMetrics({
return Object.keys(series).length > 0 ? Object.values(series) : undefined;
}, [statsHistory]);
const gpuComputeSeries = useMemo(() => {
if (!statsHistory) {
return [];
}
const series: {
[key: string]: { name: string; data: { x: number; y: string }[] };
} = {};
let hasValidGpu = false;
statsHistory.forEach((stats, statsIdx) => {
if (!stats) {
return;
}
Object.entries(stats.gpu_usages || {}).forEach(([key, stats]) => {
if (!(key in series)) {
series[key] = { name: key, data: [] };
}
if (stats.compute) {
hasValidGpu = true;
series[key].data.push({
x: statsIdx + 1,
y: stats.compute.slice(0, -1),
});
}
});
});
if (!hasValidGpu) {
return [];
}
return Object.keys(series).length > 0 ? Object.values(series) : undefined;
}, [statsHistory]);
const gpuDecSeries = useMemo(() => {
if (!statsHistory) {
return [];
@@ -409,9 +471,7 @@ export default function GeneralMetrics({
}
const gpuKeys = Object.keys(statsHistory[0]?.gpu_usages ?? {});
const hasIntelGpu = gpuKeys.some(
(key) => key === "intel-vaapi" || key === "intel-qsv",
);
const hasIntelGpu = gpuKeys.some((key) => key === "intel-gpu");
if (!hasIntelGpu) {
return false;
@@ -427,7 +487,7 @@ export default function GeneralMetrics({
}
Object.entries(stats.gpu_usages || {}).forEach(([key, gpuStats]) => {
if (key === "intel-vaapi" || key === "intel-qsv") {
if (key === "intel-gpu") {
if (gpuStats.gpu) {
hasDataPoints = true;
const gpuValue = parseFloat(gpuStats.gpu.slice(0, -1));
@@ -546,22 +606,18 @@ 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: t(`general.otherProcesses.series.${key}`),
data: [],
};
}
if (!(key in series)) {
series[key] = {
name: t(`general.otherProcesses.series.${key}`),
data: [],
};
}
const data = stats.cpu_usages[procStats.pid.toString()]?.cpu;
if (data != undefined) {
series[key].data.push({
x: statsIdx + 1,
y: data,
});
}
if (procStats.cpu != undefined) {
series[key].data.push({
x: statsIdx + 1,
y: procStats.cpu,
});
}
});
});
@@ -583,22 +639,18 @@ 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: t(`general.otherProcesses.series.${key}`),
data: [],
};
}
if (!(key in series)) {
series[key] = {
name: t(`general.otherProcesses.series.${key}`),
data: [],
};
}
const data = stats.cpu_usages[procStats.pid.toString()]?.mem;
if (data) {
series[key].data.push({
x: statsIdx + 1,
y: data,
});
}
if (procStats.mem) {
series[key].data.push({
x: statsIdx + 1,
y: procStats.mem,
});
}
});
});
@@ -635,6 +687,7 @@ export default function GeneralMetrics({
threshold={InferenceThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -657,6 +710,7 @@ export default function GeneralMetrics({
threshold={DetectorTempThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -695,6 +749,7 @@ export default function GeneralMetrics({
threshold={DetectorCpuThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -713,6 +768,7 @@ export default function GeneralMetrics({
threshold={DetectorMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -744,8 +800,9 @@ export default function GeneralMetrics({
className={cn(
"mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2",
gpuTempSeries?.length && "md:grid-cols-3",
gpuEncSeries?.length && "xl:grid-cols-4",
gpuEncSeries?.length &&
(gpuEncSeries?.length || gpuComputeSeries?.length) &&
"xl:grid-cols-4",
(gpuEncSeries?.length || gpuComputeSeries?.length) &&
gpuTempSeries?.length &&
"3xl:grid-cols-5",
)}
@@ -804,6 +861,7 @@ export default function GeneralMetrics({
threshold={GPUUsageThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -826,6 +884,7 @@ export default function GeneralMetrics({
threshold={GPUMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -850,6 +909,32 @@ export default function GeneralMetrics({
threshold={GPUMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
)}
</>
) : (
<Skeleton className="aspect-video w-full" />
)}
{statsHistory.length != 0 ? (
<>
{gpuComputeSeries && gpuComputeSeries?.length != 0 && (
<div className="rounded-lg bg-background_alt p-2.5 md:rounded-2xl">
<div className="mb-5">
{t("general.hardwareInfo.gpuCompute")}
</div>
{gpuComputeSeries.map((series) => (
<ThresholdBarGraph
key={series.name}
graphId={`${series.name}-compute`}
unit="%"
name={series.name}
threshold={GPUMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -874,6 +959,7 @@ export default function GeneralMetrics({
threshold={GPUMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -898,6 +984,7 @@ export default function GeneralMetrics({
threshold={DetectorTempThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -923,6 +1010,7 @@ export default function GeneralMetrics({
threshold={GPUUsageThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -945,6 +1033,7 @@ export default function GeneralMetrics({
threshold={DetectorTempThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -978,6 +1067,7 @@ export default function GeneralMetrics({
threshold={DetectorCpuThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
@@ -997,6 +1087,7 @@ export default function GeneralMetrics({
threshold={DetectorMemThreshold}
updateTimes={updateTimes}
data={[series]}
isActive={isActive}
/>
))}
</div>
+14 -5
View File
@@ -1,7 +1,7 @@
import { CombinedStorageGraph } from "@/components/graph/CombinedStorageGraph";
import { StorageGraph } from "@/components/graph/StorageGraph";
import { FrigateStats } from "@/types/stats";
import { useMemo } from "react";
import { useEffect, useMemo } from "react";
import {
Popover,
PopoverContent,
@@ -10,7 +10,11 @@ import {
import useSWR from "swr";
import { CiCircleAlert } from "react-icons/ci";
import { FrigateConfig } from "@/types/frigateConfig";
import { useFormattedTimestamp, useTimezone } from "@/hooks/use-date-utils";
import {
useFormattedTimestamp,
useTimeFormat,
useTimezone,
} from "@/hooks/use-date-utils";
import { RecordingsSummary } from "@/types/review";
import { useTranslation } from "react-i18next";
import { TZDate } from "react-day-picker";
@@ -56,9 +60,14 @@ export default function StorageMetrics({
Object.values(cameraStorage).forEach(
(cam) => (totalStorage.camera += cam.usage),
);
setLastUpdated(Date.now() / 1000);
return totalStorage;
}, [cameraStorage, stats, setLastUpdated]);
}, [cameraStorage, stats]);
useEffect(() => {
if (totalStorage) {
setLastUpdated(Math.floor(Date.now() / 1000));
}
}, [totalStorage, setLastUpdated]);
// recordings summary
@@ -76,7 +85,7 @@ export default function StorageMetrics({
: null;
}, [recordingsSummary, timezone]);
const timeFormat = config?.ui.time_format === "24hour" ? "24hour" : "12hour";
const timeFormat = useTimeFormat(config);
const format = useMemo(() => {
return t(`time.formattedTimestampMonthDayYear.${timeFormat}`, {
ns: "common",