mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
feat(studio): the open editor takes saves made elsewhere and keeps its own undo
This commit is contained in:
@@ -42,6 +42,18 @@ import { addListener, removeListener } from '../../api/websocket'
|
||||
* save conflicts, and the conflict offers a choice, which is the whole point of
|
||||
* the version. Quietly replacing someone's open document with somebody else's
|
||||
* is exactly the failure this design exists to avoid.
|
||||
*
|
||||
* ── Why the refetch is coalesced ──────────────────────────────────────────
|
||||
*
|
||||
* The assistant can apply many page edits in one step, each a save and each a
|
||||
* broadcast. Fetching the book once per event would be a burst of identical
|
||||
* reads racing each other, and an older answer landing last would roll the
|
||||
* editor back. So one read is open at a time, events that arrive during it ask
|
||||
* for exactly one more, and a document no newer than the one held is dropped.
|
||||
* An event that lands while this client's own write is open is not dropped
|
||||
* either: it is remembered and read once that work has reached the server,
|
||||
* because the save response and the broadcast travel on different channels and
|
||||
* either can arrive first.
|
||||
*/
|
||||
|
||||
/** How long the document has to stay still before it is written. */
|
||||
@@ -59,10 +71,22 @@ export type SaveState =
|
||||
| { status: 'readonly' }
|
||||
| { status: 'error' }
|
||||
|
||||
/** What the editor needs to know about a version it is handed from elsewhere. */
|
||||
interface RemoteBookMeta {
|
||||
/**
|
||||
* Whether every save folded into it was this user's own (their assistant, or
|
||||
* another tab of theirs), so taking it back with Ctrl+Z only undoes their own
|
||||
* work. False as soon as somebody else's save is among them.
|
||||
*/
|
||||
undoable: boolean
|
||||
}
|
||||
|
||||
export function useBookStore(
|
||||
journeyId: number,
|
||||
/** Called when another editor's version is taken, with their document. */
|
||||
onRemote?: (document: BookDocument) => void,
|
||||
onRemote?: (document: BookDocument, meta: RemoteBookMeta) => void,
|
||||
/** The signed-in user, to tell their own saves from everybody else's. */
|
||||
selfId?: number | null,
|
||||
) {
|
||||
const [record, setRecord] = useState<BookRecord | null>(null)
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
@@ -70,6 +94,11 @@ export function useBookStore(
|
||||
|
||||
/** The version every save is made against, and what a conflict compares to. */
|
||||
const version = useRef<number | null>(null)
|
||||
/**
|
||||
* The id of the book that version belongs to. A book deleted and made again
|
||||
* starts its versions over, so a lower version is only stale for the same book.
|
||||
*/
|
||||
const bookId = useRef<number | null>(null)
|
||||
const timer = useRef<number | null>(null)
|
||||
const firstDirtyAt = useRef<number | null>(null)
|
||||
const pending = useRef<{ document: BookDocument; title: string } | null>(null)
|
||||
@@ -115,10 +144,20 @@ export function useBookStore(
|
||||
*/
|
||||
const blocked = useRef(false)
|
||||
|
||||
/** The write that is open, so `flush` can wait for it rather than poll. */
|
||||
const flight = useRef<Promise<void> | null>(null)
|
||||
|
||||
/** Kept in a ref so the socket listener is not re-subscribed per render. */
|
||||
const onRemoteRef = useRef(onRemote)
|
||||
onRemoteRef.current = onRemote
|
||||
|
||||
/**
|
||||
* Read the book again if a save from elsewhere was passed over while this
|
||||
* client had work of its own. Set by the listener below, called once that
|
||||
* work has settled.
|
||||
*/
|
||||
const catchUp = useRef<() => void>(() => {})
|
||||
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(journeyId)) return
|
||||
let cancelled = false
|
||||
@@ -140,6 +179,7 @@ export function useBookStore(
|
||||
const book = res.book ? { ...res.book, document: normalizeBookDocument(res.book.document) } : null
|
||||
setRecord(book)
|
||||
version.current = book?.version ?? null
|
||||
bookId.current = book?.id ?? null
|
||||
synced.current = book?.document ?? null
|
||||
latest.current = book?.document ?? null
|
||||
})
|
||||
@@ -152,6 +192,8 @@ export function useBookStore(
|
||||
const next = pending.current
|
||||
if (!next || inFlight.current || blocked.current) return
|
||||
inFlight.current = true
|
||||
let settle = () => {}
|
||||
flight.current = new Promise<void>(resolve => { settle = resolve })
|
||||
pending.current = null
|
||||
firstDirtyAt.current = null
|
||||
setState({ status: 'saving' })
|
||||
@@ -164,6 +206,7 @@ export function useBookStore(
|
||||
})
|
||||
setRecord(saved)
|
||||
version.current = saved.version
|
||||
bookId.current = saved.id
|
||||
synced.current = next.document
|
||||
setState({ status: 'saved', at: Date.now() })
|
||||
} catch (err) {
|
||||
@@ -192,9 +235,11 @@ export function useBookStore(
|
||||
}
|
||||
} finally {
|
||||
inFlight.current = false
|
||||
settle()
|
||||
// Anything that arrived while the request was open goes next, so a save
|
||||
// during a save is queued rather than dropped.
|
||||
if (pending.current) void write()
|
||||
else catchUp.current()
|
||||
}
|
||||
}, [journeyId])
|
||||
|
||||
@@ -230,16 +275,48 @@ export function useBookStore(
|
||||
return write()
|
||||
}, [write])
|
||||
|
||||
/**
|
||||
* Hand everything this client holds to the server, and say whether it landed.
|
||||
*
|
||||
* For the moments where a write from somewhere else is about to happen on
|
||||
* purpose: the assistant is sent a turn, or one of its cards is applied. Its
|
||||
* write is checked against the version, so an edit still sitting in the
|
||||
* debounce would turn the assistant's change into a conflict, or the other way
|
||||
* round. Resolves false when the work could not be written (a conflict, a
|
||||
* viewer, a failed request), so the caller can hold off instead of racing it.
|
||||
*/
|
||||
const flush = useCallback(async (): Promise<boolean> => {
|
||||
if (timer.current != null) {
|
||||
window.clearTimeout(timer.current)
|
||||
timer.current = null
|
||||
}
|
||||
// Work that is local but not queued, as after a failed request.
|
||||
if (!blocked.current && !pending.current && !inFlight.current && latest.current && latest.current !== synced.current) {
|
||||
pending.current = { document: latest.current, title: lastTitle.current }
|
||||
}
|
||||
// Bounded: every round writes once or waits for one write to settle.
|
||||
for (let round = 0; round < 8 && !blocked.current; round++) {
|
||||
if (inFlight.current) await flight.current
|
||||
else if (pending.current) await write()
|
||||
else break
|
||||
}
|
||||
return !blocked.current && !hasLocalWork()
|
||||
}, [write])
|
||||
|
||||
/** Take the other version, discarding the local one. */
|
||||
const acceptTheirs = useCallback((current: BookRecord) => {
|
||||
const document = normalizeBookDocument(current.document)
|
||||
blocked.current = false
|
||||
setRecord({ ...current, document })
|
||||
version.current = current.version
|
||||
bookId.current = current.id
|
||||
synced.current = document
|
||||
latest.current = document
|
||||
pending.current = null
|
||||
setState({ status: 'idle' })
|
||||
// A save from elsewhere passed over while the conflict was open may be
|
||||
// newer than the record it carried.
|
||||
catchUp.current()
|
||||
return document
|
||||
}, [])
|
||||
|
||||
@@ -279,44 +356,104 @@ export function useBookStore(
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(journeyId)) return
|
||||
let cancelled = false
|
||||
/** A read is open; events that arrive meanwhile ask for one more after it. */
|
||||
let fetching = false
|
||||
let again = false
|
||||
/** A save was passed over because this client had work of its own. */
|
||||
let missed = false
|
||||
/** The versions saved by somebody other than this user, not taken yet. */
|
||||
let foreign: number[] = []
|
||||
|
||||
const handler = (event: Record<string, unknown>) => {
|
||||
if (event.type !== 'journey:book:saved') return
|
||||
if (event.journeyId !== journeyId) return
|
||||
if (hasLocalWork()) return
|
||||
// Already ours: the server excludes the saving socket, but a second tab
|
||||
// on the same account is a different socket and the same person.
|
||||
if (typeof event.version === 'number' && event.version === version.current) return
|
||||
/** Whether a version is one this client does not hold yet. */
|
||||
const isNewer = (v: unknown) =>
|
||||
typeof v !== 'number' || version.current == null || v > version.current
|
||||
|
||||
const refetch = () => {
|
||||
fetching = true
|
||||
again = false
|
||||
missed = false
|
||||
void journeyApi.getBook(journeyId)
|
||||
.then(res => {
|
||||
if (cancelled || !res.book) return
|
||||
// Re-checked after the round trip: the user may have started editing
|
||||
// while it was in the air, and their work outranks the refresh.
|
||||
if (hasLocalWork()) return
|
||||
// while it was in the air, and their work outranks the refresh. Kept
|
||||
// for later, in case that work lands without a conflict.
|
||||
if (hasLocalWork()) {
|
||||
missed = true
|
||||
return
|
||||
}
|
||||
// An answer overtaken by one already taken would roll the editor
|
||||
// back. A different book (deleted and made again) is never stale.
|
||||
const sameBook = bookId.current == null || res.book.id === bookId.current
|
||||
if (sameBook && !isNewer(res.book.version)) return
|
||||
// Normalised for the same reason the initial load is: a document
|
||||
// written by an older build is missing whatever the contract has
|
||||
// gained since.
|
||||
const document = normalizeBookDocument(res.book.document)
|
||||
const held = version.current
|
||||
const taken = res.book.version
|
||||
// Undoable only when every save it folds in, past the version held,
|
||||
// was this user's own.
|
||||
const undoable = sameBook && !foreign.some(v => held == null || (v > held && v <= taken))
|
||||
foreign = foreign.filter(v => v > taken)
|
||||
setRecord({ ...res.book, document })
|
||||
version.current = res.book.version
|
||||
version.current = taken
|
||||
bookId.current = res.book.id
|
||||
synced.current = document
|
||||
latest.current = document
|
||||
onRemoteRef.current?.(document)
|
||||
onRemoteRef.current?.(document, { undoable })
|
||||
})
|
||||
.catch(() => { /* The next save will conflict and offer the choice. */ })
|
||||
.finally(() => {
|
||||
fetching = false
|
||||
if (!again || cancelled) return
|
||||
if (hasLocalWork()) missed = true
|
||||
else refetch()
|
||||
})
|
||||
}
|
||||
|
||||
catchUp.current = () => {
|
||||
if (cancelled || !missed || hasLocalWork()) return
|
||||
if (fetching) again = true
|
||||
else refetch()
|
||||
}
|
||||
|
||||
const handler = (event: Record<string, unknown>) => {
|
||||
if (event.type !== 'journey:book:saved') return
|
||||
if (event.journeyId !== journeyId) return
|
||||
// Already ours: the server excludes the saving socket, but a second tab
|
||||
// on the same account is a different socket and the same person. Older
|
||||
// than ours is a broadcast that arrived after a newer read.
|
||||
if (!isNewer(event.version)) return
|
||||
// Unknown who saved, or not this user: their change is not ours to undo.
|
||||
if (selfId == null || event.savedBy !== selfId) {
|
||||
// A version that did not come along counts against the next one taken.
|
||||
foreign.push(typeof event.version === 'number' ? event.version : (version.current ?? 0) + 1)
|
||||
}
|
||||
if (hasLocalWork()) {
|
||||
// Remembered rather than dropped: the user's own write may land first
|
||||
// and leave this one unseen, with no conflict to bring it up.
|
||||
missed = true
|
||||
return
|
||||
}
|
||||
if (fetching) {
|
||||
again = true
|
||||
return
|
||||
}
|
||||
refetch()
|
||||
}
|
||||
|
||||
addListener(handler)
|
||||
return () => {
|
||||
cancelled = true
|
||||
catchUp.current = () => {}
|
||||
removeListener(handler)
|
||||
}
|
||||
}, [journeyId])
|
||||
}, [journeyId, selfId])
|
||||
|
||||
useEffect(() => () => {
|
||||
if (timer.current != null) window.clearTimeout(timer.current)
|
||||
}, [])
|
||||
|
||||
return { record, loaded, state, queueSave, saveNow, acceptTheirs, keepMine, version }
|
||||
return { record, loaded, state, queueSave, saveNow, flush, acceptTheirs, keepMine, version }
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { JourneyStats } from '@trek/shared'
|
||||
import type { BookRecord, JourneyStats } from '@trek/shared'
|
||||
import { useStudioStore } from '../../store/studioStore'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { addListener } from '../../api/websocket'
|
||||
import { uploadStudioPhotos } from '../../components/Studio/studioUpload'
|
||||
|
||||
vi.mock('../../components/Studio/studioUpload', () => ({
|
||||
@@ -295,3 +297,98 @@ describe('pictures and stops', () => {
|
||||
expect(result.current.canEdit).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* A save from elsewhere while the book is open (the assistant applying a page
|
||||
* edit, or another editor): the shell hands it to the store's adoptRemote, not
|
||||
* to load, so the user stays on their page, and flushBook is what the chat
|
||||
* panel calls before it lets the assistant write.
|
||||
*/
|
||||
describe('saves from elsewhere', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(addListener).mockClear()
|
||||
useAuthStore.setState({ user: { id: 2 } } as never)
|
||||
vi.mocked(journeyApi.saveBook).mockImplementation(
|
||||
async (_id, body) =>
|
||||
({
|
||||
id: 3, journeyId: 9, title: 'Iceland', version: 2,
|
||||
updatedAt: '2026-10-22 10:00:00', updatedBy: 2, document: body.document,
|
||||
}) as BookRecord,
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAuthStore.setState({ user: null } as never)
|
||||
})
|
||||
|
||||
/** Write a pending edit through flushBook, so nothing local is outstanding. */
|
||||
async function openAndFlush() {
|
||||
const view = await mountStudio()
|
||||
act(() => { useStudioStore.getState().commit(d => ({ ...d, title: 'edited' })) })
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await view.result.current.flushBook() })
|
||||
return { ...view, ok }
|
||||
}
|
||||
|
||||
/** The book as the server now has it: one page more, in front of the page the user is on. */
|
||||
function remoteWithPageBefore(index: number) {
|
||||
const local = useStudioStore.getState().doc
|
||||
if (!local) throw new Error('the book is not open')
|
||||
const at = local.spreads[index]
|
||||
const spreads = [
|
||||
...local.spreads.slice(0, index),
|
||||
{ ...at, id: 'from-elsewhere', elements: [] },
|
||||
...local.spreads.slice(index),
|
||||
]
|
||||
return { document: { ...local, spreads }, activeId: at.id }
|
||||
}
|
||||
|
||||
async function deliverSave(savedBy: number) {
|
||||
await act(async () => {
|
||||
for (const call of vi.mocked(addListener).mock.calls) {
|
||||
call[0]({ type: 'journey:book:saved', journeyId: 9, version: 5, savedBy })
|
||||
}
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
it('FE-STUDIO-WIRE-001: flushBook writes the pending edit and says it landed', async () => {
|
||||
const { ok } = await openAndFlush()
|
||||
expect(ok).toBe(true)
|
||||
const calls = vi.mocked(journeyApi.saveBook).mock.calls
|
||||
expect(calls[calls.length - 1][1].document.title).toBe('edited')
|
||||
})
|
||||
|
||||
it('FE-STUDIO-WIRE-002: a save of this user keeps the page by its id and is one undo away', async () => {
|
||||
await openAndFlush()
|
||||
act(() => { useStudioStore.getState().setActiveSpread(2) })
|
||||
const { document, activeId } = remoteWithPageBefore(2)
|
||||
vi.mocked(journeyApi.getBook).mockResolvedValue({
|
||||
book: { id: 3, journeyId: 9, title: 'Iceland', version: 5, updatedAt: '', updatedBy: 2, document },
|
||||
} as never)
|
||||
|
||||
await deliverSave(2)
|
||||
|
||||
await waitFor(() => expect(useStudioStore.getState().doc?.spreads[2].id).toBe('from-elsewhere'))
|
||||
const state = useStudioStore.getState()
|
||||
expect(state.activeSpread).toBe(3)
|
||||
expect(state.doc?.spreads[3].id).toBe(activeId)
|
||||
expect(state.canUndo()).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-STUDIO-WIRE-003: a save by somebody else keeps the page but is not one Ctrl+Z away', async () => {
|
||||
await openAndFlush()
|
||||
act(() => { useStudioStore.getState().setActiveSpread(2) })
|
||||
const { document, activeId } = remoteWithPageBefore(2)
|
||||
vi.mocked(journeyApi.getBook).mockResolvedValue({
|
||||
book: { id: 3, journeyId: 9, title: 'Iceland', version: 5, updatedAt: '', updatedBy: 7, document },
|
||||
} as never)
|
||||
|
||||
await deliverSave(7)
|
||||
|
||||
await waitFor(() => expect(useStudioStore.getState().doc?.spreads[2].id).toBe('from-elsewhere'))
|
||||
const state = useStudioStore.getState()
|
||||
expect(state.doc?.spreads[state.activeSpread].id).toBe(activeId)
|
||||
expect(state.canUndo()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import { bookElementId as elementId, bookPageSetupSchema } from '@trek/shared'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { useJourneyStore, type GalleryPhoto, type JourneyEntry, type JourneyPhoto } from '../../store/journeyStore'
|
||||
import { useStudioStore } from '../../store/studioStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { uploadStudioPhotos, type StudioUploader } from '../../components/Studio/studioUpload'
|
||||
import { useBookStore } from '../../components/Studio/useBookStore'
|
||||
@@ -101,6 +102,8 @@ export function useJourneyStudio() {
|
||||
|
||||
const doc = useStudioStore(s => s.doc)
|
||||
const loadDoc = useStudioStore(s => s.load)
|
||||
const adoptRemote = useStudioStore(s => s.adoptRemote)
|
||||
const selfId = useAuthStore(s => s.user?.id ?? null)
|
||||
const activeSpread = useStudioStore(s => s.activeSpread)
|
||||
const setActiveSpread = useStudioStore(s => s.setActiveSpread)
|
||||
const selection = useStudioStore(s => s.selection)
|
||||
@@ -142,7 +145,9 @@ export function useJourneyStudio() {
|
||||
* was not a starting point but the only point — close the tab and the
|
||||
* afternoon went with it.
|
||||
*/
|
||||
const book = useBookStore(journeyId, loadDoc)
|
||||
// A save from elsewhere (another editor, the assistant) keeps the page; only
|
||||
// this user's own saves (their assistant) become an undo step.
|
||||
const book = useBookStore(journeyId, adoptRemote, selfId)
|
||||
// Pulled out because close() needs it and the store object itself is new on
|
||||
// every render — depending on that made the save effect fire per render.
|
||||
const { queueSave, saveNow, loaded: bookLoaded } = book
|
||||
@@ -828,6 +833,8 @@ export function useJourneyStudio() {
|
||||
/** Autosave: its state, and the two ways out of a conflict. */
|
||||
saveState: book.state,
|
||||
saveNow: book.saveNow,
|
||||
/** Writes everything local and says whether it landed: before an assistant turn or apply. */
|
||||
flushBook: book.flush,
|
||||
acceptTheirs: book.acceptTheirs,
|
||||
keepMine: book.keepMine,
|
||||
spread,
|
||||
|
||||
@@ -34,6 +34,21 @@ interface StudioState {
|
||||
clipboard: StudioClipboard | null
|
||||
|
||||
load: (doc: BookDocument) => void
|
||||
/**
|
||||
* Take a version saved somewhere else (another editor, the assistant) into
|
||||
* the open book without throwing the user out of it.
|
||||
*
|
||||
* `load` is for opening: back to the cover, history gone. Here the page stays
|
||||
* the one the user was on (found by its spread id, wherever it moved to),
|
||||
* what is still on that page stays selected, and the document it replaces
|
||||
* becomes an undo step, so Ctrl+Z takes an assistant's change back.
|
||||
*
|
||||
* `undoable: false` is for a save by somebody else: the page and selection
|
||||
* stay, but the history goes, as with `load`. Otherwise their whole save would
|
||||
* sit one Ctrl+Z away, and undoing what the user took for their own last step
|
||||
* would quietly write the older book over another person's work.
|
||||
*/
|
||||
adoptRemote: (doc: BookDocument, opts?: { undoable?: boolean }) => void
|
||||
setActiveSpread: (i: number) => void
|
||||
select: (ids: string[]) => void
|
||||
toggleSelect: (id: string, additive: boolean) => void
|
||||
@@ -115,6 +130,29 @@ export const useStudioStore = create<StudioState>((set, get) => ({
|
||||
clipboard: null,
|
||||
|
||||
load: doc => set({ doc, selection: [], activeSpread: 0, past: [], future: [], gestureBase: null }),
|
||||
adoptRemote: (doc, opts) => set(s => {
|
||||
if (!s.doc) return { doc, selection: [], activeSpread: 0, past: [], future: [], gestureBase: null }
|
||||
if (doc === s.doc) return {}
|
||||
const spreadId = s.doc.spreads[s.activeSpread]?.id
|
||||
const found = spreadId ? doc.spreads.findIndex(sp => sp.id === spreadId) : -1
|
||||
// A page that is gone (deleted elsewhere) leaves the user where it was, or on the last page.
|
||||
const activeSpread = found >= 0 ? found : Math.max(0, Math.min(s.activeSpread, doc.spreads.length - 1))
|
||||
const onPage = new Set((doc.spreads[activeSpread]?.elements ?? []).map(e => e.id))
|
||||
// A gesture that has already moved is replaced half done, so the step to go
|
||||
// back to is where it started, not the half-finished frame.
|
||||
const replaced = s.gestureBase ?? s.doc
|
||||
return {
|
||||
doc,
|
||||
activeSpread,
|
||||
selection: found >= 0 ? s.selection.filter(id => onPage.has(id)) : [],
|
||||
past: opts?.undoable === false ? [] : [...s.past, replaced].slice(-HISTORY_LIMIT),
|
||||
// A new branch: redoing what was undone before this arrived would write over it.
|
||||
future: [],
|
||||
// An open gesture carries on from the new document, so closing it records
|
||||
// that, not the old one a second time.
|
||||
gestureBase: s.gestureBase ? doc : null,
|
||||
}
|
||||
}),
|
||||
setActiveSpread: i => set({ activeSpread: i, selection: [] }),
|
||||
select: ids => set({ selection: ids }),
|
||||
toggleSelect: (id, additive) => set(s => {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import type { BookDocument, BookElement, BookSpread } from '@trek/shared';
|
||||
import { useStudioStore } from '../../../src/store/studioStore';
|
||||
|
||||
/**
|
||||
* Taking a version saved elsewhere into the open book.
|
||||
*
|
||||
* `load` is for opening a book: cover, empty history. A save that arrives while
|
||||
* the book is open (another editor, or the assistant applying a page edit) has
|
||||
* to leave the user on their page with their undo history, and the document it
|
||||
* replaces has to be one Ctrl+Z away.
|
||||
*/
|
||||
|
||||
const el = (id: string): BookElement =>
|
||||
({
|
||||
id,
|
||||
kind: 'shape',
|
||||
frame: { x: 0, y: 0, w: 10, h: 10 },
|
||||
rotation: 0,
|
||||
opacity: 1,
|
||||
locked: false,
|
||||
shape: 'rect',
|
||||
fill: '#000000',
|
||||
gradient: 'none',
|
||||
stroke: null,
|
||||
strokeWidth: 0,
|
||||
strokeStyle: 'solid',
|
||||
radius: 0,
|
||||
}) as BookElement;
|
||||
|
||||
const spread = (id: string, role: BookSpread['role'], elements: BookElement[] = []): BookSpread => ({
|
||||
id,
|
||||
role,
|
||||
background: null,
|
||||
elements,
|
||||
parked: [],
|
||||
entryId: null,
|
||||
});
|
||||
|
||||
function book(...spreads: BookSpread[]): BookDocument {
|
||||
return {
|
||||
version: 1,
|
||||
title: 'T',
|
||||
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
|
||||
spreads,
|
||||
} as BookDocument;
|
||||
}
|
||||
|
||||
const store = () => useStudioStore.getState();
|
||||
|
||||
const opened = book(
|
||||
spread('cover', 'cover'),
|
||||
spread('a', 'inner', [el('a1'), el('a2')]),
|
||||
spread('b', 'inner', [el('b1')]),
|
||||
spread('back', 'back')
|
||||
);
|
||||
|
||||
/** Two pages left, the cover and the back: what a remote save that deleted every inner page looks like. */
|
||||
const bare = () => book(spread('cover', 'cover'), spread('back', 'back'));
|
||||
|
||||
beforeEach(() => {
|
||||
useStudioStore.setState({ doc: null, selection: [], activeSpread: 0, past: [], future: [], gestureBase: null });
|
||||
store().load(opened);
|
||||
});
|
||||
|
||||
describe('adoptRemote', () => {
|
||||
it('FE-STUDIO-ADOPT-001: keeps the page the user is on, by its id, when pages moved in front of it', () => {
|
||||
store().setActiveSpread(2);
|
||||
const moved = book(
|
||||
spread('cover', 'cover'),
|
||||
spread('new', 'inner'),
|
||||
spread('a', 'inner', [el('a1'), el('a2')]),
|
||||
spread('b', 'inner', [el('b1')]),
|
||||
spread('back', 'back')
|
||||
);
|
||||
store().adoptRemote(moved);
|
||||
expect(store().activeSpread).toBe(3);
|
||||
expect(store().doc?.spreads[store().activeSpread].id).toBe('b');
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-002: makes the replaced document an undo step, so Ctrl+Z takes the change back', () => {
|
||||
store().commit((d) => ({ ...d, title: 'local edit' }));
|
||||
const before = store().doc;
|
||||
const remote = book(spread('cover', 'cover'), spread('a', 'inner'), spread('back', 'back'));
|
||||
store().adoptRemote(remote);
|
||||
|
||||
expect(store().doc).toBe(remote);
|
||||
expect(store().past).toHaveLength(2);
|
||||
store().undo();
|
||||
expect(store().doc).toBe(before);
|
||||
// The earlier local step is still there behind it.
|
||||
store().undo();
|
||||
expect(store().doc).toBe(opened);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-003: keeps the selected elements that are still on the page and drops the rest', () => {
|
||||
store().setActiveSpread(1);
|
||||
store().select(['a1', 'a2']);
|
||||
const trimmed = book(
|
||||
spread('cover', 'cover'),
|
||||
spread('a', 'inner', [el('a1')]),
|
||||
spread('b', 'inner', [el('b1')]),
|
||||
spread('back', 'back')
|
||||
);
|
||||
store().adoptRemote(trimmed);
|
||||
expect(store().selection).toEqual(['a1']);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-004: a page deleted elsewhere leaves the user nearby with nothing selected', () => {
|
||||
store().setActiveSpread(2);
|
||||
store().select(['b1']);
|
||||
store().adoptRemote(book(spread('cover', 'cover'), spread('a', 'inner'), spread('back', 'back')));
|
||||
expect(store().activeSpread).toBe(2);
|
||||
expect(store().doc?.spreads[2].id).toBe('back');
|
||||
expect(store().selection).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-005: clears redo, which would otherwise write an older document over the new one', () => {
|
||||
store().commit((d) => ({ ...d, title: 'edit' }));
|
||||
store().undo();
|
||||
expect(store().canRedo()).toBe(true);
|
||||
store().adoptRemote(bare());
|
||||
expect(store().canRedo()).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-006: the same document again changes nothing and adds no undo step', () => {
|
||||
store().adoptRemote(opened);
|
||||
expect(store().past).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-007: with no book open yet it opens the one that arrived', () => {
|
||||
useStudioStore.setState({ doc: null, activeSpread: 3, selection: ['x'] });
|
||||
const remote = bare();
|
||||
store().adoptRemote(remote);
|
||||
expect(store().doc).toBe(remote);
|
||||
expect(store().activeSpread).toBe(0);
|
||||
expect(store().selection).toEqual([]);
|
||||
expect(store().past).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-008: an open gesture that has not moved does not record the old document a second time', () => {
|
||||
store().beginGesture();
|
||||
store().adoptRemote(bare());
|
||||
store().endGesture();
|
||||
expect(store().past).toEqual([opened]);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-009: a save by somebody else keeps the page and selection but clears the history', () => {
|
||||
store().commit((d) => ({ ...d, title: 'local edit' }));
|
||||
store().setActiveSpread(2);
|
||||
store().select(['b1']);
|
||||
const theirs = book(
|
||||
spread('cover', 'cover'),
|
||||
spread('new', 'inner'),
|
||||
spread('a', 'inner'),
|
||||
spread('b', 'inner', [el('b1')]),
|
||||
spread('back', 'back')
|
||||
);
|
||||
store().adoptRemote(theirs, { undoable: false });
|
||||
|
||||
expect(store().doc).toBe(theirs);
|
||||
expect(store().doc?.spreads[store().activeSpread].id).toBe('b');
|
||||
expect(store().selection).toEqual(['b1']);
|
||||
expect(store().canUndo()).toBe(false);
|
||||
expect(store().canRedo()).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ADOPT-010: a gesture that already moved records where it started, not its half-finished frame', () => {
|
||||
store().beginGesture();
|
||||
store().apply((d) => ({ ...d, title: 'mid-drag' }));
|
||||
const remote = bare();
|
||||
store().adoptRemote(remote);
|
||||
expect(store().past).toEqual([opened]);
|
||||
|
||||
store().endGesture();
|
||||
expect(store().past).toEqual([opened]);
|
||||
store().undo();
|
||||
expect(store().doc).toBe(opened);
|
||||
});
|
||||
});
|
||||
@@ -27,9 +27,9 @@ vi.mock('../../../src/api/websocket', () => ({
|
||||
}))
|
||||
|
||||
/** Deliver a `journey:book:saved` the way the server broadcasts it. */
|
||||
async function remoteSave(version = 6, journeyId = 9) {
|
||||
async function remoteSave(version = 6, journeyId = 9, savedBy = 2) {
|
||||
await act(async () => {
|
||||
for (const fn of listeners) fn({ type: 'journey:book:saved', journeyId, version, savedBy: 2 })
|
||||
for (const fn of listeners) fn({ type: 'journey:book:saved', journeyId, version, savedBy })
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve()
|
||||
})
|
||||
}
|
||||
@@ -543,6 +543,226 @@ describe('another editor saving', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// -- A burst of saves from elsewhere (the assistant applying page edits) ------
|
||||
|
||||
describe('a burst of saves from elsewhere', () => {
|
||||
async function withBook(selfId?: number) {
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 4, document: doc('theirs') }) })
|
||||
const onRemote = vi.fn()
|
||||
const view = renderHook(() => useBookStore(9, onRemote, selfId))
|
||||
await tick(0)
|
||||
return { ...view, onRemote }
|
||||
}
|
||||
|
||||
/** The next getBook stays open until released with the given record. */
|
||||
function holdNextRead() {
|
||||
let release: (r: BookRecord) => void = () => {}
|
||||
api.getBook.mockImplementationOnce(
|
||||
() => new Promise(resolve => { release = (r: BookRecord) => resolve({ book: r }) }),
|
||||
)
|
||||
return (r: BookRecord) => act(async () => {
|
||||
release(r)
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-001: events during an open read ask for one more read, not one per event', async () => {
|
||||
const { result, onRemote } = await withBook()
|
||||
const releaseFirst = holdNextRead()
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 8, document: doc('newest') }) })
|
||||
|
||||
await remoteSave(6)
|
||||
await remoteSave(7)
|
||||
await remoteSave(8)
|
||||
// The load at open, then the one read the first event started.
|
||||
expect(api.getBook).toHaveBeenCalledTimes(2)
|
||||
|
||||
await releaseFirst(record({ version: 6, document: doc('older') }))
|
||||
expect(api.getBook).toHaveBeenCalledTimes(3)
|
||||
expect(onRemote).toHaveBeenCalledTimes(2)
|
||||
expect(onRemote.mock.calls[1][0].title).toBe('newest')
|
||||
expect(result.current.record?.version).toBe(8)
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-002: an answer no newer than the book held is not taken', async () => {
|
||||
const { onRemote } = await withBook()
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 4, document: doc('same') }) })
|
||||
await remoteSave(6)
|
||||
expect(onRemote).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-003: a broadcast older than the version held is not read at all', async () => {
|
||||
const { onRemote } = await withBook()
|
||||
await remoteSave(3)
|
||||
expect(api.getBook).toHaveBeenCalledTimes(1)
|
||||
expect(onRemote).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-004: local work started during the read wins, and no second read follows', async () => {
|
||||
const { result, onRemote } = await withBook()
|
||||
const releaseFirst = holdNextRead()
|
||||
await remoteSave(6)
|
||||
await remoteSave(7)
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
|
||||
await releaseFirst(record({ version: 7, document: doc('newer') }))
|
||||
expect(onRemote).not.toHaveBeenCalled()
|
||||
expect(api.getBook).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
/*
|
||||
* The save response and the broadcast travel on different channels. When the
|
||||
* assistant's write lands just after the user's own, its broadcast can arrive
|
||||
* while that write is still open, and dropping it left the editor on the old
|
||||
* book with no conflict to bring the change up.
|
||||
*/
|
||||
it('FE-STUDIO-BOOKSYNC-010: a save that arrives during a write of this user is read once it lands', async () => {
|
||||
const { result, onRemote } = await withBook()
|
||||
let release: (r: BookRecord) => void = () => {}
|
||||
api.saveBook.mockImplementationOnce(() => new Promise<BookRecord>(resolve => { release = resolve }))
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
await tick()
|
||||
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 9, document: doc('assistant') }) })
|
||||
await remoteSave(9)
|
||||
expect(api.getBook).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => {
|
||||
release(record({ version: 7 }))
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve()
|
||||
})
|
||||
expect(api.getBook).toHaveBeenCalledTimes(2)
|
||||
expect(onRemote).toHaveBeenCalledTimes(1)
|
||||
expect(onRemote.mock.calls[0][0].title).toBe('assistant')
|
||||
expect(result.current.record?.version).toBe(9)
|
||||
})
|
||||
|
||||
/* The user's own assistant writes as them, so its change is theirs to take back. */
|
||||
it('FE-STUDIO-BOOKSYNC-011: a save by this user is handed over as undoable', async () => {
|
||||
const { onRemote } = await withBook(2)
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('own') }) })
|
||||
await remoteSave(6, 9, 2)
|
||||
expect(onRemote).toHaveBeenCalledWith(expect.objectContaining({ title: 'own' }), { undoable: true })
|
||||
})
|
||||
|
||||
/*
|
||||
* Undoing somebody else's save would write the older book over their work
|
||||
* with a current version, so no conflict would ever stop it.
|
||||
*/
|
||||
it('FE-STUDIO-BOOKSYNC-012: a save by somebody else, or by an unknown user, is not undoable', async () => {
|
||||
const other = await withBook(1)
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('theirs-6') }) })
|
||||
await remoteSave(6, 9, 2)
|
||||
expect(other.onRemote.mock.calls[0][1]).toEqual({ undoable: false })
|
||||
other.unmount()
|
||||
|
||||
const unknown = await withBook()
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('theirs-6') }) })
|
||||
await remoteSave(6, 9, 2)
|
||||
expect(unknown.onRemote.mock.calls[0][1]).toEqual({ undoable: false })
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-013: in a burst, only the read that folds in a save by someone else loses undo', async () => {
|
||||
const { onRemote } = await withBook(2)
|
||||
const releaseFirst = holdNextRead()
|
||||
await remoteSave(5, 9, 2)
|
||||
await remoteSave(6, 9, 5)
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('with-theirs') }) })
|
||||
|
||||
await releaseFirst(record({ version: 5, document: doc('own') }))
|
||||
expect(onRemote).toHaveBeenCalledTimes(2)
|
||||
expect(onRemote.mock.calls[0][1]).toEqual({ undoable: true })
|
||||
expect(onRemote.mock.calls[1][1]).toEqual({ undoable: false })
|
||||
})
|
||||
|
||||
/* A book deleted and made again starts its versions over; a low number is not stale then. */
|
||||
it('FE-STUDIO-BOOKSYNC-014: a book made again under a new id is taken despite its lower version', async () => {
|
||||
const { result, onRemote } = await withBook(2)
|
||||
api.getBook.mockResolvedValue({ book: record({ id: 8, version: 1, document: doc('again') }) })
|
||||
await remoteSave(5, 9, 2)
|
||||
expect(onRemote).toHaveBeenCalledTimes(1)
|
||||
expect(onRemote.mock.calls[0][1]).toEqual({ undoable: false })
|
||||
expect(result.current.record?.id).toBe(8)
|
||||
expect(result.current.record?.version).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
// -- flush --------------------------------------------------------------------
|
||||
|
||||
describe('flush', () => {
|
||||
it('FE-STUDIO-BOOKSYNC-005: writes a debounced edit at once and says it landed', async () => {
|
||||
const { result } = await mount()
|
||||
act(() => { result.current.queueSave(doc('unsaved'), 'T') })
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.flush() })
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(api.saveBook).toHaveBeenCalledTimes(1)
|
||||
expect(api.saveBook.mock.calls[0][1].document.title).toBe('unsaved')
|
||||
// The debounce it replaced does not fire a second write later.
|
||||
await tick(5000)
|
||||
expect(api.saveBook).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-006: waits for an open write and the edit queued behind it', async () => {
|
||||
let release: (r: BookRecord) => void = () => {}
|
||||
api.saveBook.mockImplementationOnce(() => new Promise<BookRecord>(resolve => { release = resolve }))
|
||||
const { result } = await mount()
|
||||
act(() => { result.current.queueSave(doc('first'), 'T') })
|
||||
await tick()
|
||||
act(() => { result.current.queueSave(doc('second'), 'T') })
|
||||
|
||||
let ok: boolean | undefined
|
||||
let done: Promise<void> = Promise.resolve()
|
||||
act(() => { done = result.current.flush().then(v => { ok = v }) })
|
||||
expect(ok).toBeUndefined()
|
||||
await act(async () => {
|
||||
release(record({ version: 2 }))
|
||||
await done
|
||||
})
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(api.saveBook).toHaveBeenCalledTimes(2)
|
||||
expect(api.saveBook.mock.calls[1][1].document.title).toBe('second')
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-007: says false when the write is refused as a conflict', async () => {
|
||||
api.saveBook.mockRejectedValue(conflictError(record({ version: 6 })))
|
||||
const { result } = await mount()
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.flush() })
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(result.current.state.status).toBe('conflict')
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-008: sends again what a failed request left behind', async () => {
|
||||
api.saveBook.mockRejectedValueOnce(new Error('offline'))
|
||||
const { result } = await mount()
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
await tick()
|
||||
expect(result.current.state.status).toBe('error')
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.flush() })
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(api.saveBook).toHaveBeenCalledTimes(2)
|
||||
expect(api.saveBook.mock.calls[1][1].document.title).toBe('mine')
|
||||
})
|
||||
|
||||
it('FE-STUDIO-BOOKSYNC-009: with nothing local it writes nothing and says true', async () => {
|
||||
const { result } = await mount()
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.flush() })
|
||||
expect(ok).toBe(true)
|
||||
expect(api.saveBook).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// -- Teardown -----------------------------------------------------------------
|
||||
|
||||
describe('unmounting', () => {
|
||||
|
||||
Reference in New Issue
Block a user