Files
faunosteo/apps/app/src/components/editor/views/useCropGroup.ts
T

82 lines
2.3 KiB
TypeScript

import { useEffect, useRef, useState } from 'react'
import type { ViewBox } from '@faunosteo/core-wasm/types'
import {
BOX_KEYS,
fieldsOf,
parseBox,
sameBox,
type BoxFields,
} from '@/editor/viewBox'
import { useViewUpdate, type ViewUpdateApi } from '@/editor/useViewUpdate'
export interface CropGroup {
draft: BoxFields
refused: boolean
views: ViewUpdateApi
/** The rectangle to draw: the typed group when it parses, else the saved box. */
rectangle: ViewBox | null
setField: (key: keyof BoxFields, value: string) => void
apply: () => void
revert: () => void
}
const differs = (a: BoxFields, b: BoxFields) =>
BOX_KEYS.some((key) => a[key] !== b[key])
/**
* The four `view_box` fields as one group: `apply` proposes all four together under the
* geometry check; a refused group stays typed and `refused`. A new saved box (undo, reload,
* restore, an accepted apply) replaces what was typed; unmounting applies a pending group.
*/
export function useCropGroup(viewId: string, box: ViewBox | null): CropGroup {
const views = useViewUpdate()
const saved = fieldsOf(box)
const [draft, setDraft] = useState<BoxFields>(saved)
const [seen, setSeen] = useState<BoxFields>(saved)
const [refused, setRefused] = useState(false)
if (differs(seen, saved)) {
setSeen(saved)
setDraft(saved)
setRefused(false)
}
const apply = (): void => {
const parsed = parseBox(draft)
if (!parsed.ok) {
views.reject('crop', `editor.views.crop.${parsed.reason}`)
setRefused(true)
} else if (sameBox(parsed.box, box)) {
views.clear()
setRefused(false)
} else {
const done = views.update('crop', viewId, { view_box: parsed.box }, true)
setRefused(!done)
}
}
const latest = useRef({ draft, saved, apply })
useEffect(() => {
latest.current = { draft, saved, apply }
})
useEffect(
() => () => {
if (differs(latest.current.draft, latest.current.saved)) {
latest.current.apply()
}
},
[],
)
const shown = parseBox(draft)
return {
draft,
refused,
views,
rectangle: shown.ok ? shown.box : box,
setField: (key, value) => setDraft({ ...draft, [key]: value }),
apply,
revert: () => {
setDraft(saved)
setRefused(false)
views.clear()
},
}
}