Masks and zones improvements (#22163)

* migrator and runtime config changes

* component changes to use rasterized_mask

* frontend

* convert none to empty string for config save

* i18n

* update tests

* add enabled config to zones

* zones frontend

* i18n

* docs

* tweaks

* use dashed stroke to indicate disabled

* allow toggle from icon

* use filelock to ensure atomic config updates from endpoint

* enforce atomic config update in the frontend

* toggle via mqtt

* fix global object masks

* correctly handle global object masks in dispatcher

* ws hooks

* render masks and zones based on ws enabled state

* use enabled_in_config for zones and masks

* frontend for enabled_in_config

* tweaks

* i18n

* publish websocket on config save

* i18n tweaks

* pydantic title and description

* i18n generation

* tweaks

* fix typing
This commit is contained in:
Josh Hawkins
2026-02-28 07:04:43 -07:00
committed by GitHub
parent fa1f9a1fa4
commit 6a21b2952d
37 changed files with 1964 additions and 739 deletions
+268 -124
View File
@@ -20,11 +20,7 @@ import { FaDrawPolygon, FaObjectGroup } from "react-icons/fa";
import { BsPersonBoundingBox } from "react-icons/bs";
import { HiOutlineDotsVertical, HiTrash } from "react-icons/hi";
import { isDesktop, isMobile } from "react-device-detect";
import {
flattenPoints,
parseCoordinates,
toRGBColorString,
} from "@/utils/canvasUtil";
import { toRGBColorString } from "@/utils/canvasUtil";
import { Polygon, PolygonType } from "@/types/canvas";
import { useCallback, useMemo, useState } from "react";
import axios from "axios";
@@ -36,6 +32,9 @@ import { reviewQueries } from "@/utils/zoneEdutUtil";
import IconWrapper from "../ui/icon-wrapper";
import { buttonVariants } from "../ui/button";
import { Trans, useTranslation } from "react-i18next";
import ActivityIndicator from "../indicators/activity-indicator";
import { cn } from "@/lib/utils";
import { useMotionMaskState, useObjectMaskState, useZoneState } from "@/api/ws";
type PolygonItemProps = {
polygon: Polygon;
@@ -45,6 +44,10 @@ type PolygonItemProps = {
setActivePolygonIndex: (index: number | undefined) => void;
setEditPane: (type: PolygonType) => void;
handleCopyCoordinates: (index: number) => void;
isLoading: boolean;
setIsLoading: (loading: boolean) => void;
loadingPolygonIndex: number | undefined;
setLoadingPolygonIndex: (index: number | undefined) => void;
};
export default function PolygonItem({
@@ -55,12 +58,40 @@ export default function PolygonItem({
setActivePolygonIndex,
setEditPane,
handleCopyCoordinates,
isLoading,
setIsLoading,
loadingPolygonIndex,
setLoadingPolygonIndex,
}: PolygonItemProps) {
const { t } = useTranslation("views/settings");
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const { payload: motionMaskState, send: sendMotionMaskState } =
useMotionMaskState(polygon.camera, polygon.name);
const { payload: objectMaskState, send: sendObjectMaskState } =
useObjectMaskState(polygon.camera, polygon.name);
const { payload: zoneState, send: sendZoneState } = useZoneState(
polygon.camera,
polygon.name,
);
const isPolygonEnabled = useMemo(() => {
const wsState =
polygon.type === "zone"
? zoneState
: polygon.type === "motion_mask"
? motionMaskState
: objectMaskState;
const wsEnabled =
wsState === "ON" ? true : wsState === "OFF" ? false : undefined;
return wsEnabled ?? polygon.enabled ?? true;
}, [
polygon.enabled,
polygon.type,
zoneState,
motionMaskState,
objectMaskState,
]);
const cameraConfig = useMemo(() => {
if (polygon?.camera && config) {
@@ -81,93 +112,6 @@ export default function PolygonItem({
if (!polygon || !cameraConfig) {
return;
}
let url = "";
if (polygon.type == "zone") {
const { alertQueries, detectionQueries } = reviewQueries(
polygon.name,
false,
false,
polygon.camera,
cameraConfig?.review.alerts.required_zones || [],
cameraConfig?.review.detections.required_zones || [],
);
url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}`;
}
if (polygon.type == "motion_mask") {
const filteredMask = (
Array.isArray(cameraConfig.motion.mask)
? cameraConfig.motion.mask
: [cameraConfig.motion.mask]
).filter((_, currentIndex) => currentIndex !== polygon.typeIndex);
url = filteredMask
.map((pointsArray) => {
const coordinates = flattenPoints(
parseCoordinates(pointsArray),
).join(",");
return `cameras.${polygon?.camera}.motion.mask=${coordinates}&`;
})
.join("");
if (!url) {
// deleting last mask
url = `cameras.${polygon?.camera}.motion.mask&`;
}
}
if (polygon.type == "object_mask") {
let configObject;
let globalMask = false;
// global mask on camera for all objects
if (!polygon.objects.length) {
configObject = cameraConfig.objects.mask;
globalMask = true;
} else {
configObject = cameraConfig.objects.filters[polygon.objects[0]].mask;
}
if (!configObject) {
return;
}
const globalObjectMasksArray = Array.isArray(cameraConfig.objects.mask)
? cameraConfig.objects.mask
: cameraConfig.objects.mask
? [cameraConfig.objects.mask]
: [];
let filteredMask;
if (globalMask) {
filteredMask = (
Array.isArray(configObject) ? configObject : [configObject]
).filter((_, currentIndex) => currentIndex !== polygon.typeIndex);
} else {
filteredMask = (
Array.isArray(configObject) ? configObject : [configObject]
)
.filter((mask) => !globalObjectMasksArray.includes(mask))
.filter((_, currentIndex) => currentIndex !== polygon.typeIndex);
}
url = filteredMask
.map((pointsArray) => {
const coordinates = flattenPoints(
parseCoordinates(pointsArray),
).join(",");
return globalMask
? `cameras.${polygon?.camera}.objects.mask=${coordinates}&`
: `cameras.${polygon?.camera}.objects.filters.${polygon.objects[0]}.mask=${coordinates}&`;
})
.join("");
if (!url) {
// deleting last mask
url = globalMask
? `cameras.${polygon?.camera}.objects.mask&`
: `cameras.${polygon?.camera}.objects.filters.${polygon.objects[0]}.mask`;
}
}
const updateTopicType =
polygon.type === "zone"
@@ -179,9 +123,117 @@ export default function PolygonItem({
: polygon.type;
setIsLoading(true);
setLoadingPolygonIndex(index);
if (polygon.type === "zone") {
// Zones use query string format
const { alertQueries, detectionQueries } = reviewQueries(
polygon.name,
false,
false,
polygon.camera,
cameraConfig?.review.alerts.required_zones || [],
cameraConfig?.review.detections.required_zones || [],
);
const url = `cameras.${polygon.camera}.zones.${polygon.name}${alertQueries}${detectionQueries}`;
await axios
.put(`config/set?${url}`, {
requires_restart: 0,
update_topic: `config/cameras/${polygon.camera}/${updateTopicType}`,
})
.then((res) => {
if (res.status === 200) {
toast.success(
t("masksAndZones.form.polygonDrawing.delete.success", {
name: polygon?.friendly_name ?? polygon?.name,
}),
{ position: "top-center" },
);
updateConfig();
} else {
toast.error(
t("toast.save.error.title", {
ns: "common",
errorMessage: res.statusText,
}),
{ 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);
});
return;
}
// Motion masks and object masks use JSON body format
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let configUpdate: any = {};
if (polygon.type === "motion_mask") {
// Delete mask from motion.mask dict by setting it to undefined
configUpdate = {
cameras: {
[polygon.camera]: {
motion: {
mask: {
[polygon.name]: null, // Setting to null will delete the key
},
},
},
},
};
}
if (polygon.type === "object_mask") {
// Determine if this is a global mask or object-specific mask
const isGlobalMask = !polygon.objects.length;
if (isGlobalMask) {
configUpdate = {
cameras: {
[polygon.camera]: {
objects: {
mask: {
[polygon.name]: null, // Setting to null will delete the key
},
},
},
},
};
} else {
configUpdate = {
cameras: {
[polygon.camera]: {
objects: {
filters: {
[polygon.objects[0]]: {
mask: {
[polygon.name]: null, // Setting to null will delete the key
},
},
},
},
},
},
};
}
}
await axios
.put(`config/set?${url}`, {
.put("config/set", {
config_data: configUpdate,
requires_restart: 0,
update_topic: `config/cameras/${polygon.camera}/${updateTopicType}`,
})
@@ -191,9 +243,7 @@ export default function PolygonItem({
t("masksAndZones.form.polygonDrawing.delete.success", {
name: polygon?.friendly_name ?? polygon?.name,
}),
{
position: "top-center",
},
{ position: "top-center" },
);
updateConfig();
} else {
@@ -202,9 +252,7 @@ export default function PolygonItem({
ns: "common",
errorMessage: res.statusText,
}),
{
position: "top-center",
},
{ position: "top-center" },
);
}
})
@@ -215,16 +263,22 @@ export default function PolygonItem({
"Unknown error";
toast.error(
t("toast.save.error.title", { errorMessage, ns: "common" }),
{
position: "top-center",
},
{ position: "top-center" },
);
})
.finally(() => {
setIsLoading(false);
setLoadingPolygonIndex(undefined);
});
},
[updateConfig, cameraConfig, t],
[
updateConfig,
cameraConfig,
t,
setIsLoading,
index,
setLoadingPolygonIndex,
],
);
const handleDelete = () => {
@@ -232,6 +286,43 @@ export default function PolygonItem({
saveToConfig(polygon);
};
const handleToggleEnabled = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation();
// Prevent toggling if disabled in config
if (polygon.enabled_in_config === false) {
return;
}
if (!polygon) {
return;
}
const isEnabled = isPolygonEnabled;
const nextState = isEnabled ? "OFF" : "ON";
if (polygon.type === "zone") {
sendZoneState(nextState);
return;
}
if (polygon.type === "motion_mask") {
sendMotionMaskState(nextState);
return;
}
if (polygon.type === "object_mask") {
sendObjectMaskState(nextState);
}
},
[
isPolygonEnabled,
polygon,
sendZoneState,
sendMotionMaskState,
sendObjectMaskState,
],
);
return (
<>
<Toaster position="top-center" closeButton={true} />
@@ -256,17 +347,52 @@ export default function PolygonItem({
: "text-primary-variant"
}`}
>
{PolygonItemIcon && (
<PolygonItemIcon
className="mr-2 size-5"
style={{
fill: toRGBColorString(polygon.color, true),
color: toRGBColorString(polygon.color, true),
}}
/>
)}
<p className="cursor-default">
{PolygonItemIcon &&
(isLoading && loadingPolygonIndex === index ? (
<div className="mr-2">
<ActivityIndicator className="size-5" />
</div>
) : (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={handleToggleEnabled}
disabled={isLoading || polygon.enabled_in_config === false}
className="mr-2 cursor-pointer border-none bg-transparent p-0 transition-opacity hover:opacity-70 disabled:cursor-not-allowed disabled:opacity-50"
>
<PolygonItemIcon
className="size-5"
style={{
fill: toRGBColorString(polygon.color, isPolygonEnabled),
color: toRGBColorString(
polygon.color,
isPolygonEnabled,
),
}}
/>
</button>
</TooltipTrigger>
<TooltipContent>
{polygon.enabled_in_config === false
? t("masksAndZones.disabledInConfig", {
ns: "views/settings",
})
: isPolygonEnabled
? t("button.disable", { ns: "common" })
: t("button.enable", { ns: "common" })}
</TooltipContent>
</Tooltip>
))}
<p
className={cn(
"cursor-default",
!isPolygonEnabled && "opacity-60",
polygon.enabled_in_config === false && "line-through",
)}
>
{polygon.friendly_name ?? polygon.name}
{!isPolygonEnabled && " (disabled)"}
</p>
</div>
<AlertDialog
@@ -316,6 +442,7 @@ export default function PolygonItem({
<DropdownMenuContent>
<DropdownMenuItem
aria-label={t("button.edit", { ns: "common" })}
disabled={isLoading}
onClick={() => {
setActivePolygonIndex(index);
setEditPane(polygon.type);
@@ -325,6 +452,7 @@ export default function PolygonItem({
</DropdownMenuItem>
<DropdownMenuItem
aria-label={t("button.copy", { ns: "common" })}
disabled={isLoading}
onClick={() => handleCopyCoordinates(index)}
>
{t("button.copy", { ns: "common" })}
@@ -346,10 +474,17 @@ export default function PolygonItem({
<TooltipTrigger asChild>
<IconWrapper
icon={LuPencil}
className={`size-[15px] cursor-pointer ${hoveredPolygonIndex === index && "text-primary-variant"}`}
disabled={isLoading}
className={cn(
"size-[15px] cursor-pointer",
hoveredPolygonIndex === index && "text-primary-variant",
isLoading && "cursor-not-allowed opacity-50",
)}
onClick={() => {
setActivePolygonIndex(index);
setEditPane(polygon.type);
if (!isLoading) {
setActivePolygonIndex(index);
setEditPane(polygon.type);
}
}}
/>
</TooltipTrigger>
@@ -362,10 +497,16 @@ export default function PolygonItem({
<TooltipTrigger asChild>
<IconWrapper
icon={LuCopy}
className={`size-[15px] cursor-pointer ${
hoveredPolygonIndex === index && "text-primary-variant"
}`}
onClick={() => handleCopyCoordinates(index)}
className={cn(
"size-[15px] cursor-pointer",
hoveredPolygonIndex === index && "text-primary-variant",
isLoading && "cursor-not-allowed opacity-50",
)}
onClick={() => {
if (!isLoading) {
handleCopyCoordinates(index);
}
}}
/>
</TooltipTrigger>
<TooltipContent>
@@ -377,10 +518,13 @@ export default function PolygonItem({
<TooltipTrigger asChild>
<IconWrapper
icon={HiTrash}
className={`size-[15px] cursor-pointer ${
disabled={isLoading}
className={cn(
"size-[15px] cursor-pointer",
hoveredPolygonIndex === index &&
"fill-primary-variant text-primary-variant"
}`}
"fill-primary-variant text-primary-variant",
isLoading && "cursor-not-allowed opacity-50",
)}
onClick={() => !isLoading && setDeleteDialogOpen(true)}
/>
</TooltipTrigger>