section fields

This commit is contained in:
Josh Hawkins 2026-01-23 10:04:50 -06:00
parent 737de2f53a
commit 0280c2ec43
13 changed files with 478 additions and 305 deletions

View File

@ -43,6 +43,8 @@ export interface ConfigFormProps {
liveValidate?: boolean;
/** Form context passed to all widgets */
formContext?: Record<string, unknown>;
/** i18n namespace for field labels */
i18nNamespace?: string;
}
export function ConfigForm({
@ -61,8 +63,9 @@ export function ConfigForm({
className,
liveValidate = false,
formContext,
i18nNamespace,
}: ConfigFormProps) {
const { t } = useTranslation(["views/settings"]);
const { t } = useTranslation([i18nNamespace || "common", "views/settings"]);
const [showAdvanced, setShowAdvanced] = useState(false);
// Determine which fields to hide based on advanced toggle
@ -81,8 +84,16 @@ export function ConfigForm({
fieldOrder,
hiddenFields: effectiveHiddenFields,
advancedFields: showAdvanced ? advancedFields : [],
i18nNamespace,
}),
[schema, fieldOrder, effectiveHiddenFields, advancedFields, showAdvanced],
[
schema,
fieldOrder,
effectiveHiddenFields,
advancedFields,
showAdvanced,
i18nNamespace,
],
);
// Merge generated uiSchema with custom overrides
@ -116,6 +127,16 @@ export function ConfigForm({
const hasAdvancedFields = advancedFields && advancedFields.length > 0;
// Extended form context with i18n info
const extendedFormContext = useMemo(
() => ({
...formContext,
i18nNamespace,
t,
}),
[formContext, i18nNamespace, t],
);
return (
<div className={cn("config-form", className)}>
{hasAdvancedFields && (
@ -130,6 +151,7 @@ export function ConfigForm({
className="cursor-pointer text-sm text-muted-foreground"
>
{t("configForm.showAdvanced", {
ns: "views/settings",
defaultValue: "Show Advanced Settings",
})}
</Label>
@ -146,7 +168,7 @@ export function ConfigForm({
disabled={disabled}
readonly={readonly}
liveValidate={liveValidate}
formContext={formContext}
formContext={extendedFormContext}
transformErrors={errorTransformer}
{...frigateTheme}
/>

View File

@ -1,10 +1,12 @@
// Audio Section Component
// Reusable for both global and camera-level audio settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the audio section
export const audioSectionConfig: SectionConfig = {
export const AudioSection = createConfigSection({
sectionPath: "audio",
i18nNamespace: "config/audio",
defaultConfig: {
fieldOrder: [
"enabled",
"listen",
@ -19,12 +21,7 @@ export const audioSectionConfig: SectionConfig = {
},
hiddenFields: ["enabled_in_config"],
advancedFields: ["min_volume", "max_not_heard", "num_threads"],
};
export const AudioSection = createConfigSection({
sectionPath: "audio",
translationKey: "configForm.audio",
defaultConfig: audioSectionConfig,
},
});
export default AudioSection;

View File

@ -1,7 +1,7 @@
// Base Section Component for config form sections
// Used as a foundation for reusable section components
import { useMemo, useCallback } from "react";
import { useMemo, useCallback, useState } from "react";
import useSWR from "swr";
import axios from "axios";
import { toast } from "sonner";
@ -10,11 +10,22 @@ import { ConfigForm } from "../ConfigForm";
import { useConfigOverride } from "@/hooks/use-config-override";
import { useSectionSchema } from "@/hooks/use-config-schema";
import type { FrigateConfig } from "@/types/frigateConfig";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { LuRotateCcw } from "react-icons/lu";
import {
LuRotateCcw,
LuSave,
LuChevronDown,
LuChevronRight,
} from "react-icons/lu";
import Heading from "@/components/ui/heading";
import get from "lodash/get";
import isEqual from "lodash/isEqual";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
export interface SectionConfig {
/** Field ordering within the section */
@ -44,13 +55,19 @@ export interface BaseSectionProps {
onSave?: () => void;
/** Whether a restart is required after changes */
requiresRestart?: boolean;
/** Whether section is collapsible */
collapsible?: boolean;
/** Default collapsed state */
defaultCollapsed?: boolean;
/** Whether to show the section title (default: false for global, true for camera) */
showTitle?: boolean;
}
export interface CreateSectionOptions {
/** The config path for this section (e.g., "detect", "record") */
sectionPath: string;
/** Translation key prefix for this section */
translationKey: string;
/** i18n namespace for this section (e.g., "config/detect") */
i18nNamespace: string;
/** Default section configuration */
defaultConfig: SectionConfig;
}
@ -60,10 +77,10 @@ export interface CreateSectionOptions {
*/
export function createConfigSection({
sectionPath,
translationKey,
i18nNamespace,
defaultConfig,
}: CreateSectionOptions) {
return function ConfigSection({
const ConfigSection = function ConfigSection({
level,
cameraName,
showOverrideIndicator = true,
@ -72,8 +89,20 @@ export function createConfigSection({
readonly = false,
onSave,
requiresRestart = true,
collapsible = false,
defaultCollapsed = false,
showTitle,
}: BaseSectionProps) {
const { t } = useTranslation(["views/settings"]);
const { t } = useTranslation([i18nNamespace, "views/settings", "common"]);
const [isOpen, setIsOpen] = useState(!defaultCollapsed);
const [pendingData, setPendingData] = useState<Record<
string,
unknown
> | null>(null);
const [isSaving, setIsSaving] = useState(false);
// Default: show title for camera level (since it might be collapsible), hide for global
const shouldShowTitle = showTitle ?? level === "camera";
// Fetch config
const { data: config, mutate: refreshConfig } =
@ -83,8 +112,7 @@ export function createConfigSection({
const sectionSchema = useSectionSchema(sectionPath, level);
// Get override status
const { isOverridden, globalValue, cameraValue, resetToGlobal } =
useConfigOverride({
const { isOverridden, globalValue, cameraValue } = useConfigOverride({
config,
cameraName: level === "camera" ? cameraName : undefined,
sectionPath,
@ -101,9 +129,22 @@ export function createConfigSection({
return get(config, sectionPath) || {};
}, [config, level, cameraName]);
// Handle form submission
const handleSubmit = useCallback(
async (data: Record<string, unknown>) => {
// Track if there are unsaved changes
const hasChanges = useMemo(() => {
if (!pendingData) return false;
return !isEqual(formData, pendingData);
}, [formData, pendingData]);
// Handle form data change
const handleChange = useCallback((data: Record<string, unknown>) => {
setPendingData(data);
}, []);
// Handle save button click
const handleSave = useCallback(async () => {
if (!pendingData) return;
setIsSaving(true);
try {
const basePath =
level === "camera" && cameraName
@ -113,23 +154,24 @@ export function createConfigSection({
await axios.put("config/set", {
requires_restart: requiresRestart ? 1 : 0,
config_data: {
[basePath]: data,
[basePath]: pendingData,
},
});
toast.success(
t(`${translationKey}.toast.success`, {
t("toast.success", {
ns: "views/settings",
defaultValue: "Settings saved successfully",
}),
);
setPendingData(null);
refreshConfig();
onSave?.();
} catch (error) {
// Parse Pydantic validation errors from API response
if (axios.isAxiosError(error) && error.response?.data) {
const responseData = error.response.data;
// Pydantic errors come as { detail: [...] } or { message: "..." }
if (responseData.detail && Array.isArray(responseData.detail)) {
const validationMessages = responseData.detail
.map((err: { loc?: string[]; msg?: string }) => {
@ -138,7 +180,8 @@ export function createConfigSection({
})
.join(", ");
toast.error(
t(`${translationKey}.toast.validationError`, {
t("toast.validationError", {
ns: "views/settings",
defaultValue: `Validation failed: ${validationMessages}`,
}),
);
@ -146,70 +189,203 @@ export function createConfigSection({
toast.error(responseData.message);
} else {
toast.error(
t(`${translationKey}.toast.error`, {
t("toast.error", {
ns: "views/settings",
defaultValue: "Failed to save settings",
}),
);
}
} else {
toast.error(
t(`${translationKey}.toast.error`, {
t("toast.error", {
ns: "views/settings",
defaultValue: "Failed to save settings",
}),
);
}
} finally {
setIsSaving(false);
}
},
[level, cameraName, requiresRestart, t, refreshConfig, onSave],
);
}, [
pendingData,
level,
cameraName,
requiresRestart,
t,
refreshConfig,
onSave,
]);
// Handle reset to global
// Handle reset to global - removes camera-level override by deleting the section
const handleResetToGlobal = useCallback(async () => {
if (level !== "camera" || !cameraName) return;
try {
const basePath = `cameras.${cameraName}.${sectionPath}`;
// Reset by setting to null/undefined or removing the override
// Send empty string to delete the key from config (see update_yaml in backend)
await axios.put("config/set", {
requires_restart: requiresRestart ? 1 : 0,
config_data: {
[basePath]: resetToGlobal(),
[basePath]: "",
},
});
toast.success(
t(`${translationKey}.toast.resetSuccess`, {
t("toast.resetSuccess", {
ns: "views/settings",
defaultValue: "Reset to global defaults",
}),
);
setPendingData(null);
refreshConfig();
} catch {
toast.error(
t(`${translationKey}.toast.resetError`, {
t("toast.resetError", {
ns: "views/settings",
defaultValue: "Failed to reset settings",
}),
);
}
}, [level, cameraName, requiresRestart, t, refreshConfig, resetToGlobal]);
}, [level, cameraName, requiresRestart, t, refreshConfig]);
if (!sectionSchema) {
return null;
}
const title = t(`${translationKey}.title`, {
defaultValue: sectionPath.charAt(0).toUpperCase() + sectionPath.slice(1),
// Get section title from config namespace
const title = t("label", {
ns: i18nNamespace,
defaultValue:
sectionPath.charAt(0).toUpperCase() +
sectionPath.slice(1).replace(/_/g, " "),
});
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
const sectionContent = (
<div className="space-y-6">
<ConfigForm
schema={sectionSchema}
formData={pendingData || formData}
onChange={handleChange}
fieldOrder={sectionConfig.fieldOrder}
hiddenFields={sectionConfig.hiddenFields}
advancedFields={sectionConfig.advancedFields}
disabled={disabled || isSaving}
readonly={readonly}
showSubmit={false}
i18nNamespace={i18nNamespace}
formContext={{
level,
cameraName,
globalValue,
cameraValue,
}}
/>
{/* Save button */}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2">
<CardTitle className="text-lg">{title}</CardTitle>
{hasChanges && (
<span className="text-sm text-muted-foreground">
{t("unsavedChanges", {
ns: "views/settings",
defaultValue: "You have unsaved changes",
})}
</span>
)}
</div>
<Button
onClick={handleSave}
disabled={!hasChanges || isSaving || disabled}
className="gap-2"
>
<LuSave className="h-4 w-4" />
{isSaving
? t("saving", { ns: "common", defaultValue: "Saving..." })
: t("save", { ns: "common", defaultValue: "Save" })}
</Button>
</div>
</div>
);
if (collapsible) {
return (
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<div className="space-y-3">
<CollapsibleTrigger asChild>
<div className="flex cursor-pointer items-center justify-between">
<div className="flex items-center gap-3">
{isOpen ? (
<LuChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<LuChevronRight className="h-4 w-4 text-muted-foreground" />
)}
<Heading as="h4">{title}</Heading>
{showOverrideIndicator &&
level === "camera" &&
isOverridden && (
<Badge variant="secondary" className="text-xs">
{t("overridden", {
ns: "common",
defaultValue: "Overridden",
})}
</Badge>
)}
{hasChanges && (
<Badge variant="outline" className="text-xs">
{t("modified", {
ns: "common",
defaultValue: "Modified",
})}
</Badge>
)}
</div>
{level === "camera" && isOverridden && (
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleResetToGlobal();
}}
className="gap-2"
>
<LuRotateCcw className="h-4 w-4" />
{t("button.resetToGlobal", {
ns: "common",
defaultValue: "Reset to Global",
})}
</Button>
)}
</div>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="pl-7">{sectionContent}</div>
</CollapsibleContent>
</div>
</Collapsible>
);
}
return (
<div className="space-y-3">
{shouldShowTitle && (
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Heading as="h4">{title}</Heading>
{showOverrideIndicator && level === "camera" && isOverridden && (
<Badge variant="secondary" className="text-xs">
{t("common.overridden", { defaultValue: "Overridden" })}
{t("overridden", {
ns: "common",
defaultValue: "Overridden",
})}
</Badge>
)}
{hasChanges && (
<Badge variant="outline" className="text-xs">
{t("modified", { ns: "common", defaultValue: "Modified" })}
</Badge>
)}
</div>
@ -221,29 +397,37 @@ export function createConfigSection({
className="gap-2"
>
<LuRotateCcw className="h-4 w-4" />
{t("common.resetToGlobal", { defaultValue: "Reset to Global" })}
{t("button.resetToGlobal", {
ns: "common",
defaultValue: "Reset to Global",
})}
</Button>
)}
</CardHeader>
<CardContent>
<ConfigForm
schema={sectionSchema}
formData={formData}
onSubmit={handleSubmit}
fieldOrder={sectionConfig.fieldOrder}
hiddenFields={sectionConfig.hiddenFields}
advancedFields={sectionConfig.advancedFields}
disabled={disabled}
readonly={readonly}
formContext={{
level,
cameraName,
globalValue,
cameraValue,
}}
/>
</CardContent>
</Card>
</div>
)}
{/* Reset button when title is hidden but we're at camera level with override */}
{!shouldShowTitle && level === "camera" && isOverridden && (
<div className="flex justify-end">
<Button
variant="ghost"
size="sm"
onClick={handleResetToGlobal}
className="gap-2"
>
<LuRotateCcw className="h-4 w-4" />
{t("button.resetToGlobal", {
ns: "common",
defaultValue: "Reset to Global",
})}
</Button>
</div>
)}
{sectionContent}
</div>
);
};
return ConfigSection;
}

View File

@ -1,10 +1,12 @@
// Detect Section Component
// Reusable for both global and camera-level detect settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the detect section
export const detectSectionConfig: SectionConfig = {
export const DetectSection = createConfigSection({
sectionPath: "detect",
i18nNamespace: "config/detect",
defaultConfig: {
fieldOrder: [
"enabled",
"fps",
@ -26,12 +28,7 @@ export const detectSectionConfig: SectionConfig = {
"annotation_offset",
"stationary",
],
};
export const DetectSection = createConfigSection({
sectionPath: "detect",
translationKey: "configForm.detect",
defaultConfig: detectSectionConfig,
},
});
export default DetectSection;

View File

@ -1,20 +1,17 @@
// Live Section Component
// Reusable for both global and camera-level live settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the live section
export const liveSectionConfig: SectionConfig = {
export const LiveSection = createConfigSection({
sectionPath: "live",
i18nNamespace: "config/live",
defaultConfig: {
fieldOrder: ["stream_name", "height", "quality"],
fieldGroups: {},
hiddenFields: ["enabled_in_config"],
advancedFields: ["quality"],
};
export const LiveSection = createConfigSection({
sectionPath: "live",
translationKey: "configForm.live",
defaultConfig: liveSectionConfig,
},
});
export default LiveSection;

View File

@ -1,10 +1,12 @@
// Motion Section Component
// Reusable for both global and camera-level motion settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the motion section
export const motionSectionConfig: SectionConfig = {
export const MotionSection = createConfigSection({
sectionPath: "motion",
i18nNamespace: "config/motion",
defaultConfig: {
fieldOrder: [
"enabled",
"threshold",
@ -31,12 +33,7 @@ export const motionSectionConfig: SectionConfig = {
"frame_height",
"mqtt_off_delay",
],
};
export const MotionSection = createConfigSection({
sectionPath: "motion",
translationKey: "configForm.motion",
defaultConfig: motionSectionConfig,
},
});
export default MotionSection;

View File

@ -1,20 +1,17 @@
// Notifications Section Component
// Reusable for both global and camera-level notification settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the notifications section
export const notificationsSectionConfig: SectionConfig = {
export const NotificationsSection = createConfigSection({
sectionPath: "notifications",
i18nNamespace: "config/notifications",
defaultConfig: {
fieldOrder: ["enabled", "email"],
fieldGroups: {},
hiddenFields: ["enabled_in_config"],
advancedFields: [],
};
export const NotificationsSection = createConfigSection({
sectionPath: "notifications",
translationKey: "configForm.notifications",
defaultConfig: notificationsSectionConfig,
},
});
export default NotificationsSection;

View File

@ -1,10 +1,12 @@
// Objects Section Component
// Reusable for both global and camera-level objects settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the objects section
export const objectsSectionConfig: SectionConfig = {
export const ObjectsSection = createConfigSection({
sectionPath: "objects",
i18nNamespace: "config/objects",
defaultConfig: {
fieldOrder: ["track", "alert", "detect", "filters", "mask"],
fieldGroups: {
tracking: ["track", "alert", "detect"],
@ -12,12 +14,7 @@ export const objectsSectionConfig: SectionConfig = {
},
hiddenFields: ["enabled_in_config"],
advancedFields: ["filters", "mask"],
};
export const ObjectsSection = createConfigSection({
sectionPath: "objects",
translationKey: "configForm.objects",
defaultConfig: objectsSectionConfig,
},
});
export default ObjectsSection;

View File

@ -1,10 +1,12 @@
// Record Section Component
// Reusable for both global and camera-level record settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the record section
export const recordSectionConfig: SectionConfig = {
export const RecordSection = createConfigSection({
sectionPath: "record",
i18nNamespace: "config/record",
defaultConfig: {
fieldOrder: [
"enabled",
"expire_interval",
@ -21,12 +23,7 @@ export const recordSectionConfig: SectionConfig = {
},
hiddenFields: ["enabled_in_config"],
advancedFields: ["expire_interval", "preview", "export"],
};
export const RecordSection = createConfigSection({
sectionPath: "record",
translationKey: "configForm.record",
defaultConfig: recordSectionConfig,
},
});
export default RecordSection;

View File

@ -1,20 +1,17 @@
// Review Section Component
// Reusable for both global and camera-level review settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the review section
export const reviewSectionConfig: SectionConfig = {
export const ReviewSection = createConfigSection({
sectionPath: "review",
i18nNamespace: "config/review",
defaultConfig: {
fieldOrder: ["alerts", "detections"],
fieldGroups: {},
hiddenFields: ["enabled_in_config"],
advancedFields: [],
};
export const ReviewSection = createConfigSection({
sectionPath: "review",
translationKey: "configForm.review",
defaultConfig: reviewSectionConfig,
},
});
export default ReviewSection;

View File

@ -1,10 +1,12 @@
// Snapshots Section Component
// Reusable for both global and camera-level snapshots settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the snapshots section
export const snapshotsSectionConfig: SectionConfig = {
export const SnapshotsSection = createConfigSection({
sectionPath: "snapshots",
i18nNamespace: "config/snapshots",
defaultConfig: {
fieldOrder: [
"enabled",
"bounding_box",
@ -18,12 +20,7 @@ export const snapshotsSectionConfig: SectionConfig = {
},
hiddenFields: ["enabled_in_config"],
advancedFields: ["quality", "retain"],
};
export const SnapshotsSection = createConfigSection({
sectionPath: "snapshots",
translationKey: "configForm.snapshots",
defaultConfig: snapshotsSectionConfig,
},
});
export default SnapshotsSection;

View File

@ -1,22 +1,19 @@
// Timestamp Section Component
// Reusable for both global and camera-level timestamp_style settings
import { createConfigSection, type SectionConfig } from "./BaseSection";
import { createConfigSection } from "./BaseSection";
// Configuration for the timestamp_style section
export const timestampSectionConfig: SectionConfig = {
export const TimestampSection = createConfigSection({
sectionPath: "timestamp_style",
i18nNamespace: "config/timestamp_style",
defaultConfig: {
fieldOrder: ["position", "format", "color", "thickness", "effect"],
fieldGroups: {
appearance: ["color", "thickness", "effect"],
},
hiddenFields: ["enabled_in_config"],
advancedFields: ["thickness", "effect"],
};
export const TimestampSection = createConfigSection({
sectionPath: "timestamp_style",
translationKey: "configForm.timestampStyle",
defaultConfig: timestampSectionConfig,
},
});
export default TimestampSection;

View File

@ -8,16 +8,13 @@ export {
type CreateSectionOptions,
} from "./BaseSection";
export { DetectSection, detectSectionConfig } from "./DetectSection";
export { RecordSection, recordSectionConfig } from "./RecordSection";
export { SnapshotsSection, snapshotsSectionConfig } from "./SnapshotsSection";
export { MotionSection, motionSectionConfig } from "./MotionSection";
export { ObjectsSection, objectsSectionConfig } from "./ObjectsSection";
export { ReviewSection, reviewSectionConfig } from "./ReviewSection";
export { AudioSection, audioSectionConfig } from "./AudioSection";
export {
NotificationsSection,
notificationsSectionConfig,
} from "./NotificationsSection";
export { LiveSection, liveSectionConfig } from "./LiveSection";
export { TimestampSection, timestampSectionConfig } from "./TimestampSection";
export { DetectSection } from "./DetectSection";
export { RecordSection } from "./RecordSection";
export { SnapshotsSection } from "./SnapshotsSection";
export { MotionSection } from "./MotionSection";
export { ObjectsSection } from "./ObjectsSection";
export { ReviewSection } from "./ReviewSection";
export { AudioSection } from "./AudioSection";
export { NotificationsSection } from "./NotificationsSection";
export { LiveSection } from "./LiveSection";
export { TimestampSection } from "./TimestampSection";