Add canvas foundation: SVG viewport, pan/zoom/pinch, geometry lib (#9)
The editor's technically-riskiest slice, built against mock data so #11 only adds interactions on top. - lib/geometry.ts (+ vitest): world<->screen and object-local<->world transforms, clampScale, zoomViewportAt (the wheel/pinch "keep the point under the cursor stationary" math), zoomToFitRect. 11 geometry tests (round-trips, rotation, cursor-anchored zoom, fit) + 6 units tests. - editor/store.ts: Zustand store for ephemeral editor state — viewport, selection, focusedObjectId (selection interactions grow in #11). - editor/useViewport.ts: @use-gesture wiring — wheel + pinch zoom toward the pointer, drag-pan, scale clamped to [0.05, 20] px/cm, and an animated fitToRect (eased rAF tween). touch-action:none so the browser doesn't fight gestures. - editor/ObjectShape.tsx: rect/circle centered + rotated, kind default colors, name label; non-scaling strokes so outlines stay 1px at any zoom. - editor/GardenCanvas.tsx: full-size svg, single world <g>, fading 1m grid, garden boundary, z-ordered objects; ResizeObserver-driven auto-fit, a zoom readout, and a Fit control. Deps: zustand, @use-gesture/react, vitest (+ test scripts). - GardenEditorPage renders the canvas with a mock scene (#11 swaps in /full). Verified in a real browser: wheel zoom keeps the world point under the cursor stationary (sub-cm drift on a 12m garden), a real drag pans, and Fit animates to frame the garden. tsc + vitest green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { Size } from '@/lib/geometry'
|
||||
import { ObjectShape } from './ObjectShape'
|
||||
import { useEditorStore } from './store'
|
||||
import { useViewport } from './useViewport'
|
||||
import type { EditorGarden, EditorObject } from './types'
|
||||
|
||||
const GRID_CM = 100 // 1 m grid
|
||||
const GRID_MIN_CELL_PX = 6 // hide the grid when cells get this small (zoomed out)
|
||||
|
||||
/**
|
||||
* The editor canvas: a full-size SVG with a single world <g> that pan/zoom/pinch
|
||||
* transforms. Renders a fading 1 m grid, the garden boundary, and its objects.
|
||||
* Interactions beyond viewport + basic select (move/resize/rotate, palette) land
|
||||
* in #11; this is the foundation, driven by mock data until then.
|
||||
*/
|
||||
export function GardenCanvas({ garden, objects }: { garden: EditorGarden; objects: EditorObject[] }) {
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [size, setSize] = useState<Size>({ w: 0, h: 0 })
|
||||
const fittedRef = useRef(false)
|
||||
|
||||
const viewport = useEditorStore((s) => s.viewport)
|
||||
const selectedId = useEditorStore((s) => s.selectedId)
|
||||
const select = useEditorStore((s) => s.select)
|
||||
const { fitToRect } = useViewport(svgRef)
|
||||
|
||||
const gardenRect = useMemo(
|
||||
() => ({ x: 0, y: 0, w: garden.widthCm, h: garden.heightCm }),
|
||||
[garden.widthCm, garden.heightCm],
|
||||
)
|
||||
|
||||
// Track the container's pixel size for fit math.
|
||||
useEffect(() => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
const ro = new ResizeObserver(([entry]) => {
|
||||
setSize({ w: entry.contentRect.width, h: entry.contentRect.height })
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
// Frame the garden the first time we know the canvas size.
|
||||
useEffect(() => {
|
||||
if (!fittedRef.current && size.w > 0 && size.h > 0) {
|
||||
fittedRef.current = true
|
||||
fitToRect(gardenRect, size)
|
||||
}
|
||||
}, [size, gardenRect, fitToRect])
|
||||
|
||||
const showGrid = GRID_CM * viewport.scale >= GRID_MIN_CELL_PX
|
||||
const ordered = useMemo(() => [...objects].sort((a, b) => a.zIndex - b.zIndex), [objects])
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-xl border border-border bg-bg">
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="h-full w-full select-none"
|
||||
style={{ touchAction: 'none' }}
|
||||
// Any pointerdown reaching the svg is empty space (objects stopPropagation),
|
||||
// so it deselects.
|
||||
onPointerDown={() => select(null)}
|
||||
>
|
||||
<g transform={`translate(${viewport.tx} ${viewport.ty}) scale(${viewport.scale})`}>
|
||||
{showGrid && (
|
||||
<>
|
||||
<defs>
|
||||
<pattern id="garden-grid" width={GRID_CM} height={GRID_CM} patternUnits="userSpaceOnUse">
|
||||
<path
|
||||
d={`M ${GRID_CM} 0 L 0 0 0 ${GRID_CM}`}
|
||||
fill="none"
|
||||
stroke="#808080"
|
||||
strokeOpacity={0.18}
|
||||
strokeWidth={1}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x={0} y={0} width={garden.widthCm} height={garden.heightCm} fill="url(#garden-grid)" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Garden boundary. */}
|
||||
<rect
|
||||
x={0}
|
||||
y={0}
|
||||
width={garden.widthCm}
|
||||
height={garden.heightCm}
|
||||
fill="none"
|
||||
stroke="#3f8f4f"
|
||||
strokeOpacity={0.7}
|
||||
strokeWidth={1.5}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
|
||||
{ordered.map((o) => (
|
||||
<ObjectShape key={o.id} object={o} selected={o.id === selectedId} onSelect={select} />
|
||||
))}
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
{/* Overlay: zoom readout + fit control. */}
|
||||
<div className="pointer-events-none absolute left-3 top-3 rounded-md bg-surface/80 px-2 py-1 text-xs text-muted backdrop-blur">
|
||||
{viewport.scale.toFixed(2)} px/cm
|
||||
</div>
|
||||
<div className="absolute bottom-3 right-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => size.w > 0 && fitToRect(gardenRect, size)}
|
||||
className="rounded-md border border-border bg-surface/90 px-3 py-1.5 text-sm font-medium text-fg shadow-sm outline-none backdrop-blur transition-colors hover:bg-border/50 focus-visible:ring-2 focus-visible:ring-accent/40"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { PointerEvent } from 'react'
|
||||
import type { EditorObject } from './types'
|
||||
|
||||
// Default fills by kind (overridable per object via object.color). Muted, earthy
|
||||
// tones so plops (added in #15) read clearly on top.
|
||||
const kindColors: Record<string, string> = {
|
||||
bed: '#8a6d4b',
|
||||
grow_bag: '#9c7a52',
|
||||
container: '#6b7f8a',
|
||||
in_ground: '#7a6a4a',
|
||||
tree: '#4f7a4f',
|
||||
path: '#b8b0a0',
|
||||
structure: '#8a8a8a',
|
||||
}
|
||||
|
||||
function fillFor(o: EditorObject): string {
|
||||
return o.color ?? kindColors[o.kind] ?? '#8a8a8a'
|
||||
}
|
||||
|
||||
/**
|
||||
* One garden object in world (cm) space: a centered rect or circle, rotated
|
||||
* about its center, with the object's name. The parent world <g> applies the
|
||||
* viewport scale, so geometry is authored in cm; strokes use
|
||||
* vector-effect=non-scaling-stroke to stay a constant pixel width at any zoom.
|
||||
* Full move/resize/rotate interactions come in #11.
|
||||
*/
|
||||
export function ObjectShape({
|
||||
object,
|
||||
selected,
|
||||
onSelect,
|
||||
}: {
|
||||
object: EditorObject
|
||||
selected: boolean
|
||||
onSelect: (id: number) => void
|
||||
}) {
|
||||
const fill = fillFor(object)
|
||||
const halfW = object.widthCm / 2
|
||||
const halfH = object.heightCm / 2
|
||||
// Label size scales with the object but is clamped to a sensible cm range.
|
||||
const fontCm = Math.max(8, Math.min(40, Math.min(object.widthCm, object.heightCm) * 0.28))
|
||||
|
||||
function handleDown(e: PointerEvent) {
|
||||
e.stopPropagation() // don't let the canvas treat this as an empty-space pan/deselect
|
||||
onSelect(object.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<g
|
||||
transform={`translate(${object.xCm} ${object.yCm}) rotate(${object.rotationDeg})`}
|
||||
onPointerDown={handleDown}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
{object.shape === 'circle' ? (
|
||||
<circle
|
||||
cx={0}
|
||||
cy={0}
|
||||
r={halfW}
|
||||
fill={fill}
|
||||
fillOpacity={0.85}
|
||||
stroke={selected ? '#2f7a3e' : '#00000033'}
|
||||
strokeWidth={selected ? 2 : 1}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
) : (
|
||||
<rect
|
||||
x={-halfW}
|
||||
y={-halfH}
|
||||
width={object.widthCm}
|
||||
height={object.heightCm}
|
||||
rx={Math.min(halfW, halfH) * 0.06}
|
||||
fill={fill}
|
||||
fillOpacity={0.85}
|
||||
stroke={selected ? '#2f7a3e' : '#00000033'}
|
||||
strokeWidth={selected ? 2 : 1}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
)}
|
||||
|
||||
{object.name && (
|
||||
<text
|
||||
x={0}
|
||||
y={0}
|
||||
fontSize={fontCm}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="central"
|
||||
fill="#ffffff"
|
||||
style={{ pointerEvents: 'none', userSelect: 'none' }}
|
||||
>
|
||||
{object.name}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { create } from 'zustand'
|
||||
import type { Viewport } from '@/lib/geometry'
|
||||
|
||||
// Ephemeral editor state only (per DESIGN § State): the viewport, the current
|
||||
// selection, and which object is "focused" (zoomed into for plops, #15). All
|
||||
// server state stays in react-query. Selection interactions grow in #11.
|
||||
|
||||
export const MIN_SCALE = 0.05 // px per cm — fully zoomed out
|
||||
export const MAX_SCALE = 20 // px per cm — fully zoomed in
|
||||
|
||||
interface EditorState {
|
||||
viewport: Viewport
|
||||
setViewport: (next: Viewport | ((prev: Viewport) => Viewport)) => void
|
||||
|
||||
selectedId: number | null
|
||||
select: (id: number | null) => void
|
||||
|
||||
focusedObjectId: number | null
|
||||
setFocusedObject: (id: number | null) => void
|
||||
}
|
||||
|
||||
export const useEditorStore = create<EditorState>((set) => ({
|
||||
viewport: { tx: 0, ty: 0, scale: 1 },
|
||||
setViewport: (next) =>
|
||||
set((s) => ({ viewport: typeof next === 'function' ? next(s.viewport) : next })),
|
||||
|
||||
selectedId: null,
|
||||
select: (id) => set({ selectedId: id }),
|
||||
|
||||
focusedObjectId: null,
|
||||
setFocusedObject: (id) => set({ focusedObjectId: id }),
|
||||
}))
|
||||
@@ -0,0 +1,28 @@
|
||||
// The object shape the canvas renders. A subset of the server's garden object
|
||||
// (#10); #11 maps /full's objects onto this. Positioned by center in garden cm.
|
||||
|
||||
export type ObjectShapeKind = 'rect' | 'circle'
|
||||
|
||||
export interface EditorObject {
|
||||
id: number
|
||||
kind: string
|
||||
name: string
|
||||
shape: ObjectShapeKind
|
||||
xCm: number
|
||||
yCm: number
|
||||
widthCm: number
|
||||
heightCm: number
|
||||
rotationDeg: number
|
||||
zIndex: number
|
||||
color?: string | null
|
||||
plantable: boolean
|
||||
}
|
||||
|
||||
/** The garden being edited: its bounds define the canvas extent. */
|
||||
export interface EditorGarden {
|
||||
id: number
|
||||
name: string
|
||||
widthCm: number
|
||||
heightCm: number
|
||||
unitPref: 'metric' | 'imperial'
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useCallback, useEffect, useRef, type RefObject } from 'react'
|
||||
import { useGesture } from '@use-gesture/react'
|
||||
import { zoomToFitRect, zoomViewportAt, type Point, type Rect, type Size } from '@/lib/geometry'
|
||||
import { MAX_SCALE, MIN_SCALE, useEditorStore } from './store'
|
||||
|
||||
const WHEEL_SENSITIVITY = 0.0015 // exponential zoom per wheel delta unit
|
||||
const FIT_PADDING = 32 // px margin around a fitted rect
|
||||
const FIT_DURATION_MS = 350
|
||||
|
||||
const easeInOutCubic = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2)
|
||||
const lerp = (a: number, b: number, t: number) => a + (b - a) * t
|
||||
|
||||
/**
|
||||
* Wires pan/zoom/pinch gestures onto the svg (via @use-gesture) and returns an
|
||||
* animated `fitToRect`. Wheel and pinch zoom toward the pointer; drag on empty
|
||||
* space pans (object dragging in #11 stops propagation). Scale is clamped to
|
||||
* [MIN_SCALE, MAX_SCALE]. The svg must set touch-action:none so the browser
|
||||
* doesn't hijack the gestures.
|
||||
*/
|
||||
export function useViewport(svgRef: RefObject<SVGSVGElement | null>) {
|
||||
const setViewport = useEditorStore((s) => s.setViewport)
|
||||
const animRef = useRef<number | null>(null)
|
||||
|
||||
const cancelAnim = useCallback(() => {
|
||||
if (animRef.current != null) {
|
||||
cancelAnimationFrame(animRef.current)
|
||||
animRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const toLocal = useCallback(
|
||||
(clientX: number, clientY: number): Point => {
|
||||
const rect = svgRef.current?.getBoundingClientRect()
|
||||
return rect ? { x: clientX - rect.left, y: clientY - rect.top } : { x: clientX, y: clientY }
|
||||
},
|
||||
[svgRef],
|
||||
)
|
||||
|
||||
useGesture(
|
||||
{
|
||||
onDragStart: cancelAnim,
|
||||
onDrag: ({ delta: [dx, dy], pinching, cancel }) => {
|
||||
if (pinching) {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
setViewport((vp) => ({ ...vp, tx: vp.tx + dx, ty: vp.ty + dy }))
|
||||
},
|
||||
onWheelStart: cancelAnim,
|
||||
onWheel: ({ event, delta: [, dy] }) => {
|
||||
event.preventDefault()
|
||||
const p = toLocal(event.clientX, event.clientY)
|
||||
setViewport((vp) => zoomViewportAt(vp, p, vp.scale * Math.exp(-dy * WHEEL_SENSITIVITY), MIN_SCALE, MAX_SCALE))
|
||||
},
|
||||
onPinchStart: cancelAnim,
|
||||
onPinch: ({ origin: [ox, oy], offset: [scale] }) => {
|
||||
const p = toLocal(ox, oy)
|
||||
setViewport((vp) => zoomViewportAt(vp, p, scale, MIN_SCALE, MAX_SCALE))
|
||||
},
|
||||
},
|
||||
{
|
||||
target: svgRef,
|
||||
eventOptions: { passive: false }, // so onWheel can preventDefault
|
||||
drag: { filterTaps: true },
|
||||
pinch: {
|
||||
// Seed the pinch offset with the current scale so offset[0] is absolute.
|
||||
from: () => [useEditorStore.getState().viewport.scale, 0],
|
||||
scaleBounds: { min: MIN_SCALE, max: MAX_SCALE },
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const fitToRect = useCallback(
|
||||
(rect: Rect, viewport: Size) => {
|
||||
cancelAnim()
|
||||
const from = useEditorStore.getState().viewport
|
||||
const to = zoomToFitRect(rect, viewport, FIT_PADDING, MIN_SCALE, MAX_SCALE)
|
||||
const start = performance.now()
|
||||
const step = (now: number) => {
|
||||
const t = Math.min(1, (now - start) / FIT_DURATION_MS)
|
||||
const e = easeInOutCubic(t)
|
||||
setViewport({ tx: lerp(from.tx, to.tx, e), ty: lerp(from.ty, to.ty, e), scale: lerp(from.scale, to.scale, e) })
|
||||
animRef.current = t < 1 ? requestAnimationFrame(step) : null
|
||||
}
|
||||
animRef.current = requestAnimationFrame(step)
|
||||
},
|
||||
[cancelAnim, setViewport],
|
||||
)
|
||||
|
||||
useEffect(() => cancelAnim, [cancelAnim]) // stop any tween on unmount
|
||||
|
||||
return { fitToRect }
|
||||
}
|
||||
Reference in New Issue
Block a user