Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 189 additions & 0 deletions e2e/main-view-sound.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import { expect, test, type BrowserContext, type Page } from '@playwright/test'
import { setLayerMoves } from './cubeView3DHelpers'

// Sound on the main 3D view on the PuzlWerk viewer (`?viewer=puzlwerk`): the Sound toggle of the existing
// toolbar, the click of a finished turn and the cue of a selected wide turn. A stand-in for Web Audio
// counts the sounds the page starts (`window.__sound`).
const PUZLWERK = '.cube-card .cube-3d-puzlwerk'
const SOUND_COOKIE = 'cube-assembler-turn-sound'
const base = () => `http://127.0.0.1:${process.env.E2E_PORT ?? '4174'}`

async function countSounds(page: Page) {
await page.addInitScript(() => {
const counts = { clicks: 0, cues: 0 }
;(window as unknown as { __sound: typeof counts }).__sound = counts
const node = (): Record<string, unknown> => {
const self: Record<string, unknown> = {
connect: (next: unknown) => next,
start: () => {},
stop: () => {},
frequency: { value: 0 },
Q: { value: 0 },
gain: {
setValueAtTime: () => {},
exponentialRampToValueAtTime: () => {},
},
}
return self
}
class FakeAudio {
state = 'running'
currentTime = 0
sampleRate = 8000
destination = node()
resume() {}
createBuffer(_c: number, length: number) {
return { getChannelData: () => new Float32Array(length) }
}
createBufferSource() {
counts.clicks += 1
return node()
}
createBiquadFilter() {
return node()
}
createGain() {
return node()
}
createOscillator() {
counts.cues += 1
return node()
}
}
;(window as unknown as { AudioContext: unknown }).AudioContext = FakeAudio
})
}

const sounds = (page: Page) =>
page.evaluate(
() =>
(window as unknown as { __sound: { clicks: number; cues: number } })
.__sound,
)

async function setSound(context: BrowserContext, on: boolean) {
await context.addCookies([
{ name: SOUND_COOKIE, value: on ? '1' : '0', url: base() },
{ name: 'cube-assembler-turn-ms', value: '60', url: base() },
{ name: 'cube-assembler-scramble-length', value: 'short', url: base() },
{ name: 'cube-assembler-view-help', value: '0', url: base() },
])
}

async function openMainView(page: Page) {
await page.goto('/?viewer=puzlwerk')
await page.getByRole('button', { name: 'Solved cube' }).click()
await page.getByRole('button', { name: '3D View' }).click()
await expect(page.locator(`${PUZLWERK} canvas`)).toBeVisible()
await expect(page.locator(PUZLWERK)).toHaveAttribute('data-interaction', /.+/)
}

const soundButton = (page: Page) =>
page.locator('.cube-card .cube-3d-actions').getByRole('button', {
name: 'Sound',
exact: true,
})

async function drag(page: Page, shift = false) {
const bounds = await page.locator(PUZLWERK).boundingBox()
if (!bounds) throw new Error('No stage')
const cx = bounds.x + bounds.width / 2
const cy = bounds.y + bounds.height / 2
if (shift) await page.keyboard.down('Shift')
await page.mouse.move(cx - 60, cy + 40)
await page.mouse.down()
await page.mouse.move(cx - 60, cy - 30, { steps: 6 })
await page.mouse.up()
if (shift) await page.keyboard.up('Shift')
}

test('the Sound toggle sits with the other toggles and stores the setting', async ({
page,
context,
}) => {
await setSound(context, true)
await openMainView(page)
const labels = page.locator('.cube-card .cube-3d-actions button')
await expect(labels).toHaveText([
'Stickerless',
'Auto-rotate',
'Move layers',
'Sound',
])
await expect(soundButton(page)).toHaveAttribute('aria-pressed', 'true')
await expect(soundButton(page)).toHaveClass(/cube-3d-btn-active/)
await soundButton(page).click()
await expect(soundButton(page)).toHaveAttribute('aria-pressed', 'false')
await expect(soundButton(page)).not.toHaveClass(/cube-3d-btn-active/)
const stored = async () =>
(await context.cookies()).find((c) => c.name === SOUND_COOKIE)?.value
expect(await stored()).toBe('0')
await soundButton(page).click()
expect(await stored()).toBe('1')
})

test('a turn by gesture clicks with sound on and stays silent with it off', async ({
page,
context,
}) => {
await countSounds(page)
await setLayerMoves(context)
await setSound(context, true)
await openMainView(page)
expect((await sounds(page)).clicks).toBe(0)
await drag(page)
await expect(page.locator(PUZLWERK)).toHaveAttribute('data-turn', 'end')
await expect.poll(async () => (await sounds(page)).clicks).toBe(1)
await soundButton(page).click()
await drag(page)
// The same layer again: the history merges the two quarter turns.
await expect(page.locator('.cube-card .cube-3d-move-history')).toHaveText(
/^Moves: \S+2$/,
)
await page.waitForTimeout(500)
expect((await sounds(page)).clicks).toBe(1)
})

test('each step of a scramble and an undo click; a stopped-sound scramble does not', async ({
page,
context,
}) => {
await countSounds(page)
await setSound(context, true)
await openMainView(page)
const scramble = page
.locator('.cube-card')
.getByRole('button', { name: 'Scramble', exact: true })
await scramble.click()
await expect(scramble).toBeVisible({ timeout: 60_000 })
// A short 3x3 scramble is ten turns.
await expect.poll(async () => (await sounds(page)).clicks).toBe(10)
await page
.locator('.cube-card')
.getByRole('button', { name: 'Undo', exact: true })
.click()
await expect.poll(async () => (await sounds(page)).clicks).toBe(11)
await soundButton(page).click()
await scramble.click()
await expect(scramble).toBeVisible({ timeout: 60_000 })
await page.waitForTimeout(500)
expect((await sounds(page)).clicks).toBe(11)
})

test('selecting a wide block plays the cue once, only with sound on', async ({
page,
context,
}) => {
await countSounds(page)
await setLayerMoves(context)
await setSound(context, true)
await openMainView(page)
await drag(page, true)
await expect(page.locator(PUZLWERK)).toHaveAttribute('data-turn', 'end')
expect((await sounds(page)).cues).toBe(1)
await soundButton(page).click()
await drag(page, true)
await expect(page.locator(PUZLWERK)).toHaveAttribute('data-turn', 'end')
await page.waitForTimeout(300)
expect((await sounds(page)).cues).toBe(1)
})
10 changes: 2 additions & 8 deletions src/client/view3d/cubeView3D.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import { lockedHintDue } from './cubeGesture'
import {
LAYER_MOVES_COOKIE,
STICKERLESS_COOKIE,
TURN_SOUND_COOKIE,
layerMovesOn,
preferenceCookie,
readPreference,
turnSoundOn,
} from '../preferences'
import { useTurnSound } from './turnSound'
import type { FaceKey } from '../../cube/cubeAssembly'
import type { CubeState } from '../../cube/cubeAssembly'
import type { colorFrame as ColorFrame } from '../../core/view/AxisGizmo.gen'
Expand Down Expand Up @@ -129,12 +128,7 @@ export function CubeView3D({
const [layerMoves, setLayerMoves] = useState<boolean>(() =>
layerMovesOn(document.cookie),
)
const [turnSound, setTurnSound] = useState(() => turnSoundOn(document.cookie))
const toggleTurnSound = () => {
const enabled = !turnSoundOn(document.cookie)
document.cookie = preferenceCookie(TURN_SOUND_COOKIE, enabled)
setTurnSound(enabled)
}
const [turnSound, toggleTurnSound] = useTurnSound()
// Dragging a sticker while locked explains the lock, at most once per gap.
const [lockedHint, setLockedHint] = useState(false)
const lockedHintShownAtRef = useRef<number | null>(null)
Expand Down
26 changes: 2 additions & 24 deletions src/client/view3d/cubeView3DPresentation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
undoDisabled,
} from './cubeToolbarSections'
import { useCubeHelpHint } from './useCubeHelpHint'
import { TurnSoundButton } from './turnSound'

interface CubeView3DPresentationProps {
isSupported: boolean
Expand Down Expand Up @@ -294,30 +295,7 @@ export function CubeView3DPresentation({
</svg>{' '}
Move layers
</button>
<button
type="button"
class={`cube-3d-btn ${turnSound ? 'cube-3d-btn-active' : ''}`}
aria-pressed={turnSound}
onClick={onToggleTurnSound}
>
<svg
viewBox="0 0 16 16"
width="14"
height="14"
aria-hidden="true"
fill="none"
stroke="currentColor"
stroke-width="1.6"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2 6h2l4-3v10l-4-3H2z" />
<path
d={turnSound ? 'M11 5a4 4 0 0 1 0 6' : 'm11 6 4 4m0-4-4 4'}
/>
</svg>{' '}
Sound
</button>
<TurnSoundButton on={turnSound} onToggle={onToggleTurnSound} />
</div>
</div>
</>
Expand Down
4 changes: 4 additions & 0 deletions src/client/view3d/puzlwerkCubeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { applyConstruction, mountMainPlay, type MainPlay } from './puzlwerkPlay'
import { arrowOrientation, keyPreset } from './puzlwerkBars'
import { PuzlwerkToolbar } from './puzlwerkToolbar'
import { usePuzlwerkTurns } from './usePuzlwerkTurns'
import { useTurnSound } from './turnSound'
import { resetDisabled, undoDisabled } from './cubeToolbarSections'
import type { CubeTurn } from './cubeView3DState'
import {
Expand Down Expand Up @@ -133,6 +134,7 @@ export function PuzlwerkCubeView({
playInputsRef.current = { palette, seamWide: hints.seamWide }
turns.invalidate()
}
const [turnSound, toggleTurnSound] = useTurnSound()
const turnsRef = useRef(turns)
turnsRef.current = turns
// The display orientation the stage reported last, for the arrow keys.
Expand Down Expand Up @@ -397,6 +399,8 @@ export function PuzlwerkCubeView({
onToggleAutoRotate={() => setAutoRotate((value) => !value)}
layerMoves={layerMoves}
onToggleLayerMoves={() => setLayerMoves((value) => !value)}
turnSound={turnSound}
onToggleTurnSound={toggleTurnSound}
cube={{
isScrambling: turns.scrambling,
onToggleScramble: turns.toggleScramble,
Expand Down
8 changes: 7 additions & 1 deletion src/client/view3d/puzlwerkToolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// The controls under the stage of the main 3D view on the PuzlWerk viewer, with the classes and markup of
// the existing toolbar: the FACES presets, the CUBE group (scramble, random state, undo, reset), the move
// history and the Stickerless, Auto-rotate and Move layers toggles. The CUBE group and the history are the
// history and the Stickerless, Auto-rotate, Move layers and Sound toggles. The CUBE group and the history are the
// parts the existing view shares (cubeToolbarSections.tsx); their state is held by usePuzlwerkTurns.ts.
import type { ViewPreset } from '@puzlwerk/viewer'
import {
Expand All @@ -10,6 +10,7 @@ import {
} from './cubeToolbarSections'
import type { CubeTurn } from './cubeView3DState'
import { autoRotateLabel, FACE_BUTTONS, stickerlessLabel } from './puzlwerkBars'
import { TurnSoundButton } from './turnSound'

export interface PuzlwerkToolbarProps {
onPreset: (preset: ViewPreset) => void
Expand All @@ -19,6 +20,8 @@ export interface PuzlwerkToolbarProps {
onToggleAutoRotate: () => void
layerMoves: boolean
onToggleLayerMoves: () => void
turnSound: boolean
onToggleTurnSound: () => void
// The CUBE group, and the moves and size of the history under it.
cube: CubeActionsSectionProps
moves: CubeTurn[]
Expand All @@ -33,6 +36,8 @@ export function PuzlwerkToolbar({
onToggleAutoRotate,
layerMoves,
onToggleLayerMoves,
turnSound,
onToggleTurnSound,
cube,
moves,
size,
Expand Down Expand Up @@ -100,6 +105,7 @@ export function PuzlwerkToolbar({
</svg>{' '}
Move layers
</button>
<TurnSoundButton on={turnSound} onToggle={onToggleTurnSound} />
</div>
</div>
)
Expand Down
Loading