/** * The crop of a crop camera (#611), drawn on its source camera's snapshot: one * highlighted rectangle, dragged to move and resized from its corners. The * canvas is the library's `SourceCropCanvas`, the one the camera grid's * per-cell crop uses; the geometry is the engine's own (`crop-geometry`), so * what is locked here is what the engine will cut. * * The ratio presets are a segmented control: a preset re-seeds the rectangle * for that ratio and locks the corners to it, `Free` unlocks them. */ import { CROP_ASPECTS, type CropAspect, type CropHandle, type GridRect, moveCropRect, resizeCropRect, seedCropRect, } from '@camstack/types' import { Button, SourceCropCanvas, type SourceCropDrag } from '@camstack/ui-library' import { type ReactNode, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { DEFAULT_SOURCE_ASPECT } from './helper-form-model' const CORNERS: readonly CropHandle[] = ['nw', 'ne', 'se', 'sw'] function isCorner(mode: SourceCropDrag['mode']): mode is CropHandle { return mode === 'nw' || mode === 'ne' || mode === 'se' || mode === 'sw' } export interface CropValue { readonly rect: GridRect readonly aspect: CropAspect } export interface CropCameraEditorProps { /** The source camera whose snapshot is drawn; null until one is picked. */ readonly sourceDeviceId: number | null readonly value: CropValue /** * Create: the rectangle is re-seeded once the snapshot tells the frame's real * shape, unless the operator already moved it. Edit: the stored rectangle stands. */ readonly reseedOnLoad: boolean readonly disabled?: boolean readonly onChange: (next: CropValue) => void } export function CropCameraEditor({ sourceDeviceId, value, reseedOnLoad, disabled = false, onChange, }: CropCameraEditorProps): ReactNode { const { t } = useTranslation() const [sourceAspect, setSourceAspect] = useState(DEFAULT_SOURCE_ASPECT) const touched = useRef(!reseedOnLoad) if (sourceDeviceId === null) { return (
{t('helper.crop.pickSource')}
) } const onDrag = (drag: SourceCropDrag): void => { if (disabled) return touched.current = true if (drag.mode === 'move') { onChange({ ...value, rect: moveCropRect(drag.origin, drag.dx, drag.dy) }) return } if (!isCorner(drag.mode)) return onChange({ ...value, rect: resizeCropRect({ rect: drag.origin, handle: drag.mode, point: drag.point, aspect: value.aspect, sourceAspect: drag.sourceAspect, }), }) } return ({t('helper.crop.hint')}