diff --git a/src/App.tsx b/src/App.tsx index 1c6ae75..7edd101 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,7 +1,6 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'; import { ArrowDownToLine, - ArrowRight, Box, BookOpen, Check, @@ -56,10 +55,9 @@ import { editorCommands, executeEditorCommand, redoAvailable, - saveCurrentScene, undoAvailable, } from './core/commands'; -import { driveAutosave, flushDriveBeforeReplace, useDrive } from './core/drive-sync'; +import { driveAutosave, useDrive } from './core/drive-sync'; import { DriveButton, GoogleDriveDialog } from './components/GoogleDrive'; import { ActivityCenter, NotificationToasts } from './components/ActivityCenter'; import { WhatsNew } from './components/WhatsNew'; @@ -73,8 +71,8 @@ import { PreferencesPanel } from './components/PreferencesPanel'; import { PartsPanel } from './components/PartsPanel'; import { Inspector } from './components/Inspector'; import { moveSteps, rotationSteps } from './components/TransformAdjustments'; -import { Dialogs } from './components/Dialogs'; -import { IconButton, Keyboard, Logo, Modal, NumericInput, useDismiss } from './components/ui'; +import { Dialogs, ReplaceSceneDialog } from './components/Dialogs'; +import { IconButton, Keyboard, Logo, NumericInput, useDismiss } from './components/ui'; import { clipLimits } from './core/clipping'; import { partColorModes } from './core/appearance'; import type { SceneDocument } from './core/types'; @@ -729,7 +727,8 @@ export default function App() { [right, setRight] = useState(() => window.innerWidth > 1050), [dragging, setDragging] = useState(false), [importFiles, setImportFiles] = useState([]), - [pendingScene, setPendingScene] = useState(null); + [pendingScene, setPendingScene] = useState<{ scene: SceneDocument; id: number } | null>(null); + const openRequestId = useRef(0); const fileInput = useRef(null), dragDepth = useRef(0); const tool = useEditor((s) => s.tool), @@ -817,11 +816,10 @@ export default function App() { if (files.length === 1 && files[0].name.toLowerCase().endsWith('.kitbash')) { editor.setBusy('Opening scene…'); try { - setPendingScene( - await readSceneFile(files[0], (fraction) => - editor.setBusy(`Opening scene… ${Math.round(fraction * 100)}%`), - ), + const scene = await readSceneFile(files[0], (fraction) => + editor.setBusy(`Opening scene… ${Math.round(fraction * 100)}%`), ); + setPendingScene({ scene, id: ++openRequestId.current }); } catch (error) { editor.notify((error as Error).message, 'error'); } finally { @@ -1031,38 +1029,11 @@ export default function App() { /> {pendingScene ? ( - setPendingScene(null)} - > -
- -
- - {pendingScene.parts.length} parts · {pendingScene.joints.length} joints - -

All geometry, placement, and joint constraints will be restored.

-
-
-
- - -
-
+ /> ) : null} {dragging ? ( diff --git a/src/components/Dialogs.tsx b/src/components/Dialogs.tsx index 91184f2..dead874 100644 --- a/src/components/Dialogs.tsx +++ b/src/components/Dialogs.tsx @@ -21,8 +21,9 @@ import { X, } from 'lucide-react'; import { useEditor } from '../core/store'; -import { saveCurrentScene } from '../core/commands'; -import { flushDriveBeforeReplace } from '../core/drive-sync'; +import { downloadCurrentScene, saveCurrentScene } from '../core/commands'; +import { driveAutosave } from '../core/drive-sync'; +import type { SceneDocument } from '../core/types'; import { bindingsFor, formatBindings } from '../core/keybindings'; import type { KeyActionId } from '../core/keybindings'; import { usePreferences } from '../core/preferences'; @@ -763,41 +764,139 @@ function HelpDialog() { ); } -function NewDialog() { - const create = async (sample: boolean) => { - if (!(await flushDriveBeforeReplace())) return; - useEditor - .getState() - .setScene(sample ? createSample() : { name: 'Untitled assembly', parts: [], joints: [] }); +type SceneTarget = SceneDocument | 'empty' | 'sample'; + +export function ReplaceSceneDialog({ + scene, + onClose, +}: { + scene?: SceneDocument; + onClose: () => void; +}) { + const busy = useEditor((state) => state.busy); + const [checking, setChecking] = useState(false); + const [discard, setDiscard] = useState<{ target: SceneTarget; epoch: number } | null>(null); + const cancelButton = useRef(null); + const dismissed = useRef(false); + + useEffect(() => { + dismissed.current = false; + return () => { + dismissed.current = true; + }; + }, []); + useEffect(() => { + if (discard) cancelButton.current?.focus(); + }, [discard]); + + const replace = (target: SceneTarget) => { + const state = useEditor.getState(); + const next = + target === 'empty' + ? { name: 'Untitled assembly', parts: [], joints: [] } + : target === 'sample' + ? createSample() + : target; + state.setScene(next); + if (scene) state.notify('Scene opened'); + onClose(); }; + const requestReplace = async (target: SceneTarget) => { + const epoch = useEditor.getState().sceneEpoch; + setChecking(true); + try { + const saved = await driveAutosave.flush(); + if (dismissed.current || useEditor.getState().sceneEpoch !== epoch) return; + if (saved) replace(target); + else setDiscard({ target, epoch }); + } finally { + setChecking(false); + } + }; + const close = () => { + dismissed.current = true; + onClose(); + }; + return ( useEditor.getState().setModal(null)} + title={scene ? `Open ${scene.name}?` : 'Start something new.'} + subtitle={ + checking + ? 'Saving the current scene to Drive…' + : discard + ? undefined + : scene + ? 'This replaces the current workbench. Save a scene copy if you want to keep it.' + : 'Save a copy if you want to keep your current assembly.' + } + onClose={close} > -
- - -
+ {discard ? ( +

+ Changes to the current scene that haven’t been saved to Drive will be discarded. +

+ ) : scene ? ( +
+ +
+ + {scene.parts.length} parts · {scene.joints.length} joints + +

All geometry, placement, and joint constraints will be restored.

+
+
+ ) : ( +
+ + +
+ )}
- - + ) : null} + + {discard ? ( + + ) : scene ? ( + + ) : null}
); @@ -810,7 +909,8 @@ export function Dialogs({ importFiles }: { importFiles: File[] }) { if (modal === 'merge') return ; if (modal === 'mesh') return ; if (modal === 'help') return ; - if (modal === 'new') return ; + if (modal === 'new') + return useEditor.getState().setModal(null)} />; if (modal === 'rename') return ; return null; } diff --git a/src/components/GoogleDrive.tsx b/src/components/GoogleDrive.tsx index 9ae2bac..eee7c21 100644 --- a/src/components/GoogleDrive.tsx +++ b/src/components/GoogleDrive.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Cloud, CloudCheck, @@ -75,6 +75,8 @@ function DriveDialog() { const [files, setFiles] = useState([]); const [nextPage, setNextPage] = useState(); const [selected, setSelected] = useState(null); + const [discardEpoch, setDiscardEpoch] = useState(null); + const cancelOpen = useRef(null); const [refresh, setRefresh] = useState(0); const [resolution, setResolution] = useState<'load' | 'overwrite' | null>(null); const close = () => useDrive.setState({ dialogOpen: false }); @@ -98,6 +100,9 @@ function DriveDialog() { setWorking(false); } }; + useEffect(() => { + if (discardEpoch !== null) cancelOpen.current?.focus(); + }, [discardEpoch]); useEffect(() => { if (!googleClientId) return; let active = true; @@ -332,15 +337,26 @@ function DriveDialog() { {selected ? (
Open {selected.name}? -

- This replaces the current workbench. Save or download any changes you want to - keep first. -

+ {discardEpoch !== null ? ( +

+ Changes to the current scene that haven’t been saved to Drive will be + discarded. +

+ ) : ( +

+ This replaces the current workbench. Save or download any changes you want + to keep first. +

+ )}
@@ -349,12 +365,19 @@ function DriveDialog() { disabled={working} onClick={() => void perform(async () => { - if (await openDriveScene(selected.id)) close(); + const epoch = useEditor.getState().sceneEpoch; + if (discardEpoch !== null && discardEpoch !== epoch) { + setDiscardEpoch(null); + return; + } + if (await openDriveScene(selected.id, discardEpoch !== null)) close(); + else if (useEditor.getState().sceneEpoch === epoch) + setDiscardEpoch(epoch); }) } > - Open scene + {discardEpoch !== null ? 'Discard and open scene' : 'Open scene'}
diff --git a/src/core/drive-sync.ts b/src/core/drive-sync.ts index 159547e..9833c80 100644 --- a/src/core/drive-sync.ts +++ b/src/core/drive-sync.ts @@ -379,18 +379,6 @@ export class DriveAutosave { export const driveAutosave = new DriveAutosave(); -export async function flushDriveBeforeReplace() { - if (await driveAutosave.flush()) return true; - useDrive.setState({ dialogOpen: true }); - useEditor - .getState() - .notify( - 'The current scene has not reached Drive. Retry saving, or download a copy and stop autosave before replacing it.', - 'error', - ); - return false; -} - export function stopDriveAutosave() { useEditor.setState({ driveFile: null }); } @@ -410,9 +398,11 @@ export async function saveNewDriveScene() { } export async function openDriveScene(id: string, discardLocal = false) { - if (!discardLocal && !(await flushDriveBeforeReplace())) return false; + const epoch = useEditor.getState().sceneEpoch; + if (!discardLocal && !(await driveAutosave.flush())) return false; return driveAutosave.whilePaused(async () => { const state = useEditor.getState(); + if (state.sceneEpoch !== epoch) return false; state.setBusy('Opening scene from Google Drive…'); try { const { scene, file } = await googleDrive.open(id); diff --git a/tests/e2e/google-drive.spec.ts b/tests/e2e/google-drive.spec.ts index f21690b..66798fd 100644 --- a/tests/e2e/google-drive.spec.ts +++ b/tests/e2e/google-drive.spec.ts @@ -17,6 +17,7 @@ async function mockGoogle(page: Page, denied = false, hosted = false) { const cloud = { files: new Map(), uploads: [] as string[], + downloads: [] as string[], expired: false, renewals: 0, authorizations: 0, @@ -130,6 +131,7 @@ async function mockGoogle(page: Page, denied = false, hosted = false) { return; } if (url.searchParams.get('alt') === 'media') { + cloud.downloads.push(file.id); await route.fulfill({ contentType: 'application/octet-stream', body: file.bytes }); return; } @@ -376,6 +378,104 @@ async function conflictingScene(page: Page) { return cloud; } +test('discards a recovered Drive conflict and starts an empty assembly without loading Drive', async ({ + page, + context, +}) => { + const cloud = await mockGoogle(page); + await connectAndSave(page); + const remote = cloud.files.get('cloud-1')!; + await changeRemote(remote, 'Cloud assembly'); + await context.setOffline(true); + await rename(page, 'Recovered local edits'); + await expect(page.getByText('Saved locally', { exact: true })).toBeVisible(); + page.once('dialog', (dialog) => dialog.accept()); + await page.goto('about:blank'); + await context.setOffline(false); + await page.goto('/'); + await expect(page.getByText('Recovered your local assembly', { exact: true })).toBeVisible(); + await expect(driveButton(page)).toHaveAccessibleName('Google Drive: Drive file changed'); + const downloadsBeforeDiscard = [...cloud.downloads]; + + const chooseEmptyAssembly = async () => { + await page.getByRole('button', { name: 'File', exact: true }).click(); + await page.getByRole('button', { name: /New assembly/ }).click(); + await page.getByRole('button', { name: /Empty assembly/ }).click(); + }; + const discard = page.getByRole('button', { name: 'Discard and start new', exact: true }); + const sceneName = page.getByTitle('Rename assembly', { exact: true }); + await chooseEmptyAssembly(); + await expect(discard).toBeVisible(); + await expect(page.getByRole('dialog', { name: 'Google Drive', exact: true })).toHaveCount(0); + await page.keyboard.press('Escape'); + await expect(discard).toHaveCount(0); + await expect(sceneName).toContainText('Recovered local edits'); + await expect(driveButton(page)).toHaveAccessibleName('Google Drive: Drive file changed'); + + await chooseEmptyAssembly(); + await discard.click(); + await expect(sceneName).toContainText('Untitled assembly'); + await expect(page.locator('.part-row')).toHaveCount(0); + await expect(driveButton(page)).toHaveAccessibleName('Google Drive: Google Drive'); + await expect(page.getByText('Saved locally', { exact: true })).toBeVisible(); + await page.reload(); + await expect(page.getByText('Recovered your local assembly', { exact: true })).toBeVisible(); + await expect(sceneName).toContainText('Untitled assembly'); + expect(cloud.downloads).toEqual(downloadsBeforeDiscard); + expect(cloud.uploads).toEqual(['cloud-1']); + expect(remote.name).toBe('Cloud assembly.kitbash'); +}); + +test('opens a local file after discarding a Drive conflict', async ({ page }) => { + const cloud = await conflictingScene(page); + const downloadsBeforeOpen = [...cloud.downloads]; + await page.getByRole('button', { name: 'Done', exact: true }).click(); + const blob = await sceneFileBlob({ name: 'Local file', parts: [], joints: [] }); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'Local file.kitbash', + mimeType: 'application/octet-stream', + buffer: Buffer.from(await blob.arrayBuffer()), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await page.getByRole('button', { name: 'Discard and open scene', exact: true }).click(); + await expect(page.getByTitle('Rename assembly', { exact: true })).toContainText('Local file'); + await expect(driveButton(page)).toHaveAccessibleName('Google Drive: Google Drive'); + expect(cloud.downloads).toEqual(downloadsBeforeOpen); + expect(cloud.uploads).toEqual(['cloud-1']); +}); + +test('discards a Drive conflict only after the selected Drive scene opens successfully', async ({ + page, +}) => { + const cloud = await conflictingScene(page); + const downloadsBeforeOpen = [...cloud.downloads]; + await page.getByRole('button', { name: 'Done', exact: true }).click(); + const other = { ...cloud.files.get('cloud-1')!, id: 'cloud-2' }; + await changeRemote(other, 'Another assembly'); + cloud.files.set(other.id, other); + + await driveButton(page).click(); + const dialog = page.getByRole('dialog', { name: 'Google Drive', exact: true }); + await dialog.getByRole('button', { name: 'Another assembly.kitbash' }).click(); + await dialog.getByRole('button', { name: 'Open scene', exact: true }).click(); + const discard = dialog.getByRole('button', { name: 'Discard and open scene', exact: true }); + const mediaUrl = '**/drive/v3/files/cloud-2?alt=media'; + await page.route(mediaUrl, (route) => route.fulfill({ status: 503, json: {} })); + await discard.click(); + await expect(dialog.getByText(/temporarily unavailable/)).toBeVisible(); + await expect(page.getByTitle('Rename assembly', { exact: true })).toContainText('Local assembly'); + await expect(driveButton(page)).toHaveAccessibleName('Google Drive: Drive file changed'); + + await page.unroute(mediaUrl); + await discard.click(); + await saved(page); + await expect(page.getByTitle('Rename assembly', { exact: true })).toContainText( + 'Another assembly', + ); + expect(cloud.downloads).toEqual([...downloadsBeforeOpen, 'cloud-2']); + expect(cloud.uploads).toEqual(['cloud-1']); +}); + test('loads the cloud version directly from a conflict, with cancel leaving local edits intact', async ({ page, }) => {