edit pane

This commit is contained in:
Josh Hawkins 2024-04-11 22:53:50 -05:00
parent bd64e6f873
commit 30c2762e53
9 changed files with 465 additions and 225 deletions

2
web/package-lock.json generated
View File

@ -9,7 +9,7 @@
"version": "0.0.0",
"dependencies": {
"@cycjimmy/jsmpeg-player": "^6.0.5",
"@hookform/resolvers": "^3.3.2",
"@hookform/resolvers": "^3.3.4",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-aspect-ratio": "^1.0.3",
"@radix-ui/react-context-menu": "^2.1.5",

View File

@ -14,7 +14,7 @@
},
"dependencies": {
"@cycjimmy/jsmpeg-player": "^6.0.5",
"@hookform/resolvers": "^3.3.2",
"@hookform/resolvers": "^3.3.4",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-aspect-ratio": "^1.0.3",
"@radix-ui/react-context-menu": "^2.1.5",

View File

@ -1,12 +1,4 @@
import { Separator } from "@/components/ui/separator";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
@ -16,14 +8,17 @@ import { PolygonCanvas } from "./PolygonCanvas";
import { Polygon } from "@/types/canvas";
import { interpolatePoints, toRGBColorString } from "@/utils/canvasUtil";
import { isDesktop } from "react-device-detect";
import ZoneControls, {
NewZoneButton,
ZoneObjectSelector,
} from "./NewZoneButton";
import { NewZoneButton } from "./NewZoneButton";
import { Skeleton } from "../ui/skeleton";
import { useResizeObserver } from "@/hooks/resize-observer";
import { LuCopy, LuPencil, LuPlusSquare, LuTrash } from "react-icons/lu";
import { LuCopy, LuPencil, LuTrash } from "react-icons/lu";
import { FaDrawPolygon } from "react-icons/fa";
import copy from "copy-to-clipboard";
import { toast } from "sonner";
import { Toaster } from "../ui/sonner";
import Heading from "../ui/heading";
import { Input } from "../ui/input";
import { ZoneEditPane } from "./ZoneEditPane";
const parseCoordinates = (coordinatesString: string) => {
const coordinates = coordinatesString.split(",");
@ -56,10 +51,14 @@ export default function MasksAndZones({
const { data: config } = useSWR<FrigateConfig>("config");
const [zonePolygons, setZonePolygons] = useState<Polygon[]>([]);
const [zoneObjects, setZoneObjects] = useState<ZoneObjects[]>([]);
const [activePolygonIndex, setActivePolygonIndex] = useState<number | null>(
null,
);
const [activePolygonIndex, setActivePolygonIndex] = useState<
number | undefined
>(undefined);
const containerRef = useRef<HTMLDivElement | null>(null);
const editViews = ["zone", "motion_mask", "object_mask", undefined] as const;
type EditPaneType = (typeof editViews)[number];
const [editPane, setEditPane] = useState<EditPaneType>(undefined);
const cameras = useMemo(() => {
if (!config) {
@ -77,22 +76,6 @@ export default function MasksAndZones({
}
}, [config, selectedCamera]);
const allLabels = useMemo<string[]>(() => {
if (!cameras) {
return [];
}
const labels = new Set<string>();
cameras.forEach((camera) => {
camera.objects.track.forEach((label) => {
labels.add(label);
});
});
return [...labels].sort();
}, [cameras]);
// const saveZoneObjects = useCallback(
// (camera: string, zoneName: string, newObjects?: string[]) => {
// setZoneObjects((prevZoneObjects) =>
@ -243,6 +226,23 @@ export default function MasksAndZones({
[scaledHeight, aspectRatio],
);
const handleCopyCoordinates = useCallback(
(index: number) => {
if (zonePolygons) {
const poly = zonePolygons[index];
copy(
interpolatePoints(poly.points, scaledWidth, scaledHeight, 1, 1)
.map((point) => `${point[0]},${point[1]}`)
.join(","),
);
toast.success(`Copied coordinates for ${poly.name} to clipboard.`);
} else {
toast.error("Could not copy coordinates to clipboard.");
}
},
[zonePolygons, scaledHeight, scaledWidth],
);
useEffect(() => {
if (cameraConfig && containerRef.current) {
setZonePolygons(
@ -273,21 +273,21 @@ export default function MasksAndZones({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cameraConfig, containerRef]);
useEffect(() => {
console.log(
"config zone objects",
Object.entries(cameraConfig.zones).map(([name, zoneData]) => ({
camera: cameraConfig.name,
zoneName: name,
objects: Object.keys(zoneData.filters),
})),
);
console.log("component zone objects", zoneObjects);
}, [zoneObjects]);
// useEffect(() => {
// console.log(
// "config zone objects",
// Object.entries(cameraConfig.zones).map(([name, zoneData]) => ({
// camera: cameraConfig.name,
// zoneName: name,
// objects: Object.keys(zoneData.filters),
// })),
// );
// console.log("component zone objects", zoneObjects);
// }, [zoneObjects]);
useEffect(() => {
if (selectedCamera) {
setActivePolygonIndex(null);
setActivePolygonIndex(undefined);
}
}, [selectedCamera]);
@ -297,73 +297,122 @@ export default function MasksAndZones({
return (
<>
{cameraConfig && (
{cameraConfig && zonePolygons && (
<div className="flex flex-col md:flex-row size-full">
<div className="flex flex-col order-last w-full md:w-3/12 md:order-none md:mr-2">
<div className="flex mb-3">
<Toaster position="top-center" />
<div className="flex flex-col order-last w-full overflow-y-auto md:w-3/12 md:order-none md:mr-2 rounded-lg border-secondary-foreground border-[1px] p-2 bg-background_alt">
{/* <div className="flex mb-3">
<Separator />
</div>
<div className="flex flex-row justify-between items-center mb-3">
<div className="text-md">Zones</div>
<NewZoneButton
camera={cameraConfig.name}
</div> */}
{editPane == "zone" && (
<ZoneEditPane
polygons={zonePolygons}
setPolygons={setZonePolygons}
activePolygonIndex={activePolygonIndex}
setActivePolygonIndex={setActivePolygonIndex}
/>
</div>
{zonePolygons.map((polygon, index) => (
<div
key={index}
className="flex p-1 rounded-lg flex-row items-center justify-between mx-2 mb-1"
style={{
backgroundColor:
activePolygonIndex === index
? toRGBColorString(polygon.color, false)
: "",
onCancel={() => {
setEditPane(undefined);
setActivePolygonIndex(undefined);
}}
>
<div
className={`flex items-center ${activePolygonIndex === index ? "text-primary" : "text-secondary-foreground"}`}
>
<FaDrawPolygon
className="size-4 mr-2"
style={{
fill: toRGBColorString(polygon.color, true),
color: toRGBColorString(polygon.color, true),
}}
/>
)}
{editPane == "motion_mask" && (
<ZoneEditPane
polygons={zonePolygons}
activePolygonIndex={activePolygonIndex}
onCancel={() => {
setEditPane(undefined);
setActivePolygonIndex(undefined);
}}
/>
)}
{editPane == "object_mask" && (
<ZoneEditPane
polygons={zonePolygons}
activePolygonIndex={activePolygonIndex}
onCancel={() => {
setEditPane(undefined);
setActivePolygonIndex(undefined);
}}
/>
)}
{editPane == undefined && (
<>
<div className="flex flex-row justify-between items-center mb-3">
<div className="text-md">Zones</div>
<NewZoneButton
camera={cameraConfig.name}
polygons={zonePolygons}
setPolygons={setZonePolygons}
activePolygonIndex={activePolygonIndex}
setActivePolygonIndex={setActivePolygonIndex}
/>
{polygon.name}
</div>
<div className="flex flex-row gap-2">
{zonePolygons.map((polygon, index) => (
<div
className="cursor-pointer"
onClick={() => setActivePolygonIndex(index)}
key={index}
className="flex p-1 rounded-lg flex-row items-center justify-between mx-2 mb-1"
// style={{
// backgroundColor:
// activePolygonIndex === index
// ? toRGBColorString(polygon.color, false)
// : "",
// }}
>
<LuPencil
className={`size-4 ${activePolygonIndex === index ? "text-primary" : "text-secondary-foreground"}`}
/>
<div
className={`flex items-center ${activePolygonIndex === index ? "text-primary" : "text-muted-foreground"}`}
>
<FaDrawPolygon
className="size-4 mr-2"
style={{
fill: toRGBColorString(polygon.color, true),
color: toRGBColorString(polygon.color, true),
}}
/>
<p>{polygon.name}</p>
</div>
<div className="flex flex-row gap-2">
<div
className="cursor-pointer"
onClick={() => {
setActivePolygonIndex(index);
setEditPane("zone");
// if (activePolygonIndex == index) {
// setActivePolygonIndex(null);
// } else {
// setActivePolygonIndex(index);
// }
}}
>
<LuPencil
className={`size-4 ${activePolygonIndex === index ? "text-primary" : "text-muted-foreground"}`}
/>
</div>
<div
className="cursor-pointer"
onClick={() => handleCopyCoordinates(index)}
>
<LuCopy
className={`size-4 ${activePolygonIndex === index ? "text-primary" : "text-muted-foreground"}`}
/>
</div>
<div
className="cursor-pointer"
onClick={() => {
setZonePolygons((oldPolygons) => {
return oldPolygons.filter((_, i) => i !== index);
});
setActivePolygonIndex(undefined);
}}
>
<LuTrash
className={`size-4 ${activePolygonIndex === index ? "text-primary fill-primary" : "text-muted-foreground fill-muted-foreground"}`}
/>
</div>
</div>
</div>
<LuCopy
className={`size-4 ${activePolygonIndex === index ? "text-primary" : "text-secondary-foreground"}`}
/>
<div
className="cursor-pointer"
onClick={() => {
setZonePolygons((oldPolygons) => {
return oldPolygons.filter((_, i) => i !== index);
});
setActivePolygonIndex(null);
}}
>
<LuTrash
className={`size-4 ${activePolygonIndex === index ? "text-primary fill-primary" : "text-secondary-foreground fill-secondary-foreground"}`}
/>
</div>
</div>
</div>
))}
))}
</>
)}
{/* <Table>
<TableHeader>
<TableRow>
@ -446,7 +495,7 @@ export default function MasksAndZones({
</div>
<div
ref={containerRef}
className="flex md:w-7/12 md:grow md:h-dvh md:max-h-[90%]"
className="flex md:w-7/12 md:grow md:h-dvh md:max-h-full"
>
<div className="size-full">
{cameraConfig ? (

View File

@ -18,115 +18,6 @@ import useSWR from "swr";
import { isMobile } from "react-device-detect";
import { LuPlusSquare } from "react-icons/lu";
type ZoneObjectSelectorProps = {
camera: string;
zoneName: string;
allLabels: string[];
updateLabelFilter: (labels: string[] | undefined) => void;
};
export function ZoneObjectSelector({
camera,
zoneName,
allLabels,
updateLabelFilter,
}: ZoneObjectSelectorProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const [open, setOpen] = useState(false);
const cameraConfig = useMemo(() => {
if (config && camera) {
return config.cameras[camera];
}
}, [config, camera]);
const zoneLabels = useMemo<string[]>(() => {
if (!cameraConfig || !zoneName) {
return [];
}
const labels = new Set<string>();
cameraConfig.objects.track.forEach((label) => {
if (!ATTRIBUTES.includes(label)) {
labels.add(label);
}
});
if (cameraConfig.zones[zoneName]) {
cameraConfig.zones[zoneName].objects.forEach((label) => {
if (!ATTRIBUTES.includes(label)) {
labels.add(label);
}
});
}
return [...labels].sort() || [];
}, [cameraConfig, zoneName]);
const [currentLabels, setCurrentLabels] = useState<string[] | undefined>(
zoneLabels,
);
const trigger = (
<Button
className={`flex items-center gap-2 capitalize ${false ? "bg-selected hover:bg-selected" : ""}`}
size="sm"
>
<FaObjectGroup
className={`${false ? "text-background dark:text-primary" : "text-secondary-foreground"}`}
/>
</Button>
);
const content = (
<GeneralFilterContent
allLabels={allLabels}
selectedLabels={zoneLabels}
currentLabels={currentLabels}
updateLabelFilter={updateLabelFilter}
setCurrentLabels={setCurrentLabels}
onClose={() => setOpen(false)}
/>
);
if (isMobile) {
return (
<Drawer
open={open}
onOpenChange={(open) => {
if (!open) {
setCurrentLabels(zoneLabels);
}
setOpen(open);
}}
>
<DrawerTrigger asChild>{trigger}</DrawerTrigger>
<DrawerContent className="max-h-[75dvh] overflow-hidden">
{content}
</DrawerContent>
</Drawer>
);
}
return (
<Popover
open={open}
onOpenChange={(open) => {
if (!open) {
setCurrentLabels(zoneLabels);
}
setOpen(open);
}}
>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent>{content}</PopoverContent>
</Popover>
);
}
type NewZoneButtonProps = {
camera: string;
polygons: Polygon[];

View File

@ -12,7 +12,7 @@ type PolygonCanvasProps = {
height: number;
polygons: Polygon[];
setPolygons: React.Dispatch<React.SetStateAction<Polygon[]>>;
activePolygonIndex: number | null;
activePolygonIndex: number | undefined;
};
export function PolygonCanvas({
@ -68,7 +68,7 @@ export function PolygonCanvas({
};
const handleMouseDown = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
if (activePolygonIndex == null || !polygons) {
if (!activePolygonIndex || !polygons) {
return;
}
@ -103,7 +103,7 @@ export function PolygonCanvas({
const handleMouseOverStartPoint = (
e: KonvaEventObject<MouseEvent | TouchEvent>,
) => {
if (activePolygonIndex == null || !polygons) {
if (!activePolygonIndex || !polygons) {
return;
}
@ -118,7 +118,7 @@ export function PolygonCanvas({
) => {
e.currentTarget.scale({ x: 1, y: 1 });
if (activePolygonIndex == null || !polygons) {
if (!activePolygonIndex || !polygons) {
return;
}
@ -134,7 +134,7 @@ export function PolygonCanvas({
const handlePointDragMove = (
e: KonvaEventObject<MouseEvent | TouchEvent>,
) => {
if (activePolygonIndex == null || !polygons) {
if (!activePolygonIndex || !polygons) {
return;
}
@ -165,7 +165,7 @@ export function PolygonCanvas({
};
const handleGroupDragEnd = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
if (activePolygonIndex !== null && e.target.name() === "polygon") {
if (activePolygonIndex && e.target.name() === "polygon") {
const updatedPolygons = [...polygons];
const activePolygon = updatedPolygons[activePolygonIndex];
const result: number[][] = [];

View File

@ -99,7 +99,7 @@ export default function PolygonDrawer({
stroke={colorString(true)}
strokeWidth={3}
closed={isFinished}
fill={colorString(false)}
fill={colorString(isActive ? true : false)}
/>
{points.map((point, index) => {
if (!isActive) {
@ -122,9 +122,9 @@ export default function PolygonDrawer({
x={x}
y={y}
radius={vertexRadius}
fill={colorString(false)}
stroke="#cccccc"
strokeWidth={2}
stroke={colorString(true)}
fill="#ffffff"
strokeWidth={3}
draggable={isActive}
onDragMove={isActive ? handlePointDragMove : undefined}
dragBoundFunc={(pos) => {

View File

@ -0,0 +1,300 @@
import Heading from "../ui/heading";
import { Separator } from "../ui/separator";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { Drawer, DrawerContent, DrawerTrigger } from "../ui/drawer";
import { useEffect, useMemo, useState } from "react";
import { GeneralFilterContent } from "../filter/ReviewFilterGroup";
import { FaObjectGroup } from "react-icons/fa";
import { ATTRIBUTES, FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import { isMobile } from "react-device-detect";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Polygon } from "@/types/canvas";
import { Switch } from "../ui/switch";
import { Label } from "../ui/label";
type ZoneObjectSelectorProps = {
camera: string;
zoneName: string;
updateLabelFilter: (labels: string[] | undefined) => void;
};
export function ZoneObjectSelector({
camera,
zoneName,
updateLabelFilter,
}: ZoneObjectSelectorProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const cameraConfig = useMemo(() => {
if (config && camera) {
return config.cameras[camera];
}
}, [config, camera]);
const allLabels = useMemo<string[]>(() => {
if (!config) {
return [];
}
const labels = new Set<string>();
Object.values(config.cameras).forEach((camera) => {
camera.objects.track.forEach((label) => {
if (!ATTRIBUTES.includes(label)) {
labels.add(label);
}
});
});
return [...labels].sort();
}, [config]);
const zoneLabels = useMemo<string[]>(() => {
if (!cameraConfig || !zoneName) {
return [];
}
const labels = new Set<string>();
cameraConfig.objects.track.forEach((label) => {
if (!ATTRIBUTES.includes(label)) {
labels.add(label);
}
});
if (cameraConfig.zones[zoneName]) {
cameraConfig.zones[zoneName].objects.forEach((label) => {
if (!ATTRIBUTES.includes(label)) {
labels.add(label);
}
});
}
return [...labels].sort() || [];
}, [cameraConfig, zoneName]);
const [currentLabels, setCurrentLabels] = useState<string[] | undefined>(
zoneLabels,
);
useEffect(() => {
updateLabelFilter(currentLabels);
}, [currentLabels, updateLabelFilter]);
return (
<>
<div className="h-auto overflow-y-auto overflow-x-hidden">
<div className="flex justify-between items-center my-2.5">
<Label
className="mx-2 text-primary cursor-pointer"
htmlFor="allLabels"
>
All Labels
</Label>
<Switch
className="ml-1"
id="allLabels"
checked={currentLabels == undefined}
onCheckedChange={(isChecked) => {
if (isChecked) {
setCurrentLabels(undefined);
}
}}
/>
</div>
<Separator />
<div className="my-2.5 flex flex-col gap-2.5">
{allLabels.map((item) => (
<div key={item} className="flex justify-between items-center">
<Label
className="w-full mx-2 text-primary capitalize cursor-pointer"
htmlFor={item}
>
{item.replaceAll("_", " ")}
</Label>
<Switch
key={item}
className="ml-1"
id={item}
checked={currentLabels?.includes(item) ?? false}
onCheckedChange={(isChecked) => {
if (isChecked) {
const updatedLabels = currentLabels
? [...currentLabels]
: [];
updatedLabels.push(item);
setCurrentLabels(updatedLabels);
} else {
const updatedLabels = currentLabels
? [...currentLabels]
: [];
// can not deselect the last item
if (updatedLabels.length > 1) {
updatedLabels.splice(updatedLabels.indexOf(item), 1);
setCurrentLabels(updatedLabels);
}
}
}}
/>
</div>
))}
</div>
</div>
</>
);
}
const formSchema = z.object({
name: z.string().min(2, {
message: "Zone name must be at least 2 characters.",
}),
inertia: z.number(),
loitering_time: z.number(),
});
type ZoneEditPaneProps = {
polygons: Polygon[];
activePolygonIndex?: number;
onCancel: () => void;
};
export function ZoneEditPane({
polygons,
activePolygonIndex,
onCancel,
}: ZoneEditPaneProps) {
const polygon = useMemo(() => {
if (polygons && activePolygonIndex !== undefined) {
return polygons[activePolygonIndex];
} else {
return null;
}
}, [polygons, activePolygonIndex]);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
name: "",
inertia: 3,
loitering_time: 10,
},
});
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values);
}
if (!polygon) {
return;
}
return (
<>
<Heading as="h3">Edit Zone</Heading>
<div className="flex my-3">
<Separator className="bg-secondary" />
</div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input
placeholder={polygon.name ?? "Enter a name..."}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex my-3">
<Separator className="bg-secondary" />
</div>
<FormField
control={form.control}
name="inertia"
render={({ field }) => (
<FormItem>
<FormLabel>Inertia</FormLabel>
<FormControl>
<Input placeholder="" {...field} />
</FormControl>
<FormDescription>
Specifies how many frames that an object must be in a zone
before they are considered in the zone.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="flex my-3">
<Separator className="bg-secondary" />
</div>
<FormField
control={form.control}
name="loitering_time"
render={({ field }) => (
<FormItem>
<FormLabel>Loitering Time</FormLabel>
<FormControl>
<Input placeholder="" {...field} />
</FormControl>
<FormDescription>
Sets a minimum amount of time in seconds that the object must
be in the zone for it to activate.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="flex my-3">
<Separator className="bg-secondary" />
</div>
<FormItem>
<FormLabel>Objects</FormLabel>
<FormDescription>
List of objects that apply to this zone.
</FormDescription>
<ZoneObjectSelector
camera={polygon.camera}
zoneName={polygon.name}
updateLabelFilter={(objects) => {
// console.log(objects);
}}
/>
</FormItem>
<div className="flex flex-row gap-2">
<Button className="flex flex-1" onClick={onCancel}>
Cancel
</Button>
<Button variant="select" className="flex flex-1" type="submit">
Save
</Button>
</div>
</form>
</Form>
</>
);
}

View File

@ -176,7 +176,7 @@ export default function Settings() {
</div>
)}
</div>
<div className="mt-2 flex flex-col items-start">
<div className="mt-2 flex flex-col items-start w-full h-dvh md:pb-24">
{page == "general" && <General />}
{page == "objects" && <></>}
{page == "masks / zones" && (

View File

@ -69,5 +69,5 @@ export const toRGBColorString = (color: number[], darkened: boolean) => {
return "rgb(220,0,0,0.5)";
}
return `rgba(${color[2]},${color[1]},${color[0]},${darkened ? "0.9" : "0.5"})`;
return `rgba(${color[2]},${color[1]},${color[0]},${darkened ? "0.7" : "0.3"})`;
};