Full UI configuration (#22151)

* use react-jsonschema-form for UI config

* don't use properties wrapper when generating config i18n json

* configure for full i18n support

* section fields

* add descriptions to all fields for i18n

* motion i18n

* fix nullable fields

* sanitize internal fields

* add switches widgets and use friendly names

* fix nullable schema entries

* ensure update_topic is added to api calls

this needs further backend implementation to work correctly

* add global sections, camera config overrides, and reset button

* i18n

* add reset logic to global config view

* tweaks

* fix sections and live validation

* fix validation for schema objects that can be null

* generic and custom per-field validation

* improve generic error validation messages

* remove show advanced fields switch

* tweaks

* use shadcn theme

* fix array field template

* i18n tweaks

* remove collapsible around root section

* deep merge schema for advanced fields

* add array field item template and fix ffmpeg section

* add missing i18n keys

* tweaks

* comment out api call for testing

* add config groups as a separate i18n namespace

* add descriptions to all pydantic fields

* make titles more concise

* new titles as i18n

* update i18n config generation script to use json schema

* tweaks

* tweaks

* rebase

* clean up

* form tweaks

* add wildcards and fix object filter fields

* add field template for additionalproperties schema objects

* improve typing

* add section description from schema and clarify global vs camera level descriptions

* separate and consolidate global and camera i18n namespaces

* clean up now obsolete namespaces

* tweaks

* refactor sections and overrides

* add ability to render components before and after fields

* fix titles

* chore(sections): remove legacy single-section components replaced by template

* refactor configs to use individual files with a template

* fix review description

* apply hidden fields after ui schema

* move util

* remove unused i18n

* clean up error messages

* fix fast refresh

* add custom validation and use it for ffmpeg input roles

* update nav tree

* remove unused

* re-add override and modified indicators

* mark pending changes and add confirmation dialog for resets

* fix red unsaved dot

* tweaks

* add docs links, readonly keys, and restart required per field

* add special case and comments for global motion section

* add section form special cases

* combine review sections

* tweaks

* add audio labels endpoint

* add audio label switches and input to filter list

* fix type

* remove key from config when resetting to default/global

* don't show description for new key/val fields

* tweaks

* spacing tweaks

* add activity indicator and scrollbar tweaks

* add docs to filter fields

* wording changes

* fix global ffmpeg section

* add review classification zones to review form

* add backend endpoint and frontend widget for ffmpeg presets and manual args

* improve wording

* hide descriptions for additional properties arrays

* add warning log about incorrectly nested model config

* spacing and language tweaks

* fix i18n keys

* networking section docs and description

* small wording tweaks

* add layout grid field

* refactor with shared utilities

* field order

* add individual detectors to schema

add detector titles and descriptions (docstrings in pydantic are used for descriptions) and add i18n keys to globals

* clean up detectors section and i18n

* don't save model config back to yaml when saving detectors

* add full detectors config to api model dump

works around the way we use detector plugins so we can have the full detector config for the frontend

* add restart button to toast when restart is required

* add ui option to remove inner cards

* fix buttons

* section tweaks

* don't zoom into text on mobile

* make buttons sticky at bottom of sections

* small tweaks

* highlight label of changed fields

* add null to enum list when unwrapping

* refactor to shared utils and add save all button

* add undo all button

* add RJSF to dictionary

* consolidate utils

* preserve form data when changing cameras

* add mono fonts

* add popover to show what fields will be saved

* fix mobile menu not re-rendering with unsaved dots

* tweaks

* fix logger and env vars config section saving

use escaped periods in keys to retain them in the config file (eg "frigate.embeddings")

* add timezone widget

* role map field with validation

* fix validation for model section

* add another hidden field

* add footer message for required restart

* use rjsf for notifications view

* fix config saving

* add replace rules field

* default column layout and add field sizing

* clean up field template

* refactor profile settings to match rjsf forms

* tweaks

* refactor frigate+ view and make tweaks to sections

* show frigate+ model info in detection model settings when using a frigate+ model

* update restartRequired for all fields

* fix restart fields

* tweaks and add ability enable disabled cameras

more backend changes required

* require restart when enabling camera that is disabled in config

* disable save when form is invalid

* refactor ffmpeg section for readability

* change label

* clean up camera inputs fields

* misc tweaks to ffmpeg section

- add raw paths endpoint to ensure credentials get saved
- restart required tooltip

* maintenance settings tweaks

* don't mutate with lodash

* fix description re-rendering for nullable object fields

* hide reindex field

* update rjsf

* add frigate+ description to settings pane

* disable save all when any section is invalid

* show translated field name in validation error pane

* clean up

* remove unused

* fix genai merge

* fix genai
This commit is contained in:
Josh Hawkins
2026-02-27 08:55:36 -07:00
committed by GitHub
parent eeefbf2bb5
commit e7250f24cb
206 changed files with 22200 additions and 4435 deletions
+199 -27
View File
@@ -1,5 +1,11 @@
import Heading from "@/components/ui/heading";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
CONTROL_COLUMN_CLASS_NAME,
SettingsGroupCard,
SPLIT_ROW_CLASS_NAME,
} from "@/components/card/SettingsGroupCard";
import { toast } from "sonner";
import { Toaster } from "@/components/ui/sonner";
import { Button } from "@/components/ui/button";
import useSWR from "swr";
@@ -13,8 +19,12 @@ import { isDesktop } from "react-device-detect";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import { Switch } from "@/components/ui/switch";
import { Trans } from "react-i18next";
import { Separator } from "@/components/ui/separator";
import { useEnabledState } from "@/api/ws";
import { useEnabledState, useRestart } from "@/api/ws";
import { Label } from "@/components/ui/label";
import axios from "axios";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import RestartDialog from "@/components/overlay/dialog/RestartDialog";
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
type CameraManagementViewProps = {
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
@@ -36,10 +46,25 @@ export default function CameraManagementView({
); // Track camera being edited
const [showWizard, setShowWizard] = useState(false);
// State for restart dialog when enabling a disabled camera
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
const { send: sendRestart } = useRestart();
// List of cameras for dropdown
const cameras = useMemo(() => {
const enabledCameras = useMemo(() => {
if (config) {
return Object.keys(config.cameras).sort();
return Object.keys(config.cameras)
.filter((camera) => config.cameras[camera].enabled_in_config)
.sort();
}
return [];
}, [config]);
const disabledCameras = useMemo(() => {
if (config) {
return Object.keys(config.cameras)
.filter((camera) => !config.cameras[camera].enabled_in_config)
.sort();
}
return [];
}, [config]);
@@ -64,51 +89,102 @@ export default function CameraManagementView({
position="top-center"
closeButton
/>
<div className="flex size-full flex-col md:flex-row">
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2 md:order-none">
<div className="flex size-full space-y-6">
<div className="scrollbar-container flex-1 overflow-y-auto pb-2">
{viewMode === "settings" ? (
<>
<Heading as="h4" className="mb-2">
<Heading as="h4" className="mb-6">
{t("cameraManagement.title")}
</Heading>
<div className="my-4 flex flex-col gap-4">
<div className="w-full max-w-5xl space-y-6">
<Button
variant="select"
onClick={() => setShowWizard(true)}
className="flex max-w-48 items-center gap-2"
className="mb-2 flex max-w-48 items-center gap-2"
>
<LuPlus className="h-4 w-4" />
{t("cameraManagement.addCamera")}
</Button>
{cameras.length > 0 && (
<>
<Separator className="my-2 flex bg-secondary" />
<div className="max-w-7xl space-y-4">
<Heading as="h4" className="my-2">
<Trans ns="views/settings">
cameraManagement.streams.title
</Trans>
</Heading>
<div className="mt-3 text-sm text-muted-foreground">
<Trans ns="views/settings">
cameraManagement.streams.desc
</Trans>
</div>
{enabledCameras.length > 0 && (
<SettingsGroupCard
title={
<Trans ns="views/settings">
cameraManagement.streams.title
</Trans>
}
>
<div className={SPLIT_ROW_CLASS_NAME}>
<div className="space-y-1.5">
<Label
className="cursor-pointer"
htmlFor={"enabled-cameras-switch"}
>
{t("cameraManagement.streams.enableLabel")}
<p className="hidden text-sm text-muted-foreground md:block">
<Trans ns="views/settings">
cameraManagement.streams.enableDesc
</Trans>
</p>
</Label>
</div>
<div className="max-w-md space-y-2 rounded-lg bg-secondary p-4">
{cameras.map((camera) => (
{enabledCameras.map((camera) => (
<div
key={camera}
className="flex items-center justify-between smart-capitalize"
className="flex flex-row items-center justify-between"
>
<CameraNameLabel camera={camera} />
<CameraEnableSwitch cameraName={camera} />
</div>
))}
</div>
<p className="text-sm text-muted-foreground md:hidden">
<Trans ns="views/settings">
cameraManagement.streams.enableDesc
</Trans>
</p>
</div>
<Separator className="mb-2 mt-4 flex bg-secondary" />
</>
{disabledCameras.length > 0 && (
<div className={SPLIT_ROW_CLASS_NAME}>
<div className="space-y-1.5">
<Label
className="cursor-pointer"
htmlFor={"disabled-cameras-switch"}
>
{t("cameraManagement.streams.disableLabel")}
<RestartRequiredIndicator className="ml-1" />
</Label>
<p className="hidden text-sm text-muted-foreground md:block">
{t("cameraManagement.streams.disableDesc")}
</p>
</div>
<div
className={`${CONTROL_COLUMN_CLASS_NAME} space-y-1.5`}
>
<div className="max-w-md space-y-2 rounded-lg bg-secondary p-4">
{disabledCameras.map((camera) => (
<div
key={camera}
className="flex flex-row items-center justify-between"
>
<CameraNameLabel camera={camera} />
<CameraConfigEnableSwitch
cameraName={camera}
onConfigChanged={updateConfig}
setRestartDialogOpen={setRestartDialogOpen}
/>
</div>
))}
</div>
<p className="text-sm text-muted-foreground md:hidden">
{t("cameraManagement.streams.disableDesc")}
</p>
</div>
</div>
)}
</SettingsGroupCard>
)}
</div>
</>
@@ -145,6 +221,11 @@ export default function CameraManagementView({
open={showWizard}
onClose={() => setShowWizard(false)}
/>
<RestartDialog
isOpen={restartDialogOpen}
onClose={() => setRestartDialogOpen(false)}
onRestart={() => sendRestart("restart")}
/>
</>
);
}
@@ -169,3 +250,94 @@ function CameraEnableSwitch({ cameraName }: CameraEnableSwitchProps) {
</div>
);
}
type CameraConfigEnableSwitchProps = {
cameraName: string;
setRestartDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
onConfigChanged: () => Promise<unknown>;
};
function CameraConfigEnableSwitch({
cameraName,
onConfigChanged,
setRestartDialogOpen,
}: CameraConfigEnableSwitchProps) {
const { t } = useTranslation([
"common",
"views/settings",
"components/dialog",
]);
const [isSaving, setIsSaving] = useState(false);
const onCheckedChange = useCallback(
async (isChecked: boolean) => {
if (!isChecked || isSaving) {
return;
}
setIsSaving(true);
try {
await axios.put("config/set", {
requires_restart: 1,
config_data: {
cameras: {
[cameraName]: {
enabled: true,
},
},
},
});
await onConfigChanged();
toast.success(
t("cameraManagement.streams.enableSuccess", {
ns: "views/settings",
cameraName,
}),
{
position: "top-center",
action: (
<a onClick={() => setRestartDialogOpen(true)}>
<Button>
{t("restart.button", { ns: "components/dialog" })}
</Button>
</a>
),
},
);
} catch (error) {
const errorMessage =
axios.isAxiosError(error) &&
(error.response?.data?.message || error.response?.data?.detail)
? error.response?.data?.message || error.response?.data?.detail
: t("toast.save.error.noMessage", { ns: "common" });
toast.error(
t("toast.save.error.title", { errorMessage, ns: "common" }),
{
position: "top-center",
},
);
} finally {
setIsSaving(false);
}
},
[cameraName, isSaving, onConfigChanged, setRestartDialogOpen, t],
);
return (
<div className="flex flex-row items-center">
{isSaving ? (
<ActivityIndicator className="h-5 w-8" size={16} />
) : (
<Switch
id={`camera-enabled-${cameraName}`}
checked={false}
onCheckedChange={onCheckedChange}
/>
)}
</div>
);
}
@@ -1,751 +0,0 @@
import Heading from "@/components/ui/heading";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Toaster } from "@/components/ui/sonner";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { Checkbox } from "@/components/ui/checkbox";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
import axios from "axios";
import { Link } from "react-router-dom";
import { LuExternalLink } from "react-icons/lu";
import { MdCircle } from "react-icons/md";
import { cn } from "@/lib/utils";
import { Trans, useTranslation } from "react-i18next";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { getTranslatedLabel } from "@/utils/i18n";
import {
useAlertsState,
useDetectionsState,
useObjectDescriptionState,
useReviewDescriptionState,
} from "@/api/ws";
import { useCameraFriendlyName } from "@/hooks/use-camera-friendly-name";
import { resolveZoneName } from "@/hooks/use-zone-friendly-name";
import { formatList } from "@/utils/stringUtil";
type CameraReviewSettingsViewProps = {
selectedCamera: string;
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
};
type CameraReviewSettingsValueType = {
alerts_zones: string[];
detections_zones: string[];
};
export default function CameraReviewSettingsView({
selectedCamera,
setUnsavedChanges,
}: CameraReviewSettingsViewProps) {
const { t } = useTranslation(["views/settings"]);
const { getLocaleDocUrl } = useDocDomain();
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
}
}, [config, selectedCamera]);
const [changedValue, setChangedValue] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [selectDetections, setSelectDetections] = useState(false);
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
const selectCameraName = useCameraFriendlyName(selectedCamera);
// zones and labels
const getZoneName = useCallback(
(zoneId: string, cameraId?: string) =>
resolveZoneName(config, zoneId, cameraId),
[config],
);
const zones = useMemo(() => {
if (cameraConfig) {
return Object.entries(cameraConfig.zones).map(([name, zoneData]) => ({
camera: cameraConfig.name,
name,
friendly_name: cameraConfig.zones[name].friendly_name,
objects: zoneData.objects,
color: zoneData.color,
}));
}
}, [cameraConfig]);
const alertsLabels = useMemo(() => {
return cameraConfig?.review.alerts.labels
? formatList(
cameraConfig.review.alerts.labels.map((label) =>
getTranslatedLabel(
label,
cameraConfig?.audio?.listen?.includes(label) ? "audio" : "object",
),
),
)
: "";
}, [cameraConfig]);
const detectionsLabels = useMemo(() => {
return cameraConfig?.review.detections.labels
? formatList(
cameraConfig.review.detections.labels.map((label) =>
getTranslatedLabel(
label,
cameraConfig?.audio?.listen?.includes(label) ? "audio" : "object",
),
),
)
: "";
}, [cameraConfig]);
// form
const formSchema = z.object({
alerts_zones: z.array(z.string()),
detections_zones: z.array(z.string()),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
mode: "onChange",
defaultValues: {
alerts_zones: cameraConfig?.review.alerts.required_zones || [],
detections_zones: cameraConfig?.review.detections.required_zones || [],
},
});
const watchedAlertsZones = form.watch("alerts_zones");
const watchedDetectionsZones = form.watch("detections_zones");
const { payload: alertsState, send: sendAlerts } =
useAlertsState(selectedCamera);
const { payload: detectionsState, send: sendDetections } =
useDetectionsState(selectedCamera);
const { payload: objDescState, send: sendObjDesc } =
useObjectDescriptionState(selectedCamera);
const { payload: revDescState, send: sendRevDesc } =
useReviewDescriptionState(selectedCamera);
const handleCheckedChange = useCallback(
(isChecked: boolean) => {
if (!isChecked) {
form.reset({
alerts_zones: watchedAlertsZones,
detections_zones: [],
});
}
setChangedValue(true);
setUnsavedChanges(true);
setSelectDetections(isChecked as boolean);
},
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
[watchedAlertsZones, setUnsavedChanges],
);
const saveToConfig = useCallback(
async (
{ alerts_zones, detections_zones }: CameraReviewSettingsValueType, // values submitted via the form
) => {
const createQuery = (zones: string[], type: "alerts" | "detections") =>
zones.length
? zones
.map(
(zone) =>
`&cameras.${selectedCamera}.review.${type}.required_zones=${zone}`,
)
.join("")
: cameraConfig?.review[type]?.required_zones &&
cameraConfig?.review[type]?.required_zones.length > 0
? `&cameras.${selectedCamera}.review.${type}.required_zones`
: "";
const alertQueries = createQuery(alerts_zones, "alerts");
const detectionQueries = createQuery(detections_zones, "detections");
axios
.put(`config/set?${alertQueries}${detectionQueries}`, {
requires_restart: 0,
})
.then((res) => {
if (res.status === 200) {
toast.success(
t("cameraReview.reviewClassification.toast.success"),
{
position: "top-center",
},
);
setChangedValue(false);
setUnsavedChanges(false);
updateConfig();
} else {
toast.error(
t("toast.save.error.title", {
errorMessage: res.statusText,
ns: "common",
}),
{
position: "top-center",
},
);
}
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(
t("toast.save.error.title", {
errorMessage,
ns: "common",
}),
{
position: "top-center",
},
);
})
.finally(() => {
setIsLoading(false);
});
},
[
updateConfig,
setIsLoading,
selectedCamera,
cameraConfig,
t,
setUnsavedChanges,
],
);
const onCancel = useCallback(() => {
if (!cameraConfig) {
return;
}
setChangedValue(false);
setUnsavedChanges(false);
removeMessage(
"camera_settings",
`review_classification_settings_${selectedCamera}`,
);
form.reset({
alerts_zones: cameraConfig?.review.alerts.required_zones ?? [],
detections_zones: cameraConfig?.review.detections.required_zones || [],
});
setSelectDetections(
!!cameraConfig?.review.detections.required_zones?.length,
);
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [removeMessage, selectedCamera, setUnsavedChanges, cameraConfig]);
useEffect(() => {
onCancel();
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedCamera]);
useEffect(() => {
if (changedValue) {
addMessage(
"camera_settings",
t("cameraReview.reviewClassification.unsavedChanges", {
camera: selectedCamera,
}),
undefined,
`review_classification_settings_${selectedCamera}`,
);
} else {
removeMessage(
"camera_settings",
`review_classification_settings_${selectedCamera}`,
);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [changedValue, selectedCamera]);
function onSubmit(values: z.infer<typeof formSchema>) {
setIsLoading(true);
saveToConfig(values as CameraReviewSettingsValueType);
}
useEffect(() => {
document.title = t("documentTitle.cameraReview");
}, [t]);
if (!cameraConfig && !selectedCamera) {
return <ActivityIndicator />;
}
return (
<>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2 md:order-none">
<Heading as="h4" className="mb-2">
{t("cameraReview.title")}
</Heading>
<Heading as="h4" className="my-2">
<Trans ns="views/settings">cameraReview.review.title</Trans>
</Heading>
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 space-y-3 text-sm text-primary-variant">
<div className="flex flex-row items-center">
<Switch
id="alerts-enabled"
className="mr-3"
checked={alertsState == "ON"}
onCheckedChange={(isChecked) => {
sendAlerts(isChecked ? "ON" : "OFF");
}}
/>
<div className="space-y-0.5">
<Label htmlFor="alerts-enabled">
<Trans ns="views/settings">cameraReview.review.alerts</Trans>
</Label>
</div>
</div>
<div className="flex flex-col">
<div className="flex flex-row items-center">
<Switch
id="detections-enabled"
className="mr-3"
checked={detectionsState == "ON"}
onCheckedChange={(isChecked) => {
sendDetections(isChecked ? "ON" : "OFF");
}}
/>
<div className="space-y-0.5">
<Label htmlFor="detections-enabled">
<Trans ns="views/settings">camera.review.detections</Trans>
</Label>
</div>
</div>
<div className="mt-3 text-sm text-muted-foreground">
<Trans ns="views/settings">cameraReview.review.desc</Trans>
</div>
</div>
</div>
{cameraConfig?.objects?.genai?.enabled_in_config && (
<>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
<Trans ns="views/settings">
cameraReview.object_descriptions.title
</Trans>
</Heading>
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 space-y-3 text-sm text-primary-variant">
<div className="flex flex-row items-center">
<Switch
id="alerts-enabled"
className="mr-3"
checked={objDescState == "ON"}
onCheckedChange={(isChecked) => {
sendObjDesc(isChecked ? "ON" : "OFF");
}}
/>
<div className="space-y-0.5">
<Label htmlFor="genai-enabled">
<Trans>button.enabled</Trans>
</Label>
</div>
</div>
<div className="mt-3 text-sm text-muted-foreground">
<Trans ns="views/settings">
cameraReview.object_descriptions.desc
</Trans>
</div>
</div>
</>
)}
{cameraConfig?.review?.genai?.enabled_in_config && (
<>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
<Trans ns="views/settings">
cameraReview.review_descriptions.title
</Trans>
</Heading>
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 space-y-3 text-sm text-primary-variant">
<div className="flex flex-row items-center">
<Switch
id="alerts-enabled"
className="mr-3"
checked={revDescState == "ON"}
onCheckedChange={(isChecked) => {
sendRevDesc(isChecked ? "ON" : "OFF");
}}
/>
<div className="space-y-0.5">
<Label htmlFor="genai-enabled">
<Trans>button.enabled</Trans>
</Label>
</div>
</div>
<div className="mt-3 text-sm text-muted-foreground">
<Trans ns="views/settings">
cameraReview.review_descriptions.desc
</Trans>
</div>
</div>
</>
)}
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
<Trans ns="views/settings">
cameraReview.reviewClassification.title
</Trans>
</Heading>
<div className="max-w-6xl">
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 text-sm text-primary-variant">
<p>
<Trans ns="views/settings">
cameraReview.reviewClassification.desc
</Trans>
</p>
<div className="flex items-center text-primary">
<Link
to={getLocaleDocUrl("configuration/review")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</div>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="mt-2 space-y-6"
>
<div
className={cn(
"w-full max-w-5xl space-y-0",
zones &&
zones?.length > 0 &&
"grid items-start gap-5 md:grid-cols-2",
)}
>
<FormField
control={form.control}
name="alerts_zones"
render={() => (
<FormItem>
{zones && zones?.length > 0 ? (
<>
<div className="mb-2">
<FormLabel className="flex flex-row items-center text-base">
<Trans ns="views/settings">
camera.review.alerts
</Trans>
<MdCircle className="ml-3 size-2 text-severity_alert" />
</FormLabel>
<FormDescription>
<Trans ns="views/settings">
cameraReview.reviewClassification.selectAlertsZones
</Trans>
</FormDescription>
</div>
<div className="max-w-md rounded-lg bg-secondary p-4 md:max-w-full">
{zones?.map((zone) => (
<FormField
key={zone.name}
control={form.control}
name="alerts_zones"
render={({ field }) => (
<FormItem
key={zone.name}
className="mb-3 flex flex-row items-center space-x-3 space-y-0 last:mb-0"
>
<FormControl>
<Checkbox
className="size-5 text-white accent-white data-[state=checked]:bg-selected data-[state=checked]:text-white"
checked={field.value?.includes(
zone.name,
)}
onCheckedChange={(checked) => {
setChangedValue(true);
setUnsavedChanges(true);
return checked
? field.onChange([
...field.value,
zone.name,
])
: field.onChange(
field.value?.filter(
(value) =>
value !== zone.name,
),
);
}}
/>
</FormControl>
<FormLabel
className={cn(
"font-normal",
!zone.friendly_name &&
"smart-capitalize",
)}
>
{zone.friendly_name || zone.name}
</FormLabel>
</FormItem>
)}
/>
))}
</div>
</>
) : (
<div className="font-normal text-destructive">
<Trans ns="views/settings">
cameraReview.reviewClassification.noDefinedZones
</Trans>
</div>
)}
<FormMessage />
<div className="text-sm">
{watchedAlertsZones && watchedAlertsZones.length > 0
? t(
"cameraReview.reviewClassification.zoneObjectAlertsTips",
{
alertsLabels,
zone: formatList(
watchedAlertsZones.map((zone) =>
getZoneName(zone),
),
),
cameraName: selectCameraName,
},
)
: t(
"cameraReview.reviewClassification.objectAlertsTips",
{
alertsLabels,
cameraName: selectCameraName,
},
)}
</div>
</FormItem>
)}
/>
<FormField
control={form.control}
name="detections_zones"
render={() => (
<FormItem>
{zones && zones?.length > 0 && (
<>
<div className="mb-2">
<FormLabel className="flex flex-row items-center text-base">
<Trans ns="views/settings">
camera.review.detections
</Trans>
<MdCircle className="ml-3 size-2 text-severity_detection" />
</FormLabel>
{selectDetections && (
<FormDescription>
<Trans ns="views/settings">
cameraReview.reviewClassification.selectDetectionsZones
</Trans>
</FormDescription>
)}
</div>
{selectDetections && (
<div className="max-w-md rounded-lg bg-secondary p-4 md:max-w-full">
{zones?.map((zone) => (
<FormField
key={zone.name}
control={form.control}
name="detections_zones"
render={({ field }) => (
<FormItem
key={zone.name}
className="mb-3 flex flex-row items-center space-x-3 space-y-0 last:mb-0"
>
<FormControl>
<Checkbox
className="size-5 text-white accent-white data-[state=checked]:bg-selected data-[state=checked]:text-white"
checked={field.value?.includes(
zone.name,
)}
onCheckedChange={(checked) => {
setChangedValue(true);
setUnsavedChanges(true);
return checked
? field.onChange([
...field.value,
zone.name,
])
: field.onChange(
field.value?.filter(
(value) =>
value !== zone.name,
),
);
}}
/>
</FormControl>
<FormLabel
className={cn(
"font-normal",
!zone.friendly_name &&
"smart-capitalize",
)}
>
{zone.friendly_name || zone.name}
</FormLabel>
</FormItem>
)}
/>
))}
</div>
)}
<FormMessage />
<div className="mb-0 flex flex-row items-center gap-2">
<Checkbox
id="select-detections"
className="size-5 text-white accent-white data-[state=checked]:bg-selected data-[state=checked]:text-white"
checked={selectDetections}
onCheckedChange={handleCheckedChange}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor="select-detections"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
<Trans ns="views/settings">
cameraReview.reviewClassification.limitDetections
</Trans>
</label>
</div>
</div>
</>
)}
<div className="text-sm">
{watchedDetectionsZones &&
watchedDetectionsZones.length > 0 ? (
!selectDetections ? (
<Trans
i18nKey="cameraReview.reviewClassification.zoneObjectDetectionsTips.text"
values={{
detectionsLabels,
zone: formatList(
watchedDetectionsZones.map((zone) =>
getZoneName(zone),
),
),
cameraName: selectCameraName,
}}
ns="views/settings"
/>
) : (
<Trans
i18nKey="cameraReview.reviewClassification.zoneObjectDetectionsTips.notSelectDetections"
values={{
detectionsLabels,
zone: formatList(
watchedDetectionsZones.map((zone) =>
getZoneName(zone),
),
),
cameraName: selectCameraName,
}}
ns="views/settings"
/>
)
) : (
<Trans
i18nKey="cameraReview.reviewClassification.objectDetectionsTips"
values={{
detectionsLabels,
cameraName: selectCameraName,
}}
ns="views/settings"
/>
)}
</div>
</FormItem>
)}
/>
</div>
<div className="flex w-full flex-row items-center gap-2 pt-2 md:w-[25%]">
<Button
className="flex flex-1"
aria-label={t("button.reset", { ns: "common" })}
onClick={onCancel}
type="button"
>
<Trans>button.reset</Trans>
</Button>
<Button
variant="select"
disabled={!changedValue || isLoading}
className="flex flex-1"
aria-label={t("button.save", { ns: "common" })}
type="submit"
>
{isLoading ? (
<div className="flex flex-row items-center gap-2">
<ActivityIndicator />
<span>
<Trans>button.saving</Trans>
</span>
</div>
) : (
<Trans>button.save</Trans>
)}
</Button>
</div>
</form>
</Form>
</div>
</div>
</>
);
}
+265 -319
View File
@@ -1,8 +1,6 @@
import Heading from "@/components/ui/heading";
import { Label } from "@/components/ui/label";
import { useCallback, useContext, useEffect, useState } from "react";
import { Toaster } from "@/components/ui/sonner";
import { Separator } from "../../components/ui/separator";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { toast } from "sonner";
import useSWR from "swr";
@@ -24,6 +22,11 @@ import {
} from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import {
SettingsGroupCard,
SplitCardRow,
} from "@/components/card/SettingsGroupCard";
import FrigatePlusCurrentModelSummary from "@/views/settings/components/FrigatePlusCurrentModelSummary";
type FrigatePlusModel = {
id: string;
@@ -208,331 +211,274 @@ export default function FrigatePlusSettingsView({
}
return (
<>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2 md:order-none">
<Heading as="h4" className="mb-2">
{t("frigatePlus.title")}
</Heading>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="mt-2 flex h-full w-full flex-col">
<div className="scrollbar-container flex-1 overflow-y-auto">
<div className="w-full max-w-5xl space-y-6">
<div className="flex flex-col gap-0">
<Heading as="h4" className="mb-2">
{t("frigatePlus.title")}
</Heading>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
{t("frigatePlus.apiKey.title")}
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-3">
<div className="flex items-center gap-2">
{config?.plus?.enabled ? (
<CheckCircle2 className="h-5 w-5 text-green-500" />
) : (
<XCircle className="h-5 w-5 text-red-500" />
)}
<Label>
{config?.plus?.enabled
? t("frigatePlus.apiKey.validated")
: t("frigatePlus.apiKey.notValidated")}
</Label>
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("frigatePlus.apiKey.desc")}</p>
{!config?.model.plus && (
<>
<div className="mt-2 flex items-center text-primary-variant">
<Link
to="https://frigate.video/plus"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("frigatePlus.apiKey.plusLink")}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</>
)}
</div>
<p className="text-sm text-muted-foreground">
{t("frigatePlus.description")}
</p>
</div>
{config?.model.plus && (
<>
<Separator className="my-2 flex bg-secondary" />
<div className="mt-2 max-w-2xl">
<Heading as="h4" className="my-2">
{t("frigatePlus.modelInfo.title")}
</Heading>
<div className="mt-2 space-y-3">
{!config?.model?.plus && (
<p className="text-muted-foreground">
{t("frigatePlus.modelInfo.loading")}
</p>
)}
{config?.model?.plus === null && (
<p className="text-danger">
{t("frigatePlus.modelInfo.error")}
</p>
)}
{config?.model?.plus && (
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-muted-foreground">
{t("frigatePlus.modelInfo.baseModel")}
</Label>
<p>
{config.model.plus.baseModel} (
{config.model.plus.isBaseModel
? t(
"frigatePlus.modelInfo.plusModelType.baseModel",
)
: t(
"frigatePlus.modelInfo.plusModelType.userModel",
)}
)
</p>
<div className="space-y-6">
<SettingsGroupCard title={t("frigatePlus.cardTitles.api")}>
<SplitCardRow
label={t("frigatePlus.apiKey.title")}
description={
<>
<p>{t("frigatePlus.apiKey.desc")}</p>
{!config?.model.plus && (
<div className="mt-2 flex items-center text-primary-variant">
<Link
to="https://frigate.video/plus"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("frigatePlus.apiKey.plusLink")}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
<div>
<Label className="text-muted-foreground">
{t("frigatePlus.modelInfo.trainDate")}
</Label>
<p>
)}
</>
}
content={
<div className="flex items-center gap-2">
{config?.plus?.enabled ? (
<CheckCircle2 className="h-5 w-5 text-green-500" />
) : (
<XCircle className="h-5 w-5 text-red-500" />
)}
<span className="text-sm">
{config?.plus?.enabled
? t("frigatePlus.apiKey.validated")
: t("frigatePlus.apiKey.notValidated")}
</span>
</div>
}
/>
</SettingsGroupCard>
{config?.model.plus && (
<FrigatePlusCurrentModelSummary plusModel={config.model.plus} />
)}
{config?.model.plus && (
<SettingsGroupCard
title={t("frigatePlus.cardTitles.otherModels")}
>
<SplitCardRow
label={t("frigatePlus.modelInfo.availableModels")}
description={
<Trans ns="views/settings">
frigatePlus.modelInfo.modelSelect
</Trans>
}
content={
<Select
value={frigatePlusSettings.model.id}
onValueChange={(value) =>
handleFrigatePlusConfigChange({
model: { id: value as string },
})
}
>
{frigatePlusSettings.model.id &&
availableModels?.[frigatePlusSettings.model.id] ? (
<SelectTrigger className="w-full">
{new Date(
config.model.plus.trainDate,
).toLocaleString()}
</p>
</div>
<div>
<Label className="text-muted-foreground">
{t("frigatePlus.modelInfo.modelType")}
</Label>
<p>
{config.model.plus.name} (
{config.model.plus.width +
availableModels[
frigatePlusSettings.model.id
].trainDate,
).toLocaleString() +
" " +
availableModels[frigatePlusSettings.model.id]
.baseModel +
" (" +
(availableModels[frigatePlusSettings.model.id]
.isBaseModel
? t(
"frigatePlus.modelInfo.plusModelType.baseModel",
)
: t(
"frigatePlus.modelInfo.plusModelType.userModel",
)) +
") " +
availableModels[frigatePlusSettings.model.id]
.name +
" (" +
availableModels[frigatePlusSettings.model.id]
.width +
"x" +
config.model.plus.height}
)
</p>
</div>
<div>
<Label className="text-muted-foreground">
{t("frigatePlus.modelInfo.supportedDetectors")}
</Label>
<p>
{config.model.plus.supportedDetectors.join(", ")}
</p>
</div>
<div className="col-span-2">
<div className="space-y-2">
<div className="text-md">
{t("frigatePlus.modelInfo.availableModels")}
</div>
<div className="space-y-3 text-sm text-muted-foreground">
<p>
availableModels[frigatePlusSettings.model.id]
.height +
")"}
</SelectTrigger>
) : (
<SelectTrigger className="w-full">
{t("frigatePlus.modelInfo.loadingAvailableModels")}
</SelectTrigger>
)}
<SelectContent>
<SelectGroup>
{Object.entries(availableModels || {}).map(
([id, model]) => (
<SelectItem
key={id}
className="cursor-pointer"
value={id}
disabled={
!model.supportedDetectors.includes(
Object.values(config.detectors)[0].type,
)
}
>
{new Date(model.trainDate).toLocaleString()}{" "}
<div>
{model.baseModel} {" ("}
{model.isBaseModel
? t(
"frigatePlus.modelInfo.plusModelType.baseModel",
)
: t(
"frigatePlus.modelInfo.plusModelType.userModel",
)}
{")"}
</div>
<div>
{model.name} (
{model.width + "x" + model.height})
</div>
<div>
{t(
"frigatePlus.modelInfo.supportedDetectors",
)}
: {model.supportedDetectors.join(", ")}
</div>
<div className="text-xs text-muted-foreground">
{id}
</div>
</SelectItem>
),
)}
</SelectGroup>
</SelectContent>
</Select>
}
/>
</SettingsGroupCard>
)}
<SettingsGroupCard
title={t("frigatePlus.cardTitles.configuration")}
>
<SplitCardRow
label={t("frigatePlus.snapshotConfig.title")}
description={
<>
<p>
<Trans ns="views/settings">
frigatePlus.snapshotConfig.desc
</Trans>
</p>
<div className="mt-2 flex items-center text-primary-variant">
<Link
to={getLocaleDocUrl("plus/faq")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</>
}
content={
<div className="space-y-3">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-secondary">
<th className="px-4 py-2 text-left">
{t("frigatePlus.snapshotConfig.table.camera")}
</th>
<th className="px-4 py-2 text-center">
{t(
"frigatePlus.snapshotConfig.table.snapshots",
)}
</th>
<th className="px-4 py-2 text-center">
<Trans ns="views/settings">
frigatePlus.modelInfo.modelSelect
frigatePlus.snapshotConfig.table.cleanCopySnapshots
</Trans>
</p>
</th>
</tr>
</thead>
<tbody>
{Object.entries(config.cameras).map(
([name, camera]) => (
<tr
key={name}
className="border-b border-secondary"
>
<td className="px-4 py-2">
<CameraNameLabel camera={name} />
</td>
<td className="px-4 py-2 text-center">
{camera.snapshots.enabled ? (
<CheckCircle2 className="mx-auto size-5 text-green-500" />
) : (
<XCircle className="mx-auto size-5 text-danger" />
)}
</td>
<td className="px-4 py-2 text-center">
{camera.snapshots?.enabled &&
camera.snapshots?.clean_copy ? (
<CheckCircle2 className="mx-auto size-5 text-green-500" />
) : (
<XCircle className="mx-auto size-5 text-danger" />
)}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
{needCleanSnapshots() && (
<div className="rounded-lg border border-secondary-foreground bg-secondary p-4 text-sm text-danger">
<div className="flex items-center gap-2">
<IoIosWarning className="mr-2 size-5 text-danger" />
<div className="max-w-[85%] text-sm">
<Trans ns="views/settings">
frigatePlus.snapshotConfig.cleanCopyWarning
</Trans>
</div>
</div>
<Select
value={frigatePlusSettings.model.id}
onValueChange={(value) =>
handleFrigatePlusConfigChange({
model: { id: value as string },
})
}
>
{frigatePlusSettings.model.id &&
availableModels?.[frigatePlusSettings.model.id] ? (
<SelectTrigger>
{new Date(
availableModels[
frigatePlusSettings.model.id
].trainDate,
).toLocaleString() +
" " +
availableModels[frigatePlusSettings.model.id]
.baseModel +
" (" +
(availableModels[frigatePlusSettings.model.id]
.isBaseModel
? t(
"frigatePlus.modelInfo.plusModelType.baseModel",
)
: t(
"frigatePlus.modelInfo.plusModelType.userModel",
)) +
") " +
availableModels[frigatePlusSettings.model.id]
.name +
" (" +
availableModels[frigatePlusSettings.model.id]
.width +
"x" +
availableModels[frigatePlusSettings.model.id]
.height +
")"}
</SelectTrigger>
) : (
<SelectTrigger>
{t(
"frigatePlus.modelInfo.loadingAvailableModels",
)}
</SelectTrigger>
)}
<SelectContent>
<SelectGroup>
{Object.entries(availableModels || {}).map(
([id, model]) => (
<SelectItem
key={id}
className="cursor-pointer"
value={id}
disabled={
!model.supportedDetectors.includes(
Object.values(config.detectors)[0]
.type,
)
}
>
{new Date(
model.trainDate,
).toLocaleString()}{" "}
<div>
{model.baseModel} {" ("}
{model.isBaseModel
? t(
"frigatePlus.modelInfo.plusModelType.baseModel",
)
: t(
"frigatePlus.modelInfo.plusModelType.userModel",
)}
{")"}
</div>
<div>
{model.name} (
{model.width + "x" + model.height})
</div>
<div>
{t(
"frigatePlus.modelInfo.supportedDetectors",
)}
: {model.supportedDetectors.join(", ")}
</div>
<div className="text-xs text-muted-foreground">
{id}
</div>
</SelectItem>
),
)}
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>
)}
</div>
</div>
</>
)}
<Separator className="my-2 flex bg-secondary" />
<div className="mt-2 max-w-5xl">
<Heading as="h4" className="my-2">
{t("frigatePlus.snapshotConfig.title")}
</Heading>
<div className="mt-2 space-y-3">
<div className="my-2 text-sm text-muted-foreground">
<p>
<Trans ns="views/settings">
frigatePlus.snapshotConfig.desc
</Trans>
</p>
<div className="mt-2 flex items-center text-primary-variant">
<Link
to={getLocaleDocUrl("plus/faq")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
{config && (
<div className="overflow-x-auto">
<table className="max-w-2xl text-sm">
<thead>
<tr className="border-b border-secondary">
<th className="px-4 py-2 text-left">
{t("frigatePlus.snapshotConfig.table.camera")}
</th>
<th className="px-4 py-2 text-center">
{t("frigatePlus.snapshotConfig.table.snapshots")}
</th>
<th className="px-4 py-2 text-center">
<Trans ns="views/settings">
frigatePlus.snapshotConfig.table.cleanCopySnapshots
</Trans>
</th>
</tr>
</thead>
<tbody>
{Object.entries(config.cameras).map(
([name, camera]) => (
<tr
key={name}
className="border-b border-secondary"
>
<td className="px-4 py-2">
<CameraNameLabel camera={name} />
</td>
<td className="px-4 py-2 text-center">
{camera.snapshots.enabled ? (
<CheckCircle2 className="mx-auto size-5 text-green-500" />
) : (
<XCircle className="mx-auto size-5 text-danger" />
)}
</td>
<td className="px-4 py-2 text-center">
{camera.snapshots?.enabled &&
camera.snapshots?.clean_copy ? (
<CheckCircle2 className="mx-auto size-5 text-green-500" />
) : (
<XCircle className="mx-auto size-5 text-danger" />
)}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
)}
{needCleanSnapshots() && (
<div className="mt-2 max-w-xl rounded-lg border border-secondary-foreground bg-secondary p-4 text-sm text-danger">
<div className="flex items-center gap-2">
<IoIosWarning className="mr-2 size-5 text-danger" />
<div className="max-w-[85%] text-sm">
<Trans ns="views/settings">
frigatePlus.snapshotConfig.cleanCopyWarning
</Trans>
</div>
)}
</div>
</div>
)}
</div>
}
/>
</SettingsGroupCard>
</div>
</div>
</div>
<Separator className="my-2 flex bg-secondary" />
<div className="flex w-full flex-row items-center gap-2 pt-2 md:w-[25%]">
<div className="sticky bottom-0 z-50 w-full border-t border-secondary bg-background pb-5 pt-0 md:pr-2">
<div className="flex flex-col items-center gap-4 pt-2 md:flex-row md:justify-end">
<div className="flex w-full items-center gap-2 md:w-auto">
<Button
className="flex flex-1"
className="flex min-w-36 flex-1 gap-2"
variant="outline"
aria-label={t("button.reset", { ns: "common" })}
onClick={onCancel}
>
@@ -541,15 +487,15 @@ export default function FrigatePlusSettingsView({
<Button
variant="select"
disabled={!changedValue || isLoading}
className="flex flex-1"
aria-label="Save"
className="flex min-w-36 flex-1 gap-2"
aria-label={t("button.save", { ns: "common" })}
onClick={saveToConfig}
>
{isLoading ? (
<div className="flex flex-row items-center gap-2">
<ActivityIndicator />
<span>{t("button.saving", { ns: "common" })}</span>
</div>
<>
<ActivityIndicator className="h-4 w-4" />
{t("button.saving", { ns: "common" })}
</>
) : (
t("button.save", { ns: "common" })
)}
@@ -558,6 +504,6 @@ export default function FrigatePlusSettingsView({
</div>
</div>
</div>
</>
</div>
);
}
@@ -108,7 +108,7 @@ export default function MaintenanceSettingsView() {
</Heading>
<div className="max-w-6xl">
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 text-sm text-primary-variant">
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 text-sm text-muted-foreground">
<p>{t("maintenance.sync.desc")}</p>
</div>
</div>
@@ -165,16 +165,9 @@ export default function MaintenanceSettingsView() {
</div>
{/* Options */}
<div className="space-y-4">
<div className="max-w-md space-y-4">
<div className="flex flex-col">
<div className="flex flex-row items-center">
<Switch
id="dry-run"
className="mr-3"
checked={dryRun}
onCheckedChange={setDryRun}
disabled={isJobRunning}
/>
<div className="flex flex-row items-center justify-between gap-4">
<div className="space-y-0.5">
<Label htmlFor="dry-run" className="cursor-pointer">
{t("maintenance.sync.dryRun")}
@@ -185,18 +178,17 @@ export default function MaintenanceSettingsView() {
: t("maintenance.sync.dryRunDisabled")}
</p>
</div>
<Switch
id="dry-run"
checked={dryRun}
onCheckedChange={setDryRun}
disabled={isJobRunning}
/>
</div>
</div>
<div className="flex flex-col">
<div className="flex flex-row items-center">
<Switch
id="force"
className="mr-3"
checked={force}
onCheckedChange={setForce}
disabled={isJobRunning}
/>
<div className="flex flex-row items-center justify-between gap-4">
<div className="space-y-0.5">
<Label htmlFor="force" className="cursor-pointer">
{t("maintenance.sync.force")}
@@ -205,6 +197,12 @@ export default function MaintenanceSettingsView() {
{t("maintenance.sync.forceDesc")}
</p>
</div>
<Switch
id="force"
checked={force}
onCheckedChange={setForce}
disabled={isJobRunning}
/>
</div>
</div>
</div>
@@ -1,785 +0,0 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import Heading from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Toaster } from "@/components/ui/sonner";
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
import { FrigateConfig } from "@/types/frigateConfig";
import { zodResolver } from "@hookform/resolvers/zod";
import axios from "axios";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { LuCheck, LuExternalLink, LuX } from "react-icons/lu";
import { CiCircleAlert } from "react-icons/ci";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import useSWR from "swr";
import { z } from "zod";
import {
useNotifications,
useNotificationSuspend,
useNotificationTest,
} from "@/api/ws";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
import FilterSwitch from "@/components/filter/FilterSwitch";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Trans, useTranslation } from "react-i18next";
import { useDateLocale } from "@/hooks/use-date-locale";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { cn } from "@/lib/utils";
const NOTIFICATION_SERVICE_WORKER = "notifications-worker.js";
type NotificationSettingsValueType = {
allEnabled: boolean;
email?: string;
cameras: string[];
};
type NotificationsSettingsViewProps = {
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
};
export default function NotificationView({
setUnsavedChanges,
}: NotificationsSettingsViewProps) {
const { t } = useTranslation(["views/settings"]);
const { getLocaleDocUrl } = useDocDomain();
// roles
const isAdmin = useIsAdmin();
const { data: config, mutate: updateConfig } = useSWR<FrigateConfig>(
"config",
{
revalidateOnFocus: false,
},
);
const allCameras = useMemo(() => {
if (!config) {
return [];
}
return Object.values(config.cameras).sort(
(aConf, bConf) => aConf.ui.order - bConf.ui.order,
);
}, [config]);
const notificationCameras = useMemo(() => {
if (!config) {
return [];
}
return Object.values(config.cameras)
.filter(
(conf) =>
conf.enabled_in_config &&
conf.notifications &&
conf.notifications.enabled_in_config,
)
.sort((aConf, bConf) => aConf.ui.order - bConf.ui.order);
}, [config]);
const { send: sendTestNotification } = useNotificationTest();
// status bar
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
const [changedValue, setChangedValue] = useState(false);
useEffect(() => {
if (changedValue) {
addMessage(
"notification_settings",
t("notification.unsavedChanges"),
undefined,
`notification_settings`,
);
} else {
removeMessage("notification_settings", `notification_settings`);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [changedValue]);
// notification state
const [registration, setRegistration] =
useState<ServiceWorkerRegistration | null>();
useEffect(() => {
if (!("Notification" in window) || !window.isSecureContext) {
return;
}
navigator.serviceWorker
.getRegistration(NOTIFICATION_SERVICE_WORKER)
.then((worker) => {
if (worker) {
setRegistration(worker);
} else {
setRegistration(null);
}
})
.catch(() => {
setRegistration(null);
});
}, []);
// form
const [isLoading, setIsLoading] = useState(false);
const formSchema = z.object({
allEnabled: z.boolean(),
email: z.string(),
cameras: z.array(z.string()),
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
mode: "onChange",
defaultValues: {
allEnabled: config?.notifications.enabled,
email: config?.notifications.email,
cameras: config?.notifications.enabled
? []
: notificationCameras.map((c) => c.name),
},
});
const watchAllEnabled = form.watch("allEnabled");
const watchCameras = form.watch("cameras");
const anyCameraNotificationsEnabled = useMemo(
() =>
config &&
Object.values(config.cameras).some(
(c) =>
c.enabled_in_config &&
c.notifications &&
c.notifications.enabled_in_config,
),
[config],
);
const shouldFetchPubKey = Boolean(
config &&
(config.notifications?.enabled || anyCameraNotificationsEnabled) &&
(watchAllEnabled ||
(Array.isArray(watchCameras) && watchCameras.length > 0)),
);
const { data: publicKey } = useSWR(
shouldFetchPubKey ? "notifications/pubkey" : null,
{ revalidateOnFocus: false },
);
const subscribeToNotifications = useCallback(
(registration: ServiceWorkerRegistration) => {
if (registration) {
addMessage(
"notification_settings",
t("notification.unsavedRegistrations"),
undefined,
"registration",
);
registration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey,
})
.then((pushSubscription) => {
axios
.post("notifications/register", {
sub: pushSubscription,
})
.catch(() => {
toast.error(t("notification.toast.error.registerFailed"), {
position: "top-center",
});
pushSubscription.unsubscribe();
registration.unregister();
setRegistration(null);
});
toast.success(t("notification.toast.success.registered"), {
position: "top-center",
});
});
}
},
[publicKey, addMessage, t],
);
useEffect(() => {
if (watchCameras.length > 0) {
form.setValue("allEnabled", false);
}
}, [watchCameras, allCameras, form]);
const onCancel = useCallback(() => {
if (!config) {
return;
}
setUnsavedChanges(false);
setChangedValue(false);
form.reset({
allEnabled: config.notifications.enabled,
email: config.notifications.email || "",
cameras: config?.notifications.enabled
? []
: notificationCameras.map((c) => c.name),
});
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [config, removeMessage, setUnsavedChanges]);
const saveToConfig = useCallback(
async (
{ allEnabled, email, cameras }: NotificationSettingsValueType, // values submitted via the form
) => {
const allCameraNames = allCameras.map((cam) => cam.name);
const enabledCameraQueries = cameras
.map((cam) => `&cameras.${cam}.notifications.enabled=True`)
.join("");
const disabledCameraQueries = allCameraNames
.filter((cam) => !cameras.includes(cam))
.map(
(cam) =>
`&cameras.${cam}.notifications.enabled=${allEnabled ? "True" : "False"}`,
)
.join("");
const allCameraQueries = enabledCameraQueries + disabledCameraQueries;
axios
.put(
`config/set?notifications.enabled=${allEnabled ? "True" : "False"}&notifications.email=${email}${allCameraQueries}`,
{
requires_restart: 0,
},
)
.then((res) => {
if (res.status === 200) {
toast.success(t("notification.toast.success.settingSaved"), {
position: "top-center",
});
updateConfig();
} else {
toast.error(
t("toast.save.error.title", {
errorMessage: res.statusText,
ns: "common",
}),
{
position: "top-center",
},
);
}
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(
t("toast.save.error.title", { errorMessage, ns: "common" }),
{
position: "top-center",
},
);
})
.finally(() => {
setIsLoading(false);
});
},
[updateConfig, setIsLoading, allCameras, t],
);
function onSubmit(values: z.infer<typeof formSchema>) {
setIsLoading(true);
saveToConfig(values as NotificationSettingsValueType);
}
useEffect(() => {
document.title = t("documentTitle.notifications");
}, [t]);
if (!("Notification" in window) || !window.isSecureContext) {
return (
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2 md:order-none">
<div className="grid w-full grid-cols-1 gap-4 md:grid-cols-2">
<div className="col-span-1">
<Heading as="h4" className="mb-2">
{t("notification.notificationSettings.title")}
</Heading>
<div className="max-w-6xl">
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 text-sm text-primary-variant">
<p>{t("notification.notificationSettings.desc")}</p>
<div className="flex items-center text-primary">
<Link
to={getLocaleDocUrl("configuration/notifications")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</div>
<Alert variant="destructive">
<CiCircleAlert className="size-5" />
<AlertTitle>
{t("notification.notificationUnavailable.title")}
</AlertTitle>
<AlertDescription>
<Trans ns="views/settings">
notification.notificationUnavailable.desc
</Trans>
<div className="mt-3 flex items-center">
<Link
to={getLocaleDocUrl("configuration/authentication")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</AlertDescription>
</Alert>
</div>
</div>
</div>
);
}
return (
<>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto px-2 md:order-none">
<div
className={cn(
isAdmin && "grid w-full grid-cols-1 gap-4 md:grid-cols-2",
)}
>
<div className="col-span-1">
<Heading as="h4" className="mb-2">
{t("notification.notificationSettings.title")}
</Heading>
<div className="max-w-6xl">
<div className="mb-5 mt-2 flex max-w-5xl flex-col gap-2 text-sm text-primary-variant">
<p>{t("notification.notificationSettings.desc")}</p>
<div className="flex items-center text-primary">
<Link
to={getLocaleDocUrl("configuration/notifications")}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</div>
{isAdmin && (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="mt-2 space-y-6"
>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("notification.email.title")}</FormLabel>
<FormControl>
<Input
className="text-md w-full border border-input bg-background p-2 hover:bg-accent hover:text-accent-foreground dark:[color-scheme:dark] md:w-72"
placeholder={t("notification.email.placeholder")}
{...field}
/>
</FormControl>
<FormDescription>
{t("notification.email.desc")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="cameras"
render={({ field }) => (
<FormItem>
{allCameras && allCameras?.length > 0 ? (
<>
<div className="mb-2">
<FormLabel className="flex flex-row items-center text-base">
{t("notification.cameras.title")}
</FormLabel>
</div>
<div className="max-w-md space-y-2 rounded-lg bg-secondary p-4">
<FormField
control={form.control}
name="allEnabled"
render={({ field }) => (
<FilterSwitch
label={t("cameras.all.title", {
ns: "components/filter",
})}
isChecked={field.value}
onCheckedChange={(checked) => {
setChangedValue(true);
if (checked) {
form.setValue("cameras", []);
}
field.onChange(checked);
}}
/>
)}
/>
{allCameras?.map((camera) => (
<FilterSwitch
key={camera.name}
label={camera.name}
type={"camera"}
isChecked={field.value?.includes(
camera.name,
)}
onCheckedChange={(checked) => {
setChangedValue(true);
let newCameras;
if (checked) {
newCameras = [
...field.value,
camera.name,
];
} else {
newCameras = field.value?.filter(
(value) => value !== camera.name,
);
}
field.onChange(newCameras);
form.setValue("allEnabled", false);
}}
/>
))}
</div>
</>
) : (
<div className="font-normal text-destructive">
{t("notification.cameras.noCameras")}
</div>
)}
<FormMessage />
<FormDescription>
{t("notification.cameras.desc")}
</FormDescription>
</FormItem>
)}
/>
<div className="flex w-full flex-row items-center gap-2 pt-2 md:w-[50%]">
<Button
className="flex flex-1"
aria-label={t("button.cancel", { ns: "common" })}
onClick={onCancel}
type="button"
>
{t("button.cancel", { ns: "common" })}
</Button>
<Button
variant="select"
disabled={isLoading}
className="flex flex-1"
aria-label={t("button.save", { ns: "common" })}
type="submit"
>
{isLoading ? (
<div className="flex flex-row items-center gap-2">
<ActivityIndicator />
<span>{t("button.saving", { ns: "common" })}</span>
</div>
) : (
t("button.save", { ns: "common" })
)}
</Button>
</div>
</form>
</Form>
)}
</div>
<div className="col-span-1">
<div className="mt-4 gap-2 space-y-6">
<div
className={cn(
isAdmin && "flex flex-col gap-2 md:max-w-[50%]",
)}
>
<Separator
className={cn(
"my-2 flex bg-secondary",
isAdmin && "md:hidden",
)}
/>
<Heading as="h4" className={cn(isAdmin ? "my-2" : "my-4")}>
{t("notification.deviceSpecific")}
</Heading>
<Button
aria-label={t("notification.registerDevice")}
disabled={!shouldFetchPubKey || publicKey == undefined}
onClick={() => {
if (registration == null) {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
navigator.serviceWorker
.register(NOTIFICATION_SERVICE_WORKER)
.then((registration) => {
setRegistration(registration);
if (registration.active) {
subscribeToNotifications(registration);
} else {
setTimeout(
() =>
subscribeToNotifications(registration),
1000,
);
}
});
}
});
} else {
registration.pushManager
.getSubscription()
.then((pushSubscription) => {
pushSubscription?.unsubscribe();
registration.unregister();
setRegistration(null);
removeMessage(
"notification_settings",
"registration",
);
});
}
}}
>
{registration != null
? t("notification.unregisterDevice")
: t("notification.registerDevice")}
</Button>
{isAdmin && registration != null && registration.active && (
<Button
aria-label={t("notification.sendTestNotification")}
onClick={() => sendTestNotification("notification_test")}
>
{t("notification.sendTestNotification")}
</Button>
)}
</div>
</div>
{isAdmin && notificationCameras.length > 0 && (
<div className="mt-4 gap-2 space-y-6">
<div className="space-y-3">
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
{t("notification.globalSettings.title")}
</Heading>
<div className="max-w-xl">
<div className="mb-5 mt-2 flex flex-col gap-2 text-sm text-primary-variant">
<p>{t("notification.globalSettings.desc")}</p>
</div>
</div>
<div className="flex max-w-2xl flex-col gap-2.5">
<div className="rounded-lg bg-secondary p-5">
<div className="grid gap-6">
{notificationCameras.map((item) => (
<CameraNotificationSwitch
config={config}
camera={item.name}
/>
))}
</div>
</div>
</div>
</div>
</div>
)}
</div>
</div>
</div>
</div>
</>
);
}
type CameraNotificationSwitchProps = {
config?: FrigateConfig;
camera: string;
};
export function CameraNotificationSwitch({
config,
camera,
}: CameraNotificationSwitchProps) {
const { t } = useTranslation(["views/settings"]);
const { payload: notificationState, send: sendNotification } =
useNotifications(camera);
const { payload: notificationSuspendUntil, send: sendNotificationSuspend } =
useNotificationSuspend(camera);
const [isSuspended, setIsSuspended] = useState<boolean>(false);
useEffect(() => {
if (notificationSuspendUntil) {
setIsSuspended(
notificationSuspendUntil !== "0" || notificationState === "OFF",
);
}
}, [notificationSuspendUntil, notificationState]);
const handleSuspend = (duration: string) => {
setIsSuspended(true);
if (duration == "off") {
sendNotification("OFF");
} else {
sendNotificationSuspend(parseInt(duration));
}
};
const handleCancelSuspension = () => {
sendNotification("ON");
sendNotificationSuspend(0);
};
const locale = useDateLocale();
const formatSuspendedUntil = (timestamp: string) => {
// Some languages require a change in word order
if (timestamp === "0") return t("time.untilForRestart", { ns: "common" });
const time = formatUnixTimestampToDateTime(parseInt(timestamp), {
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",
}),
locale: locale,
});
return t("time.untilForTime", { ns: "common", time });
};
return (
<div className="flex items-center justify-between gap-2">
<div className="flex flex-col items-start justify-start">
<div className="flex flex-row items-center justify-start gap-3">
{!isSuspended ? (
<LuCheck className="size-6 text-success" />
) : (
<LuX className="size-6 text-danger" />
)}
<div className="flex flex-col">
<CameraNameLabel
className="text-md cursor-pointer text-primary smart-capitalize"
htmlFor="camera"
camera={camera}
/>
{!isSuspended ? (
<div className="flex flex-row items-center gap-2 text-sm text-success">
{t("notification.active")}
</div>
) : (
<div className="flex flex-row items-center gap-2 text-sm text-danger">
{t("notification.suspended", {
time: formatSuspendedUntil(notificationSuspendUntil),
})}
</div>
)}
</div>
</div>
</div>
{!isSuspended ? (
<Select onValueChange={handleSuspend}>
<SelectTrigger className="w-auto">
<SelectValue placeholder={t("notification.suspendTime.suspend")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">
{t("notification.suspendTime.5minutes")}
</SelectItem>
<SelectItem value="10">
{t("notification.suspendTime.10minutes")}
</SelectItem>
<SelectItem value="30">
{t("notification.suspendTime.30minutes")}
</SelectItem>
<SelectItem value="60">
{t("notification.suspendTime.1hour")}
</SelectItem>
<SelectItem value="840">
{t("notification.suspendTime.12hours")}
</SelectItem>
<SelectItem value="1440">
{t("notification.suspendTime.24hours")}
</SelectItem>
<SelectItem value="off">
{t("notification.suspendTime.untilRestart")}
</SelectItem>
</SelectContent>
</Select>
) : (
<Button
variant="destructive"
size="sm"
onClick={handleCancelSuspension}
>
{t("notification.cancelSuspension")}
</Button>
)}
</div>
);
}
@@ -0,0 +1,166 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { SectionConfig } from "@/components/config-form/sections";
import { ConfigSectionTemplate } from "@/components/config-form/sections";
import type { PolygonType } from "@/types/canvas";
import { Badge } from "@/components/ui/badge";
import type { ConfigSectionData } from "@/types/configForm";
import { getSectionConfig } from "@/utils/configUtil";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { Link } from "react-router-dom";
import { LuExternalLink } from "react-icons/lu";
import Heading from "@/components/ui/heading";
export type SettingsPageProps = {
selectedCamera?: string;
setUnsavedChanges?: React.Dispatch<React.SetStateAction<boolean>>;
selectedZoneMask?: PolygonType[];
onSectionStatusChange?: (
sectionKey: string,
level: "global" | "camera",
status: SectionStatus,
) => void;
pendingDataBySection?: Record<string, unknown>;
onPendingDataChange?: (
sectionKey: string,
cameraName: string | undefined,
data: ConfigSectionData | null,
) => void;
};
export type SectionStatus = {
hasChanges: boolean;
isOverridden: boolean;
hasValidationErrors: boolean;
};
export type SingleSectionPageOptions = {
sectionKey: string;
level: "global" | "camera";
sectionConfig?: SectionConfig;
requiresRestart?: boolean;
showOverrideIndicator?: boolean;
};
export type SingleSectionPageProps = SettingsPageProps &
SingleSectionPageOptions;
export function SingleSectionPage({
sectionKey,
level,
sectionConfig,
requiresRestart,
showOverrideIndicator = true,
selectedCamera,
setUnsavedChanges,
onSectionStatusChange,
pendingDataBySection,
onPendingDataChange,
}: SingleSectionPageProps) {
const sectionNamespace =
level === "camera" ? "config/cameras" : "config/global";
const { t, i18n } = useTranslation([
sectionNamespace,
"views/settings",
"common",
]);
const { getLocaleDocUrl } = useDocDomain();
const [sectionStatus, setSectionStatus] = useState<SectionStatus>({
hasChanges: false,
isOverridden: false,
hasValidationErrors: false,
});
const resolvedSectionConfig = useMemo(
() => sectionConfig ?? getSectionConfig(sectionKey, level),
[level, sectionConfig, sectionKey],
);
const sectionDocsUrl = resolvedSectionConfig.sectionDocs
? getLocaleDocUrl(resolvedSectionConfig.sectionDocs)
: undefined;
const handleSectionStatusChange = useCallback(
(status: SectionStatus) => {
setSectionStatus(status);
onSectionStatusChange?.(sectionKey, level, status);
},
[level, onSectionStatusChange, sectionKey],
);
if (level === "camera" && !selectedCamera) {
return (
<div className="flex h-full items-center justify-center text-muted-foreground">
{t("configForm.camera.noCameras", { ns: "views/settings" })}
</div>
);
}
return (
<div className="flex size-full flex-col lg:pr-2">
<div className="mb-5 flex items-center justify-between gap-4">
<div className="flex flex-col">
<Heading as="h4">
{t(`${sectionKey}.label`, { ns: sectionNamespace })}
</Heading>
{i18n.exists(`${sectionKey}.description`, {
ns: sectionNamespace,
}) && (
<div className="my-1 text-sm text-muted-foreground">
{t(`${sectionKey}.description`, { ns: sectionNamespace })}
</div>
)}
{sectionDocsUrl && (
<div className="flex items-center text-sm text-primary-variant">
<Link
to={sectionDocsUrl}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
)}
</div>
<div className="flex flex-col items-end gap-2 md:flex-row md:items-center">
<div className="flex flex-wrap items-center justify-end gap-2">
{level === "camera" &&
showOverrideIndicator &&
sectionStatus.isOverridden && (
<Badge
variant="secondary"
className="cursor-default border-2 border-selected text-xs text-primary-variant"
>
{t("button.overridden", {
ns: "common",
defaultValue: "Overridden",
})}
</Badge>
)}
{sectionStatus.hasChanges && (
<Badge
variant="secondary"
className="cursor-default bg-danger text-xs text-white hover:bg-danger"
>
{t("modified", { ns: "common", defaultValue: "Modified" })}
</Badge>
)}
</div>
</div>
</div>
<ConfigSectionTemplate
sectionKey={sectionKey}
level={level}
cameraName={level === "camera" ? selectedCamera : undefined}
showOverrideIndicator={showOverrideIndicator}
onSave={() => setUnsavedChanges?.(false)}
showTitle={false}
sectionConfig={resolvedSectionConfig}
pendingDataBySection={pendingDataBySection}
onPendingDataChange={onPendingDataChange}
requiresRestart={requiresRestart}
onStatusChange={handleSectionStatusChange}
/>
</div>
);
}
@@ -0,0 +1,88 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import Heading from "@/components/ui/heading";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import useSWR from "swr";
import type { FrigateConfig } from "@/types/frigateConfig";
import {
SettingsGroupCard,
SplitCardRow,
} from "@/components/card/SettingsGroupCard";
import {
SingleSectionPage,
type SettingsPageProps,
} from "@/views/settings/SingleSectionPage";
import FrigatePlusCurrentModelSummary from "@/views/settings/components/FrigatePlusCurrentModelSummary";
import { useTranslation } from "react-i18next";
export default function SystemDetectionModelSettingsView(
props: SettingsPageProps,
) {
const { t } = useTranslation(["config/global", "views/settings"]);
const { data: config } = useSWR<FrigateConfig>("config");
const [showModelForm, setShowModelForm] = useState(false);
const navigate = useNavigate();
if (!config) {
return <ActivityIndicator />;
}
const isPlusModelActive = Boolean(config?.model?.plus?.id);
if (!isPlusModelActive || showModelForm) {
return <SingleSectionPage sectionKey="model" level="global" {...props} />;
}
return (
<div className="flex size-full max-w-5xl flex-col lg:pr-2">
<div className="mb-5 flex items-center justify-between gap-4">
<div className="flex flex-col">
<Heading as="h4">{t("model.label", { ns: "config/global" })}</Heading>
<div className="my-1 text-sm text-muted-foreground">
{t("model.description", { ns: "config/global" })}
</div>
</div>
</div>
<div className="space-y-6">
<SettingsGroupCard
title={t("detectionModel.plusActive.title", { ns: "views/settings" })}
>
<SplitCardRow
label={t("detectionModel.plusActive.label", {
ns: "views/settings",
})}
description={t("detectionModel.plusActive.description", {
ns: "views/settings",
})}
content={
<div className="flex flex-col items-start gap-3">
<Button
variant="outline"
onClick={() => navigate("/settings?page=frigateplus")}
>
{t("detectionModel.plusActive.goToFrigatePlus", {
ns: "views/settings",
})}
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setShowModelForm(true)}
>
{t("detectionModel.plusActive.showModelForm", {
ns: "views/settings",
})}
</Button>
</div>
}
/>
</SettingsGroupCard>
<FrigatePlusCurrentModelSummary plusModel={config.model.plus} />
</div>
</div>
);
}
+276 -232
View File
@@ -1,10 +1,7 @@
import Heading from "@/components/ui/heading";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useCallback, useContext, useEffect } from "react";
import { Toaster } from "@/components/ui/sonner";
import { toast } from "sonner";
import { Separator } from "../../components/ui/separator";
import { ReactNode, useCallback, useContext, useEffect } from "react";
import { Toaster, toast } from "sonner";
import { Button } from "../../components/ui/button";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
@@ -22,28 +19,108 @@ import {
} from "../../components/ui/select";
import { useTranslation } from "react-i18next";
import { AuthContext } from "@/context/auth-context";
import {
SettingsGroupCard,
SPLIT_ROW_CLASS_NAME,
DESCRIPTION_CLASS_NAME,
CONTROL_COLUMN_CLASS_NAME,
} from "@/components/card/SettingsGroupCard";
import Heading from "@/components/ui/heading";
const PLAYBACK_RATE_DEFAULT = isSafari ? [0.5, 1, 2] : [0.5, 1, 2, 4, 8, 16];
const WEEK_STARTS_ON = ["Sunday", "Monday"];
type SwitchSettingRowProps = {
id: string;
label: string;
description: string;
checked: boolean | undefined;
onCheckedChange: (checked: boolean | undefined) => void;
};
function SwitchSettingRow({
id,
label,
description,
checked,
onCheckedChange,
}: SwitchSettingRowProps) {
return (
<div className={SPLIT_ROW_CLASS_NAME}>
<div className="space-y-1.5">
<div className="flex items-center justify-between gap-4 md:block">
<Label className="cursor-pointer" htmlFor={id}>
{label}
</Label>
<div className="md:hidden">
<Switch
id={id}
checked={checked ?? false}
onCheckedChange={onCheckedChange}
/>
</div>
</div>
<p className={DESCRIPTION_CLASS_NAME}>{description}</p>
</div>
<div className="hidden w-full md:flex md:max-w-2xl md:items-center">
<Switch
id={`${id}-desktop`}
checked={checked ?? false}
onCheckedChange={onCheckedChange}
/>
</div>
</div>
);
}
type ValueSettingRowProps = {
id: string;
label: string;
description: string;
control: ReactNode;
};
function ValueSettingRow({
id,
label,
description,
control,
}: ValueSettingRowProps) {
return (
<div className={SPLIT_ROW_CLASS_NAME}>
<div className="space-y-1.5">
<Label className="cursor-pointer" htmlFor={id}>
{label}
</Label>
<p className="hidden text-sm text-muted-foreground md:block">
{description}
</p>
</div>
<div className={`${CONTROL_COLUMN_CLASS_NAME} space-y-1.5`}>
{control}
<p className="text-sm text-muted-foreground md:hidden">{description}</p>
</div>
</div>
);
}
export default function UiSettingsView() {
const { data: config } = useSWR<FrigateConfig>("config");
const { t } = useTranslation("views/settings");
const { auth } = useContext(AuthContext);
const username = auth?.user?.username;
const PLAYBACK_RATE_DEFAULT = isSafari ? [0.5, 1, 2] : [0.5, 1, 2, 4, 8, 16];
const clearStoredLayouts = useCallback(() => {
if (!config) {
return [];
}
Object.entries(config.camera_groups).forEach(async (value) => {
await deleteUserNamespacedKey(`${value[0]}-draggable-layout`, username)
Object.entries(config.camera_groups).forEach(async ([cameraName]) => {
await deleteUserNamespacedKey(`${cameraName}-draggable-layout`, username)
.then(() => {
toast.success(
t("general.toast.success.clearStoredLayout", {
cameraName: value[0],
}),
t("general.toast.success.clearStoredLayout", { cameraName }),
{
position: "top-center",
},
@@ -69,7 +146,7 @@ export default function UiSettingsView() {
return [];
}
await deleteUserNamespacedKey(`streaming-settings`, username)
await deleteUserNamespacedKey("streaming-settings", username)
.then(() => {
toast.success(t("general.toast.success.clearStreamingSettings"), {
position: "top-center",
@@ -95,8 +172,6 @@ export default function UiSettingsView() {
document.title = t("documentTitle.general");
}, [t]);
// settings
const [autoLive, setAutoLive] = useUserPersistence("autoLiveView", true);
const [cameraNames, setCameraName] = useUserPersistence(
"displayCameraNames",
@@ -110,229 +185,198 @@ export default function UiSettingsView() {
3,
);
const liveDashboardSwitchRows = [
{
id: "auto-live",
label: t("general.liveDashboard.automaticLiveView.label"),
description: t("general.liveDashboard.automaticLiveView.desc"),
checked: autoLive,
onCheckedChange: setAutoLive,
},
{
id: "images-only",
label: t("general.liveDashboard.playAlertVideos.label"),
description: t("general.liveDashboard.playAlertVideos.desc"),
checked: alertVideos,
onCheckedChange: setAlertVideos,
},
{
id: "camera-names",
label: t("general.liveDashboard.displayCameraNames.label"),
description: t("general.liveDashboard.displayCameraNames.desc"),
checked: cameraNames,
onCheckedChange: setCameraName,
},
];
return (
<>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="scrollbar-container order-last mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2 md:order-none">
<Heading as="h4" className="mb-2">
{t("general.title")}
</Heading>
<div className="flex size-full flex-col md:pb-8">
<Toaster position="top-center" closeButton={true} />
<Heading as="h4" className="mb-3">
{t("general.title")}
</Heading>
<div className="scrollbar-container mb-2 mt-2 flex h-full w-full flex-col overflow-y-auto pb-2">
<div className="w-full max-w-5xl space-y-6">
<SettingsGroupCard title={t("general.liveDashboard.title")}>
<div className="space-y-6">
{liveDashboardSwitchRows.map((row) => (
<SwitchSettingRow key={row.id} {...row} />
))}
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
{t("general.liveDashboard.title")}
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-3">
<div className="flex flex-row items-center justify-start gap-2">
<Switch
id="auto-live"
checked={autoLive}
onCheckedChange={setAutoLive}
/>
<Label className="cursor-pointer" htmlFor="auto-live">
{t("general.liveDashboard.automaticLiveView.label")}
</Label>
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("general.liveDashboard.automaticLiveView.desc")}</p>
</div>
</div>
<div className="space-y-3">
<div className="flex flex-row items-center justify-start gap-2">
<Switch
id="images-only"
checked={alertVideos}
onCheckedChange={setAlertVideos}
/>
<Label className="cursor-pointer" htmlFor="images-only">
{t("general.liveDashboard.playAlertVideos.label")}
</Label>
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("general.liveDashboard.playAlertVideos.desc")}</p>
</div>
</div>
<div className="space-y-3">
<div className="flex flex-row items-center justify-start gap-2">
<Switch
id="camera-names"
checked={cameraNames}
onCheckedChange={setCameraName}
/>
<Label className="cursor-pointer" htmlFor="camera-names">
{t("general.liveDashboard.displayCameraNames.label")}
</Label>
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("general.liveDashboard.displayCameraNames.desc")}</p>
</div>
</div>
<div className="space-y-3">
<div className="flex flex-row items-center justify-start gap-2">
<Label
className="cursor-pointer"
htmlFor="live-fallback-timeout"
>
{t("general.liveDashboard.liveFallbackTimeout.label")}
</Label>
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("general.liveDashboard.liveFallbackTimeout.desc")}</p>
</div>
<Select
value={fallbackTimeout?.toString()}
onValueChange={(value) => setFallbackTimeout(parseInt(value))}
>
<SelectTrigger className="w-36">
{t("time.second", {
ns: "common",
time: fallbackTimeout,
count: fallbackTimeout,
})}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{[1, 2, 3, 5, 8, 10, 12, 15].map((timeout) => (
<SelectItem
key={timeout}
className="cursor-pointer"
value={timeout.toString()}
>
{t("time.second", {
ns: "common",
time: timeout,
count: timeout,
})}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>
<div className="my-3 flex w-full flex-col space-y-6">
<div className="mt-2 space-y-3">
<div className="space-y-0.5">
<div className="text-md">
{t("general.storedLayouts.title")}
</div>
<div className="my-2 text-sm text-muted-foreground">
<p>{t("general.storedLayouts.desc")}</p>
</div>
</div>
<Button
aria-label={t("general.storedLayouts.clearAll")}
onClick={clearStoredLayouts}
>
{t("general.storedLayouts.clearAll")}
</Button>
</div>
<div className="mt-2 space-y-3">
<div className="space-y-0.5">
<div className="text-md">
{t("general.cameraGroupStreaming.title")}
</div>
<div className="my-2 max-w-5xl text-sm text-muted-foreground">
<p>{t("general.cameraGroupStreaming.desc")}</p>
</div>
</div>
<Button
aria-label={t("general.cameraGroupStreaming.clearAll")}
onClick={clearStreamingSettings}
>
{t("general.cameraGroupStreaming.clearAll")}
</Button>
</div>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
{t("general.recordingsViewer.title")}
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<div className="text-md">
{t("general.recordingsViewer.defaultPlaybackRate.label")}
</div>
<div className="my-2 text-sm text-muted-foreground">
<p>
{t("general.recordingsViewer.defaultPlaybackRate.desc")}
</p>
</div>
</div>
</div>
<Select
value={playbackRate?.toString()}
onValueChange={(value) => setPlaybackRate(parseFloat(value))}
>
<SelectTrigger className="w-20">
{`${playbackRate}x`}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{PLAYBACK_RATE_DEFAULT.map((rate) => (
<SelectItem
key={rate}
className="cursor-pointer"
value={rate.toString()}
>
{rate}x
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
{t("general.calendar.title")}
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<div className="text-md">
{t("general.calendar.firstWeekday.label")}
</div>
<div className="my-2 text-sm text-muted-foreground">
<p>{t("general.calendar.firstWeekday.desc")}</p>
</div>
</div>
</div>
<Select
value={weekStartsOn?.toString()}
onValueChange={(value) => setWeekStartsOn(parseInt(value))}
>
<SelectTrigger className="w-32">
{t(
"general.calendar.firstWeekday." +
WEEK_STARTS_ON[weekStartsOn ?? 0].toLowerCase(),
<ValueSettingRow
id="live-fallback-timeout"
label={t("general.liveDashboard.liveFallbackTimeout.label")}
description={t(
"general.liveDashboard.liveFallbackTimeout.desc",
)}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{WEEK_STARTS_ON.map((day, index) => (
<SelectItem
key={index}
className="cursor-pointer"
value={index.toString()}
control={
<Select
value={fallbackTimeout?.toString()}
onValueChange={(value) =>
setFallbackTimeout(parseInt(value, 10))
}
>
<SelectTrigger
id="live-fallback-timeout"
className="w-full md:w-36"
>
{t("general.calendar.firstWeekday." + day.toLowerCase())}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<Separator className="my-2 flex bg-secondary" />
</div>
{t("time.second", {
ns: "common",
time: fallbackTimeout,
count: fallbackTimeout,
})}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{[1, 2, 3, 5, 8, 10, 12, 15].map((timeout) => (
<SelectItem
key={timeout}
className="cursor-pointer"
value={timeout.toString()}
>
{t("time.second", {
ns: "common",
time: timeout,
count: timeout,
})}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
}
/>
<ValueSettingRow
id="stored-layouts-clear"
label={t("general.storedLayouts.title")}
description={t("general.storedLayouts.desc")}
control={
<Button
id="stored-layouts-clear"
aria-label={t("general.storedLayouts.clearAll")}
className="w-full md:w-auto"
onClick={clearStoredLayouts}
>
{t("general.storedLayouts.clearAll")}
</Button>
}
/>
<ValueSettingRow
id="camera-group-streaming-clear"
label={t("general.cameraGroupStreaming.title")}
description={t("general.cameraGroupStreaming.desc")}
control={
<Button
id="camera-group-streaming-clear"
aria-label={t("general.cameraGroupStreaming.clearAll")}
className="w-full md:w-auto"
onClick={clearStreamingSettings}
>
{t("general.cameraGroupStreaming.clearAll")}
</Button>
}
/>
</div>
</SettingsGroupCard>
<SettingsGroupCard title={t("general.recordingsViewer.title")}>
<ValueSettingRow
id="default-playback-rate"
label={t("general.recordingsViewer.defaultPlaybackRate.label")}
description={t(
"general.recordingsViewer.defaultPlaybackRate.desc",
)}
control={
<Select
value={playbackRate?.toString()}
onValueChange={(value) => setPlaybackRate(parseFloat(value))}
>
<SelectTrigger
id="default-playback-rate"
className="w-full md:w-20"
>
{`${playbackRate}x`}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{PLAYBACK_RATE_DEFAULT.map((rate) => (
<SelectItem
key={rate}
className="cursor-pointer"
value={rate.toString()}
>
{rate}x
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
}
/>
</SettingsGroupCard>
<SettingsGroupCard title={t("general.calendar.title")}>
<ValueSettingRow
id="first-weekday"
label={t("general.calendar.firstWeekday.label")}
description={t("general.calendar.firstWeekday.desc")}
control={
<Select
value={weekStartsOn?.toString()}
onValueChange={(value) =>
setWeekStartsOn(parseInt(value, 10))
}
>
<SelectTrigger id="first-weekday" className="w-full md:w-32">
{t(
"general.calendar.firstWeekday." +
WEEK_STARTS_ON[weekStartsOn ?? 0].toLowerCase(),
)}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{WEEK_STARTS_ON.map((day, index) => (
<SelectItem
key={index}
className="cursor-pointer"
value={index.toString()}
>
{t(
"general.calendar.firstWeekday." +
day.toLowerCase(),
)}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
}
/>
</SettingsGroupCard>
</div>
</div>
</>
</div>
);
}
@@ -0,0 +1,61 @@
import {
SettingsGroupCard,
SplitCardRow,
} from "@/components/card/SettingsGroupCard";
import type { FrigateConfig } from "@/types/frigateConfig";
import { useTranslation } from "react-i18next";
type FrigatePlusCurrentModelSummaryProps = {
plusModel: FrigateConfig["model"]["plus"];
};
export default function FrigatePlusCurrentModelSummary({
plusModel,
}: FrigatePlusCurrentModelSummaryProps) {
const { t } = useTranslation("views/settings");
return (
<SettingsGroupCard title={t("frigatePlus.cardTitles.currentModel")}>
{plusModel === undefined && (
<p className="text-muted-foreground">
{t("frigatePlus.modelInfo.loading")}
</p>
)}
{plusModel === null && (
<p className="text-danger">{t("frigatePlus.modelInfo.error")}</p>
)}
{plusModel && (
<div className="space-y-6">
<SplitCardRow
label={t("frigatePlus.modelInfo.baseModel")}
content={
<p>
{plusModel.baseModel} (
{plusModel.isBaseModel
? t("frigatePlus.modelInfo.plusModelType.baseModel")
: t("frigatePlus.modelInfo.plusModelType.userModel")}
)
</p>
}
/>
<SplitCardRow
label={t("frigatePlus.modelInfo.trainDate")}
content={<p>{new Date(plusModel.trainDate).toLocaleString()}</p>}
/>
<SplitCardRow
label={t("frigatePlus.modelInfo.modelType")}
content={
<p>
{plusModel.name} ({plusModel.width + "x" + plusModel.height})
</p>
}
/>
<SplitCardRow
label={t("frigatePlus.modelInfo.supportedDetectors")}
content={<p>{plusModel.supportedDetectors.join(", ")}</p>}
/>
</div>
)}
</SettingsGroupCard>
);
}