/** * The camera-grid layout editor. * * A grid's geometry is the one thing a DERIVED settings form cannot express: a * generated form renders "cell 1 source = 592, cell 1 crop x = 0.25, cell 1 crop * width = 0.5…" and nobody can hold a picture in their head from that. So the * geometry gets a widget — the canvas, drawn at the grid's own aspect ratio, * with the cells on it — while the knobs that ARE ordinary fields (the name, * the canvas size, the frame rate) sit beside it in the same panel. * * Every rectangle in here is NORMALIZED [0,1], on both sides: the crop taken * out of a source, and the cell it lands in. That is how the addon stores them * (a source camera can change resolution, and a stored pixel rectangle would * quietly start cutting the wrong region), so the editor speaks the same * language rather than converting at the boundary. * * The preview is the source cameras' own snapshots, positioned by CSS from the * SAME normalized numbers that will become the ffmpeg `crop`/`overlay`. It costs * the server nothing and it is wrong in exactly the ways the real composition * would be wrong. */ import { Slider } from '../../primitives/slider' import { Checkbox } from '../../primitives/checkbox' import { useUiText, type UiTextFn } from '../../contexts/ui-text' import { DeviceValuePicker } from '../device-value-picker/DeviceValuePicker' import { useCallback, useEffect, useMemo, useState, type JSX } from 'react' import { AlertCircle, Grid2x2, LayoutGrid, Loader2, Maximize2, Plus, Save, Trash2, } from 'lucide-react' import { DeviceType, type DeviceInfo } from '@camstack/types' import { useSystem } from '../../contexts/system-context.js' import { useDeviceProxy } from '../../hooks/use-device-proxy.js' import { useDevices } from '../../hooks/use-devices.js' import { useDeviceSnapshotImage } from '../../hooks/use-device-snapshot.js' import { WidgetPanel } from '../widget-panel.js' import { capturePointer, DRAG_SURFACE, HANDLE_HIT, HANDLE_STYLE, HANDLES, SourceCropCanvas, } from './SourceCropCanvas.js' import { autofillCellRects, clampNormalizedRect, moveNormalizedRect, parseGridView, resizeNormalizedRectFrom, type GridLayoutCell, type GridResizeHandle, type GridLayoutView, type GridNormalizedRect, type GridProfileOffer, } from './camera-grid-layout.js' const FULL_FRAME: GridNormalizedRect = { x: 0, y: 0, width: 1, height: 1 } const MAX_CELLS = 16 /** Hoisted so `useDevices` does not re-subscribe on every render. */ const CAMERA_FILTER = { type: DeviceType.Camera } as const const CAMERA_TYPES: readonly string[] = [DeviceType.Camera] export interface CameraGridLayoutEditorProps { readonly deviceId: number } /** What the editor knows about the grid right now. `undefined` = not yet asked. */ type LoadState = GridLayoutView | null | 'unreadable' | undefined /** * A drag in progress. * * `target` is what is being dragged — the CELL (where the picture lands on the * canvas) or the SOURCE (which part of the camera is taken). They are two * different rectangles on two different canvases and the operator edits both by * hand now, so the state has to say which; a single `mode` could not. */ interface DragState { readonly index: number readonly target: 'cell' | 'source' readonly mode: 'move' | GridResizeHandle readonly startX: number readonly startY: number readonly origin: GridNormalizedRect } /** Move or resize, from one drag and one delta. */ function applyDrag(drag: DragState, dx: number, dy: number): GridNormalizedRect { return drag.mode === 'move' ? moveNormalizedRect(drag.origin, dx, dy) : resizeNormalizedRectFrom(drag.origin, drag.mode, dx, dy) } export function CameraGridLayoutEditor({ deviceId }: CameraGridLayoutEditorProps): JSX.Element { const t = useUiText() const system = useSystem() // The proxies drive REACTIVITY (they change as devices come and go); the // infos carry the NAME, which a DeviceProxy deliberately does not. const cameraProxies = useDevices(CAMERA_FILTER) const cameras = useMemo(() => system.listDeviceInfos(CAMERA_FILTER), [system, cameraProxies]) const [loaded, setLoaded] = useState(undefined) const [draft, setDraft] = useState(null) const [saving, setSaving] = useState(false) const [saveError, setSaveError] = useState(null) const [selected, setSelected] = useState(0) const [drag, setDrag] = useState(null) // The geometry is a CAPABILITY of this camera (`camera-grid-layout`), not an // addon action: the widget asks THE DEVICE, through the same proxy PTZ and // motion-zones use, and the framework is what mounted this widget here in the // first place. It used to reach the addon by name over `addons.custom`, which // is why it rendered nowhere the addon was not on a hand-written list. const dev = useDeviceProxy(system.trpcClient, deviceId) const reload = useCallback(async () => { const layout = dev?.cameraGridLayout if (!layout) return const outcome = parseGridView(await layout.getLayout({})) setLoaded(outcome) setDraft(outcome === null || outcome === 'unreadable' ? null : outcome) }, [dev]) useEffect(() => { // `dev` is briefly null while the proxy resolves its bindings, and a camera // that does not bind the cap answers nothing at all. Neither is "not a // grid": the pending state stays pending until something answers (D315). if (!dev) return if (!dev.cameraGridLayout) { setLoaded(null) return } void reload().catch(() => { setLoaded('unreadable') }) }, [dev, reload]) const save = useCallback( async (extra?: { readonly publishedProfiles?: readonly ('high' | 'mid' | 'low')[] }) => { const layout = dev?.cameraGridLayout if (draft === null || !layout) return setSaving(true) setSaveError(null) try { const outcome = parseGridView( await layout.saveLayout({ fps: draft.fps, cells: draft.cells.map((cell) => ({ ...cell })), ...(extra?.publishedProfiles !== undefined ? { publishedProfiles: [...extra.publishedProfiles] } : {}), }), ) if (outcome !== null && outcome !== 'unreadable') { setLoaded(outcome) setDraft(outcome) } } catch (error) { setSaveError(error instanceof Error ? error.message : String(error)) } finally { setSaving(false) } }, [dev, draft], ) const patchCell = useCallback((index: number, patch: Partial) => { setDraft((prev) => prev === null ? prev : { ...prev, cells: prev.cells.map((cell, i) => (i === index ? { ...cell, ...patch } : cell)), }, ) }, []) /** * The shape the grid will actually come out as. * * The canvas is no longer a field: each profile derives its own from the * cells and the sources' dimensions, and the server reports what it came out * as. Drawing at that aspect is the only way the editor shows the truth — * before, it drew at whatever two numbers had been typed, which is exactly * how a layout could look right here and wrong on screen. * * 16:9 while nothing is offered yet: a grid with no cells has no shape, and * an empty editor has to be drawn at something. */ const canvasAspect = useMemo(() => { const offered = loaded === undefined || loaded === null || loaded === 'unreadable' ? [] : loaded.profiles for (const row of offered) { if (!row.offered) continue const [width, height] = row.canvas.split('x').map(Number) if (width !== undefined && height !== undefined && width > 0 && height > 0) { return width / height } } return 16 / 9 }, [loaded]) // ── Read outcomes, kept distinct ─────────────────────────────────────── if (loaded === undefined) { return ( } >
{' '} {t('uiLibrary.cameraGridLayout.loading', 'Loading the layout…')}
) } if (loaded === 'unreadable') { return ( } >
{t( 'uiLibrary.cameraGridLayout.unreadable', 'The Camera Grids addon did not answer, so this layout is unknown — not empty.', )}
) } if (loaded === null || draft === null) { return ( } >
{t('uiLibrary.cameraGridLayout.notGrid', 'This camera is not a grid.')}
) } const onPointerMove = (event: React.PointerEvent): void => { if (drag === null) return const bounds = event.currentTarget.getBoundingClientRect() if (bounds.width === 0 || bounds.height === 0) return if (drag.target !== 'cell') return const dx = (event.clientX - drag.startX) / bounds.width const dy = (event.clientY - drag.startY) / bounds.height patchCell(drag.index, { cell: applyDrag(drag, dx, dy) }) } return ( } headerRight={
} >
{saveError !== null && (
{saveError}
)} {/* ── the canvas ─────────────────────────────────────────────── */}
{ setDrag(null) }} onPointerCancel={() => { setDrag(null) }} > {draft.cells.map((cell, index) => ( { setSelected(index) }} onDragStart={(mode, event) => { setSelected(index) setDrag({ index, target: 'cell', mode, startX: event.clientX, startY: event.clientY, origin: cell.cell, }) }} /> ))} {draft.cells.length === 0 && (
{t('uiLibrary.cameraGridLayout.noCells', 'No cells yet — add one below.')}
)}
{/* ── the non-spatial knobs, beside the picture they describe ── */}
{/* No Width/Height. A grid's resolution is derived per profile from the cells and the sources' own dimensions — see the report below for what each one came out as. */} { setDraft({ ...draft, fps }) }} />
{/* ── what this grid can actually publish, and what stops it ── */} { if (draft === null) return const current = loaded.profiles.filter((row) => row.published).map((row) => row.profile) const next = current.includes(profile) ? current.filter((entry) => entry !== profile) : [...current, profile] void save({ publishedProfiles: next }) }} /> {/* ── the selected cell: its source, and the crop taken from it ─ */} {draft.cells[selected] !== undefined && ( { patchCell(selected, patch) }} onRemove={() => { setDraft({ ...draft, cells: draft.cells.filter((_, i) => i !== selected), }) setSelected(0) }} /> )}
) } interface GridProfileReportProps { readonly onToggle: (profile: 'high' | 'mid' | 'low') => void readonly offers: readonly GridProfileOffer[] readonly cameras: readonly DeviceInfo[] } /** * The honest report. A grid's `high` composes its sources' `high` and its `low` * their `low`, so a profile is on offer only when EVERY source can serve it — * and the refusal names the source, because "this grid has no low" is not * something an operator can act on and "101 has no low" is. * * Read-only on purpose: what is on offer is decided by the source cameras' * assignments, and a control here would be a switch that writes nothing (D62). */ function GridProfileReport({ offers, cameras, onToggle }: GridProfileReportProps) { const t = useUiText() const nameOf = (deviceId: number): string => cameras.find((camera) => camera.id === deviceId)?.name ?? `#${String(deviceId)}` return (
{t('uiLibrary.cameraGridLayout.published', 'Published profiles')} {offers.map((offer) => (
{/* Only a SERVICEABLE profile can be toggled: the checkbox says what this grid publishes, never what its cameras can do. */} { onToggle(offer.profile) }} /> {offer.profile} {offer.offered ? ( {offer.canvas} —{' '} {offer.published ? t( 'uiLibrary.cameraGridLayout.composed', 'composed from every source’s {{profile}}', { profile: offer.profile }, ) : t('uiLibrary.cameraGridLayout.serviceable', 'serviceable, not published')} ) : ( {offer.missingSources.length === 0 ? t( 'uiLibrary.cameraGridLayout.noCellsOffer', 'not offered — this grid has no cells yet', ) : t( 'uiLibrary.cameraGridLayout.missing', 'not offered — no {{profile}} on {{sources}}', { profile: offer.profile, sources: offer.missingSources.map(nameOf).join(', '), }, )} )}
))}
) } interface GridCellBoxProps { readonly cell: GridLayoutCell readonly selected: boolean readonly onSelect: () => void readonly onDragStart: (mode: 'move' | GridResizeHandle, event: React.PointerEvent) => void } function GridCellBox({ cell, selected, onSelect, onDragStart }: GridCellBoxProps) { const { src } = useDeviceSnapshotImage(cell.deviceId, { width: 640 }) // The SAME normalized crop the ffmpeg graph will apply, expressed as a // background window: a source rect of half the width is a background twice // as wide, offset to the rect's own origin. const backgroundSize = `${String(100 / cell.source.width)}% ${String(100 / cell.source.height)}%` const backgroundPosition = cell.source.width >= 1 && cell.source.height >= 1 ? 'center' : `${String((cell.source.x / Math.max(1e-6, 1 - cell.source.width)) * 100)}% ` + `${String((cell.source.y / Math.max(1e-6, 1 - cell.source.height)) * 100)}%` return (
{ onSelect() capturePointer(event) onDragStart('move', event) }} className={`absolute cursor-move border ${selected ? 'border-primary' : 'border-border/60'}`} style={{ ...DRAG_SURFACE, left: `${String(cell.cell.x * 100)}%`, top: `${String(cell.cell.y * 100)}%`, width: `${String(cell.cell.width * 100)}%`, height: `${String(cell.cell.height * 100)}%`, backgroundImage: src === null ? undefined : `url(${src})`, backgroundSize, backgroundPosition, backgroundRepeat: 'no-repeat', }} > {/* The grips appear on the SELECTED cell only. Eight of them on every cell at once would cover a four-camera canvas in dots and make the picture — the thing being edited — unreadable. */} {selected && HANDLES.map((handle) => (
{ event.stopPropagation() capturePointer(event) onDragStart(handle, event) }} className={`${HANDLE_HIT} ${HANDLE_STYLE[handle]}`} style={DRAG_SURFACE} >
))}
) } interface CellInspectorProps { readonly cell: GridLayoutCell readonly index: number /** The camera this grid belongs to: never offered as one of its own sources. */ readonly selfDeviceId: number readonly onChange: (patch: Partial) => void readonly onRemove: () => void } function CellInspector({ cell, index, selfDeviceId, onChange, onRemove }: CellInspectorProps) { const t = useUiText() return (
{t('uiLibrary.cameraGridLayout.cellN', 'Cell {{index}}', { index: index + 1, })}
{t('uiLibrary.cameraGridLayout.source', 'Source')} { if (picked !== null) onChange({ deviceId: picked.deviceId }) }} />
{/* The part of the camera this cell shows, dragged on the camera's own picture. The numbers below still work and are the way to type an exact value; they are no longer the ONLY way, which is what made a crop a guess-and-check exercise. */} { onChange({ source }) }} />
{(['x', 'y', 'width', 'height'] as const).map((key) => ( { onChange({ source: clampNormalizedRect({ ...cell.source, [key]: next }), }) }} /> ))}
) } interface SourceCropEditorProps { readonly deviceId: number readonly source: GridNormalizedRect readonly onChange: (source: GridNormalizedRect) => void } /** * The crop of one grid cell, on the source camera's own frame: the shared * {@link SourceCropCanvas} with the eight grips, plus the whole-frame reset. */ function SourceCropEditor({ deviceId, source, onChange }: SourceCropEditorProps) { const t = useUiText() const full = source.x === 0 && source.y === 0 && source.width === 1 && source.height === 1 return (
{t('uiLibrary.cameraGridLayout.visiblePart', 'Visible part of the camera')}
{ onChange( drag.mode === 'move' ? moveNormalizedRect(drag.origin, drag.dx, drag.dy) : resizeNormalizedRectFrom(drag.origin, drag.mode, drag.dx, drag.dy), ) }} />
) } function cropLabel(t: UiTextFn, key: 'x' | 'y' | 'width' | 'height'): string { switch (key) { case 'x': return t('uiLibrary.cameraGridLayout.cropX', 'Crop x') case 'y': return t('uiLibrary.cameraGridLayout.cropY', 'Crop y') case 'width': return t('uiLibrary.cameraGridLayout.cropWidth', 'Crop width') case 'height': return t('uiLibrary.cameraGridLayout.cropHeight', 'Crop height') } } interface CropSliderProps { readonly label: string readonly value: number readonly onChange: (value: number) => void } /** * One crop number, as a slider AND as a number. * * The slider is what makes this usable with a thumb — a `number` input on a * phone opens a keyboard, and adjusting a crop by typing 0.37 then 0.39 then * 0.38 is not adjusting, it is guessing. The typed field stays because a slider * cannot express "exactly a third" and because a value you can read is how you * copy a crop from one cell to another. * * Both write through `clampNormalizedRect` upstream, so neither can hand the * addon a rectangle that leaves the frame — it THROWS on one, by design. */ function CropSlider({ label, value, onChange }: CropSliderProps) { const rounded = Math.round(value * 100) / 100 return ( ) } interface LabelledNumberProps { readonly label: string readonly value: number readonly step?: number readonly onChange: (value: number) => void } function LabelledNumber({ label, value, step = 1, onChange }: LabelledNumberProps) { return ( ) }