diff --git a/docs/docs/reference/react/pages/Editor/index.md b/docs/docs/reference/react/pages/Editor/index.md new file mode 100644 index 000000000..832a37a60 --- /dev/null +++ b/docs/docs/reference/react/pages/Editor/index.md @@ -0,0 +1,80 @@ +--- +title: Editor Page +description: Interactive SVG editor page with pan/zoom and a “color reveal” mode for inspecting generated SVG regions. +keywords: [editor, svg, pan, zoom, pinch, pointer events, react-router, Img2Num] +sidebar_label: Editor +--- + +## Overview + +- Interactive SVG viewer that supports pan, zoom (wheel/pinch), and a one-way “reveal color” mode; preview mode disables interaction but keeps revealed regions visible. +- Reached at `/editor` with an SVG string passed via navigation state (`navigate('/editor', { state: { svg } })`); if missing, the page shows “No SVG data found.” +- Layout: outer GlassCard with a top-right mode switch; inner viewport applies translate + scale to a wrapper while the SVG is parsed by `html-react-parser`. + +## Where things live + +- Page: [src/pages/Editor/index.jsx](https://github.com/Ryan-Millard/Img2Num/blob/main/src/pages/Editor/index.jsx) +- Helmet: [src/pages/Editor/EditorHelmet.jsx](https://github.com/Ryan-Millard/Img2Num/blob/main/src/pages/Editor/EditorHelmet.jsx) +- Styles: [src/pages/Editor/Editor.module.css](https://github.com/Ryan-Millard/Img2Num/blob/main/src/pages/Editor/Editor.module.css) + +## Routing + data flow + +- Route: `/editor` via [src/App.jsx](https://github.com/Ryan-Millard/Img2Num/blob/main/src/App.jsx). +- Entry: `navigate('/editor', { state: { svg } });` from the pipeline end ([src/components/WasmImageProcessor.jsx](https://github.com/Ryan-Millard/Img2Num/blob/main/src/components/WasmImageProcessor.jsx)). +- No `svg` in navigation state → render the “No SVG data found” empty state. + +## Mental model + +- Layout: outer `GlassCard` wrapper; top-right `GlassSwitch` toggles Color vs Preview. +- Viewport: inner `GlassCard` captures pointer + wheel; `div.inner` carries `translate + scale`. +- Rendering: SVG string → React elements via `html-react-parser`; transform sits on the wrapper, not the ``. + +## Core state + refs + +- `isColorMode`: true = reveal-on-tap; false = preview (interaction off, reveal state kept). +- `transform { scale, tx, ty }`: clamp scale `[0.25, 6]`; apply `translate(${tx}px, ${ty}px) scale(${scale})`. +- Refs: `viewportRef` (captures + pointer lock), `innerRef` (locate ``), `activePointersRef` (multi-touch map), `pinchRef` (pinch anchor data). + +## Interactions + +- Wheel zoom: step `1.12`, clamp to `[0.25, 6]`. +- Pan: one active pointer; movement must exceed ~5px before treating as drag. +- Pinch: two pointers; keeps midpoint fixed by anchoring the content point beneath it: + $$nextTx = m_x - c_x \cdot nextScale, \quad nextTy = m_y - c_y \cdot nextScale$$ + where $(m_x, m_y)$ is the screen midpoint and $(c_x, c_y)$ is the content point under it at pinch start. +- Tap-to-reveal (Color mode only): on pointer up with no drag, `elementFromPoint(...).closest(SHAPE_SELECTOR)` then add `styles.coloredRegion` (one-way reveal, no toggle-off). + +## Key classes + +| Class | Purpose | +| --------------- | --------------------------------------------------------------------------------- | +| `viewport` | Clipped interaction surface; `touch-action: none` for consistent pointer handling | +| `inner` | Transform wrapper (`translate + scale`); uses `will-change: transform` | +| `grabbing` | Applied during drag to show a grabbing cursor | +| `colorMode` | Applied on the outer card when color mode is active | +| `previewMode` | Applied on the outer card when preview mode is active | +| `coloredRegion` | Added on shapes to reveal original fills | + +## Styling and selectors + +- `SHAPE_SELECTOR = 'path,rect,circle,polygon,ellipse'`. +- Color mode: primitives without `.coloredRegion` are forced to white; adding `.coloredRegion` restores original fill. +- Preview mode: common primitives get `pointer-events: none` so current reveal state is view-only. +- Adding new SVG primitives: update `SHAPE_SELECTOR` and mirror rules in `Editor.module.css` (color override + preview pointer-events). + +## Helmet + +- Non-indexable workspace view: `` plus title/description and canonical in [EditorHelmet.jsx](https://github.com/Ryan-Millard/Img2Num/blob/main/src/pages/Editor/EditorHelmet.jsx). + +## Troubleshooting quick hits + +- “Tap” doesn’t reveal: ensure pointer movement stayed under the drag threshold and you are in Color mode. +- Zoom feels jumpy: check scale clamps and the fixed wheel step (`1.12`). +- Pinch drifts: confirm midpoint math uses the content point captured at gesture start. +- Shapes not affected: verify the element tag is in `SHAPE_SELECTOR` and CSS selectors cover it. + +## Tests and docs + +- Behavior coverage: [src/pages/Editor/Editor.test.jsx](../../../../src/pages/Editor/Editor.test.jsx). +- Helmet: [src/pages/Editor/EditorHelmet.test.jsx](../../../../src/pages/Editor/EditorHelmet.test.jsx). +- Extra guidance: [docs/docs/reference/pages/Editor/tests.md](./tests). diff --git a/docs/docs/reference/react/pages/Editor/tests.md b/docs/docs/reference/react/pages/Editor/tests.md new file mode 100644 index 000000000..38af96a37 --- /dev/null +++ b/docs/docs/reference/react/pages/Editor/tests.md @@ -0,0 +1,52 @@ +--- +title: Editor Tests +description: Testing strategy and suggestions for the Editor page (pan/zoom, mode switching, and shape toggling). +keywords: [tests, vitest, testing-library, editor, svg, pointer events] +sidebar_label: Tests +--- + +# Editor Tests + +The Editor page ([`src/pages/Editor/index.jsx`](https://github.com/Ryan-Millard/Img2Num/blob/main/src/pages/Editor/index.jsx)) is interaction-heavy, so coverage focuses on end-to-end behavior with **React Testing Library**. + +## Current coverage + +- [src/pages/Editor/Editor.test.jsx](../../../../src/pages/Editor/Editor.test.jsx): + - renders fallback when `location.state.svg` is missing + - renders provided SVG content + - adds `coloredRegion` on tap in color mode (one-way reveal) + - switches to preview mode (disables toggling) via the `GlassSwitch` +- [src/pages/Editor/EditorHelmet.test.jsx](../../../../src/pages/Editor/EditorHelmet.test.jsx): title, robots, description, and canonical meta. + +## High-value behaviors to keep covered + +- Empty state: direct navigation shows the “No SVG data found” panel. +- Mode switch: `aria-label` flips and the container class toggles between `colorMode` and `previewMode`. +- Shape reveal: tapping a supported primitive (`path`, `rect`, `circle`, `polygon`, `ellipse`) adds `coloredRegion` and keeps it applied on repeat taps (no toggle-off). + +## Supplying SVG in tests + +Render the page inside a router and pass state through `MemoryRouter` entries: + +```jsx +render( + ' } }]}> + + +); +``` + +This avoids mocking `useLocation` and matches production usage. + +## Pointer and wheel events (practical notes) + +- `document.elementFromPoint` can be stubbed to return the shape you want to toggle; restore it after each test. +- Pan tests should move more than the ~5px threshold to be treated as a drag. +- Wheel zoom can be asserted by reading the inline `transform` on the wrapper. +- Pinch is multi-pointer; prefer unit-testing math in a helper if the logic is extracted. + +## Common pitfalls + +- Remember `act(...)` around pointer/wheel interactions that change React state. +- CSS modules hash class names; check `.classList.contains(styles.coloredRegion)` rather than string literals. +- Keep tests colocated under `src/pages/Editor/` (page-local) for discoverability. diff --git a/docs/docs/reference/react/pages/_category_.json b/docs/docs/reference/react/pages/_category_.json new file mode 100644 index 000000000..1a7a1566e --- /dev/null +++ b/docs/docs/reference/react/pages/_category_.json @@ -0,0 +1,10 @@ +{ + "label": "Pages", + "position": 1, + "link": { + "type": "generated-index", + "title": "React Pages", + "description": "Reference for route-level React pages (screens) in Img2Num", + "slug": "/reference/react/pages" + } +} diff --git a/docs/docs/reference/react/pages/overview.md b/docs/docs/reference/react/pages/overview.md new file mode 100644 index 000000000..bf2801f6f --- /dev/null +++ b/docs/docs/reference/react/pages/overview.md @@ -0,0 +1,21 @@ +--- +title: Pages +description: Reference documentation for Img2Num route-level pages (screens), their inputs, and key behaviors. +keywords: [reference, pages, routing, react-router, screens, Img2Num] +sidebar_label: Pages +sidebar_position: 1 +--- + +# Pages + +Route-level pages are the top-level screens rendered by React Router in [`src/App.jsx`](https://github.com/Ryan-Millard/Img2Num/blob/main/src/App.jsx). +This section documents what each page expects as input (URL params, `location.state`, etc.), what it renders, and any interaction logic worth knowing when contributing. + +## Conventions + +- Pages should be resilient to direct navigation (e.g., missing `location.state`) and show a friendly empty/error state. +- Page docs should call out: + - Route path + - Expected navigation state / inputs + - Main UI responsibilities + - Testing strategy (unit vs integration) diff --git a/src/pages/Editor/Editor.module.css b/src/pages/Editor/Editor.module.css index 9baf9d011..752303e6c 100644 --- a/src/pages/Editor/Editor.module.css +++ b/src/pages/Editor/Editor.module.css @@ -2,6 +2,8 @@ .viewport { position: relative; overflow: hidden; + touch-action: none; + user-select: none; transition: transform 180ms ease, box-shadow 180ms ease; @@ -12,15 +14,19 @@ cursor: grab; background: transparent; } -/* Default path appearance */ -.colorMode .viewport svg path:not(.coloredRegion) { +/* Default shape appearance in color mode: hide original fills until revealed */ +.colorMode .viewport svg path:not(.coloredRegion), +.colorMode .viewport svg rect:not(.coloredRegion), +.colorMode .viewport svg circle:not(.coloredRegion), +.colorMode .viewport svg polygon:not(.coloredRegion), +.colorMode .viewport svg ellipse:not(.coloredRegion) { fill: white; cursor: pointer; transition: 150ms ease; } -/* while dragging */ -.viewport.grabbing { +/* while dragging (added via JS: styles.grabbing) */ +.grabbing { cursor: grabbing; } @@ -83,6 +89,9 @@ /* responsiveness */ @media (max-width: 800px) { + .grabbing { + cursor: move; + } .viewport { min-height: 240px; } diff --git a/src/pages/Editor/Editor.test.jsx b/src/pages/Editor/Editor.test.jsx new file mode 100644 index 000000000..7da491e6a --- /dev/null +++ b/src/pages/Editor/Editor.test.jsx @@ -0,0 +1,130 @@ +import { render, screen, fireEvent } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { vi, afterEach } from 'vitest'; +import { act } from 'react'; +import Editor from './index.jsx'; +import styles from './Editor.module.css'; + +const renderEditor = (svg) => { + return render( + + + + ); +}; + +const svgSample = ''; + +const getViewport = (container) => container.querySelector('.flex-center'); + +const withElementFromPoint = async (element, fn) => { + const original = document.elementFromPoint; + document.elementFromPoint = vi.fn(() => element); + try { + await fn(); + } finally { + document.elementFromPoint = original; + } +}; + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('Editor page', () => { + it('renders fallback when no svg data is present', () => { + renderEditor(); + + expect(screen.getByText(/No SVG data found/i)).toBeInTheDocument(); + expect(screen.getByText(/Please upload an image first/i)).toBeInTheDocument(); + }); + + it('renders provided svg content', () => { + renderEditor(svgSample); + + expect(screen.getByTestId('svg-root')).toBeInTheDocument(); + expect(screen.getByTestId('shape')).toBeInTheDocument(); + }); + + it('reveals original colour once and keeps it on repeated taps in color mode', async () => { + const { container } = renderEditor(svgSample); + const shape = screen.getByTestId('shape'); + const viewport = getViewport(container); + + expect(viewport).toBeTruthy(); + + await withElementFromPoint(shape, async () => { + await act(async () => { + fireEvent.pointerDown(viewport, { + pointerId: 1, + button: 0, + pointerType: 'mouse', + clientX: 10, + clientY: 10, + }); + + fireEvent.pointerUp(viewport, { + pointerId: 1, + pointerType: 'mouse', + clientX: 10, + clientY: 10, + }); + }); + + await act(async () => { + fireEvent.pointerDown(viewport, { + pointerId: 1, + button: 0, + pointerType: 'mouse', + clientX: 12, + clientY: 12, + }); + + fireEvent.pointerUp(viewport, { + pointerId: 1, + pointerType: 'mouse', + clientX: 12, + clientY: 12, + }); + }); + }); + + expect(shape.classList.contains(styles.coloredRegion)).toBe(true); + }); + + it('enters preview mode via switch and skips color reveal', async () => { + const { container } = renderEditor(svgSample); + const viewport = getViewport(container); + const shape = screen.getByTestId('shape'); + + const modeSwitch = screen.getByRole('switch'); + expect(modeSwitch).toHaveAttribute('aria-checked', 'true'); + + await act(async () => { + fireEvent.click(modeSwitch); + }); + + expect(modeSwitch).toHaveAttribute('aria-checked', 'false'); + expect(container.querySelector(`.${styles.previewMode}`)).toBeTruthy(); + + await withElementFromPoint(shape, async () => { + await act(async () => { + fireEvent.pointerDown(viewport, { + pointerId: 2, + button: 0, + pointerType: 'mouse', + clientX: 5, + clientY: 5, + }); + fireEvent.pointerUp(viewport, { + pointerId: 2, + pointerType: 'mouse', + clientX: 5, + clientY: 5, + }); + }); + }); + + expect(shape.classList.contains(styles.coloredRegion)).toBe(false); + }); +}); diff --git a/src/pages/Editor/EditorHelmet.test.jsx b/src/pages/Editor/EditorHelmet.test.jsx new file mode 100644 index 000000000..5b29e47fb --- /dev/null +++ b/src/pages/Editor/EditorHelmet.test.jsx @@ -0,0 +1,34 @@ +import { render, waitFor } from '@testing-library/react'; +import EditorHelmet from './EditorHelmet'; + +describe('EditorHelmet', () => { + const resetHead = () => { + document.title = ''; + document.head.innerHTML = ''; + }; + + beforeEach(() => { + resetHead(); + }); + + afterEach(() => { + resetHead(); + }); + + it('sets title, meta, and canonical link', async () => { + render(); + + await waitFor(() => { + expect(document.title).toBe('Editor – Img2Num'); + }); + + const robots = document.querySelector('meta[name="robots"]'); + expect(robots?.getAttribute('content')).toBe('noindex, nofollow'); + + const description = document.querySelector('meta[name="description"]'); + expect(description?.getAttribute('content')).toBe('Img2Num editor page (private, do not index).'); + + const canonical = document.querySelector('link[rel="canonical"]'); + expect(canonical?.getAttribute('href')).toBe('https://ryan-millard.github.io/Img2Num/editor'); + }); +}); diff --git a/src/pages/Editor/index.jsx b/src/pages/Editor/index.jsx index 7fb289aad..47d836d47 100644 --- a/src/pages/Editor/index.jsx +++ b/src/pages/Editor/index.jsx @@ -18,7 +18,19 @@ export default function Editor() { const viewportRef = useRef(null); const innerRef = useRef(null); const [transform, setTransform] = useState({ scale: 1, tx: 0, ty: 0 }); - const pointerState = useRef({ dragging: false, lastX: 0, lastY: 0, moving: false }); + const pointerState = useRef({ dragging: false, lastX: 0, lastY: 0, moved: false }); + const activePointersRef = useRef(new Map()); + const pinchRef = useRef({ + active: false, + startDist: 0, + startScale: 1, + startTx: 0, + startTy: 0, + startCx: 0, + startCy: 0, + }); + + const clamp = (value, min, max) => Math.max(min, Math.min(max, value)); // Wheel zoom (keeps tx/ty; can be improved later to zoom to pointer) const handleWheel = (e) => { @@ -34,10 +46,38 @@ export default function Editor() { // Panning handlers (pointer events) const onPointerDown = (e) => { if (!viewportRef.current) return; + + // Only start a drag for primary button on mouse. + if (e.pointerType === 'mouse' && e.button !== 0) return; + + activePointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY }); + pointerState.current.dragging = true; pointerState.current.moved = false; pointerState.current.lastX = e.clientX; pointerState.current.lastY = e.clientY; + + // Pinch start when second pointer goes down + if (activePointersRef.current.size === 2) { + const points = Array.from(activePointersRef.current.values()); + const p1 = points[0]; + const p2 = points[1]; + const midX = (p1.x + p2.x) / 2; + const midY = (p1.y + p2.y) / 2; + pinchRef.current.active = true; + pinchRef.current.startDist = Math.hypot(p1.x - p2.x, p1.y - p2.y); + pinchRef.current.startScale = transform.scale; + pinchRef.current.startTx = transform.tx; + pinchRef.current.startTy = transform.ty; + + // content coordinate under the pinch midpoint at start + pinchRef.current.startCx = (midX - transform.tx) / transform.scale; + pinchRef.current.startCy = (midY - transform.ty) / transform.scale; + + // don't treat pinch as a tap + pointerState.current.moved = true; + } + try { viewportRef.current.setPointerCapture(e.pointerId); } catch {} @@ -46,6 +86,37 @@ export default function Editor() { const onPointerMove = (e) => { if (!pointerState.current.dragging) return; + + // Keep active pointer positions updated + if (activePointersRef.current.has(e.pointerId)) { + activePointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY }); + } + + // Pinch zoom: when two pointers are active + if (pinchRef.current.active && activePointersRef.current.size === 2) { + const points = Array.from(activePointersRef.current.values()); + const p1 = points[0]; + const p2 = points[1]; + const midX = (p1.x + p2.x) / 2; + const midY = (p1.y + p2.y) / 2; + const dist = Math.hypot(p1.x - p2.x, p1.y - p2.y); + + if (pinchRef.current.startDist > 0) { + const scaleFactor = dist / pinchRef.current.startDist; + const nextScale = clamp(pinchRef.current.startScale * scaleFactor, 0.25, 6); + + // Keep the content point under the pinch midpoint anchored under the fingers. + const nextTx = midX - pinchRef.current.startCx * nextScale; + const nextTy = midY - pinchRef.current.startCy * nextScale; + + setTransform((t) => ({ ...t, scale: nextScale, tx: nextTx, ty: nextTy })); + } + return; + } + + // Pan only when exactly one pointer is active + if (activePointersRef.current.size !== 1) return; + const dx = e.clientX - pointerState.current.lastX; const dy = e.clientY - pointerState.current.lastY; @@ -64,7 +135,24 @@ export default function Editor() { const onPointerUp = (e) => { const moved = pointerState.current.moved; - pointerState.current.dragging = false; + + // Remove pointer from active set first + activePointersRef.current.delete(e.pointerId); + + if (activePointersRef.current.size < 2) { + pinchRef.current.active = false; + } + + // Keep dragging true if another pointer remains down + pointerState.current.dragging = activePointersRef.current.size > 0; + + // If exactly one pointer remains, reset lastX/lastY so pan can continue smoothly + if (activePointersRef.current.size === 1) { + const remaining = Array.from(activePointersRef.current.values())[0]; + pointerState.current.lastX = remaining.x; + pointerState.current.lastY = remaining.y; + } + try { viewportRef.current.releasePointerCapture(e.pointerId); } catch {} @@ -79,7 +167,7 @@ export default function Editor() { const shape = document.elementFromPoint(e.clientX, e.clientY)?.closest(SHAPE_SELECTOR); if (!shape || !svgRoot.contains(shape)) return; - // Apply your color class + // Adds original colour on tap/click shape.classList.add(styles.coloredRegion); } }; @@ -126,7 +214,6 @@ export default function Editor() { {svgElements} -
Click shapes to reveal their original colour. Use mouse wheel to zoom, drag to pan. Switching modes preserves fills.