diff --git a/e2e/main-view-state.spec.ts b/e2e/main-view-state.spec.ts
new file mode 100644
index 00000000..a382b486
--- /dev/null
+++ b/e2e/main-view-state.spec.ts
@@ -0,0 +1,320 @@
+import { expect, test, type BrowserContext, type Page } from '@playwright/test'
+import { setLayerMoves } from './cubeView3DHelpers'
+
+// The state of the main 3D view on the PuzlWerk viewer (`?viewer=puzlwerk`): the CUBE group, the move
+// list ("Moves: ..."), a turn by gesture, scramble, undo, reset and random state. The app's 2D net shows
+// the state the view reports (`onTurnStateChange`); its parity verdict is the oracle that the state is a
+// valid cube.
+const PUZLWERK = '.cube-card .cube-3d-puzlwerk'
+const base = () => `http://127.0.0.1:${process.env.E2E_PORT ?? '4174'}`
+
+async function openMainView(page: Page, size = 3) {
+ await page.goto('/?viewer=puzlwerk')
+ await page
+ .getByRole('combobox', { name: 'Cube' })
+ .selectOption({ label: `${size}×${size}` })
+ 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-appearance', /.+/)
+}
+
+// Short, fast scrambles keep the software renderer's run short.
+async function quickTurns(context: BrowserContext) {
+ await context.addCookies(
+ [
+ ['cube-assembler-turn-ms', '60'],
+ ['cube-assembler-scramble-length', 'short'],
+ // No help line over the stage: screenshots of it are compared.
+ ['cube-assembler-view-help', '0'],
+ ].map(([name, value]) => ({ name, value, url: base() })),
+ )
+}
+
+// Share of pixels that differ clearly between two PNG screenshots, compared in the page.
+async function differingShare(page: Page, first: Buffer, second: Buffer) {
+ return page.evaluate(
+ async ([x, y]) => {
+ const pixels = async (base64: string) => {
+ const blob = await (
+ await fetch(`data:image/png;base64,${base64}`)
+ ).blob()
+ const bitmap = await createImageBitmap(blob)
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)
+ const context = canvas.getContext('2d')
+ if (!context) throw new Error('No 2d context')
+ context.drawImage(bitmap, 0, 0)
+ return context.getImageData(0, 0, bitmap.width, bitmap.height).data
+ }
+ const [p, q] = [await pixels(x), await pixels(y)]
+ let differing = 0
+ for (let i = 0; i < p.length; i += 4)
+ if (
+ Math.abs(p[i] - q[i]) +
+ Math.abs(p[i + 1] - q[i + 1]) +
+ Math.abs(p[i + 2] - q[i + 2]) >
+ 60
+ )
+ differing += 1
+ return differing / (p.length / 4)
+ },
+ [first.toString('base64'), second.toString('base64')],
+ )
+}
+
+// The stage as the viewer shows it after playing turns equals the stage made again from the state the app
+// holds (the 2D net and back). Only the thin cubie sides can differ (a made-again cube has no piece
+// identities), under 2% of the pixels; a wrong state changes whole sticker blocks (over 25%).
+async function expectHeldStateShown(page: Page) {
+ const stage = page.locator(PUZLWERK)
+ // No hover highlight under the pointer.
+ await page.mouse.move(0, 0)
+ // Settled: two shots a moment apart are the same.
+ let played = await stage.screenshot()
+ await expect
+ .poll(
+ async () => {
+ await page.waitForTimeout(300)
+ const next = await stage.screenshot()
+ const same = next.equals(played)
+ played = next
+ return same
+ },
+ { timeout: 20_000 },
+ )
+ .toBe(true)
+ await page.getByRole('button', { name: '2D Net' }).click()
+ await expect(page.locator('.cube-card .cube-net')).toBeVisible()
+ await page.getByRole('button', { name: '3D View' }).click()
+ await expect(page.locator(`${PUZLWERK} canvas`)).toBeVisible()
+ await expect(stage).toHaveAttribute('data-appearance', /.+/)
+ await expect
+ .poll(async () => differingShare(page, played, await stage.screenshot()), {
+ timeout: 20_000,
+ })
+ .toBeLessThan(0.02)
+}
+
+const history = (page: Page) => page.locator('.cube-card .cube-3d-move-history')
+const button = (page: Page, name: string) =>
+ page.locator('.cube-card').getByRole('button', { name, exact: true })
+const moveCount = async (page: Page) => {
+ const text = (await history(page).innerText()).replace(/\s+/g, ' ').trim()
+ return text === 'Moves: None' ? 0 : text.split(' ').length - 1
+}
+
+// The 2D net of the state the view reported, and back to the 3D view (which starts from that state).
+async function netVerdict(page: Page) {
+ await page.getByRole('button', { name: '2D Net' }).click()
+ const verdict = page.locator('.cube-card .verdict')
+ await expect(verdict).toBeVisible()
+ const valid = await verdict.evaluate((el) =>
+ el.classList.contains('is-valid'),
+ )
+ await page.getByRole('button', { name: '3D View' }).click()
+ await expect(page.locator(`${PUZLWERK} canvas`)).toBeVisible()
+ return valid
+}
+
+test('the CUBE group and the move list show with the groups of the existing view', async ({
+ page,
+}) => {
+ await openMainView(page)
+ const labels = page.locator('.cube-card .cube-3d-toolbar .cube-3d-label')
+ await expect(labels).toHaveText(['Faces:', 'Cube:'])
+ const group = page.locator('.cube-card .cube-3d-section', {
+ has: page.locator('.cube-3d-label', { hasText: 'Cube:' }),
+ })
+ await expect(group.getByRole('button')).toHaveText([
+ 'Scramble',
+ 'Random State',
+ 'Undo',
+ 'Reset',
+ ])
+ await expect(history(page)).toHaveText('Moves: None')
+ await expect(button(page, 'Undo')).toBeDisabled()
+ await expect(button(page, 'Reset')).toBeDisabled()
+})
+
+test('a turn by gesture enters the move list; Undo takes it back; Reset starts over', async ({
+ page,
+ context,
+}) => {
+ await setLayerMoves(context)
+ await quickTurns(context)
+ await openMainView(page)
+ const view = page.locator(PUZLWERK)
+ const bounds = await view.boundingBox()
+ if (!bounds) throw new Error('No stage')
+ const cx = bounds.x + bounds.width / 2
+ const cy = bounds.y + bounds.height / 2
+ 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()
+ await expect(view).toHaveAttribute('data-turn', 'end')
+ await expect(history(page)).not.toHaveText('Moves: None')
+ expect(await moveCount(page)).toBe(1)
+ await expect(button(page, 'Undo')).toBeEnabled()
+ await expect(button(page, 'Reset')).toBeEnabled()
+ await expectHeldStateShown(page)
+ expect(await netVerdict(page)).toBe(true)
+ // The state survives the switch to the net and back.
+ expect(await moveCount(page)).toBe(1)
+ await button(page, 'Undo').click()
+ await expect(history(page)).toHaveText('Moves: None')
+ await expect(button(page, 'Undo')).toBeDisabled()
+ await expect(button(page, 'Reset')).toBeDisabled()
+ await expectHeldStateShown(page)
+ // A turn, then Reset.
+ 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()
+ await expect.poll(() => moveCount(page)).toBe(1)
+ await button(page, 'Reset').click()
+ await expect(history(page)).toHaveText('Moves: None')
+ await expect(button(page, 'Reset')).toBeDisabled()
+ await expectHeldStateShown(page)
+})
+
+test('Scramble turns the cube move by move, Undo takes one back, Reset solves it', async ({
+ page,
+ context,
+}) => {
+ await quickTurns(context)
+ await openMainView(page)
+ await button(page, 'Scramble').click()
+ await expect(button(page, 'Stop')).toBeVisible()
+ await expect(button(page, 'Undo')).toBeDisabled()
+ await expect(button(page, 'Scramble')).toBeVisible({ timeout: 60_000 })
+ // A short scramble of a 3x3 is ten turns, none of them cancelling.
+ await expect.poll(() => moveCount(page)).toBe(10)
+ await expect(button(page, 'Undo')).toBeEnabled()
+ await expectHeldStateShown(page)
+ expect(await netVerdict(page)).toBe(true)
+ await button(page, 'Undo').click()
+ await expect.poll(() => moveCount(page)).toBe(9)
+ await expectHeldStateShown(page)
+ expect(await netVerdict(page)).toBe(true)
+ await button(page, 'Reset').click()
+ await expect(history(page)).toHaveText('Moves: None')
+ await expect(button(page, 'Reset')).toBeDisabled()
+ await expectHeldStateShown(page)
+})
+
+test('Stop ends a scramble after the turn in progress', async ({
+ page,
+ context,
+}) => {
+ await context.addCookies([
+ { name: 'cube-assembler-turn-ms', value: '60', url: base() },
+ ])
+ await openMainView(page, 5)
+ await button(page, 'Scramble').click()
+ await expect.poll(() => moveCount(page)).toBeGreaterThan(1)
+ await button(page, 'Stop').click()
+ await expect(button(page, 'Scramble')).toBeVisible()
+ const stopped = await moveCount(page)
+ expect(stopped).toBeLessThan(40)
+ // A scramble that went on would add about a move every half second.
+ await page.waitForTimeout(3000)
+ // At most the turn that was playing joined the list.
+ expect(await moveCount(page)).toBeLessThanOrEqual(stopped + 1)
+ await expect(button(page, 'Undo')).toBeEnabled()
+})
+
+for (const size of [2, 3, 4, 7, 15]) {
+ test(`Random State at ${size}x${size} shows a valid cube with no moves`, async ({
+ page,
+ }) => {
+ await openMainView(page, size)
+ await button(page, 'Random State').click()
+ await expect(history(page)).toHaveText('Moves: None')
+ await expect(button(page, 'Reset')).toBeEnabled()
+ await expect(page.getByText('3D view unavailable')).toHaveCount(0)
+ await expect(page.locator(`${PUZLWERK} canvas`)).toBeVisible()
+ await expectHeldStateShown(page)
+ expect(await netVerdict(page)).toBe(true)
+ await button(page, 'Reset').click()
+ await expect(button(page, 'Reset')).toBeDisabled()
+ await expectHeldStateShown(page)
+ })
+}
+
+test('the CUBE group works while layer moves are locked', async ({
+ page,
+ context,
+}) => {
+ await quickTurns(context)
+ await openMainView(page)
+ // Locked (the default): a drag only orbits; the CUBE group still works.
+ await expect(page.locator(PUZLWERK)).toHaveAttribute(
+ 'data-interaction',
+ 'view',
+ )
+ await button(page, 'Scramble').click()
+ await expect(button(page, 'Undo')).toBeDisabled()
+ await expect(button(page, 'Scramble')).toBeVisible({ timeout: 60_000 })
+ await expect.poll(() => moveCount(page)).toBe(10)
+})
+
+// A turn of a scramble can end right after Reset or Random State, before the old player is gone; it must
+// leave no move on the new state. Alternating the two, with a growing delay, catches the old race often
+// (4 of 12 tries, tried again 12 times) without a fixed timing.
+test('Reset and Random State during a scramble leave no move behind', async ({
+ page,
+ context,
+}) => {
+ test.setTimeout(240_000)
+ await context.addCookies([
+ { name: 'cube-assembler-turn-ms', value: '200', url: base() },
+ { name: 'cube-assembler-view-help', value: '0', url: base() },
+ ])
+ await openMainView(page, 5)
+ const left: string[] = []
+ for (let i = 0; i < 12; i += 1) {
+ const action = i % 2 ? 'Random State' : 'Reset'
+ await button(page, 'Scramble').click()
+ await expect.poll(() => moveCount(page)).toBeGreaterThan(0)
+ await page.waitForTimeout(37 * (i % 5))
+ await button(page, action).click()
+ await page.waitForTimeout(800)
+ const text = (await history(page).innerText()).trim()
+ if (text !== 'Moves: None') left.push(`${i} ${action}: ${text}`)
+ if (await button(page, 'Stop').count()) await button(page, 'Stop').click()
+ if (await button(page, 'Reset').isEnabled())
+ await button(page, 'Reset').click()
+ }
+ expect(left).toEqual([])
+})
+
+// A new source of the same size ("Solved cube") while a scramble step plays: the step may end between the
+// render that brings the source and its effect. It must leave no move and no unsolved cube in the app.
+test('Solved cube during a scramble leaves the app cube solved', async ({
+ page,
+ context,
+}) => {
+ test.setTimeout(240_000)
+ await context.addCookies([
+ { name: 'cube-assembler-turn-ms', value: '200', url: base() },
+ { name: 'cube-assembler-view-help', value: '0', url: base() },
+ ])
+ await openMainView(page, 5)
+ const notation = page.getByRole('textbox', { name: 'Notation' })
+ const solved = await notation.inputValue()
+ const left: string[] = []
+ for (let i = 0; i < 14; i += 1) {
+ await button(page, 'Scramble').click()
+ await expect.poll(() => moveCount(page)).toBeGreaterThan(0)
+ await page.waitForTimeout(13 * (i % 12))
+ await page.getByRole('button', { name: 'Solved cube' }).click()
+ await page.waitForTimeout(800)
+ const text = (await history(page).innerText()).trim()
+ const now = await notation.inputValue()
+ if (text !== 'Moves: None' || now !== solved)
+ left.push(`${i}: ${text}, notation solved: ${now === solved}`)
+ if (await button(page, 'Stop').count()) await button(page, 'Stop').click()
+ }
+ expect(left).toEqual([])
+})
diff --git a/src/client/cubeDisplayCard.tsx b/src/client/cubeDisplayCard.tsx
index 1ba35771..55d46d23 100644
--- a/src/client/cubeDisplayCard.tsx
+++ b/src/client/cubeDisplayCard.tsx
@@ -185,10 +185,22 @@ export function CubeDisplayCard({
{...puzlwerkMainViewProps({
cube: shownSource,
initialCube: shownVisible,
+ initialMoves: presentationMoves(initialMoves, displayRecovery),
puzzleSize: size,
palette: stickerColors,
})}
colorFrame={mainFrame}
+ initialFrame={mainFrame}
+ publicMoves={(moves) =>
+ presentationMoves(moves, displayRecovery, true)
+ }
+ onTurnStateChange={(value, moves, frame) =>
+ onTurnStateChange(
+ presentationCube(value, size, displayRecovery, true),
+ presentationMoves(moves, displayRecovery, true),
+ presentationColorFrame(frame, displayRecovery, true),
+ )
+ }
main
/>
) : (
diff --git a/src/client/view3d/cubeToolbarSections.tsx b/src/client/view3d/cubeToolbarSections.tsx
new file mode 100644
index 00000000..ad06f054
--- /dev/null
+++ b/src/client/view3d/cubeToolbarSections.tsx
@@ -0,0 +1,105 @@
+// Parts of the 3D toolbar that the existing view and the PuzlWerk main view show alike: the CUBE group
+// (scramble, random state, undo, reset) and the move history. Classes and markup are the toolbar's.
+import { CUBELAB_MOVES_ID, cubeLabMovesJson } from '../cubeLabFingerprint'
+import { formatCubeTurn, type CubeTurn } from './cubeView3DState'
+
+// Undo needs a completed move and no turn in progress.
+export const undoDisabled = (moves: CubeTurn[], isTurning: boolean): boolean =>
+ moves.length === 0 || isTurning
+
+// Reset is off only while the cube is the initial one and nothing was turned.
+export const resetDisabled = (isInitial: boolean, moves: CubeTurn[]): boolean =>
+ isInitial && moves.length === 0
+
+export const moveHistoryText = (moves: CubeTurn[], size: number): string =>
+ moves.length
+ ? moves.map((move) => formatCubeTurn(move, size)).join(' ')
+ : 'None'
+
+export interface CubeActionsSectionProps {
+ isScrambling: boolean
+ onToggleScramble: () => void
+ onRandomState: () => void
+ onUndo: () => void
+ onReset: () => void
+ undoDisabled: boolean
+ resetDisabled: boolean
+ // Whether a drag turns a layer; off, scrambling and a random state are unavailable.
+ allowLayerMoves?: boolean
+}
+
+export function CubeActionsSection({
+ isScrambling,
+ onToggleScramble,
+ onRandomState,
+ onUndo,
+ onReset,
+ undoDisabled: undoOff,
+ resetDisabled: resetOff,
+ allowLayerMoves = true,
+}: CubeActionsSectionProps) {
+ return (
+
+ Cube:
+
+
+
+
+
+
+
+ )
+}
+
+export interface MoveHistoryProps {
+ moves: CubeTurn[]
+ size: number
+}
+
+// The move list the user reads, and the block CubeLab reads (escaped JSON, so no "<" ends the element).
+export function MoveHistory({ moves, size }: MoveHistoryProps) {
+ return (
+ <>
+
+ Moves: {moveHistoryText(moves, size)}
+
+
+ >
+ )
+}
diff --git a/src/client/view3d/cubeView3DPresentation.tsx b/src/client/view3d/cubeView3DPresentation.tsx
index 98a8f495..bf226afa 100644
--- a/src/client/view3d/cubeView3DPresentation.tsx
+++ b/src/client/view3d/cubeView3DPresentation.tsx
@@ -1,18 +1,18 @@
import type { ComponentChildren, RefObject } from 'preact'
import type { PressLevel } from './cubeGesture'
-import {
- facePreset,
- formatCubeTurn,
- type CubeTurn,
- type ViewFace,
-} from './cubeView3DState'
+import { facePreset, type CubeTurn, type ViewFace } from './cubeView3DState'
import {
preferenceCookie,
readPreference,
VIEW_HELP_COOKIE,
SEAM_WIDE_COOKIE,
} from '../preferences'
-import { CUBELAB_MOVES_ID, cubeLabMovesJson } from '../cubeLabFingerprint'
+import {
+ CubeActionsSection,
+ MoveHistory,
+ resetDisabled,
+ undoDisabled,
+} from './cubeToolbarSections'
import { useCubeHelpHint } from './useCubeHelpHint'
interface CubeView3DPresentationProps {
@@ -237,69 +237,19 @@ export function CubeView3DPresentation({
-
diff --git a/src/client/view3d/puzlwerkMainState.ts b/src/client/view3d/puzlwerkMainState.ts
new file mode 100644
index 00000000..f852f705
--- /dev/null
+++ b/src/client/view3d/puzlwerkMainState.ts
@@ -0,0 +1,124 @@
+// The state the main 3D view on the PuzlWerk viewer holds for the app: the cube, its move list and the
+// color frame, as pure functions. The viewer plays the layers; the app records each finished turn here
+// (a gesture, Undo or a scramble step), so the same turn updates the cube the way `useCubeTurns.ts` does for
+// the existing view. `test/puzlwerkMainState.test.ts` checks that this state equals the wire state the viewer
+// bridge reads back. It imports the bridge's turn mapping, so only the PuzlWerk view's chunk loads it.
+import { moveToCubeTurn } from '@puzlwerk/viewer/bridge/cube-state'
+import {
+ advanceColorFrame,
+ initialColorFrame,
+ type colorFrame as ColorFrame,
+} from '../../core/view/AxisGizmo.gen'
+import { isInitialCube } from '../../core/view/TurnAnimation.gen'
+import type { CubeState } from '../../cube/cubeAssembly'
+import {
+ applyCubeLayerMove,
+ generateScrambleMoves,
+ recordTurn,
+ type CubeTurn,
+} from './cubeView3DState'
+import { randomCube } from '../../cube/randomState'
+
+export interface MainTurnState {
+ cube: CubeState
+ moves: CubeTurn[]
+ frame: ColorFrame
+}
+
+export const startTurnState = (
+ cube: CubeState,
+ moves: CubeTurn[],
+ frame: ColorFrame | undefined,
+ size: number,
+): MainTurnState => ({
+ cube,
+ moves,
+ frame: frame ?? initialColorFrame(cube, size),
+})
+
+const turned = (
+ state: MainTurnState,
+ size: number,
+ turn: CubeTurn,
+): Pick => ({
+ cube: applyCubeLayerMove(
+ state.cube,
+ size,
+ turn.face,
+ turn.depth,
+ turn.turns,
+ turn.width ?? 1,
+ ),
+ frame: advanceColorFrame(
+ state.frame,
+ size,
+ turn.face,
+ turn.depth,
+ turn.turns,
+ turn.width ?? 1,
+ ),
+})
+
+// A finished turn: the cube turned, the turn recorded as its shortest form in the history.
+export const afterTurn = (
+ state: MainTurnState,
+ size: number,
+ turn: CubeTurn,
+): MainTurnState => ({
+ ...turned(state, size, turn),
+ moves: recordTurn(state.moves, turn),
+})
+
+// The turn that takes the last move back, if there is one.
+export const undoTurn = (state: MainTurnState): CubeTurn | undefined => {
+ const last = state.moves.at(-1)
+ return last && { ...last, turns: -last.turns }
+}
+
+// An undo removes the last move instead of recording the inverse turn.
+export const afterUndo = (
+ state: MainTurnState,
+ size: number,
+): MainTurnState => {
+ const inverse = undoTurn(state)
+ return inverse
+ ? { ...turned(state, size, inverse), moves: state.moves.slice(0, -1) }
+ : state
+}
+
+// Back to the source cube with no history.
+export const afterReset = (source: CubeState, size: number): MainTurnState =>
+ startTurnState(source, [], undefined, size)
+
+// Another cube with no history: its frame is that of a solved cube turned into it.
+export const afterShownCube = (cube: CubeState, size: number): MainTurnState =>
+ startTurnState(cube, [], undefined, size)
+
+export const isInitialState = (
+ state: MainTurnState,
+ source: CubeState,
+): boolean => isInitialCube(state.cube, source)
+
+// A random valid cube; `random` returns numbers in [0, 1).
+export const randomShownCube = (
+ size: number,
+ random: () => number = Math.random,
+): CubeState => randomCube(size, Math.floor(random() * 0x7fffffff))
+
+// The turns of a scramble for the cube size and the scramble settings.
+export const scrambleTurns = (
+ size: number,
+ options: Parameters[1],
+ random: () => number = Math.random,
+): CubeTurn[] => generateScrambleMoves(size, options, random)
+
+// The app turn of a played gesture: the layers its `turn-begin` selected and the quarter turns its
+// `turn-end` committed. Nothing for a selection that is no contiguous run of layers.
+export const committedTurn = (
+ size: number,
+ selected: { axis: 'X' | 'Y' | 'Z'; layers: readonly number[] },
+ turns: -1 | 1 | 2,
+): CubeTurn | undefined => {
+ const mapped = moveToCubeTurn(size, { ...selected, turns })
+ return mapped.ok ? mapped.value : undefined
+}
diff --git a/src/client/view3d/puzlwerkMainView.ts b/src/client/view3d/puzlwerkMainView.ts
index 37ead2c0..819226ea 100644
--- a/src/client/view3d/puzlwerkMainView.ts
+++ b/src/client/view3d/puzlwerkMainView.ts
@@ -2,6 +2,7 @@
// No viewer import here: this module loads with the default view, the viewer stays in its own chunk.
import type { colorFrame as ColorFrame } from '../../core/view/AxisGizmo.gen'
import type { CubeState } from '../../cube/cubeAssembly'
+import type { CubeTurn } from './cubeView3DState'
export type MainViewerKind = 'classic' | 'puzlwerk'
@@ -11,15 +12,20 @@ export const mainViewerKind = (search: string): MainViewerKind =>
: 'classic'
export interface MainViewSource {
+ // The source state: what Reset returns to.
cube: CubeState
+ // The state the app is in: shown at first, with the moves that led there.
initialCube?: CubeState
+ initialMoves?: CubeTurn[]
puzzleSize: number
palette?: Record
}
-// The static view shows the state the app is in (`initialCube`, else `cube`); turns are not played yet.
+// The view starts at the state the app is in (`initialCube`, else `cube`) and resets to `cube`.
export const puzlwerkMainViewProps = (source: MainViewSource) => ({
- cube: source.initialCube ?? source.cube,
+ cube: source.cube,
+ initialCube: source.initialCube ?? source.cube,
+ initialMoves: source.initialMoves ?? [],
puzzleSize: source.puzzleSize,
palette: source.palette,
})
diff --git a/src/client/view3d/puzlwerkPlay.ts b/src/client/view3d/puzlwerkPlay.ts
index 8099132e..6d0924be 100644
--- a/src/client/view3d/puzlwerkPlay.ts
+++ b/src/client/view3d/puzlwerkPlay.ts
@@ -1,6 +1,6 @@
// The main view's layers on the PuzlWerk viewer: one player and one stage child per shown state.
-// The player owns its child (`dispose` disposes the scene), so a new state gets a new child. Turns
-// are played in the viewer; holding them in app state is a later package.
+// The player owns its child (`dispose` disposes the scene), so a new state gets a new child. The viewer
+// plays the turns (gestures, `turn`); the app state that records them is puzlwerkMainState.ts.
import {
standardLayerWidths,
type Construction,
@@ -8,8 +8,12 @@ import {
type InteractionMode,
} from '@puzlwerk/viewer'
import { createPlayer } from '@puzlwerk/viewer/bridge'
-import { cubeStateDocuments } from '@puzlwerk/viewer/bridge/cube-state'
+import {
+ cubeStateDocuments,
+ cubeTurnToMove,
+} from '@puzlwerk/viewer/bridge/cube-state'
import type { CubeState } from '../../cube/cubeAssembly'
+import type { CubeTurn } from './cubeView3DState'
export interface MainPlayInput {
stage: CubeStage
@@ -29,10 +33,17 @@ export interface MainPlayInput {
export interface MainPlay {
// Switches between play mode (layer moves on) and view mode (locked) without touching the state shown.
setLayerMoves(on: boolean): void
+ // Plays one turn of the app (a scramble step or an undo) in `durationMs`. True once it is played on
+ // this player; false when the player is busy, gone or refuses the move, and nothing changed.
+ turn(turn: CubeTurn, durationMs: number): Promise
dispose(): void
}
-const NOTHING: MainPlay = { setLayerMoves: () => {}, dispose: () => {} }
+const NOTHING: MainPlay = {
+ setLayerMoves: () => {},
+ turn: async () => false,
+ dispose: () => {},
+}
// Shows the state and wires the play target.
export function mountMainPlay(input: MainPlayInput): MainPlay {
@@ -98,6 +109,19 @@ export function mountMainPlay(input: MainPlayInput): MainPlay {
wanted = on
if (current && ready) applyMode()
},
+ async turn(turn, durationMs) {
+ if (!current || !ready) return false
+ const move = cubeTurnToMove(size, turn)
+ if (!move.ok) return false
+ const played = await player.turn(
+ move.value.axis,
+ move.value.layers,
+ move.value.turns,
+ durationMs,
+ )
+ // A player disposed meanwhile (a reset, a new state) took no part in the state the app holds.
+ return played.ok && current
+ },
dispose() {
current = false
stage.setPlayTarget(undefined)
diff --git a/src/client/view3d/puzlwerkToolbar.tsx b/src/client/view3d/puzlwerkToolbar.tsx
index 2e4e501b..53e12561 100644
--- a/src/client/view3d/puzlwerkToolbar.tsx
+++ b/src/client/view3d/puzlwerkToolbar.tsx
@@ -1,8 +1,14 @@
-// The controls under the stage of the main 3D view on the PuzlWerk viewer: the FACES presets and the
-// Stickerless, Auto-rotate and Move layers toggles, with the classes and markup of the existing toolbar.
-// The CUBE group (scramble, random state, undo, reset), the move history and the sound toggle need
-// state held in the app and are a later package.
+// 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
+// parts the existing view shares (cubeToolbarSections.tsx); their state is held by usePuzlwerkTurns.ts.
import type { ViewPreset } from '@puzlwerk/viewer'
+import {
+ CubeActionsSection,
+ MoveHistory,
+ type CubeActionsSectionProps,
+} from './cubeToolbarSections'
+import type { CubeTurn } from './cubeView3DState'
import { autoRotateLabel, FACE_BUTTONS, stickerlessLabel } from './puzlwerkBars'
export interface PuzlwerkToolbarProps {
@@ -13,6 +19,10 @@ export interface PuzlwerkToolbarProps {
onToggleAutoRotate: () => void
layerMoves: boolean
onToggleLayerMoves: () => void
+ // The CUBE group, and the moves and size of the history under it.
+ cube: CubeActionsSectionProps
+ moves: CubeTurn[]
+ size: number
}
export function PuzlwerkToolbar({
@@ -23,6 +33,9 @@ export function PuzlwerkToolbar({
onToggleAutoRotate,
layerMoves,
onToggleLayerMoves,
+ cube,
+ moves,
+ size,
}: PuzlwerkToolbarProps) {
return (
@@ -42,6 +55,8 @@ export function PuzlwerkToolbar({
))}