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
@@ -0,0 +1,58 @@
import type {
ArrayFieldItemTemplateProps,
FormContextType,
RJSFSchema,
StrictRJSFSchema,
} from "@rjsf/utils";
import { getTemplate, getUiOptions } from "@rjsf/utils";
/**
* Custom ArrayFieldItemTemplate to ensure array item content uses full width
* while keeping action buttons aligned to the right.
*/
export function ArrayFieldItemTemplate<
T = unknown,
S extends StrictRJSFSchema = RJSFSchema,
F extends FormContextType = FormContextType,
>(props: ArrayFieldItemTemplateProps<T, S, F>) {
const {
children,
buttonsProps,
displayLabel,
hasDescription,
hasToolbar,
uiSchema,
registry,
} = props;
const uiOptions = getUiOptions<T, S, F>(uiSchema);
const ArrayFieldItemButtonsTemplate = getTemplate<
"ArrayFieldItemButtonsTemplate",
T,
S,
F
>("ArrayFieldItemButtonsTemplate", registry, uiOptions);
const margin = hasDescription ? -6 : 22;
return (
<div className="w-full">
<div className="mb-2 flex w-full flex-row items-start gap-2">
<div className="min-w-0 flex-1">{children}</div>
{hasToolbar && (
<div
className="flex shrink-0 items-start justify-end gap-2"
style={{
marginLeft: "5px",
marginTop: displayLabel ? `${margin}px` : undefined,
}}
>
<ArrayFieldItemButtonsTemplate {...buttonsProps} />
</div>
)}
</div>
</div>
);
}
export default ArrayFieldItemTemplate;
@@ -0,0 +1,60 @@
// Array Field Template - renders array fields with add/remove controls
import type { ArrayFieldTemplateProps } from "@rjsf/utils";
import { Button } from "@/components/ui/button";
import { LuPlus } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
export function ArrayFieldTemplate(props: ArrayFieldTemplateProps) {
const { items, canAdd, onAddClick, disabled, readonly, schema } = props;
const { t } = useTranslation(["common"]);
// Simple items (strings, numbers) render inline
const isSimpleType =
schema.items &&
typeof schema.items === "object" &&
"type" in schema.items &&
["string", "number", "integer", "boolean"].includes(
schema.items.type as string,
);
return (
<div className="space-y-3">
{items.length === 0 && !canAdd && (
<p className="text-sm italic text-muted-foreground">
{t("no_items", { ns: "common", defaultValue: "No items" })}
</p>
)}
{items.map((element, index) => {
// RJSF items are pre-rendered React elements, render them directly
return (
<div
key={element.key || index}
className={cn(
"flex w-full items-start gap-2",
!isSimpleType && "flex-col",
)}
>
{element}
</div>
);
})}
{canAdd && (
<Button
type="button"
variant="outline"
size="sm"
onClick={onAddClick}
disabled={disabled || readonly}
className="gap-2"
>
<LuPlus className="h-4 w-4" />
{t("button.add", { ns: "common", defaultValue: "Add" })}
</Button>
)}
</div>
);
}
@@ -0,0 +1,48 @@
// Base Input Template - default input wrapper
import type { WidgetProps } from "@rjsf/utils";
import { Input } from "@/components/ui/input";
import { getSizedFieldClassName } from "../utils";
export function BaseInputTemplate(props: WidgetProps) {
const {
id,
type,
value,
disabled,
readonly,
onChange,
onBlur,
onFocus,
placeholder,
schema,
options,
} = props;
const inputType = type || "text";
const fieldClassName = getSizedFieldClassName(options, "xs");
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value;
if (inputType === "number") {
const num = parseFloat(val);
onChange(val === "" ? undefined : isNaN(num) ? undefined : num);
} else {
onChange(val === "" ? undefined : val);
}
};
return (
<Input
id={id}
type={inputType}
className={fieldClassName}
value={value ?? ""}
disabled={disabled || readonly}
placeholder={placeholder || ""}
onChange={handleChange}
onBlur={(e) => onBlur(id, e.target.value)}
onFocus={(e) => onFocus(id, e.target.value)}
aria-label={schema.title}
/>
);
}
@@ -0,0 +1,37 @@
// Description Field Template
import type { DescriptionFieldProps } from "@rjsf/utils";
import { useTranslation } from "react-i18next";
import { ConfigFormContext } from "@/types/configForm";
export function DescriptionFieldTemplate(props: DescriptionFieldProps) {
const { description, id } = props;
const formContext = (
props as { registry?: { formContext?: ConfigFormContext } }
).registry?.formContext;
const isCameraLevel = formContext?.level === "camera";
const sectionI18nPrefix = formContext?.sectionI18nPrefix;
const effectiveNamespace = isCameraLevel ? "config/cameras" : "config/global";
const { t, i18n } = useTranslation([effectiveNamespace, "common"]);
let resolvedDescription = description;
// Support nested keys for both camera-level and consolidated global namespace
if (sectionI18nPrefix && effectiveNamespace) {
const descriptionKey = `${sectionI18nPrefix}.description`;
if (i18n.exists(descriptionKey, { ns: effectiveNamespace })) {
resolvedDescription = t(descriptionKey, { ns: effectiveNamespace });
}
}
if (!resolvedDescription) {
return null;
}
return (
<span id={id} className="text-sm text-muted-foreground">
{resolvedDescription}
</span>
);
}
@@ -0,0 +1,193 @@
// Error List Template - displays form-level errors
import type {
ErrorListProps,
RJSFSchema,
RJSFValidationError,
} from "@rjsf/utils";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { LuCircleAlert } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { buildTranslationPath, humanizeKey } from "../utils";
import type { ConfigFormContext } from "@/types/configForm";
type ErrorSchemaNode = RJSFSchema & {
properties?: Record<string, RJSFSchema>;
items?: RJSFSchema | RJSFSchema[];
additionalProperties?: boolean | RJSFSchema;
title?: string;
};
const parsePropertyPath = (property: string): Array<string | number> => {
const normalizedProperty = property.replace(/^\./, "").trim();
if (!normalizedProperty) {
return [];
}
return normalizedProperty
.split(".")
.filter(Boolean)
.map((segment) => {
const maybeIndex = Number(segment);
return Number.isInteger(maybeIndex) ? maybeIndex : segment;
});
};
const resolveSchemaNodeForPath = (
schema: RJSFSchema | undefined,
segments: Array<string | number>,
): ErrorSchemaNode | undefined => {
if (!schema) {
return undefined;
}
let currentSchema: ErrorSchemaNode | undefined = schema as ErrorSchemaNode;
for (const segment of segments) {
if (!currentSchema) {
return undefined;
}
if (typeof segment === "number") {
const items = currentSchema.items;
if (Array.isArray(items)) {
currentSchema = items[0] as ErrorSchemaNode | undefined;
} else {
currentSchema = items as ErrorSchemaNode | undefined;
}
continue;
}
const nextFromProperties = currentSchema.properties?.[segment];
if (nextFromProperties) {
currentSchema = nextFromProperties as ErrorSchemaNode;
continue;
}
const additionalProperties = currentSchema.additionalProperties;
if (
additionalProperties &&
typeof additionalProperties === "object" &&
!Array.isArray(additionalProperties)
) {
currentSchema = additionalProperties as ErrorSchemaNode;
continue;
}
return undefined;
}
return currentSchema;
};
const resolveErrorFieldLabel = ({
error,
schema,
formContext,
t,
i18n,
}: {
error: RJSFValidationError;
schema: RJSFSchema | undefined;
formContext?: ConfigFormContext;
t: (key: string, options?: Record<string, unknown>) => string;
i18n: ReturnType<typeof useTranslation>["i18n"];
}): string | undefined => {
const segments = parsePropertyPath(error.property || "");
if (segments.length === 0) {
return undefined;
}
const stringSegments = segments.filter(
(segment): segment is string => typeof segment === "string",
);
const sectionI18nPrefix = formContext?.sectionI18nPrefix;
const effectiveNamespace =
formContext?.level === "camera"
? "config/cameras"
: formContext?.i18nNamespace;
const translationPath = buildTranslationPath(
stringSegments,
sectionI18nPrefix,
formContext,
);
if (effectiveNamespace && translationPath) {
const prefixedTranslationKey =
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${translationPath}.label`
: undefined;
const translationKey = `${translationPath}.label`;
if (
prefixedTranslationKey &&
i18n.exists(prefixedTranslationKey, { ns: effectiveNamespace })
) {
return t(prefixedTranslationKey, { ns: effectiveNamespace });
}
if (i18n.exists(translationKey, { ns: effectiveNamespace })) {
return t(translationKey, { ns: effectiveNamespace });
}
}
const schemaNode = resolveSchemaNodeForPath(schema, segments);
if (schemaNode?.title && schemaNode.title.trim().length > 0) {
return schemaNode.title;
}
const fallbackSegment =
[...stringSegments].reverse().find((segment) => segment.length > 0) ||
(typeof segments[segments.length - 1] === "string"
? (segments[segments.length - 1] as string)
: undefined);
return fallbackSegment ? humanizeKey(fallbackSegment) : undefined;
};
export function ErrorListTemplate(props: ErrorListProps) {
const { errors, schema } = props;
const formContext = (
props as { registry?: { formContext?: ConfigFormContext } }
).registry?.formContext;
const { t, i18n } = useTranslation([
formContext?.level === "camera"
? "config/cameras"
: formContext?.i18nNamespace || "config/global",
"common",
]);
if (!errors || errors.length === 0) {
return null;
}
return (
<Alert variant="destructive" className="mb-4">
<LuCircleAlert className="h-4 w-4" />
<AlertTitle>{t("validation_errors", { ns: "common" })}</AlertTitle>
<AlertDescription>
<ul className="mt-2 list-inside list-disc space-y-1">
{errors.map((error: RJSFValidationError, index: number) => {
const fieldLabel = resolveErrorFieldLabel({
error,
schema,
formContext,
t,
i18n,
});
return (
<li key={index} className="text-sm">
{fieldLabel && (
<span className="font-medium">{fieldLabel}: </span>
)}
{error.message}
</li>
);
})}
</ul>
</AlertDescription>
</Alert>
);
}
@@ -0,0 +1,616 @@
// Field Template - wraps each form field with label and description
import { FieldTemplateProps, StrictRJSFSchema, UiSchema } from "@rjsf/utils";
import {
getTemplate,
getUiOptions,
ADDITIONAL_PROPERTY_FLAG,
} from "@rjsf/utils";
import { ComponentType, ReactNode } from "react";
import { isValidElement } from "react";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import { isNullableUnionSchema } from "../fields/nullableUtils";
import { getTranslatedLabel } from "@/utils/i18n";
import { ConfigFormContext } from "@/types/configForm";
import { Link } from "react-router-dom";
import { LuExternalLink } from "react-icons/lu";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { requiresRestartForFieldPath } from "@/utils/configUtil";
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
import {
buildTranslationPath,
getFilterObjectLabel,
hasOverrideAtPath,
humanizeKey,
normalizeFieldValue,
} from "../utils";
import { normalizeOverridePath } from "../utils/overrides";
import get from "lodash/get";
import isEqual from "lodash/isEqual";
import { SPLIT_ROW_CLASS_NAME } from "@/components/card/SettingsGroupCard";
function _isArrayItemInAdditionalProperty(
pathSegments: Array<string | number>,
): boolean {
// // If we find a numeric index, this is an array item
for (let i = 0; i < pathSegments.length; i++) {
const segment = pathSegments[i];
if (typeof segment === "number") {
// Consider any array item as being inside additional properties if it's not at the root level
return i > 0;
}
}
return false;
}
type FieldRenderSpec =
| ReactNode
| ComponentType<unknown>
| {
render: string;
props?: Record<string, unknown>;
};
export function FieldTemplate(props: FieldTemplateProps) {
const {
id,
label,
children,
classNames,
style,
errors,
help,
description,
hidden,
required,
displayLabel,
schema,
uiSchema,
registry,
fieldPathId,
onKeyRename,
onKeyRenameBlur,
onRemoveProperty,
rawDescription,
rawErrors,
formData: fieldFormData,
disabled,
readonly,
} = props;
// Get i18n namespace from form context (passed through registry)
const formContext = registry?.formContext as ConfigFormContext | undefined;
const i18nNamespace = formContext?.i18nNamespace as string | undefined;
const sectionI18nPrefix = formContext?.sectionI18nPrefix as
| string
| undefined;
const isCameraLevel = formContext?.level === "camera";
const effectiveNamespace = isCameraLevel ? "config/cameras" : i18nNamespace;
const { t, i18n } = useTranslation([
effectiveNamespace || i18nNamespace || "common",
i18nNamespace || "common",
"views/settings",
]);
const { getLocaleDocUrl } = useDocDomain();
if (hidden) {
return <div className="hidden">{children}</div>;
}
// Get UI options
const uiOptionsFromSchema = uiSchema?.["ui:options"] || {};
const suppressDescription = uiOptionsFromSchema.suppressDescription === true;
const showArrayItemDescription =
uiOptionsFromSchema.showArrayItemDescription === true;
// Determine field characteristics
const isBoolean =
schema.type === "boolean" ||
(Array.isArray(schema.type) && schema.type.includes("boolean"));
const isObjectField =
schema.type === "object" ||
(Array.isArray(schema.type) && schema.type.includes("object"));
const isNullableUnion = isNullableUnionSchema(schema as StrictRJSFSchema);
const isAdditionalProperty = ADDITIONAL_PROPERTY_FLAG in schema;
const suppressMultiSchema =
(uiSchema?.["ui:options"] as UiSchema["ui:options"] | undefined)
?.suppressMultiSchema === true;
const schemaTypes = Array.isArray(schema.type)
? schema.type
: schema.type
? [schema.type]
: [];
const nonNullSchemaTypes = schemaTypes.filter((type) => type !== "null");
const isScalarValueField =
nonNullSchemaTypes.length === 1 &&
["string", "number", "integer"].includes(nonNullSchemaTypes[0]);
// Only suppress labels/descriptions if this is a multi-schema field (anyOf/oneOf) with suppressMultiSchema flag
// This prevents duplicate labels while still showing the inner field's label
const isMultiSchemaWrapper =
(schema.anyOf || schema.oneOf) && (suppressMultiSchema || isNullableUnion);
const useSplitBooleanLayout =
uiOptionsFromSchema.splitLayout !== false &&
isBoolean &&
!isMultiSchemaWrapper &&
!isObjectField &&
!isAdditionalProperty;
const forceSplitLayout = uiOptionsFromSchema.forceSplitLayout === true;
const useSplitLayout =
uiOptionsFromSchema.splitLayout !== false &&
(isScalarValueField || forceSplitLayout) &&
!isBoolean &&
!isMultiSchemaWrapper &&
!isObjectField &&
!isAdditionalProperty;
// Get translation path for this field
const pathSegments = fieldPathId.path.filter(
(segment): segment is string => typeof segment === "string",
);
// Check if this is an array item inside an object with additionalProperties
const isArrayItemInAdditionalProp = _isArrayItemInAdditionalProperty(
fieldPathId.path,
);
// Conditions for showing descriptions/docs links
const shouldShowDescription =
!isMultiSchemaWrapper &&
!isObjectField &&
!isAdditionalProperty &&
(!isArrayItemInAdditionalProp || showArrayItemDescription) &&
!suppressDescription;
const translationPath = buildTranslationPath(
pathSegments,
sectionI18nPrefix,
formContext,
);
const fieldPath = fieldPathId.path;
const overrides = formContext?.overrides;
const baselineFormData = formContext?.baselineFormData;
const normalizedFieldPath = normalizeOverridePath(
fieldPath,
formContext?.formData,
);
let baselineValue = baselineFormData
? get(baselineFormData, normalizedFieldPath)
: undefined;
if (baselineValue === undefined || baselineValue === null) {
if (schema.default !== undefined && schema.default !== null) {
baselineValue = schema.default;
}
}
const isBaselineModified =
baselineFormData !== undefined &&
!isEqual(
normalizeFieldValue(fieldFormData),
normalizeFieldValue(baselineValue),
);
const isModified = baselineFormData
? isBaselineModified
: hasOverrideAtPath(overrides, fieldPath, formContext?.formData);
const filterObjectLabel = getFilterObjectLabel(pathSegments);
const translatedFilterObjectLabel = filterObjectLabel
? getTranslatedLabel(filterObjectLabel, "object")
: undefined;
const fieldDocsKey = translationPath || pathSegments.join(".");
const fieldDocsPath = fieldDocsKey
? formContext?.fieldDocs?.[fieldDocsKey]
: undefined;
const fieldDocsUrl = fieldDocsPath
? getLocaleDocUrl(fieldDocsPath)
: undefined;
const restartRequired = formContext?.restartRequired;
const defaultRequiresRestart = formContext?.requiresRestart ?? true;
const fieldRequiresRestart = requiresRestartForFieldPath(
normalizedFieldPath,
restartRequired,
defaultRequiresRestart,
);
// Use schema title/description as primary source (from JSON Schema)
const schemaTitle = schema.title;
const schemaDescription = schema.description;
// Try to get translated label, falling back to schema title, then RJSF label
let finalLabel = label;
if (effectiveNamespace && translationPath) {
// Prefer camera-scoped translations when a section prefix is provided
const prefixedTranslationKey =
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${translationPath}.label`
: undefined;
const translationKey = `${translationPath}.label`;
if (
prefixedTranslationKey &&
i18n.exists(prefixedTranslationKey, { ns: effectiveNamespace })
) {
finalLabel = t(prefixedTranslationKey, { ns: effectiveNamespace });
} else if (i18n.exists(translationKey, { ns: effectiveNamespace })) {
finalLabel = t(translationKey, { ns: effectiveNamespace });
} else if (schemaTitle) {
finalLabel = schemaTitle;
} else if (translatedFilterObjectLabel) {
const filtersIndex = pathSegments.indexOf("filters");
const isFilterObjectField =
filtersIndex > -1 && pathSegments.length === filtersIndex + 2;
if (isFilterObjectField) {
finalLabel = translatedFilterObjectLabel;
} else {
// Try to get translated field label, fall back to humanized
const fieldName = pathSegments[pathSegments.length - 1] || "";
let fieldLabel = schemaTitle;
if (!fieldLabel) {
const fieldTranslationKey = `${fieldName}.label`;
const prefixedFieldTranslationKey =
sectionI18nPrefix &&
!fieldTranslationKey.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${fieldTranslationKey}`
: undefined;
if (
prefixedFieldTranslationKey &&
effectiveNamespace &&
i18n.exists(prefixedFieldTranslationKey, { ns: effectiveNamespace })
) {
fieldLabel = t(prefixedFieldTranslationKey, {
ns: effectiveNamespace,
});
} else if (
effectiveNamespace &&
i18n.exists(fieldTranslationKey, { ns: effectiveNamespace })
) {
fieldLabel = t(fieldTranslationKey, { ns: effectiveNamespace });
} else {
fieldLabel = humanizeKey(fieldName);
}
}
if (fieldLabel) {
finalLabel = t("configForm.filters.objectFieldLabel", {
ns: "views/settings",
field: fieldLabel,
label: translatedFilterObjectLabel,
});
}
}
}
} else if (schemaTitle) {
finalLabel = schemaTitle;
} else if (translatedFilterObjectLabel) {
const filtersIndex = pathSegments.indexOf("filters");
const isFilterObjectField =
filtersIndex > -1 && pathSegments.length === filtersIndex + 2;
if (isFilterObjectField) {
finalLabel = translatedFilterObjectLabel;
} else {
// Try to get translated field label, fall back to humanized
const fieldName = pathSegments[pathSegments.length - 1] || "";
let fieldLabel = schemaTitle;
if (!fieldLabel) {
const fieldTranslationKey = `${fieldName}.label`;
const prefixedFieldTranslationKey =
sectionI18nPrefix &&
!fieldTranslationKey.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${fieldTranslationKey}`
: undefined;
if (
prefixedFieldTranslationKey &&
effectiveNamespace &&
i18n.exists(prefixedFieldTranslationKey, { ns: effectiveNamespace })
) {
fieldLabel = t(prefixedFieldTranslationKey, {
ns: effectiveNamespace,
});
} else if (
effectiveNamespace &&
i18n.exists(fieldTranslationKey, { ns: effectiveNamespace })
) {
fieldLabel = t(fieldTranslationKey, { ns: effectiveNamespace });
} else {
fieldLabel = humanizeKey(fieldName);
}
}
if (fieldLabel) {
finalLabel = t("configForm.filters.objectFieldLabel", {
ns: "views/settings",
field: fieldLabel,
label: translatedFilterObjectLabel,
});
}
}
}
// Try to get translated description, falling back to schema description
let finalDescription = description || "";
if (effectiveNamespace && translationPath) {
const prefixedDescriptionKey =
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${translationPath}.description`
: undefined;
const descriptionKey = `${translationPath}.description`;
if (
prefixedDescriptionKey &&
i18n.exists(prefixedDescriptionKey, { ns: effectiveNamespace })
) {
finalDescription = t(prefixedDescriptionKey, { ns: effectiveNamespace });
} else if (i18n.exists(descriptionKey, { ns: effectiveNamespace })) {
finalDescription = t(descriptionKey, { ns: effectiveNamespace });
} else if (schemaDescription) {
finalDescription = schemaDescription;
}
} else if (schemaDescription) {
finalDescription = schemaDescription;
}
const uiOptions = getUiOptions(uiSchema);
const beforeSpec = uiSchema?.["ui:before"] as FieldRenderSpec | undefined;
const afterSpec = uiSchema?.["ui:after"] as FieldRenderSpec | undefined;
const renderCustom = (spec: FieldRenderSpec | undefined) => {
if (spec === undefined || spec === null) {
return null;
}
if (isValidElement(spec) || typeof spec === "string") {
return spec;
}
if (typeof spec === "number") {
return <span>{spec}</span>;
}
if (typeof spec === "function") {
const SpecComponent = spec as ComponentType<unknown>;
return <SpecComponent />;
}
if (typeof spec === "object" && "render" in spec) {
const renderKey = spec.render;
const renderers = formContext?.renderers;
const RenderComponent = renderers?.[renderKey];
if (RenderComponent) {
return (
<RenderComponent {...(spec.props ?? {})} formContext={formContext} />
);
}
}
return null;
};
const beforeContent = renderCustom(beforeSpec);
const afterContent = renderCustom(afterSpec);
const WrapIfAdditionalTemplate = getTemplate(
"WrapIfAdditionalTemplate",
registry,
uiOptions,
);
const shouldRenderStandardLabel =
displayLabel &&
finalLabel &&
!isBoolean &&
!useSplitLayout &&
!isMultiSchemaWrapper &&
!isObjectField &&
!isAdditionalProperty;
const shouldRenderSplitLabel =
displayLabel &&
finalLabel &&
!isMultiSchemaWrapper &&
!isObjectField &&
!isAdditionalProperty;
const shouldRenderBooleanLabel = displayLabel && finalLabel;
const renderDocsLink = (className?: string) => {
if (!fieldDocsUrl || !shouldShowDescription) {
return null;
}
return (
<div
className={cn(
"flex items-center text-xs text-primary-variant",
className,
)}
>
<Link
to={fieldDocsUrl}
target="_blank"
rel="noopener noreferrer"
className="inline"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
);
};
const renderDescription = (className?: string) => {
if (!finalDescription || !shouldShowDescription) {
return null;
}
return (
<p className={cn("text-xs text-muted-foreground", className)}>
{finalDescription}
</p>
);
};
const renderStandardLabel = () => {
if (!shouldRenderStandardLabel) {
return null;
}
return (
<Label
htmlFor={id}
className={cn(
"text-sm font-medium",
isModified && "text-danger",
errors && errors.props?.errors?.length > 0 && "text-destructive",
)}
>
{finalLabel}
{required && <span className="ml-1 text-destructive">*</span>}
{fieldRequiresRestart && <RestartRequiredIndicator className="ml-2" />}
</Label>
);
};
const renderBooleanLabel = () => {
if (!shouldRenderBooleanLabel) {
return null;
}
return (
<Label
htmlFor={id}
className={cn("text-sm font-medium", isModified && "text-danger")}
>
{finalLabel}
{required && <span className="ml-1 text-destructive">*</span>}
{fieldRequiresRestart && <RestartRequiredIndicator className="ml-2" />}
</Label>
);
};
const renderSplitLabel = () => {
if (!shouldRenderSplitLabel) {
return null;
}
return (
<Label
htmlFor={id}
className={cn(
"text-sm font-medium",
isModified && "text-danger",
errors && errors.props?.errors?.length > 0 && "text-destructive",
)}
>
{finalLabel}
{required && <span className="ml-1 text-destructive">*</span>}
{fieldRequiresRestart && <RestartRequiredIndicator className="ml-2" />}
</Label>
);
};
const renderBooleanSplitLayout = () => (
<>
<div className="space-y-1.5 md:hidden">
<div className="flex items-center justify-between gap-4">
{renderBooleanLabel()}
<div className="flex items-center gap-2">{children}</div>
</div>
{renderDescription()}
{renderDocsLink()}
</div>
<div className={cn("hidden md:grid", SPLIT_ROW_CLASS_NAME)}>
<div className="space-y-0.5">
{renderBooleanLabel()}
{renderDescription()}
{renderDocsLink()}
</div>
<div className="w-full max-w-2xl">
<div className="flex items-center gap-2">{children}</div>
</div>
</div>
</>
);
const renderBooleanInlineLayout = () => (
<div className="flex w-full items-center justify-between gap-4">
<div className="space-y-0.5">
{renderBooleanLabel()}
{renderDescription()}
{renderDocsLink()}
</div>
<div className="flex items-center gap-2">{children}</div>
</div>
);
const renderSplitValueLayout = () => (
<div className={cn(SPLIT_ROW_CLASS_NAME, "space-y-1.5 md:space-y-3")}>
<div className="space-y-1.5">
{renderSplitLabel()}
{renderDescription("hidden md:block")}
{renderDocsLink("hidden md:flex")}
</div>
<div className="w-full max-w-2xl space-y-1">
{children}
{renderDescription("md:hidden")}
{renderDocsLink("md:hidden")}
</div>
</div>
);
const renderDefaultValueLayout = () => (
<>
{children}
{renderDescription()}
{renderDocsLink()}
</>
);
const renderFieldLayout = () => {
if (isBoolean) {
return useSplitBooleanLayout
? renderBooleanSplitLayout()
: renderBooleanInlineLayout();
}
if (useSplitLayout) {
return renderSplitValueLayout();
}
return renderDefaultValueLayout();
};
return (
<WrapIfAdditionalTemplate
classNames={classNames}
style={style}
disabled={disabled}
id={id}
label={label}
displayLabel={displayLabel}
onKeyRename={onKeyRename}
onKeyRenameBlur={onKeyRenameBlur}
onRemoveProperty={onRemoveProperty}
rawDescription={rawDescription}
readonly={readonly}
required={required}
schema={schema}
uiSchema={uiSchema}
registry={registry}
rawErrors={rawErrors}
hideError={false}
>
<div className="flex flex-col space-y-6">
{beforeContent}
<div className={cn("space-y-1")} data-field-id={translationPath}>
{renderStandardLabel()}
{renderFieldLayout()}
{errors}
{help}
</div>
{afterContent}
</div>
</WrapIfAdditionalTemplate>
);
}
@@ -0,0 +1,45 @@
// Custom MultiSchemaFieldTemplate to handle anyOf [Type, null] fields
// Renders simple nullable types as single inputs instead of dropdowns
import {
MultiSchemaFieldTemplateProps,
StrictRJSFSchema,
FormContextType,
UiSchema,
} from "@rjsf/utils";
import { isNullableUnionSchema } from "../fields/nullableUtils";
/**
* Custom MultiSchemaFieldTemplate that:
* 1. Renders simple anyOf [Type, null] fields as single inputs
* 2. Falls back to default behavior for complex types
*/
export function MultiSchemaFieldTemplate<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T = any,
S extends StrictRJSFSchema = StrictRJSFSchema,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
F extends FormContextType = any,
>(props: MultiSchemaFieldTemplateProps<T, S, F>): JSX.Element {
const { schema, selector, optionSchemaField, uiSchema } = props;
const uiOptions = uiSchema?.["ui:options"] as
| UiSchema["ui:options"]
| undefined;
const suppressMultiSchema = uiOptions?.suppressMultiSchema === true;
// Check if this is a simple nullable field that should be handled specially
if (isNullableUnionSchema(schema) || suppressMultiSchema) {
// For simple nullable fields, just render the field directly without the dropdown selector
// This handles the case where empty input = null
return <>{optionSchemaField}</>;
}
// For all other cases, render with both selector and field (default MultiSchemaField behavior)
return (
<>
{selector}
{optionSchemaField}
</>
);
}
@@ -0,0 +1,503 @@
// Object Field Template - renders nested object fields with i18n support
import type { ObjectFieldTemplateProps } from "@rjsf/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Children, useState, useEffect, useRef } from "react";
import type { ReactNode } from "react";
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
import { LuChevronDown, LuChevronRight } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { getTranslatedLabel } from "@/utils/i18n";
import { requiresRestartForFieldPath } from "@/utils/configUtil";
import { ConfigFormContext } from "@/types/configForm";
import {
buildTranslationPath,
getDomainFromNamespace,
getFilterObjectLabel,
humanizeKey,
isSubtreeModified,
} from "../utils";
import get from "lodash/get";
import { AddPropertyButton, AdvancedCollapsible } from "../components";
export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
const {
title,
description,
properties,
uiSchema,
registry,
schema,
onAddProperty,
formData,
disabled,
readonly,
} = props;
const formContext = registry?.formContext as ConfigFormContext | undefined;
// Check if this is a root-level object
const isRoot = registry?.rootSchema === schema;
const overrides = formContext?.overrides;
const baselineFormData = formContext?.baselineFormData;
const hiddenFields = formContext?.hiddenFields;
const fieldPath = props.fieldPathId.path;
const restartRequired = formContext?.restartRequired;
const defaultRequiresRestart = formContext?.requiresRestart ?? true;
// Strip fields from an object that should be excluded from modification
// detection: fields listed in hiddenFields (stripped from baseline by
// sanitizeSectionData) and fields with ui:widget=hidden in uiSchema
// (managed by custom components, not the standard form).
const stripExcludedFields = (
data: unknown,
path: Array<string | number>,
): unknown => {
if (
!data ||
typeof data !== "object" ||
Array.isArray(data) ||
data === null
) {
return data;
}
const result = { ...(data as Record<string, unknown>) };
const pathStrings = path.map(String);
// Strip hiddenFields that match the current path prefix
if (hiddenFields) {
for (const hidden of hiddenFields) {
const parts = hidden.split(".");
if (
parts.length === pathStrings.length + 1 &&
pathStrings.every((s, i) => s === parts[i])
) {
delete result[parts[parts.length - 1]];
}
}
}
// Strip ui:widget=hidden fields from uiSchema at this level
if (uiSchema) {
// Navigate to the uiSchema subtree matching the relative path
let subUiSchema = uiSchema;
const relativePath = path.slice(fieldPath.length);
for (const segment of relativePath) {
if (
typeof segment === "string" &&
subUiSchema &&
typeof subUiSchema[segment] === "object"
) {
subUiSchema = subUiSchema[segment] as typeof uiSchema;
} else {
subUiSchema = undefined as unknown as typeof uiSchema;
break;
}
}
if (subUiSchema && typeof subUiSchema === "object") {
for (const [key, propSchema] of Object.entries(subUiSchema)) {
if (
!key.startsWith("ui:") &&
typeof propSchema === "object" &&
propSchema !== null &&
(propSchema as Record<string, unknown>)["ui:widget"] === "hidden"
) {
delete result[key];
}
}
}
}
return result;
};
// Use props.formData (always up-to-date from RJSF) rather than
// formContext.formData which can be stale in parent templates.
const checkSubtreeModified = (path: Array<string | number>): boolean => {
// Compute relative path from this object's fieldPath to get the
// value from props.formData (which represents this object's data)
const relativePath = path.slice(fieldPath.length);
let currentValue =
relativePath.length > 0 ? get(formData, relativePath) : formData;
// Strip hidden/excluded fields from the RJSF data before comparing
// against the baseline (which already has these stripped)
currentValue = stripExcludedFields(currentValue, path);
let baselineValue =
path.length > 0 ? get(baselineFormData, path) : baselineFormData;
// Also strip hidden/excluded fields from the baseline so that fields
// managed by custom components (e.g. required_zones with ui:widget=hidden)
// don't cause false modification detection.
baselineValue = stripExcludedFields(baselineValue, path);
return isSubtreeModified(
currentValue,
baselineValue,
overrides,
path,
formContext?.formData,
);
};
const hasModifiedDescendants = checkSubtreeModified(fieldPath);
const [isOpen, setIsOpen] = useState(hasModifiedDescendants);
const resetKey = `${formContext?.level ?? "global"}::${
formContext?.cameraName ?? "global"
}`;
const lastResetKeyRef = useRef<string | null>(null);
// Auto-expand collapsible when modifications are detected
useEffect(() => {
if (hasModifiedDescendants) {
setIsOpen(true);
}
}, [hasModifiedDescendants]);
const isCameraLevel = formContext?.level === "camera";
const effectiveNamespace = isCameraLevel ? "config/cameras" : "config/global";
const sectionI18nPrefix = formContext?.sectionI18nPrefix;
const { t, i18n } = useTranslation([
effectiveNamespace,
"config/groups",
"views/settings",
"common",
]);
const objectRequiresRestart = requiresRestartForFieldPath(
fieldPath,
restartRequired,
defaultRequiresRestart,
);
const domain = getDomainFromNamespace(formContext?.i18nNamespace);
const groupDefinitions =
(uiSchema?.["ui:groups"] as Record<string, string[]> | undefined) || {};
const disableNestedCard =
uiSchema?.["ui:options"]?.disableNestedCard === true;
const isHiddenProp = (prop: (typeof properties)[number]) =>
prop.content.props.uiSchema?.["ui:widget"] === "hidden";
const visibleProps = properties.filter((prop) => !isHiddenProp(prop));
// Check for advanced section grouping
const advancedProps = visibleProps.filter(
(p) => p.content.props.uiSchema?.["ui:options"]?.advanced === true,
);
const regularProps = visibleProps.filter(
(p) => p.content.props.uiSchema?.["ui:options"]?.advanced !== true,
);
const hasModifiedAdvanced = advancedProps.some((prop) =>
checkSubtreeModified([...fieldPath, prop.name]),
);
const [showAdvanced, setShowAdvanced] = useState(hasModifiedAdvanced);
// Auto-expand advanced section when modifications are detected
useEffect(() => {
if (hasModifiedAdvanced) {
setShowAdvanced(true);
}
}, [hasModifiedAdvanced]);
useEffect(() => {
if (lastResetKeyRef.current !== resetKey) {
lastResetKeyRef.current = resetKey;
setIsOpen(hasModifiedDescendants);
setShowAdvanced(hasModifiedAdvanced);
}
}, [resetKey, hasModifiedDescendants, hasModifiedAdvanced]);
const { children } = props as ObjectFieldTemplateProps & {
children?: ReactNode;
};
const hasCustomChildren = Children.count(children) > 0;
// Get the full translation path from the field path
const fieldPathId = (
props as { fieldPathId?: { path?: (string | number)[] } }
).fieldPathId;
let propertyName: string | undefined;
let translationPath: string | undefined;
const path = fieldPathId?.path;
const filterObjectLabel = path ? getFilterObjectLabel(path) : undefined;
const translatedFilterLabel = filterObjectLabel
? getTranslatedLabel(filterObjectLabel, "object")
: undefined;
if (path) {
translationPath = buildTranslationPath(
path,
sectionI18nPrefix,
formContext,
);
// Also get the last property name for fallback label generation
for (let i = path.length - 1; i >= 0; i -= 1) {
const segment = path[i];
if (typeof segment === "string") {
propertyName = segment;
break;
}
}
}
// Try i18n translation, fall back to schema or original values
const i18nNs = effectiveNamespace;
let inferredLabel: string | undefined;
if (i18nNs && translationPath) {
const prefixedLabelKey =
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${translationPath}.label`
: undefined;
const labelKey = `${translationPath}.label`;
if (prefixedLabelKey && i18n.exists(prefixedLabelKey, { ns: i18nNs })) {
inferredLabel = t(prefixedLabelKey, { ns: i18nNs });
} else if (i18n.exists(labelKey, { ns: i18nNs })) {
inferredLabel = t(labelKey, { ns: i18nNs });
}
}
if (!inferredLabel && translatedFilterLabel) {
inferredLabel = translatedFilterLabel;
}
const schemaTitle = schema?.title;
const fallbackLabel =
title ||
schemaTitle ||
(propertyName ? humanizeKey(propertyName) : undefined);
inferredLabel = inferredLabel ?? fallbackLabel;
let inferredDescription: string | undefined;
if (i18nNs && translationPath) {
const prefixedDescriptionKey =
sectionI18nPrefix && !translationPath.startsWith(`${sectionI18nPrefix}.`)
? `${sectionI18nPrefix}.${translationPath}.description`
: undefined;
const descriptionKey = `${translationPath}.description`;
if (
prefixedDescriptionKey &&
i18n.exists(prefixedDescriptionKey, { ns: i18nNs })
) {
inferredDescription = t(prefixedDescriptionKey, { ns: i18nNs });
} else if (i18n.exists(descriptionKey, { ns: i18nNs })) {
inferredDescription = t(descriptionKey, { ns: i18nNs });
}
}
const schemaDescription = schema?.description;
const fallbackDescription =
(typeof description === "string" ? description : undefined) ||
schemaDescription;
inferredDescription = inferredDescription ?? fallbackDescription;
const renderGroupedFields = (items: (typeof properties)[number][]) => {
if (!items.length) {
return null;
}
const grouped = new Set<string>();
const groups = Object.entries(groupDefinitions)
.map(([groupKey, fields]) => {
const ordered = fields
.map((field) => items.find((item) => item.name === field))
.filter(Boolean) as (typeof properties)[number][];
if (ordered.length === 0) {
return null;
}
ordered.forEach((item) => grouped.add(item.name));
const label = domain
? t(`${sectionI18nPrefix}.${domain}.${groupKey}`, {
ns: "config/groups",
defaultValue: humanizeKey(groupKey),
})
: t(`groups.${groupKey}`, {
defaultValue: humanizeKey(groupKey),
});
return {
key: groupKey,
label,
items: ordered,
};
})
.filter(Boolean) as Array<{
key: string;
label: string;
items: (typeof properties)[number][];
}>;
const ungrouped = items.filter((item) => !grouped.has(item.name));
const isObjectLikeField = (item: (typeof properties)[number]) => {
const fieldSchema = item.content.props.schema as
| { type?: string | string[] }
| undefined;
return fieldSchema?.type === "object";
};
return (
<div className="space-y-6">
{groups.map((group) => (
<div
key={group.key}
className="space-y-4 rounded-lg border border-border/70 bg-card/30 p-4"
>
<div className="text-md border-b border-border/60 pb-4 font-semibold text-primary-variant">
{group.label}
</div>
<div className="space-y-6">
{group.items.map((element) => (
<div key={element.name}>{element.content}</div>
))}
</div>
</div>
))}
{ungrouped.length > 0 && (
<div className={cn("space-y-6", groups.length > 0 && "pt-2")}>
{ungrouped.map((element) => (
<div
key={element.name}
className={cn(
groups.length > 0 && !isObjectLikeField(element) && "px-4",
)}
>
{element.content}
</div>
))}
</div>
)}
</div>
);
};
// Root level renders children directly
if (isRoot) {
return (
<div className="space-y-6">
{hasCustomChildren ? (
children
) : (
<>
{renderGroupedFields(regularProps)}
<AddPropertyButton
onAddProperty={onAddProperty}
schema={schema}
uiSchema={uiSchema}
formData={formData}
disabled={disabled}
readonly={readonly}
/>
<AdvancedCollapsible
count={advancedProps.length}
open={showAdvanced}
onOpenChange={setShowAdvanced}
isRoot
>
{renderGroupedFields(advancedProps)}
</AdvancedCollapsible>
</>
)}
</div>
);
}
if (disableNestedCard) {
return (
<div className="space-y-4">
{hasCustomChildren ? (
children
) : (
<>
{renderGroupedFields(regularProps)}
<AddPropertyButton
onAddProperty={onAddProperty}
schema={schema}
uiSchema={uiSchema}
formData={formData}
disabled={disabled}
readonly={readonly}
/>
<AdvancedCollapsible
count={advancedProps.length}
open={showAdvanced}
onOpenChange={setShowAdvanced}
>
{renderGroupedFields(advancedProps)}
</AdvancedCollapsible>
</>
)}
</div>
);
}
// Nested objects render as collapsible cards
return (
<Card className="w-full">
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<CollapsibleTrigger asChild>
<CardHeader className="cursor-pointer p-4 transition-colors hover:bg-muted/50">
<div className="flex items-center justify-between">
<div>
<CardTitle
className={cn(
"flex items-center text-sm",
hasModifiedDescendants && "text-danger",
)}
>
{inferredLabel}
{objectRequiresRestart && (
<RestartRequiredIndicator className="ml-2" />
)}
</CardTitle>
{inferredDescription && (
<p className="mt-1 text-xs text-muted-foreground">
{inferredDescription}
</p>
)}
</div>
{isOpen ? (
<LuChevronDown className="h-4 w-4" />
) : (
<LuChevronRight className="h-4 w-4" />
)}
</div>
</CardHeader>
</CollapsibleTrigger>
<CollapsibleContent>
<CardContent className="space-y-6 p-4 pt-0">
{hasCustomChildren ? (
children
) : (
<>
{renderGroupedFields(regularProps)}
<AddPropertyButton
onAddProperty={onAddProperty}
schema={schema}
uiSchema={uiSchema}
formData={formData}
disabled={disabled}
readonly={readonly}
/>
<AdvancedCollapsible
count={advancedProps.length}
open={showAdvanced}
onOpenChange={setShowAdvanced}
>
{renderGroupedFields(advancedProps)}
</AdvancedCollapsible>
</>
)}
</CardContent>
</CollapsibleContent>
</Collapsible>
</Card>
);
}
@@ -0,0 +1,17 @@
// Title Field Template
import type { TitleFieldProps } from "@rjsf/utils";
export function TitleFieldTemplate(props: TitleFieldProps) {
const { title, id, required } = props;
if (!title) {
return null;
}
return (
<h3 id={id} className="text-lg font-semibold">
{title}
{required && <span className="ml-1 text-destructive">*</span>}
</h3>
);
}
@@ -0,0 +1,123 @@
import {
ADDITIONAL_PROPERTY_FLAG,
FormContextType,
getUiOptions,
RJSFSchema,
StrictRJSFSchema,
WrapIfAdditionalTemplateProps,
} from "@rjsf/utils";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import { LuTrash2 } from "react-icons/lu";
export function WrapIfAdditionalTemplate<
T = unknown,
S extends StrictRJSFSchema = RJSFSchema,
F extends FormContextType = FormContextType,
>(props: WrapIfAdditionalTemplateProps<T, S, F>) {
const {
classNames,
style,
children,
disabled,
id,
label,
displayLabel,
onRemoveProperty,
onKeyRenameBlur,
readonly,
required,
schema,
uiSchema,
} = props;
const { t } = useTranslation(["views/settings"]);
const additional = ADDITIONAL_PROPERTY_FLAG in schema;
if (!additional) {
return (
<div className={classNames} style={style}>
{children}
</div>
);
}
const keyId = `${id}-key`;
const keyLabel = t("configForm.additionalProperties.keyLabel", {
ns: "views/settings",
});
const valueLabel = t("configForm.additionalProperties.valueLabel", {
ns: "views/settings",
});
const keyPlaceholder = t("configForm.additionalProperties.keyPlaceholder", {
ns: "views/settings",
});
const removeLabel = t("configForm.additionalProperties.remove", {
ns: "views/settings",
});
const uiOptions = getUiOptions(uiSchema);
const keyIsReadonly = uiOptions.additionalPropertyKeyReadonly === true;
return (
<div
className={cn("grid grid-cols-12 items-start gap-2", classNames)}
style={style}
>
{!keyIsReadonly && (
<div className="col-span-12 space-y-2 md:col-span-2">
{displayLabel && <Label htmlFor={keyId}>{keyLabel}</Label>}
{keyIsReadonly ? (
<div
id={keyId}
className="flex items-center text-sm text-muted-foreground"
>
{label}
</div>
) : (
<Input
id={keyId}
name={keyId}
required={required}
defaultValue={label}
placeholder={keyPlaceholder}
disabled={disabled || readonly}
onBlur={!readonly ? onKeyRenameBlur : undefined}
/>
)}
</div>
)}
<div
className={cn(
"col-span-12 space-y-2",
!keyIsReadonly && "md:col-span-9",
)}
>
{!keyIsReadonly && displayLabel && (
<Label htmlFor={id}>{valueLabel}</Label>
)}
<div className="min-w-0">{children}</div>
</div>
{!keyIsReadonly && (
<div className="col-span-12 flex items-center md:col-span-1 md:justify-center">
<Button
type="button"
variant="ghost"
size="icon"
onClick={onRemoveProperty}
disabled={disabled || readonly}
aria-label={removeLabel}
title={removeLabel}
>
<LuTrash2 className="h-4 w-4" />
</Button>
</div>
)}
</div>
);
}
export default WrapIfAdditionalTemplate;