Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

drawing-cursor.spec.ts

271 lines11.2 KB

1import { expect, test } from "@playwright/test"
2import { openGame } from "./helpers"
3import { TEAM_COLORS, TEAMS } from "../../shared/teams"
4​
5test("pencil tracks the pointer, keeps its dial on the board, and restores the footer outside", async ({
6 page,
7}) => {
8 await openGame(page)
9 const canvas = page.getByTestId("game-canvas")
10 const bounds = (await canvas.boundingBox())!
11 // Hide the native cursor before entry and keep it hidden through movement,
12 // rather than toggling its CSS alongside every pencil animation frame.
13 await expect(canvas).toHaveCSS("cursor", "none")
14 const cursor = page.getByTestId("drawing-cursor")
15 const dial = page.getByTestId("cursor-ammo")
16 const footerQuota = page.getByTestId("quota-meter")
17​
18 await page.mouse.move(bounds.x + 160, bounds.y + 140)
19 await expect(cursor).toBeVisible()
20 await expect(footerQuota).toHaveCSS("opacity", "0")
21 const hotspot = (await cursor.boundingBox())!
22 expect(hotspot.x).toBeCloseTo(bounds.x + 160, 0)
23 expect(hotspot.y).toBeCloseTo(bounds.y + 140, 0)
24 await expect(page.getByTestId("cursor-ammo-count")).toHaveText("8")
25 for (let step = 0; step < 12; step++) {
26 await page.mouse.move(bounds.x + 160 + step * 12, bounds.y + 140 + (step % 2) * 10)
27 await expect(canvas).toHaveCSS("cursor", "none")
28 await expect(cursor).toBeVisible()
29 }
30​
31 await page.mouse.move(bounds.x + bounds.width - 2, bounds.y + bounds.height - 2)
32 await expect
33 .poll(async () => {
34 const box = (await dial.boundingBox())!
35 return (
36 box.x >= bounds.x &&
37 box.y >= bounds.y &&
38 box.x + box.width <= bounds.x + bounds.width &&
39 box.y + box.height <= bounds.y + bounds.height
40 )
41 })
42 .toBe(true)
43​
44 await page.getByRole("button", { name: "About", exact: true }).hover()
45 await expect(cursor).toBeHidden()
46 await expect(page.getByRole("button", { name: "About", exact: true })).toHaveCSS(
47 "cursor",
48 "pointer",
49 )
50 await expect(canvas).toHaveCSS("cursor", "none")
51 await expect(footerQuota).toHaveCSS("opacity", "1")
52})
53​
54test("dial animates the server-aligned refill, shows empty ammo, and respects reduced motion", async ({
55 page,
56}) => {
57 // Hold the quota response until the board is loaded so the refill deadline
58 // is deterministic regardless of snapshot latency. No game rows are changed.
59 let releaseQuota!: () => void
60 const quotaReady = new Promise<void>((resolve) => {
61 releaseQuota = resolve
62 })
63 await page.route("**/api/quota", async (route) => {
64 await quotaReady
65 await route.fulfill({ json: { ok: true, quotaRemaining: 2, refillIn: 3 } })
66 })
67 await openGame(page)
68 const bounds = (await page.getByTestId("game-canvas").boundingBox())!
69 await page.mouse.move(bounds.x + 170, bounds.y + 140)
70 releaseQuota()
71 const count = page.getByTestId("cursor-ammo-count")
72 const charge = page.getByTestId("cursor-ammo-charge")
73 await expect(count).toHaveText("2")
74 await expect(charge).toBeVisible()
75 const offset = () => charge.evaluate((el) => parseFloat(getComputedStyle(el).strokeDashoffset))
76 const initialOffset = await offset()
77 await expect.poll(offset).toBeLessThan(initialOffset - 0.1)
78 await expect(count).toHaveText("3", { timeout: 5000 })
79​
80 await page.emulateMedia({ reducedMotion: "reduce" })
81 await expect(charge).toHaveCSS("animation-name", "none")
82 await page.emulateMedia({ reducedMotion: "no-preference" })
83​
84 await page.route("**/api/draw", (route) =>
85 route.fulfill({
86 status: 429,
87 json: { ok: false, code: "QUOTA_EXHAUSTED", quotaRemaining: 0, refillIn: 3 },
88 }),
89 )
90 await page
91 .getByTestId("game-canvas")
92 .click({ position: { x: bounds.width / 2 + 10, y: bounds.height / 2 } })
93 await expect(count).toHaveText("0")
94 await expect(page.getByTestId("cursor-ammo")).toHaveAttribute("data-empty", "true")
95 await expect(page.getByTestId("cursor-ammo").getByText("Refill", { exact: true })).toBeVisible()
96 const toast = page.getByTestId("error-toast")
97 await expect(toast).toContainText("Out of moves! Recharging...")
98 const dialTransform = () =>
99 page.getByTestId("cursor-ammo").evaluate((el) => getComputedStyle(el).transform)
100 await expect.poll(dialTransform).not.toBe("none")
101 await expect.poll(dialTransform).toBe("none")
102​
103 // A second attempt is rejected locally. The same message still shakes again.
104 await page
105 .getByTestId("game-canvas")
106 .click({ position: { x: bounds.width / 2 + 10, y: bounds.height / 2 } })
107 await expect.poll(dialTransform).not.toBe("none")
108 await expect(count).toHaveText("1", { timeout: 5000 })
109 await expect(toast).toBeHidden()
110})
111​
112test.describe("Touch ammo fallback", () => {
113 test.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } })
114​
115 test("touch keeps the footer ammo without a floating cursor", async ({ page }) => {
116 await openGame(page)
117 const bounds = (await page.getByTestId("game-canvas").boundingBox())!
118 // Touch input keeps the meter even when a mouse is also moved on the page.
119 await page.touchscreen.tap(bounds.x + 80, bounds.y + 100)
120 await page.mouse.move(bounds.x + 80, bounds.y + 100)
121 await expect(page.getByTestId("drawing-cursor")).toBeHidden()
122 await expect(page.getByTestId("quota-meter")).toBeVisible()
123 await expect(page.getByTestId("quota-meter")).toHaveCSS("opacity", "1")
124 })
125})
126​
127test("accepted moves trace either edge direction, then return the pencil to the pointer", async ({
128 page,
129}) => {
130 await page.route("**/api/quota", (route) =>
131 route.fulfill({ json: { ok: true, quotaRemaining: 3, refillIn: 3 } }),
132 )
133 // Keep this a visual test: the authoritative board is never changed.
134 await page.route("**/api/draw", async (route) => {
135 await new Promise((resolve) => setTimeout(resolve, 400))
136 await route.fulfill({
137 status: 409,
138 json: { ok: false, code: "EDGE_TAKEN", quotaRemaining: 3, refillIn: 3 },
139 })
140 })
141 await openGame(page)
142 const canvas = page.getByTestId("game-canvas")
143 const bounds = (await canvas.boundingBox())!
144 const pencil = page.getByTestId("drawing-pencil")
145 for (const horizontal of [true, false]) {
146 const position = {
147 x: bounds.width / 2 + (horizontal ? 10 : 0),
148 y: bounds.height / 2 + (horizontal ? 0 : 10),
149 }
150 await page.mouse.move(bounds.x + position.x, bounds.y + position.y)
151 await canvas.click({ position })
152 await expect(pencil).toHaveAttribute("data-drawing", "true")
153 const frames = await pencil.evaluate((el) =>
154 (el.getAnimations()[0].effect as KeyframeEffect)
155 .getKeyframes()
156 .map((frame) => frame.transform),
157 )
158 expect(frames[1]).toContain(horizontal ? "translate(-10px, 0px)" : "translate(0px, -10px)")
159 expect(frames[2]).toContain(horizontal ? "translate(10px, 0px)" : "translate(0px, 10px)")
160 await expect(pencil).toHaveAttribute("data-drawing", "false")
161 await expect(page.getByTestId("cursor-ammo-count")).toHaveText("3")
162 }
163})
164​
165test("empty moves and reduced motion skip pencil strokes", async ({ page }) => {
166 // Start the refill clock after snapshot hydration, keeping the empty state deterministic.
167 let releaseQuota!: () => void
168 let quotaReady = new Promise<void>((resolve) => {
169 releaseQuota = resolve
170 })
171 let quotaRemaining = 0
172 await page.route("**/api/quota", async (route) => {
173 await quotaReady
174 await route.fulfill({ json: { ok: true, quotaRemaining, refillIn: 3 } })
175 })
176 await openGame(page)
177 releaseQuota()
178 const canvas = page.getByTestId("game-canvas")
179 const bounds = (await canvas.boundingBox())!
180 const position = { x: bounds.width / 2 + 10, y: bounds.height / 2 }
181 await page.mouse.move(bounds.x + position.x, bounds.y + position.y)
182 await expect(page.getByTestId("cursor-ammo-count")).toHaveText("0")
183 await canvas.click({ position })
184 await expect(page.getByTestId("error-toast")).toContainText("Out of moves!")
185 await expect(page.getByTestId("drawing-pencil")).toHaveAttribute("data-drawing", "false")
186​
187 await page.emulateMedia({ reducedMotion: "reduce" })
188 quotaRemaining = 3
189 quotaReady = new Promise<void>((resolve) => {
190 releaseQuota = resolve
191 })
192 await page.route("**/api/draw", (route) =>
193 route.fulfill({
194 status: 409,
195 json: { ok: false, code: "EDGE_TAKEN", quotaRemaining: 3, refillIn: 3 },
196 }),
197 )
198 await openGame(page)
199 releaseQuota()
200 await page.mouse.move(bounds.x + position.x, bounds.y + position.y)
201 await expect(page.getByTestId("cursor-ammo-count")).toHaveText("3")
202 await canvas.click({ position })
203 await expect(page.getByTestId("drawing-pencil")).toHaveAttribute("data-drawing", "false")
204})
205​
206test("ink follows the pencil even when Realtime confirms before the stroke ends", async ({
207 page,
208}) => {
209 await openGame(page)
210 const identity = await (await page.request.get("/api/team")).json()
211 const color = TEAM_COLORS[TEAMS[identity.teamId as number]].primary
212 const rgb = [1, 3, 5].map((offset) => parseInt(color.slice(offset, offset + 2), 16))
213 const canvas = page.getByTestId("game-canvas")
214 const bounds = (await canvas.boundingBox())!
215 const position = { x: bounds.width / 2 + 10, y: bounds.height / 2 }
216 await page.mouse.move(bounds.x + position.x, bounds.y + position.y)
217 const saved = page.waitForResponse((response) => response.url().endsWith("/api/draw"))
218 await canvas.click({ position })
219 const pencil = page.getByTestId("drawing-pencil")
220 await expect(pencil).toHaveAttribute("data-drawing", "true")
221​
222 // Pause the real pencil clock at deterministic positions. Its canvas frame
223 // loop keeps running, so this checks actual rendered ink rather than CSS flags.
224 const sample = async (time: number) =>
225 pencil.evaluate(async (el, time) => {
226 const animation = el.getAnimations()[0]
227 animation.pause()
228 animation.currentTime = time
229 await new Promise<void>((resolve) =>
230 requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
231 )
232 const canvas = document.querySelector<HTMLCanvasElement>('[data-testid="game-canvas"]')!
233 const ctx = canvas.getContext("2d")!
234 const dpr = devicePixelRatio
235 const x = canvas.getBoundingClientRect().width / 2
236 const y = canvas.getBoundingClientRect().height / 2
237 const pixels = (offset: number) =>
238 Array.from(
239 ctx.getImageData(
240 Math.round((x + offset) * dpr),
241 Math.round((y - 3) * dpr),
242 Math.round(4 * dpr),
243 Math.round(6 * dpr),
244 ).data,
245 )
246 return { behind: pixels(2), ahead: pixels(13) }
247 }, time)
248​
249 const blank = await sample(0)
250 const response = await saved
251 expect(response.status()).toBe(200)
252 await expect(page.getByTestId("cursor-ammo-count")).toHaveText("7")
253 // Team-coloured ink proves the committed owner arrived through Realtime.
254 // Keep the pencil halfway along the edge while that confirmation happens.
255 await expect
256 .poll(async () => {
257 const pixels = (await sample(105)).behind
258 for (let i = 0; i < pixels.length; i += 4) {
259 if (rgb.every((channel, j) => Math.abs(pixels[i + j] - channel) < 3)) return true
260 }
261 return false
262 })
263 .toBe(true)
264 const halfway = await sample(105)
265 expect(halfway.behind).not.toEqual(blank.behind)
266 expect(halfway.ahead).toEqual(blank.ahead)
267 const complete = await sample(200)
268 expect(complete.ahead).not.toEqual(blank.ahead)
269 await pencil.evaluate((el) => el.getAnimations()[0].finish())
270 await expect(pencil).toHaveAttribute("data-drawing", "false")
271})