feat(manager): the floor plan editor reworked; Management -> Tables on the page rule; area colours

- Floor editor: one toolbar over the map and the panels (grid on / off, grid resolution Ultra high
  ... Very low, edit the shape, Fit width / Whole plan, undo, save), panels top-aligned and sticky.
- The floor's shape: a '+' on the edge under the pointer, press to add a corner (and drag it);
  resting on a corner shows a bubble to remove it (never below 3).
- Areas: resize handles on the sides and corners, a colour (pastel, see-through; floor_items.color,
  migration 0041), the name repeated in the corner when tables cover it (live maps too).
- Labels can be clicked again after they're placed (transparent fill, not none).
- Management -> Tables: <Page> with the tabs above (?tab=), the list as a container, toolbar
  buttons one height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 15:17:45 +02:00
co-authored by Claude Opus 5.5
parent 476c55abc0
commit 244e93f827
17 changed files with 389 additions and 111 deletions
@@ -0,0 +1,23 @@
"""A floor area's colour (UI review 2026-11-20): "#rrggbb", drawn see-through on the plan.
Revision ID: 0041_floor_item_color
Revises: 0040_channel_prices
Create Date: 2026-11-20 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0041_floor_item_color'
down_revision = '0040_channel_prices'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.add_column(sa.Column('color', sa.String(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.drop_column('color')
+1
View File
@@ -54,5 +54,6 @@ class FloorItem(Base):
height = Column(Float, nullable=False) height = Column(Float, nullable=False)
rotation = Column(Float, nullable=False, default=0.0) rotation = Column(Float, nullable=False, default=0.0)
text = Column(String, nullable=True) text = Column(String, nullable=True)
color = Column(String, nullable=True) # an area's colour, "#rrggbb" (drawn see-through; 2026-11-20)
plan = relationship("FloorPlan", back_populates="items") plan = relationship("FloorPlan", back_populates="items")
+4 -2
View File
@@ -88,6 +88,7 @@ class PlacedItem(BaseModel):
height: float = Field(gt=0, le=6000) height: float = Field(gt=0, le=6000)
rotation: float = 0.0 rotation: float = 0.0
text: Optional[str] = Field(None, max_length=60) text: Optional[str] = Field(None, max_length=60)
color: Optional[str] = Field(None, pattern=r"^#[0-9a-fA-F]{6}$") # an area's colour (2026-11-20)
class LayoutBody(BaseModel): class LayoutBody(BaseModel):
@@ -110,7 +111,7 @@ def plan_out(p: FloorPlan) -> dict:
"media_id": p.media_id, "background": media_store.image_of(p.media) if p.media_id else None, "media_id": p.media_id, "background": media_store.image_of(p.media) if p.media_id else None,
"background_opacity": p.background_opacity, "background_opacity": p.background_opacity,
"items": [{"id": i.id, "kind": i.kind, "x": i.x, "y": i.y, "width": i.width, "height": i.height, "items": [{"id": i.id, "kind": i.kind, "x": i.x, "y": i.y, "width": i.width, "height": i.height,
"rotation": i.rotation, "text": i.text} for i in p.items], "rotation": i.rotation, "text": i.text, "color": i.color} for i in p.items],
} }
@@ -211,7 +212,8 @@ def save_layout(plan_id: int, body: LayoutBody, db: Session = Depends(get_db), u
db.flush() db.flush()
for it in body.items: for it in body.items:
p.items.append(FloorItem(kind=it.kind, x=_inside(it.x, p.width), y=_inside(it.y, p.height), width=round(it.width, 1), p.items.append(FloorItem(kind=it.kind, x=_inside(it.x, p.width), y=_inside(it.y, p.height), width=round(it.width, 1),
height=round(it.height, 1), rotation=_rot(it.rotation), text=(it.text or "").strip() or None)) height=round(it.height, 1), rotation=_rot(it.rotation), text=(it.text or "").strip() or None,
color=it.color if it.kind == "area" else None))
db.commit() db.commit()
db.refresh(p) db.refresh(p)
_changed() _changed()
+13
View File
@@ -90,3 +90,16 @@ def test_the_live_map_shows_each_table_state_to_the_right_people(client, owner_h
assert len(client.get("/api/floor-plans/live", headers=owner_h).json()["tables"]) == 4 assert len(client.get("/api/floor-plans/live", headers=owner_h).json()["tables"]) == 4
# only the tables' managers set plans up # only the tables' managers set plans up
assert client.post("/api/floor-plans", headers=h, json={"name": "x"}).status_code == 403 assert client.post("/api/floor-plans", headers=h, json={"name": "x"}).status_code == 403
def test_an_area_keeps_its_colour(client, owner_h, venue):
"""2026-11-20: an area has a colour ("#rrggbb", drawn see-through); other things don't."""
p = plan(client, owner_h, group_id=venue["inside"].id)
r = client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"items": [
{"kind": "area", "x": 300, "y": 300, "width": 300, "height": 200, "text": "Terrace", "color": "#86efac"},
{"kind": "wall", "x": 10, "y": 10, "width": 100, "height": 12, "color": "#86efac"}]})
assert r.status_code == 200, r.text
assert [(i["kind"], i["color"]) for i in r.json()["items"]] == [("area", "#86efac"), ("wall", None)]
bad = client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"items": [
{"kind": "area", "x": 1, "y": 1, "width": 10, "height": 10, "color": "red; drop"}]})
assert bad.status_code == 422
@@ -1,7 +1,9 @@
// Management → Tables: the tables and their zones (the list, for typing and bulk changes), and // Management → Tables: the tables and their zones (the list, for typing and bulk changes), and
// the floor plans (plan step 6.8: where the tables stand, drawn on a map). // the floor plans (plan step 6.8: where the tables stand, drawn on a map). On the page rule
import { useState } from 'react' // (2026-11-20): the tabs above, the tab in the address (?tab=).
import { useSearchParams } from 'react-router-dom'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Page, Tabs } from '@xenia/ui'
import FloorPlansTab from '../floor/FloorPlansTab' import FloorPlansTab from '../floor/FloorPlansTab'
import TablesListTab from '../tables/TablesListTab' import TablesListTab from '../tables/TablesListTab'
@@ -9,21 +11,14 @@ const TABS = ['list', 'floor']
export default function TablesConfigPage() { export default function TablesConfigPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [tab, setTab] = useState('list') const [params, setParams] = useSearchParams()
const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'list'
const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); return n }, { replace: true })
return ( return (
<div className="flex flex-col h-full min-h-0"> <Page testId="tables-config"
<div className="flex flex-wrap gap-1 border-b border-line px-4 md:px-6 pt-3 shrink-0" role="tablist" aria-label={t('floor.pageTabs')}> top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('floor.pageTabs')}
{TABS.map(k => ( tabs={TABS.map(k => ({ id: k, label: t(`floor.tabs.${k}`), testId: `tables-tab-${k}` }))} />}>
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`tables-tab-${k}`} {tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast </Page>
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`floor.tabs.${k}`)}
</button>
))}
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
</div>
</div>
) )
} }
+164 -53
View File
@@ -1,24 +1,44 @@
// One floor plan's editor (plan step 6.8, D-31). Drag tables and things on the floor; the panel // 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 // 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, // 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 // zone, size, a background picture. The toolbar over both: the grid (on / off and its resolution),
// remove corners) and a background picture from the media library. Arrow keys move the selected // "Edit the floor's shape", fit the width or the whole plan, undo, save.
// thing (a grid cell, or 5; Shift: 1), Delete takes it off, Escape lets go. Nothing is saved // The floor's shape (2026-11-20): drag a corner; on an edge a "+" shows where a click adds a
// until "Save"; then every app's map changes at once. // corner; resting on a corner shows a bubble to remove it (a floor keeps at least 3). An area
import { useMemo, useRef, useState } from 'react' // (2026-11-20) is resized by the handles on its sides and corners, and has a colour (pastel, see-
// through); when tables cover its name, the name shows in its corner too.
// 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 { useLayoutEffect, useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react' import { RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { import {
Floor, GRID_SIZES, ITEM_KINDS, Item, SHAPES, TableShape, addCorner, defaultSize, moveCorner, moveTo, outlineOf, removeCorner, toPlan, AREA_COLOURS, Floor, GRID_LEVELS, ITEM_KINDS, Item, SHAPES, TableShape, addCornerAt, coveredAreas, defaultSize, moveCorner, moveTo,
nearestEdge, outlineOf, removeCorner, resizeBox, toPlan,
} from '@xenia/floorplan' } from '@xenia/floorplan'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Switch, cx } from '@xenia/ui' import { Button, Dialog, Dropdown, Field, IconButton, Input, Segmented, Switch, cx } from '@xenia/ui'
import MediaField from '../media/MediaField' import MediaField from '../media/MediaField'
import * as api from './floorApi' import * as api from './floorApi'
import { addItem, addable, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resize, rotate, sameLayout, update } from './editorLogic' 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 const PAD = 30 // room around the floor for the corner handles
const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']
const CURSOR = { n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize' }
/** The size of an element, kept up to date. */
function useSize(ref) {
const [size, setSize] = useState({ width: 0, height: 0 })
useLayoutEffect(() => {
const el = ref.current
if (!el) return undefined
const ro = new ResizeObserver(([e]) => setSize({ width: e.contentRect.width, height: e.contentRect.height }))
ro.observe(el)
return () => ro.disconnect()
}, [ref])
return size
}
export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) { export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -30,8 +50,14 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
const [newShape, setNewShape] = useState('square') const [newShape, setNewShape] = useState('square')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [deleting, setDeleting] = useState(false) const [deleting, setDeleting] = useState(false)
const [fit, setFit] = useState('width') // 'width' | 'all'
const [edgeHover, setEdgeHover] = useState(null) // where a click on the edge adds a corner
const [cornerTip, setCornerTip] = useState(null) // the corner showing its "remove" bubble
const tipTimer = useRef(null)
const svg = useRef(null) const svg = useRef(null)
const box = useRef(null)
const drag = useRef(null) const drag = useRef(null)
const size = useSize(box)
const plan = form // the preview follows the unsaved settings const plan = form // the preview follows the unsaved settings
const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(saved)) const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(saved))
@@ -40,6 +66,13 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
const corners = outlineOf(plan) const corners = outlineOf(plan)
const setF = (k, v) => setForm(f => ({ ...f, [k]: v })) const setF = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { own, other } = addable(data, plan, layout) const { own, other } = addable(data, plan, layout)
const covered = coveredAreas(layout.items, layout.tables)
// the scale: the plan (and its margin) fitted to the width, or whole in the box
const vbW = plan.width + 2 * PAD
const vbH = plan.height + 2 * PAD
const scale = size.width ? (fit === 'all' && size.height ? Math.min(size.width / vbW, size.height / vbH) : size.width / vbW) : 1
const r = Math.max(8, 9 / scale) // a handle's size on screen ≈ 18 px
const point = e => toPlan(svg.current, e.clientX, e.clientY) const point = e => toPlan(svg.current, e.clientX, e.clientY)
const start = (e, target) => { const start = (e, target) => {
@@ -49,6 +82,8 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
if (target.type === 'corner') { if (target.type === 'corner') {
setSel(target) setSel(target)
drag.current = { target } drag.current = { target }
} else if (target.handle) {
drag.current = { target }
} else { } else {
const thing = find(layout, target) const thing = find(layout, target)
setSel(target) setSel(target)
@@ -58,12 +93,22 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
} }
const move = e => { const move = e => {
const d = drag.current const d = drag.current
if (!d) return
const [px, py] = point(e) const [px, py] = point(e)
if (!d) {
if (shapeMode) {
const n = nearestEdge(corners, [px, py])
setEdgeHover(n && n.d < 14 / scale ? n : null)
}
return
}
if (d.target.type === 'corner') { if (d.target.type === 'corner') {
setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) })) setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) }))
return return
} }
if (d.target.handle) {
setLayout(l => update(l, d.target, resizeBox(find(l, d.target), d.target.handle, px, py, plan)))
return
}
setLayout(l => { setLayout(l => {
const thing = find(l, d.target) const thing = find(l, d.target)
if (!thing) return l if (!thing) return l
@@ -72,6 +117,17 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
}) })
} }
const end = () => { drag.current = null } const end = () => { drag.current = null }
const down = e => {
if (shapeMode && edgeHover) {
// a click on an edge adds a corner there and starts dragging it
const index = edgeHover.index + 1
setForm(f => ({ ...f, outline: addCornerAt(outlineOf(f), edgeHover.index, edgeHover.x, edgeHover.y, f) }))
setEdgeHover(null)
start(e, { type: 'corner', index })
return
}
setSel(null)
}
const keys = e => { const keys = e => {
if (!sel || sel.type === 'corner') return if (!sel || sel.type === 'corner') return
const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] } const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
@@ -79,6 +135,9 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) } else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) }
else if (e.key === 'Escape') setSel(null) else if (e.key === 'Escape') setSel(null)
} }
const showTip = i => { clearTimeout(tipTimer.current); tipTimer.current = setTimeout(() => setCornerTip(i), 600) }
const hideTip = () => { clearTimeout(tipTimer.current); tipTimer.current = setTimeout(() => setCornerTip(null), 500) }
const keepTip = () => clearTimeout(tipTimer.current)
const save = async () => { const save = async () => {
setBusy(true) setBusy(true)
@@ -90,33 +149,39 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) } } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
} }
const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone') const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone')
const gridOptions = [...GRID_LEVELS.map(([k, v]) => ({ value: v, label: t(`floor.gridLevels.${k}`), hint: t('floor.gridCell', { size: v }) })),
...(GRID_LEVELS.some(([, v]) => v === form.grid_size) ? [] : [{ value: form.grid_size, label: t('floor.gridCell', { size: form.grid_size }) }])]
const resizable = selected && sel.type === 'item' && selected.kind === 'area' && !shapeMode && Math.round(selected.rotation || 0) % 180 === 0
return ( return (
<div className="grid gap-4 lg:grid-cols-[1fr_18rem] items-start" data-testid="floor-editor" data-plan={saved.id}> <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_19rem] items-start" data-testid="floor-editor" data-plan={saved.id}>
<div className="grid gap-3 content-start min-w-0"> {/* the toolbar, over the map and the panels */}
<div className="flex flex-wrap items-center gap-2"> <div className="lg:col-span-2 flex flex-wrap items-center gap-x-4 gap-y-2 px-card py-card-y rounded-card border border-line bg-surface shadow-raised">
<h2 className="text-body-lg font-semibold text-ink mr-auto">{form.name || saved.name}</h2> <h2 className="text-body-lg font-semibold text-ink">{form.name || saved.name}</h2>
{dirty && <span className="px-2 py-0.5 rounded-full bg-warning-soft text-warning-ink text-caption font-medium" data-testid="floor-dirty">{t('floor.unsaved')}</span>} {dirty && <span className="px-2 py-0.5 rounded-full bg-warning-soft text-warning-ink text-caption font-medium" data-testid="floor-dirty">{t('floor.unsaved')}</span>}
<Button variant="secondary" size="sm" icon={<Undo2 size={16} />} disabled={!dirty || busy} <span className="flex-1" />
onClick={() => { setLayout(initial); setForm({ ...saved }); setSel(null) }}>{t('floor.undoAll')}</Button> <Switch checked={!!form.grid_on} onChange={v => setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" />
<Button size="sm" icon={<Save size={16} />} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}</Button> {form.grid_on && (
</div> <Dropdown size="sm" className="w-44" value={form.grid_size} onChange={v => setF('grid_size', v)} aria-label={t('floor.gridSize')} data-testid="floor-grid-size" options={gridOptions} />
<div className="flex flex-wrap items-center gap-3 text-label text-ink-2"> )}
<Switch checked={!!form.grid_on} onChange={v => setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" /> <Switch checked={shapeMode} onChange={v => { setShapeMode(v); setSel(null); setEdgeHover(null); setCornerTip(null) }} label={t('floor.editShape')} data-testid="floor-shape-mode" />
{form.grid_on && ( <Segmented size="sm" value={fit} onChange={setFit} aria-label={t('floor.fit')}
<Select size="sm" value={String(form.grid_size)} onChange={e => setF('grid_size', Number(e.target.value))} aria-label={t('floor.gridSize')} options={[{ value: 'width', label: t('floor.fitWidth'), testId: 'floor-fit-width' }, { value: 'all', label: t('floor.fitAll'), testId: 'floor-fit-all' }]} />
options={[...new Set([...GRID_SIZES, form.grid_size])].sort((a, b) => a - b).map(v => ({ value: String(v), label: t('floor.gridCell', { size: v }) }))} /> <Button variant="secondary" size="sm" icon={<Undo2 size={16} />} disabled={!dirty || busy}
)} onClick={() => { setLayout(initial); setForm({ ...saved }); setSel(null) }}>{t('floor.undoAll')}</Button>
<Switch checked={shapeMode} onChange={v => { setShapeMode(v); setSel(null) }} label={t('floor.editShape')} data-testid="floor-shape-mode" /> <Button size="sm" icon={<Save size={16} />} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}</Button>
</div> </div>
{shapeMode && <p className="text-caption text-ink-2">{t('floor.shapeHint')}</p>}
<div className="rounded-card border border-line bg-canvas overflow-auto max-h-[70vh]"> <div className="grid gap-2 content-start min-w-0">
<svg ref={svg} viewBox={`${-PAD} ${-PAD} ${plan.width + 2 * PAD} ${plan.height + 2 * PAD}`} tabIndex={0} onKeyDown={keys} role="application" aria-label={t('floor.canvas')} <div ref={box} className={cx('rounded-card border border-line bg-canvas overflow-auto', fit === 'all' ? 'h-[calc(100dvh-17rem)] min-h-[22rem]' : 'max-h-[calc(100dvh-17rem)]')}
className="block w-full h-auto touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--x-accent)]" style={{ scrollbarGutter: 'stable' }}>
onPointerMove={move} onPointerUp={end} onPointerCancel={end} onPointerDown={() => setSel(null)} data-testid="floor-canvas"> <svg ref={svg} viewBox={`${-PAD} ${-PAD} ${vbW} ${vbH}`} tabIndex={0} onKeyDown={keys} role="application" aria-label={t('floor.canvas')}
width={Math.max(1, vbW * scale)} height={Math.max(1, vbH * scale)}
className={cx('block mx-auto touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--x-accent)]', shapeMode && edgeHover && 'cursor-copy')}
onPointerMove={move} onPointerUp={end} onPointerCancel={end} onPointerDown={down} onPointerLeave={() => setEdgeHover(null)} data-testid="floor-canvas">
<Floor plan={plan} showGrid={!!plan.grid_on} /> <Floor plan={plan} showGrid={!!plan.grid_on} />
{layout.items.map(i => ( {layout.items.map(i => (
<Item key={i.key} item={i} label={t('floor.kinds.bar')} selected={sel?.type === 'item' && sel.id === i.key} <Item key={i.key} item={i} label={t('floor.kinds.bar')} selected={sel?.type === 'item' && sel.id === i.key} corner={covered.has(i.key)}
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined} style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'item', id: i.key })} data-testid="floor-item" data-kind={i.kind} /> onPointerDown={e => start(e, { type: 'item', id: i.key })} data-testid="floor-item" data-kind={i.kind} />
))} ))}
@@ -125,27 +190,55 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined} style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'table', id: tb.id })} data-testid="floor-table" /> onPointerDown={e => start(e, { type: 'table', id: tb.id })} data-testid="floor-table" />
))} ))}
{resizable && HANDLES.map(h => {
const x = selected.x + (h.includes('e') ? 1 : h.includes('w') ? -1 : 0) * selected.width / 2
const y = selected.y + (h.includes('s') ? 1 : h.includes('n') ? -1 : 0) * selected.height / 2
return (
<rect key={h} x={x - r / 2} y={y - r / 2} width={r} height={r} rx={r / 4} fill="var(--x-surface)" stroke="var(--x-accent)" strokeWidth={2 / scale}
style={{ cursor: CURSOR[h] }} data-testid={`floor-handle-${h}`}
onPointerDown={e => start(e, { type: 'item', id: sel.id, handle: h })} />
)
})}
{shapeMode && edgeHover && (
<g transform={`translate(${edgeHover.x} ${edgeHover.y})`} pointerEvents="none" data-testid="floor-edge-add">
<circle r={r} fill="var(--x-accent)" />
<path d={`M ${-r * 0.5} 0 H ${r * 0.5} M 0 ${-r * 0.5} V ${r * 0.5}`} stroke="var(--x-accent-fg)" strokeWidth={2.5 / scale} strokeLinecap="round" />
</g>
)}
{shapeMode && corners.map(([x, y], i) => ( {shapeMode && corners.map(([x, y], i) => (
<circle key={i} cx={x} cy={y} r={Math.max(10, plan.width / 90)} data-testid="floor-corner" <circle key={i} cx={x} cy={y} r={r} data-testid="floor-corner"
fill={sel?.type === 'corner' && sel.index === i ? 'var(--x-accent)' : 'var(--x-surface)'} stroke="var(--x-accent)" strokeWidth="3" fill={sel?.type === 'corner' && sel.index === i ? 'var(--x-accent)' : 'var(--x-surface)'} stroke="var(--x-accent)" strokeWidth={3 / scale}
style={{ cursor: 'grab' }} onPointerDown={e => start(e, { type: 'corner', index: i })} /> style={{ cursor: 'grab' }} onPointerDown={e => { setCornerTip(null); start(e, { type: 'corner', index: i }) }}
onPointerEnter={() => showTip(i)} onPointerLeave={hideTip} />
))} ))}
{shapeMode && cornerTip != null && corners[cornerTip] && (
// the bubble over a corner: remove it (not below 3 corners)
<g transform={`translate(${corners[cornerTip][0]} ${corners[cornerTip][1] - r * 3.2})`} onPointerEnter={keepTip} onPointerLeave={hideTip} data-testid="floor-corner-tip">
<rect x={-r * 1.6} y={-r * 1.3} width={r * 3.2} height={r * 2.6} rx={r * 0.5} fill="var(--x-surface)" stroke="var(--x-line-strong)" strokeWidth={1.5 / scale} />
<path d={`M ${-r * 0.35} ${r * 1.3} L 0 ${r * 1.9} L ${r * 0.35} ${r * 1.3} Z`} fill="var(--x-surface)" stroke="var(--x-line-strong)" strokeWidth={1.5 / scale} />
<g role="button" aria-label={t('floor.removeCorner')} style={{ cursor: corners.length > 3 ? 'pointer' : 'not-allowed' }} opacity={corners.length > 3 ? 1 : 0.4}
onPointerDown={e => {
e.stopPropagation()
if (corners.length <= 3) return
setForm(f => ({ ...f, outline: removeCorner(outlineOf(f), cornerTip) }))
setCornerTip(null); setSel(null)
}} data-testid="floor-corner-remove">
<rect x={-r * 1.6} y={-r * 1.3} width={r * 3.2} height={r * 2.6} fill="transparent" />
<Trash2 x={-r * 0.8} y={-r * 0.8} width={r * 1.6} height={r * 1.6} color="var(--x-danger-ink)" />
</g>
</g>
)}
</svg> </svg>
</div> </div>
<p className="text-caption text-ink-3">{t('floor.keysHint')}</p> <p className="text-caption text-ink-3">{shapeMode ? t('floor.shapeHint') : t('floor.keysHint')}</p>
</div> </div>
<aside className="grid gap-4 content-start lg:max-h-[calc(100vh-10rem)] lg:overflow-y-auto"> <aside className="grid gap-4 content-start lg:sticky lg:top-0">
{shapeMode ? ( {shapeMode ? (
<Panel title={t('floor.shapeTitle')}> <Panel title={t('floor.shapeTitle')}>
<p className="text-caption text-ink-2">{t('floor.cornerCount', { count: corners.length })}</p> <p className="text-caption text-ink-2">{t('floor.cornerCount', { count: corners.length })}</p>
<div className="flex flex-wrap gap-2"> <p className="text-caption text-ink-2">{t('floor.shapeHowTo')}</p>
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner'} data-testid="floor-corner-add" <Button size="sm" variant="secondary" disabled={!form.outline} className="justify-self-start" onClick={() => { setF('outline', null); setSel(null) }}>{t('floor.rectangle')}</Button>
onClick={() => setForm(f => ({ ...f, outline: addCorner(outlineOf(f), sel.index) }))}>{t('floor.addCorner')}</Button>
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner' || corners.length <= 3}
onClick={() => { setForm(f => ({ ...f, outline: removeCorner(outlineOf(f), sel.index) })); setSel(null) }}>{t('floor.removeCorner')}</Button>
<Button size="sm" variant="ghost" disabled={!form.outline} onClick={() => { setF('outline', null); setSel(null) }}>{t('floor.rectangle')}</Button>
</div>
</Panel> </Panel>
) : selected ? ( ) : selected ? (
<Selected thing={selected} sel={sel} plan={plan} t={t} <Selected thing={selected} sel={sel} plan={plan} t={t}
@@ -154,7 +247,7 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
) : ( ) : (
<Panel title={t('floor.add')}> <Panel title={t('floor.add')}>
<Field label={t('floor.newTableShape')}> <Field label={t('floor.newTableShape')}>
<Select size="sm" value={newShape} onChange={e => setNewShape(e.target.value)} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} /> <Segmented size="sm" value={newShape} onChange={setNewShape} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} />
</Field> </Field>
{own.length + other.length === 0 ? <p className="text-caption text-ink-3">{t('floor.allPlaced')}</p> : ( {own.length + other.length === 0 ? <p className="text-caption text-ink-3">{t('floor.allPlaced')}</p> : (
<div className="grid gap-2"> <div className="grid gap-2">
@@ -165,11 +258,11 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
</div> </div>
)} )}
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<span className="text-label font-semibold text-ink">{t('floor.things')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('floor.things')}</span>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{ITEM_KINDS.map(k => ( {ITEM_KINDS.map(k => (
<Button key={k} size="sm" variant="secondary" data-testid={`floor-add-${k}`} <Button key={k} size="sm" variant="secondary" data-testid={`floor-add-${k}`}
onClick={() => { const r = addItem(layout, plan, k, k === 'label' ? t('floor.labelText') : null); setLayout(r.layout); setSel({ type: 'item', id: r.key }) }}> onClick={() => { const res = addItem(layout, plan, k, k === 'label' ? t('floor.labelText') : null); setLayout(res.layout); setSel({ type: 'item', id: res.key }) }}>
{t(`floor.kinds.${k}`)} {t(`floor.kinds.${k}`)}
</Button> </Button>
))} ))}
@@ -181,7 +274,7 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
<Panel title={t('floor.settings')}> <Panel title={t('floor.settings')}>
<Field label={t('floor.name')}><Input size="sm" value={form.name} maxLength={60} onChange={e => setF('name', e.target.value)} data-testid="floor-name" /></Field> <Field label={t('floor.name')}><Input size="sm" value={form.name} maxLength={60} onChange={e => setF('name', e.target.value)} data-testid="floor-name" /></Field>
<Field label={t('floor.zone')} hint={t('floor.zoneHint')}> <Field label={t('floor.zone')} hint={t('floor.zoneHint')}>
<Select size="sm" value={form.group_id ?? ''} onChange={e => setF('group_id', e.target.value === '' ? null : Number(e.target.value))} <Dropdown size="sm" value={form.group_id ?? ''} onChange={v => setF('group_id', v === '' ? null : v)}
options={[{ value: '', label: t('floor.noZone') }, ...groups.map(g => ({ value: g.id, label: g.name }))]} /> options={[{ value: '', label: t('floor.noZone') }, ...groups.map(g => ({ value: g.id, label: g.name }))]} />
</Field> </Field>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
@@ -222,8 +315,8 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
function Panel({ title, children }) { function Panel({ title, children }) {
return ( return (
<section className="grid gap-3 p-4 rounded-card border border-line bg-surface shadow-raised"> <section className="grid gap-3 p-card rounded-card border border-line bg-surface shadow-raised">
<h3 className="text-label font-semibold text-ink uppercase tracking-wide">{title}</h3> <h3 className="text-overline font-semibold text-ink-3 uppercase tracking-wide">{title}</h3>
{children} {children}
</section> </section>
) )
@@ -248,6 +341,7 @@ function TableButtons({ tables, title, onAdd, quiet = false }) {
function Selected({ thing, sel, plan, t, onChange, onRemove }) { function Selected({ thing, sel, plan, t, onChange, onRemove }) {
const isTable = sel.type === 'table' const isTable = sel.type === 'table'
const isArea = !isTable && thing.kind === 'area'
const setSize = (w, h) => onChange(resize(thing, plan, w, h)) const setSize = (w, h) => onChange(resize(thing, plan, w, h))
return ( return (
<Panel title={isTable ? t('floor.table', { name: thing.name }) : t(`floor.kinds.${thing.kind}`)}> <Panel title={isTable ? t('floor.table', { name: thing.name }) : t(`floor.kinds.${thing.kind}`)}>
@@ -276,10 +370,27 @@ function Selected({ thing, sel, plan, t, onChange, onRemove }) {
<Input size="sm" value={thing.text ?? ''} maxLength={60} onChange={e => onChange({ text: e.target.value })} data-testid="floor-item-text" /> <Input size="sm" value={thing.text ?? ''} maxLength={60} onChange={e => onChange({ text: e.target.value })} data-testid="floor-item-text" />
</Field> </Field>
)} )}
<div className="grid grid-cols-2 gap-2"> {isArea ? (
<Field label={t('floor.itemWidth')}><Input size="sm" type="number" min={4} value={thing.width} onChange={e => setSize(Number(e.target.value), undefined)} /></Field> <>
<Field label={t('floor.itemHeight')}><Input size="sm" type="number" min={4} value={thing.height} onChange={e => setSize(undefined, Number(e.target.value))} /></Field> <Field label={t('floor.colour')}>
</div> <div className="flex flex-wrap gap-2" role="radiogroup" aria-label={t('floor.colour')} data-testid="floor-area-colours">
{AREA_COLOURS.map(c => (
<button key={c} type="button" role="radio" aria-checked={thing.color === c} aria-label={c} onClick={() => onChange({ color: c })}
className={cx('w-8 h-8 rounded-full border-2', thing.color === c ? 'border-accent ring-2 ring-[var(--x-accent)] ring-offset-2 ring-offset-[var(--x-surface)]' : 'border-line')}
style={{ background: c, opacity: 0.85 }} />
))}
<button type="button" role="radio" aria-checked={!thing.color} onClick={() => onChange({ color: null })}
className={cx('px-2 h-8 rounded-full border-2 text-caption text-ink-2', !thing.color ? 'border-accent' : 'border-line')}>{t('floor.noColour')}</button>
</div>
</Field>
<p className="text-caption text-ink-2">{t('floor.areaResizeHint')}</p>
</>
) : (
<div className="grid grid-cols-2 gap-2">
<Field label={t('floor.itemWidth')}><Input size="sm" type="number" min={4} value={thing.width} onChange={e => setSize(Number(e.target.value), undefined)} /></Field>
<Field label={t('floor.itemHeight')}><Input size="sm" type="number" min={4} value={thing.height} onChange={e => setSize(undefined, Number(e.target.value))} /></Field>
</div>
)}
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<span className="text-label text-ink-2 mr-auto">{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}</span> <span className="text-label text-ink-2 mr-auto">{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}</span>
<IconButton size="sm" variant="secondary" label={t('floor.rotateLeft')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, -15) })}><RotateCcw size={16} /></IconButton> <IconButton size="sm" variant="secondary" label={t('floor.rotateLeft')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, -15) })}><RotateCcw size={16} /></IconButton>
@@ -29,7 +29,7 @@ export default function FloorPlansTab() {
{ id: null, name: t('floor.noZone'), plans: plans.filter(p => p.group_id == null || !groups.some(g => g.id === p.group_id)) }].filter(z => z.plans.length) { id: null, name: t('floor.noZone'), plans: plans.filter(p => p.group_id == null || !groups.some(g => g.id === p.group_id)) }].filter(z => z.plans.length)
return ( return (
<div className="p-4 md:p-6 grid gap-4" data-testid="floor-plans"> <div className="grid gap-4" data-testid="floor-plans">
<nav className="grid gap-2" aria-label={t('floor.title')}> <nav className="grid gap-2" aria-label={t('floor.title')}>
<p className="text-label text-ink-2 max-w-4xl">{t('floor.intro')}</p> <p className="text-label text-ink-2 max-w-4xl">{t('floor.intro')}</p>
<div className="flex flex-wrap items-end gap-x-4 gap-y-2"> <div className="flex flex-wrap items-end gap-x-4 gap-y-2">
@@ -1,7 +1,7 @@
// The floor plan editor's state as plain data (plan step 6.8, D-31), tested in tests/floor.test.mjs. // The floor plan editor's state as plain data (plan step 6.8, D-31), tested in tests/floor.test.mjs.
// A layout = { tables: [...placed tables], items: [...] } for one plan; the editor changes it // A layout = { tables: [...placed tables], items: [...] } for one plan; the editor changes it
// locally and saves it whole (PUT /api/floor-plans/{id}/layout). // locally and saves it whole (PUT /api/floor-plans/{id}/layout).
import { ITEM_SIZES, clamp, defaultSize, moveTo, snapSize } from '@xenia/floorplan/geometry' import { AREA_COLOURS, ITEM_SIZES, clamp, defaultSize, moveTo, snapSize } from '@xenia/floorplan/geometry'
/** The layout of a plan from GET /api/floor-plans. Items get local keys (`key`). */ /** The layout of a plan from GET /api/floor-plans. Items get local keys (`key`). */
export function layoutOf(data, planId) { export function layoutOf(data, planId) {
@@ -52,7 +52,8 @@ let counter = 0
export function addItem(layout, plan, kind, text = null) { export function addItem(layout, plan, kind, text = null) {
const [w, h] = ITEM_SIZES[kind] const [w, h] = ITEM_SIZES[kind]
const grid = gridOf(plan) const grid = gridOf(plan)
const item = moveTo({ key: `n${++counter}`, kind, width: snapSize(w, grid), height: kind === 'wall' ? h : snapSize(h, grid), rotation: 0, text }, plan.width / 2, plan.height / 2, plan) const item = moveTo({ key: `n${++counter}`, kind, width: snapSize(w, grid), height: kind === 'wall' ? h : snapSize(h, grid), rotation: 0, text,
color: kind === 'area' ? AREA_COLOURS[layout.items.filter(i => i.kind === 'area').length % AREA_COLOURS.length] : null }, plan.width / 2, plan.height / 2, plan)
return { layout: { ...layout, items: [...layout.items, item] }, key: item.key } return { layout: { ...layout, items: [...layout.items, item] }, key: item.key }
} }
@@ -98,7 +99,7 @@ export const rotate = (deg, by) => (((deg + by) % 360) + 360) % 360
export function layoutBody(layout) { export function layoutBody(layout) {
return { return {
tables: layout.tables.map(t => ({ id: t.id, x: t.x, y: t.y, width: t.width, height: t.height, rotation: t.rotation || 0, shape: t.shape || 'square', seats: t.seats ?? null })), tables: layout.tables.map(t => ({ id: t.id, x: t.x, y: t.y, width: t.width, height: t.height, rotation: t.rotation || 0, shape: t.shape || 'square', seats: t.seats ?? null })),
items: layout.items.map(i => ({ kind: i.kind, x: i.x, y: i.y, width: i.width, height: i.height, rotation: i.rotation || 0, text: i.text || null })), items: layout.items.map(i => ({ kind: i.kind, x: i.x, y: i.y, width: i.width, height: i.height, rotation: i.rotation || 0, text: i.text || null, color: i.kind === 'area' ? i.color || null : null })),
} }
} }
@@ -75,8 +75,8 @@ export default function TablesListTab() {
} }
return ( return (
<div className="flex flex-col h-full min-h-0" data-testid="tables-list"> <div className="rounded-card border border-line bg-surface shadow-raised min-w-0" data-testid="tables-list">
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 md:px-6 py-3 shrink-0"> <div className="flex flex-wrap items-center gap-2 border-b border-line px-card py-card-y">
{picking || picked.size ? (<> {picking || picked.size ? (<>
<Button size="sm" variant="ghost" icon={<X size={14} />} onClick={stopPicking}>{picked.size ? t('tablesList.picked', { count: picked.size }) : t('tablesList.pick')}</Button> <Button size="sm" variant="ghost" icon={<X size={14} />} onClick={stopPicking}>{picked.size ? t('tablesList.picked', { count: picked.size }) : t('tablesList.pick')}</Button>
<Button size="sm" variant="ghost" onClick={pickAll}>{t(allPicked ? 'tablesList.unpickAll' : 'tablesList.pickAll')}</Button> <Button size="sm" variant="ghost" onClick={pickAll}>{t(allPicked ? 'tablesList.unpickAll' : 'tablesList.pickAll')}</Button>
@@ -92,13 +92,13 @@ export default function TablesListTab() {
</span> </span>
)} )}
<span className="flex-1" /> <span className="flex-1" />
<Button size="sm" variant={inactive ? 'primary' : 'secondary'} aria-pressed={inactive} onClick={() => setInactive(v => !v)}>{t('tablesList.showOff')}</Button> <Button variant={inactive ? 'primary' : 'secondary'} aria-pressed={inactive} onClick={() => setInactive(v => !v)}>{t('tablesList.showOff')}</Button>
{!picking && <Button size="sm" variant="secondary" onClick={() => setPicking(true)} data-testid="tables-pick">{t('tablesList.pick')}</Button>} {!picking && <Button variant="secondary" onClick={() => setPicking(true)} data-testid="tables-pick">{t('tablesList.pick')}</Button>}
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => setDialog({ kind: 'zone', zone: {} })} data-testid="zone-new">{t('tablesList.newZone')}</Button> <Button variant="secondary" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'zone', zone: {} })} data-testid="zone-new">{t('tablesList.newZone')}</Button>
<Button size="sm" icon={<Plus size={14} />} onClick={() => setDialog({ kind: 'table', table: null })} data-testid="table-new">{t('tablesList.newTable')}</Button> <Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'table', table: null })} data-testid="table-new">{t('tablesList.newTable')}</Button>
</div> </div>
<div className="flex flex-wrap border-b border-line px-4 shrink-0" role="tablist" aria-label={t('tablesList.zones')}> <div className="flex flex-wrap border-b border-line px-card" role="tablist" aria-label={t('tablesList.zones')}>
{tabs.map(x => { {tabs.map(x => {
const i = x.zone ? zones.indexOf(x.zone) : -1 const i = x.zone ? zones.indexOf(x.zone) : -1
return ( return (
@@ -119,7 +119,7 @@ export default function TablesListTab() {
</div> </div>
{zone && ( {zone && (
<div className="flex flex-wrap items-center gap-3 px-4 md:px-6 py-2 border-b border-line shrink-0"> <div className="flex flex-wrap items-center gap-3 px-card py-2.5 border-b border-line bg-surface-2">
<span className="font-semibold text-ink text-label">{zone.name}</span> <span className="font-semibold text-ink text-label">{zone.name}</span>
{zone.prefix && <Pill>{zone.prefix}</Pill>} {zone.prefix && <Pill>{zone.prefix}</Pill>}
<Button size="sm" variant="ghost" icon={<Pencil size={13} />} onClick={() => setDialog({ kind: 'zone', zone })}>{t('tablesList.editZone')}</Button> <Button size="sm" variant="ghost" icon={<Pencil size={13} />} onClick={() => setDialog({ kind: 'zone', zone })}>{t('tablesList.editZone')}</Button>
@@ -127,7 +127,7 @@ export default function TablesListTab() {
</div> </div>
)} )}
<div className="flex-1 overflow-y-auto p-4 md:p-6"> <div className="p-card">
{!shown.length ? <EmptyState title={t(inactive ? 'tablesList.none' : 'tablesList.noneActive')} /> : ( {!shown.length ? <EmptyState title={t(inactive ? 'tablesList.none' : 'tablesList.noneActive')} /> : (
<ul className="rounded-card border border-line bg-surface divide-y divide-line overflow-hidden"> <ul className="rounded-card border border-line bg-surface divide-y divide-line overflow-hidden">
{shown.map((x, i) => { {shown.map((x, i) => {
+15 -1
View File
@@ -54,8 +54,22 @@ test('what is saved', () => {
const l = layoutOf(data, 1) const l = layoutOf(data, 1)
const body = layoutBody(l) const body = layoutBody(l)
assert.deepEqual(body.tables[0], { id: 1, x: 100, y: 100, width: 100, height: 100, rotation: 0, shape: 'square', seats: 4 }) assert.deepEqual(body.tables[0], { id: 1, x: 100, y: 100, width: 100, height: 100, rotation: 0, shape: 'square', seats: 4 })
assert.deepEqual(body.items[0], { kind: 'bar', x: 500, y: 50, width: 300, height: 50, rotation: 0, text: null }) assert.deepEqual(body.items[0], { kind: 'bar', x: 500, y: 50, width: 300, height: 50, rotation: 0, text: null, color: null })
assert.equal(sameLayout(l, layoutOf(data, 1)), true) assert.equal(sameLayout(l, layoutOf(data, 1)), true)
assert.deepEqual(planBody({ ...plan, name: ' Up ', background: { id: 4 }, outline: [[0, 0], [5, 5]] }), assert.deepEqual(planBody({ ...plan, name: ' Up ', background: { id: 4 }, outline: [[0, 0], [5, 5]] }),
{ name: 'Up', group_id: 10, width: 1000, height: 600, outline: null, grid_on: true, grid_size: 50, media_id: 4, background_opacity: 0.6 }) { name: 'Up', group_id: 10, width: 1000, height: 600, outline: null, grid_on: true, grid_size: 50, media_id: 4, background_opacity: 0.6 })
}) })
test('the floor’s shape: a corner added where the edge was pressed; an area resized by its handles', async () => {
const { addCornerAt, nearestEdge, resizeBox, coveredAreas } = await import('@xenia/floorplan/geometry')
const square = [[0, 0], [100, 0], [100, 100], [0, 100]]
const e = nearestEdge(square, [50, 4])
assert.equal(e.index, 0)
assert.deepEqual(addCornerAt(square, e.index, e.x, e.y, { width: 100, height: 100 }), [[0, 0], [50, 0], [100, 0], [100, 100], [0, 100]])
const area = { x: 100, y: 100, width: 100, height: 60 }
assert.deepEqual(resizeBox(area, 'e', 220, 0, { width: 500, height: 500 }), { x: 135, y: 100, width: 170, height: 60 })
assert.deepEqual(resizeBox(area, 'nw', 40, 40, { width: 500, height: 500, grid_on: true, grid_size: 20 }), { x: 95, y: 85, width: 110, height: 90 })
const named = { key: 'a', kind: 'area', text: 'Terrace', x: 200, y: 200, width: 300, height: 200 }
assert.equal(coveredAreas([named], []).size, 0)
assert.equal(coveredAreas([named], [{ x: 200, y: 200, width: 80, height: 80 }]).has('a'), true)
})
+3 -2
View File
@@ -5,7 +5,7 @@
// Styles are inline with @xenia/ui tokens, so it fits the apps with and without Tailwind. // Styles are inline with @xenia/ui tokens, so it fits the apps with and without Tailwind.
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { plansFor, splitTables, toneOf, TONES } from './geometry.js' import { coveredAreas, plansFor, splitTables, toneOf, TONES } from './geometry.js'
import { Floor, Item, TableShape } from './Shapes.jsx' import { Floor, Item, TableShape } from './Shapes.jsx'
const ZOOMS = [0.25, 0.35, 0.5, 0.75, 1, 1.25, 1.5, 2, 3] const ZOOMS = [0.25, 0.35, 0.5, 0.75, 1, 1.25, 1.5, 2, 3]
@@ -88,6 +88,7 @@ export function FloorView({ data, zone = null, onPick, mediaBase = '', height =
</div> </div>
) )
} }
const covered = coveredAreas(plan.items, placed, i => i.id)
// the scale on screen now: a fit is worked out from the space there is // the scale on screen now: a fit is worked out from the space there is
const fitWidth = size.width ? size.width / plan.width : 1 const fitWidth = size.width ? size.width / plan.width : 1
const fitAll = size.width && size.height ? Math.min(size.width / plan.width, size.height / plan.height) : fitWidth const fitAll = size.width && size.height ? Math.min(size.width / plan.width, size.height / plan.height) : fitWidth
@@ -113,7 +114,7 @@ export function FloorView({ data, zone = null, onPick, mediaBase = '', height =
<svg viewBox={`0 0 ${plan.width} ${plan.height}`} role="img" aria-label={plan.name} <svg viewBox={`0 0 ${plan.width} ${plan.height}`} role="img" aria-label={plan.name}
style={{ display: 'block', margin: zoom === 'all' ? '0 auto' : undefined, width: `${Math.max(1, plan.width * scale)}px`, height: `${Math.max(1, plan.height * scale)}px`, touchAction: 'pan-x pan-y pinch-zoom' }}> style={{ display: 'block', margin: zoom === 'all' ? '0 auto' : undefined, width: `${Math.max(1, plan.width * scale)}px`, height: `${Math.max(1, plan.height * scale)}px`, touchAction: 'pan-x pan-y pinch-zoom' }}>
<Floor plan={plan} mediaBase={mediaBase} /> <Floor plan={plan} mediaBase={mediaBase} />
{plan.items.map(i => <Item key={i.id} item={i} label={t('floorMap.bar')} />)} {plan.items.map(i => <Item key={i.id} item={i} label={t('floorMap.bar')} corner={covered.has(i.id)} />)}
{placed.map(table => ( {placed.map(table => (
<TableShape key={table.id} table={table} now={now} role="button" tabIndex={0} style={{ cursor: 'pointer' }} <TableShape key={table.id} table={table} now={now} role="button" tabIndex={0} style={{ cursor: 'pointer' }}
aria-label={`${table.name}: ${t(`floorMap.state.${toneOf(table)}`)}`} data-testid="floor-table" aria-label={`${table.name}: ${t(`floorMap.state.${toneOf(table)}`)}`} data-testid="floor-table"
+17 -7
View File
@@ -1,7 +1,7 @@
// The pieces of a floor plan as SVG (plan step 6.8): the floor (outline, grid, background // The pieces of a floor plan as SVG (plan step 6.8): the floor (outline, grid, background
// picture), the walls / bar / labels / areas, and a table with its chairs and what it shows. // picture), the walls / bar / labels / areas, and a table with its chairs and what it shows.
// Colours are @xenia/ui tokens (CSS variables), so the same drawing works in every app. // Colours are @xenia/ui tokens (CSS variables), so the same drawing works in every app.
import { chairs, durationText, outlineOf, peopleText, pointsAttr, TONES, toneOf } from './geometry.js' import { chairs, durationText, itemFontSize, outlineOf, peopleText, pointsAttr, TONES, toneOf } from './geometry.js'
/** The floor: background picture, the floor's shape, and the grid (when asked). */ /** The floor: background picture, the floor's shape, and the grid (when asked). */
export function Floor({ plan, showGrid = false, mediaBase = '' }) { export function Floor({ plan, showGrid = false, mediaBase = '' }) {
@@ -31,25 +31,35 @@ export function Floor({ plan, showGrid = false, mediaBase = '' }) {
const ITEM_LOOK = { const ITEM_LOOK = {
wall: { fill: 'var(--x-ink-2)', stroke: 'none' }, wall: { fill: 'var(--x-ink-2)', stroke: 'none' },
bar: { fill: 'var(--x-surface-3)', stroke: 'var(--x-ink-3)' }, bar: { fill: 'var(--x-surface-3)', stroke: 'var(--x-ink-3)' },
label: { fill: 'none', stroke: 'none' }, label: { fill: 'transparent', stroke: 'none' }, // transparent, not none: a label can be clicked
area: { fill: 'var(--x-surface-2)', stroke: 'var(--x-line-strong)', dash: '8 6' }, area: { fill: 'var(--x-surface-2)', stroke: 'var(--x-line-strong)', dash: '8 6' },
} }
/** A wall, the bar, a label or an area. */ /**
export function Item({ item, selected = false, label, ...rest }) { * A wall, the bar, a label or an area. An area may have a colour (drawn see-through, 2026-11-20);
* `corner`: its name is covered by tables, so it shows in the top-left corner as well.
*/
export function Item({ item, selected = false, label, corner = false, ...rest }) {
const look = ITEM_LOOK[item.kind] ?? ITEM_LOOK.area const look = ITEM_LOOK[item.kind] ?? ITEM_LOOK.area
const w = item.width const w = item.width
const h = item.height const h = item.height
const text = item.text || (item.kind === 'bar' ? label : '') const text = item.text || (item.kind === 'bar' ? label : '')
const colour = item.kind === 'area' && item.color ? item.color : null
const fs = text ? itemFontSize(item, text) : 0
return ( return (
<g transform={`translate(${item.x} ${item.y}) rotate(${item.rotation || 0})`} {...rest}> <g transform={`translate(${item.x} ${item.y}) rotate(${item.rotation || 0})`} {...rest}>
<rect x={-w / 2} y={-h / 2} width={w} height={h} rx={item.kind === 'wall' ? 2 : 8} <rect x={-w / 2} y={-h / 2} width={w} height={h} rx={item.kind === 'wall' ? 2 : 8}
fill={look.fill} stroke={selected ? 'var(--x-accent)' : look.stroke} strokeWidth={selected ? 4 : 2} strokeDasharray={selected ? undefined : look.dash} /> fill={colour ?? look.fill} fillOpacity={colour ? 0.3 : undefined}
stroke={selected ? 'var(--x-accent)' : colour ?? look.stroke} strokeOpacity={colour && !selected ? 0.9 : undefined}
strokeWidth={selected ? 4 : 2} strokeDasharray={selected ? undefined : look.dash} />
{item.kind === 'label' && selected && <rect x={-w / 2} y={-h / 2} width={w} height={h} fill="none" stroke="var(--x-accent)" strokeWidth="2" strokeDasharray="6 4" />} {item.kind === 'label' && selected && <rect x={-w / 2} y={-h / 2} width={w} height={h} fill="none" stroke="var(--x-accent)" strokeWidth="2" strokeDasharray="6 4" />}
{text && ( {text && (
<text x="0" y="0" textAnchor="middle" dominantBaseline="central" fill="var(--x-ink-2)" pointerEvents="none" <text x="0" y="0" textAnchor="middle" dominantBaseline="central" fill="var(--x-ink-2)" pointerEvents="none"
fontSize={Math.max(12, Math.min(28, h * 0.5, (w / Math.max(text.length, 1)) * 1.6))} fontWeight="600" fontSize={fs} fontWeight="600" transform={`rotate(${-(item.rotation || 0)})`}>{text}</text>
transform={`rotate(${-(item.rotation || 0)})`}>{text}</text> )}
{text && corner && (
<text x={-w / 2 + 10} y={-h / 2 + 10 + Math.min(16, fs) / 2} dominantBaseline="central" fill="var(--x-ink-2)" pointerEvents="none"
fontSize={Math.min(16, fs)} fontWeight="700" data-testid="floor-area-corner">{text}</text>
)} )}
</g> </g>
) )
+73
View File
@@ -137,3 +137,76 @@ export function toPlan(svg, clientX, clientY) {
const vb = svg.viewBox.baseVal const vb = svg.viewBox.baseVal
return [vb.x + ((clientX - r.left) / r.width) * vb.width, vb.y + ((clientY - r.top) / r.height) * vb.height] return [vb.x + ((clientX - r.left) / r.width) * vb.width, vb.y + ((clientY - r.top) / r.height) * vb.height]
} }
// ── 2026-11-20: grid resolution, area colours, adding corners on an edge, resizing ──────────
/** The grid's resolution: a name for each cell size (ultra high = small cells, very precise). */
export const GRID_LEVELS = [['ultraHigh', 20], ['high', 40], ['normal', 50], ['low', 80], ['veryLow', 100]]
/** The colours an area can have (pastel; drawn see-through). Data, like the categories' colours. */
export const AREA_COLOURS = ['#93c5fd', '#86efac', '#fcd34d', '#f9a8d4', '#c4b5fd', '#fdba74', '#5eead4', '#cbd5e1']
/** The point of segment a–b nearest to p, and how far it is: { x, y, d, t }. */
export function nearestOnSegment([ax, ay], [bx, by], [px, py]) {
const dx = bx - ax
const dy = by - ay
const len = dx * dx + dy * dy
const t = len ? clamp(((px - ax) * dx + (py - ay) * dy) / len, 0, 1) : 0
const x = ax + t * dx
const y = ay + t * dy
return { x, y, t, d: Math.hypot(px - x, py - y) }
}
/** The floor's edge nearest to a point: { index (the corner it starts at), x, y, d }. */
export function nearestEdge(points, p) {
let best = null
points.forEach((a, i) => {
const n = nearestOnSegment(a, points[(i + 1) % points.length], p)
if (!best || n.d < best.d) best = { index: i, ...n }
})
return best
}
/** A corner added on edge `i` (after corner i) at a point (on the grid when there is one). */
export function addCornerAt(points, i, x, y, plan) {
const grid = plan?.grid_on ? plan.grid_size : 0
const out = [...points]
out.splice(i + 1, 0, [clamp(snap(x, grid), 0, plan?.width ?? x), clamp(snap(y, grid), 0, plan?.height ?? y)])
return out
}
/** Drag a side or corner of an unrotated box: handle is a mix of 'n' 's' 'e' 'w'; the opposite side stays. */
export function resizeBox(thing, handle, px, py, plan, min = 20) {
const grid = plan?.grid_on ? plan.grid_size : 0
let left = thing.x - thing.width / 2
let right = thing.x + thing.width / 2
let top = thing.y - thing.height / 2
let bottom = thing.y + thing.height / 2
const at = v => (grid ? snap(v, grid) : Math.round(v))
if (handle.includes('w')) left = Math.min(at(clamp(px, 0, plan.width)), right - min)
if (handle.includes('e')) right = Math.max(at(clamp(px, 0, plan.width)), left + min)
if (handle.includes('n')) top = Math.min(at(clamp(py, 0, plan.height)), bottom - min)
if (handle.includes('s')) bottom = Math.max(at(clamp(py, 0, plan.height)), top + min)
return { x: (left + right) / 2, y: (top + bottom) / 2, width: right - left, height: bottom - top }
}
/** The size of an item's text (as Item draws it). */
export const itemFontSize = (item, text) => Math.max(12, Math.min(28, item.height * 0.5, (item.width / Math.max(text.length, 1)) * 1.6))
const boxOf = t => ({ l: t.x - (t.width || 80) / 2, r: t.x + (t.width || 80) / 2, t: t.y - (t.height || 80) / 2, b: t.y + (t.height || 80) / 2 })
const overlaps = (a, b) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
/** The keys / ids of the areas whose name is covered by a table or another thing: those show
* their name in a corner too. things: the plan's items; tables: placed tables. */
export function coveredAreas(items, tables, keyOf = i => i.key ?? i.id) {
const out = new Set()
for (const a of items) {
if (a.kind !== 'area' || !a.text) continue
const fs = itemFontSize(a, a.text)
const w = a.text.length * fs * 0.6
const label = { l: a.x - w / 2, r: a.x + w / 2, t: a.y - fs * 0.6, b: a.y + fs * 0.6 }
const others = [...tables, ...items.filter(i => i !== a && i.kind !== 'area')]
if (others.some(o => overlaps(label, boxOf(o)))) out.add(keyOf(a))
}
return out
}
+17 -3
View File
@@ -2585,10 +2585,10 @@
"tableCount_one": "{{count}} τραπέζι", "tableCount_one": "{{count}} τραπέζι",
"tableCount_other": "{{count}} τραπέζια", "tableCount_other": "{{count}} τραπέζια",
"grid": "Πλέγμα", "grid": "Πλέγμα",
"gridSize": "Μέγεθος πλέγματος", "gridSize": "Ανάλυση πλέγματος",
"gridCell": "Κελιά των {{size}}", "gridCell": "Κελιά των {{size}}",
"editShape": "Αλλαγή σχήματος χώρου", "editShape": "Αλλαγή σχήματος χώρου",
"shapeHint": "Σύρετε τις γωνίες για να πάρει ο χώρος το πραγματικό του σχήμα (Γ, βεράντα…). Επιλέξτε μια γωνία για να προσθέσετε μία μετά από αυτή ή να την αφαιρέσετε.", "shapeHint": "Σύρετε μια γωνία για να τη μετακινήσετε. Πάνω σε μια πλευρά φαίνεται ένα +: πατήστε εκεί για νέα γωνία (και σύρετέ τη). Σταθείτε σε μια γωνία για να την αφαιρέσετε.",
"shapeTitle": "Το σχήμα του χώρου", "shapeTitle": "Το σχήμα του χώρου",
"cornerCount_one": "{{count}} γωνία", "cornerCount_one": "{{count}} γωνία",
"cornerCount_other": "{{count}} γωνίες", "cornerCount_other": "{{count}} γωνίες",
@@ -2632,7 +2632,21 @@
"rotateLeft": "Στροφή αριστερά 15°", "rotateLeft": "Στροφή αριστερά 15°",
"rotateRight": "Στροφή δεξιά 15°", "rotateRight": "Στροφή δεξιά 15°",
"takeOff": "Βγάλτε το από την κάτοψη", "takeOff": "Βγάλτε το από την κάτοψη",
"removeThing": "Αφαίρεση" "removeThing": "Αφαίρεση",
"gridLevels": {
"ultraHigh": "Πολύ υψηλή",
"high": "Υψηλή",
"normal": "Κανονική",
"low": "Χαμηλή",
"veryLow": "Πολύ χαμηλή"
},
"fit": "Προσαρμογή",
"fitWidth": "Στο πλάτος",
"fitAll": "Όλο το σχέδιο",
"shapeHowTo": "Ένας χώρος έχει τουλάχιστον 3 γωνίες.",
"colour": "Χρώμα",
"noColour": "Κανένα",
"areaResizeHint": "Σύρετε τις λαβές στις πλευρές και τις γωνίες για να αλλάξετε το μέγεθος."
}, },
"orders": { "orders": {
"back": "Πίσω", "back": "Πίσω",
+18 -4
View File
@@ -2585,15 +2585,15 @@
"tableCount_one": "{{count}} table", "tableCount_one": "{{count}} table",
"tableCount_other": "{{count}} tables", "tableCount_other": "{{count}} tables",
"grid": "Grid", "grid": "Grid",
"gridSize": "Grid size", "gridSize": "Grid resolution",
"gridCell": "Cells of {{size}}", "gridCell": "Cells of {{size}}",
"editShape": "Edit the floor's shape", "editShape": "Edit the floor's shape",
"shapeHint": "Drag the corners to give the floor its real shape (an L, a terrace…). Pick a corner to add one after it or remove it.", "shapeHint": "Drag a corner to move it. On an edge a + shows: press there to add a corner (and drag it). Rest on a corner to remove it.",
"shapeTitle": "The floor's shape", "shapeTitle": "The floor's shape",
"cornerCount_one": "{{count}} corner", "cornerCount_one": "{{count}} corner",
"cornerCount_other": "{{count}} corners", "cornerCount_other": "{{count}} corners",
"addCorner": "Add a corner after it", "addCorner": "Add a corner after it",
"removeCorner": "Remove the corner", "removeCorner": "Remove this corner",
"rectangle": "Back to a rectangle", "rectangle": "Back to a rectangle",
"canvas": "The floor plan: drag the tables and things; arrow keys move the selected one", "canvas": "The floor plan: drag the tables and things; arrow keys move the selected one",
"keysHint": "Arrow keys move what's selected (one grid cell, or 5; with Shift 1), Delete takes it off, Escape lets go.", "keysHint": "Arrow keys move what's selected (one grid cell, or 5; with Shift 1), Delete takes it off, Escape lets go.",
@@ -2632,7 +2632,21 @@
"rotateLeft": "Turn left 15°", "rotateLeft": "Turn left 15°",
"rotateRight": "Turn right 15°", "rotateRight": "Turn right 15°",
"takeOff": "Take it off the plan", "takeOff": "Take it off the plan",
"removeThing": "Remove" "removeThing": "Remove",
"gridLevels": {
"ultraHigh": "Ultra high",
"high": "High",
"normal": "Normal",
"low": "Low",
"veryLow": "Very low"
},
"fit": "Fit",
"fitWidth": "Fit width",
"fitAll": "Whole plan",
"shapeHowTo": "A floor has at least 3 corners.",
"colour": "Colour",
"noColour": "None",
"areaResizeHint": "Drag the handles on its sides and corners to resize it."
}, },
"orders": { "orders": {
"back": "Back", "back": "Back",
+10 -6
View File
@@ -1122,14 +1122,18 @@ try {
await page.mouse.up() await page.mouse.up()
// an irregular floor: a corner more, pulled in // an irregular floor: a corner more, pulled in
await page.getByTestId('floor-shape-mode').click() await page.getByTestId('floor-shape-mode').click()
await page.getByTestId('floor-corner').nth(1).click() // 2026-11-20: a "+" shows on the edge under the pointer; pressing there adds a corner and drags it
await page.getByTestId('floor-corner-add').click() const c1 = await page.getByTestId('floor-corner').nth(1).boundingBox()
await page.getByTestId('floor-corner').nth(2).scrollIntoViewIfNeeded() const c2 = await page.getByTestId('floor-corner').nth(2).boundingBox()
const corner = await page.getByTestId('floor-corner').nth(2).boundingBox() const mid = { x: (c1.x + c1.width / 2 + c2.x + c2.width / 2) / 2, y: (c1.y + c1.height / 2 + c2.y + c2.height / 2) / 2 }
await page.mouse.move(corner.x + corner.width / 2, corner.y + corner.height / 2) await page.mouse.move(mid.x, mid.y - 3)
await page.mouse.move(mid.x, mid.y, { steps: 2 })
await page.getByTestId('floor-edge-add').waitFor({ timeout: 3000 }).catch(() => {})
r.check('floor: a "+" shows on the floor's edge under the pointer', await page.getByTestId('floor-edge-add').count() === 1)
await page.mouse.down() await page.mouse.down()
await page.mouse.move(corner.x - 120, corner.y + 10, { steps: 6 }) await page.mouse.move(mid.x - 120, mid.y + 10, { steps: 6 })
await page.mouse.up() await page.mouse.up()
r.check('floor: pressing on the edge added a corner (5)', await page.getByTestId('floor-corner').count() === 5)
await page.getByTestId('floor-shape-mode').click() await page.getByTestId('floor-shape-mode').click()
await page.screenshot({ path: path.join(OUT, 'manager-floor-editor.png') }) await page.screenshot({ path: path.join(OUT, 'manager-floor-editor.png') })
await page.getByTestId('floor-save').click() await page.getByTestId('floor-save').click()
+5 -3
View File
@@ -16,14 +16,16 @@ import { killTree, login, startBackend, waitHttp } from './lib/proc.mjs'
const DIR = path.join(OUT, 'manager-layout') const DIR = path.join(OUT, 'manager-layout')
mkdirSync(DIR, { recursive: true }) mkdirSync(DIR, { recursive: true })
// pages on <Page> (the rest have their own layout: products, tables set-up, stock placeholder) // pages on <Page> (all but the stock placeholder, 2026-11-20)
const PAGES = [ const PAGES = [
'dashboard', 'tables', 'tables?view=qr', 'online-orders', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'dashboard', 'tables', 'tables?view=qr', 'online-orders', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers',
'financials/expenses', 'financials/tabs', 'management/media', 'management/signage', 'management/staff', 'management/sessions', 'financials/expenses', 'financials/tabs', 'management/media', 'management/signage', 'management/staff', 'management/sessions',
'management/approvals', 'management/schedule', 'management/prep-zones', 'management/pricing', 'inventory/throwaways', 'notes', 'management/approvals', 'management/schedule', 'management/prep-zones', 'management/pricing', 'management/pricing?tab=channels',
'management/products', 'management/tables', 'management/tables?tab=floor', 'inventory/throwaways', 'notes',
'reports/today', 'reports/store', 'devices', 'license', 'apps', 'settings?tab=operation', 'reports/today', 'reports/store', 'devices', 'license', 'apps', 'settings?tab=operation',
] ]
const SHOTS = ['dashboard', 'tables', 'tables?view=qr', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'financials/expenses'] const SHOTS = ['dashboard', 'tables', 'tables?view=qr', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'financials/expenses',
'management/products', 'management/tables?tab=floor', 'management/pricing?tab=channels', 'financials/tabs', 'management/staff']
const SCREENS = [{ id: '1080p', width: 1920, height: 1080 }, { id: 'ultrawide', width: 3440, height: 1440 }] const SCREENS = [{ id: '1080p', width: 1920, height: 1080 }, { id: 'ultrawide', width: 3440, height: 1440 }]
const MODULES = ['connect_orders', 'connect_menu', 'crm', 'tabs', 'expenses', 'inventory', 'notes', 'chat', 'reservations', 'pricing', 'signage', 'staff_planning'] const MODULES = ['connect_orders', 'connect_menu', 'crm', 'tabs', 'expenses', 'inventory', 'notes', 'chat', 'reservations', 'pricing', 'signage', 'staff_planning']