// One floor plan's editor (plan step 6.8, D-31). Drag tables and things on the floor; the panel
// on the right edits what's selected (shape, seats, size, rotation, text), adds the tables that
// aren't on the plan and walls / the bar / labels / areas, and holds the plan's settings: name,
// zone, size, the grid (snap on / off and its size), the floor's shape (drag its corners; add or
// remove corners) and a background picture from the media library. Arrow keys move the selected
// thing (a grid cell, or 5; Shift: 1), Delete takes it off, Escape lets go. Nothing is saved
// until "Save"; then every app's map changes at once.
import { useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast'
import { RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import {
Floor, GRID_SIZES, ITEM_KINDS, Item, SHAPES, TableShape, addCorner, defaultSize, moveCorner, moveTo, outlineOf, removeCorner, toPlan,
} from '@xenia/floorplan'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Switch, cx } from '@xenia/ui'
import MediaField from '../media/MediaField'
import * as api from './floorApi'
import { addItem, addable, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resize, rotate, sameLayout, update } from './editorLogic'
const PAD = 30 // room around the floor for the corner handles
export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) {
const { t } = useTranslation('manager')
const initial = useMemo(() => layoutOf(data, saved.id), [data, saved.id])
const [layout, setLayout] = useState(initial)
const [form, setForm] = useState(() => ({ ...saved }))
const [sel, setSel] = useState(null) // {type: 'table'|'item', id} | {type: 'corner', index}
const [shapeMode, setShapeMode] = useState(false)
const [newShape, setNewShape] = useState('square')
const [busy, setBusy] = useState(false)
const [deleting, setDeleting] = useState(false)
const svg = useRef(null)
const drag = useRef(null)
const plan = form // the preview follows the unsaved settings
const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(saved))
const dirty = dirtySettings || !sameLayout(layout, initial)
const selected = sel && sel.type !== 'corner' ? find(layout, sel) : null
const corners = outlineOf(plan)
const setF = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { own, other } = addable(data, plan, layout)
const point = e => toPlan(svg.current, e.clientX, e.clientY)
const start = (e, target) => {
e.stopPropagation()
svg.current?.focus()
const [px, py] = point(e)
if (target.type === 'corner') {
setSel(target)
drag.current = { target }
} else {
const thing = find(layout, target)
setSel(target)
drag.current = { target, dx: px - thing.x, dy: py - thing.y }
}
svg.current.setPointerCapture?.(e.pointerId)
}
const move = e => {
const d = drag.current
if (!d) return
const [px, py] = point(e)
if (d.target.type === 'corner') {
setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) }))
return
}
setLayout(l => {
const thing = find(l, d.target)
if (!thing) return l
const m = moveTo(thing, px - d.dx, py - d.dy, plan)
return update(l, d.target, { x: m.x, y: m.y })
})
}
const end = () => { drag.current = null }
const keys = e => {
if (!sel || sel.type === 'corner') return
const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
if (dirs[e.key]) { e.preventDefault(); setLayout(l => nudge(l, sel, plan, ...dirs[e.key], e.shiftKey)) }
else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) }
else if (e.key === 'Escape') setSel(null)
}
const save = async () => {
setBusy(true)
try {
if (dirtySettings) await api.savePlan(saved.id, planBody(form))
await api.saveLayout(saved.id, layoutBody(layout))
toast.success(t('floor.saved'))
onSaved()
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone')
return (
{form.name || saved.name}
{dirty && {t('floor.unsaved')}}
} disabled={!dirty || busy}
onClick={() => { setLayout(initial); setForm({ ...saved }); setSel(null) }}>{t('floor.undoAll')}
} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}
setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" />
{form.grid_on && (
{shapeMode &&
{t('floor.shapeHint')}
}
{t('floor.keysHint')}
{deleting && (
)}
)
}
function Panel({ title, children }) {
return (
)
}
function TableButtons({ tables, title, onAdd, quiet = false }) {
if (!tables.length) return null
return (
{title}
{tables.map(tb => (
))}
)
}
function Selected({ thing, sel, plan, t, onChange, onRemove }) {
const isTable = sel.type === 'table'
const setSize = (w, h) => onChange(resize(thing, plan, w, h))
return (
{isTable && (
<>
{SHAPES.map(s => (
))}
onChange({ seats: e.target.value === '' ? null : Math.max(0, Math.min(99, Math.round(Number(e.target.value)))) })} />
>
)}
{!isTable && thing.kind !== 'wall' && (
onChange({ text: e.target.value })} data-testid="floor-item-text" />
)}
setSize(Number(e.target.value), undefined)} />
setSize(undefined, Number(e.target.value))} />
{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}
onChange({ rotation: rotate(thing.rotation || 0, -15) })}>
onChange({ rotation: rotate(thing.rotation || 0, 15) })} data-testid="floor-rotate">
} onClick={onRemove} className="justify-self-start text-danger-ink" data-testid="floor-remove">
{isTable ? t('floor.takeOff') : t('floor.removeThing')}
)
}