AI-native design editor. Open-source Figma alternative.
feat: browse, preview, and restore a Cloud document's versions (#1275)
Danila Poyarkov24b12bd3b4c8
diff --git a/changes/1069/added.md b/changes/1069/added.mdindex f366529b4..2b69c3329 100644--- a/changes/1069/added.md+++ b/changes/1069/added.md@@ -1 +1 @@-- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. A viewer's document is read-only, as in Figma: layers can be selected, copied, and exported, the toolbar keeps Move and Hand, and edits, from the canvas, panels, shortcuts, and agents alike, are refused. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud` under the Apache License 2.0, while the protocol the editor speaks to it stays MIT; `VITE_OPENPENCIL_CLOUD=off` builds the editor without Cloud.+- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. A viewer's document is read-only, as in Figma: layers can be selected, copied, and exported, the toolbar keeps Move and Hand, and edits, from the canvas, panels, shortcuts, and agents alike, are refused. **File → Show version history** lists a document's named versions and autosaves, as in Figma: choose one to look at it read-only, then restore it for everyone in the room, duplicate it, or edit or delete its info, and **File → Save to version history…** (⌥⌘S) names the document as it is now. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud` under the Apache License 2.0, while the protocol the editor speaks to it stays MIT; `VITE_OPENPENCIL_CLOUD=off` builds the editor without Cloud.diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex c2335d661..a4fdac8d7 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -41,6 +41,17 @@"id": "save-to","label": "Save To…"},+ {+ "id": "save-version",+ "label": "Save to Version History…",+ "accelerator": "Alt+CmdOrCtrl+S",+ "feature": "cloud-document"+ },+ {+ "id": "version-history",+ "label": "Show Version History",+ "feature": "cloud-document"+ },{"type": "separator"},diff --git a/packages/cloud/src/contract/relay.ts b/packages/cloud/src/contract/relay.tsindex 8cb0573e7..c4050a4e7 100644--- a/packages/cloud/src/contract/relay.ts+++ b/packages/cloud/src/contract/relay.ts@@ -80,7 +80,9 @@ export const RELAY_CLOSE = {expired: 4403,roomFull: 4409,messageTooLarge: 4413,- protocol: 4400+ protocol: 4400,+ /** The document was restored to a version, so its room started over under a new ID. */+ restored: 4410} as constconst CLIENT_AUTH = 0diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.tsindex 3cba4be76..a59850108 100644--- a/packages/cloud/src/runtime/node/server.ts+++ b/packages/cloud/src/runtime/node/server.ts@@ -69,16 +69,6 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})}): undefined- const app = createCloudApp({- config,- database,- auth,- objects,- invitationOutbox,- transactionalEmail: email,- enrollment,- relayURL: config.relayURL ?? defaultRelayURL(config.publicURL)- })const relay = createCollaborationRelay({authSecret: config.authSecret,store: createCollaborationStateStore(database),@@ -98,8 +88,27 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})deploymentMode: config.deployment})return limit < 0 ? null : limit+ },+ async currentRoomEpoch(documentId) {+ const document = await database+ .selectFrom('document')+ .select('collaborationEpoch')+ .where('id', '=', documentId)+ .executeTakeFirst()+ return document?.collaborationEpoch ?? null}})+ const app = createCloudApp({+ config,+ database,+ auth,+ objects,+ invitationOutbox,+ transactionalEmail: email,+ enrollment,+ relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),+ onDocumentRestored: (documentId) => relay.startOver(documentId)+ })const emailWorker = emailTransport? startTransactionalEmailWorker(email, {batchSize: config.emailBatchSize,diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.tsindex eceb50e92..116f40ca4 100644--- a/packages/cloud/src/server/app.ts+++ b/packages/cloud/src/server/app.ts@@ -68,6 +68,8 @@ export type CloudServices = {* peer-to-peer and writes are not enforced by the server.*/relayURL?: string+ /** Ends a restored document's live rooms, on the relay this runtime runs, if any. */+ onDocumentRestored?: (documentId: string) => void}type CloudEnvironment = CloudAPIEnvironment@@ -201,7 +203,8 @@ export function createCloudApp(services: CloudServices) {})const versions = createDocumentVersionService(services.database, services.objects, {policy,- deploymentMode: services.config.deployment+ deploymentMode: services.config.deployment,+ onRestored: services.onDocumentRestored})const entitlements = createEntitlementService(services.database,diff --git a/packages/cloud/src/server/collaboration/relay/hub.ts b/packages/cloud/src/server/collaboration/relay/hub.tsindex c3cea68cb..e68f9ab1f 100644--- a/packages/cloud/src/server/collaboration/relay/hub.ts+++ b/packages/cloud/src/server/collaboration/relay/hub.ts@@ -34,6 +34,11 @@ export type CollaborationRelayOptions = {maximumConnectionsPerRoom: number/** The participant limit policy sets for a document, or null for none. */maximumParticipants?: (documentId: string) => Promise<number | null>+ /**+ * The document's current collaboration epoch, which a restore advances; a ticket for an earlier+ * room is turned away so nobody rejoins the document as it was.+ */+ currentRoomEpoch?: (documentId: string) => Promise<number | null>/** How long after a change the room's document is saved. */persistDelayMs?: number/** How long a room whose last save failed waits before saving again. */@@ -241,9 +246,19 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {authorization: RelayAuthorization): Promise<Peer | null> {const limit = await options.maximumParticipants?.(authorization.documentId)- let room = await openRoom(authorization)- // The room's last peer may have left while it opened; a closed room takes no newcomers.- while (rooms.get(room.id) !== room) room = await openRoom(authorization)+ let room: Room+ let epoch: number | null | undefined+ // The room's last peer may have left while it opened, or a restore ended it; a closed room+ // takes no newcomers. The epoch is read once the room is open, so a restore cannot slip between.+ do {+ room = await openRoom(authorization)+ epoch = await options.currentRoomEpoch?.(authorization.documentId)+ } while (rooms.get(room.id) !== room)+ if (epoch != null && authorization.roomEpoch < epoch) {+ socket.close(RELAY_CLOSE.restored, 'The document was restored')+ if (room.peers.size === 0) await leaveRoom(room)+ return null+ }const capacity = Math.min(limit ?? Number.POSITIVE_INFINITY, options.maximumConnectionsPerRoom)if (room.peers.size >= capacity) {socket.close(RELAY_CLOSE.roomFull, 'Collaboration room is full')@@ -418,6 +433,25 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {}},+ /**+ * Ends a restored document's rooms: everyone in them is told the document was restored, and+ * their edits to the replaced state are dropped rather than saved.+ */+ startOver(documentId: string) {+ // A map's iteration carries on past entries deleted during it.+ for (const room of rooms.values()) {+ if (room.identity.documentId !== documentId) continue+ rooms.delete(room.id)+ if (room.persistTimer) clearTimeout(room.persistTimer)+ for (const peer of room.peers.values()) {+ clearTimeout(peer.expiry)+ peer.socket.close(RELAY_CLOSE.restored, 'The document was restored')+ }+ room.peers.clear()+ room.document.destroy()+ }+ },+/** Saves every open room and closes its sockets, as the runtime shuts down. */async close() {shuttingDown = truediff --git a/packages/cloud/src/server/documents/versions/service.ts b/packages/cloud/src/server/documents/versions/service.tsindex 1e77f3d56..9aa70e2cf 100644--- a/packages/cloud/src/server/documents/versions/service.ts+++ b/packages/cloud/src/server/documents/versions/service.ts@@ -58,7 +58,12 @@ function versionOf(row: VersionRow, currentRevisionId: string | null): DocumentVexport function createDocumentVersionService(database: Kysely<CloudDatabase>,objects: ObjectStore,- options: { policy?: CloudPolicy; deploymentMode?: CloudPolicyContext['deploymentMode'] } = {}+ options: {+ policy?: CloudPolicy+ deploymentMode?: CloudPolicyContext['deploymentMode']+ /** Called once a restore lands, so the document's live room starts over. */+ onRestored?: (documentId: string) => void+ } = {}) {const deploymentMode = options.deploymentMode ?? 'self-hosted'function versions() {@@ -305,6 +310,12 @@ export function createDocumentVersionService(restoredFromVersionId: versionId})})+ // The restore stands whatever the hook does; a stale ticket is still turned away by its epoch.+ try {+ options.onRestored?.(documentId)+ } catch (error) {+ console.error('[Cloud] Ending the rooms of a restored document failed:', error)+ }const document = await findDocument(database, userId, documentId)if (!document) throw new DocumentNotFoundError()const restored = await versions()diff --git a/packages/cloud/tests/integration/server/documents/versions.test.ts b/packages/cloud/tests/integration/server/documents/versions.test.tsindex 32c6c693b..53c1a034c 100644--- a/packages/cloud/tests/integration/server/documents/versions.test.ts+++ b/packages/cloud/tests/integration/server/documents/versions.test.ts@@ -61,13 +61,15 @@ async function testApp(options: { fullHistory?: boolean } = {}) {)): undefined+ const restoredDocuments: string[] = []const app = createCloudApp({config,database: runtime.database,auth: createBetterAuthAdapter(config, runtime.database),objects: objects.store,policy,- resolveSession: async () => alice+ resolveSession: async () => alice,+ onDocumentRestored: (documentId) => restoredDocuments.push(documentId)})const request = (path: string, init: { method?: string; json?: unknown } = {}) =>app.request(`/api${path}`, {@@ -146,6 +148,7 @@ async function testApp(options: { fullHistory?: boolean } = {}) {return {runtime,+ restoredDocuments,objects,policy,request,@@ -260,6 +263,7 @@ describe('Cloud version history', () => {.where('id', '=', context.documentId).executeTakeFirstOrThrow()expect(after.collaborationEpoch).toBe(before.collaborationEpoch + 1)+ expect(context.restoredDocuments).toEqual([context.documentId])// The restored state is the same stored file, so it opens as the original and costs nothing.const [restoredDownload, originalDownload] = await Promise.all(diff --git a/packages/cloud/tests/server/collaboration/relay/hub.test.ts b/packages/cloud/tests/server/collaboration/relay/hub.test.tsindex 78611a62f..3d6df888e 100644--- a/packages/cloud/tests/server/collaboration/relay/hub.test.ts+++ b/packages/cloud/tests/server/collaboration/relay/hub.test.ts@@ -275,6 +275,56 @@ describe('collaboration relay', () => {await second.close()})+ test('ends a restored document’s room without saving the replaced state', async () => {+ const { relay: hub, states } = relay({ persistDelayMs: 60_000 })+ const alice = await join(hub)+ alice.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: edit('replaced')+ })++ hub.startOver(documentId)+ expect(alice.closed?.code).toBe(RELAY_CLOSE.restored)+ expect(states.size).toBe(0)+ })++ test('turns away a ticket for a room the document has moved on from', async () => {+ const { relay: hub } = relay({ currentRoomEpoch: async () => 1 })+ const stale = await join(hub, { roomEpoch: 0 })+ expect(stale.closed?.code).toBe(RELAY_CLOSE.restored)++ const current = await join(hub, { roomEpoch: 1 })+ expect(current.closed).toBeNull()+ expect(current.peerId()).toBeDefined()+ })++ test('turns away a peer whose room was still opening when the document was restored', async () => {+ const state = memoryStateStore()+ let epoch = 0+ let releaseLoad: (() => void) | undefined+ const { relay: hub } = relay({+ store: {+ ...state.store,+ async load(identity) {+ await new Promise<void>((resolve) => {+ releaseLoad = resolve+ })+ return state.store.load(identity)+ }+ },+ currentRoomEpoch: async () => epoch+ })+ const joining = join(hub, { roomEpoch: 0 })+ await until(() => releaseLoad !== undefined)+ epoch = 1+ hub.startOver(documentId)+ releaseLoad?.()++ expect((await joining).closed?.code).toBe(RELAY_CLOSE.restored)+ })+test('admits a newcomer to the live room when the last peer leaves while it is checked', async () => {let releaseLimit: (() => void) | undefinedlet checks = 0diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 9d7c909e5..9e98c9338 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -61,6 +61,14 @@ keeps on its own, and versions someone named (`document_version`, one per revisiversion's stored file, and advances the collaboration epoch, so the live room starts over on it.Duplicating makes a new document in the same workspace from the same file. Neither uploadsanything or uses more storage.+- A restore ends the document's rooms on the relay with close code `4410`, and the relay turns away+ tickets for an earlier epoch. A tab told so, or handed a ticket for another room, drops its queued+ uploads, shows the restored file it downloads, and joins the new room; a saver never overwrites a+ revision once its room has moved on.+- In the editor, File → Show version history makes the document read-only and lists its versions in+ the right sidebar, as Figma does. Choosing a version shows it in a read-only editor of its own in+ place of the document, whose room keeps syncing underneath; Save to version history (⌥⌘S) names+ the document once the saver's edits are uploaded.- The cleanup worker compacts saves that are neither current nor a version once they are a day old,a batch at a time, and returns the bytes of files nothing else uses to the workspace's usage. Afreed file's row stays until the object store deletes it, so a failed delete is retried. Withdiff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.mdindex 894f67628..053acf04e 100644--- a/packages/docs/user-guide/openpencil-cloud.md+++ b/packages/docs/user-guide/openpencil-cloud.md@@ -59,7 +59,7 @@ A Cloud document saves as you work, and the tab's dot shows edits that haven't r| **Saved on this device** | You are offline. Your changes are kept here and upload once you are back online. || **Changed in two places** | Someone saved a newer version while you had changes the server didn't have. || **Couldn't save** | The server refused the upload. Your changes are safe on this device; **Try again**, or sign in again if your sign-in expired. |-| **View only** | You can look and follow others, but your changes never reach the document. |+| **View only** | You can look, select, copy, and follow others; the document can't be edited, so only Move and Hand are in the toolbar. |## When a Document Changed in Two Places@@ -71,6 +71,17 @@ This happens when you edited a document offline, or before you joined a session,**Decide later** keeps both versions until you come back to it.+## Version History++Choose **File → Show version history** to list a document's versions in the right sidebar, newest first, as Figma does. While the list is open the document is read-only.++- **Current version** is the document as it is now. Named versions show their title, description, who saved them, and when; autosaves, which the server keeps as you work, are titled by their time. The filter shows everyone's versions or only yours, and hides or shows autosaves.+- Select a version to look at it. It opens read-only where the document was, while the document itself stays as it is; select **Current version** or close the list to go back.+- **File → Save to version history…** (⌥⌘S), or **+** in the list, names the document as it is now with a title and what changed.+- A version's **⋯** menu edits or deletes its info, makes a new document from it with **Duplicate**, or brings it back with **Restore this version**. Restoring keeps the state it replaces in the history, closes the list, and moves everyone who has the document open on to the restored version.++People who can only view see the history but can't change it.+## Share a DocumentSelect **Share** on a Cloud document.diff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonindex e55dcfc11..67ec79f3f 100644--- a/packages/vue/src/i18n/locales/de/cloud/editor.json+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -274,5 +274,29 @@"workspaceNotEmpty": "Lösche oder verschiebe zuerst seine Dokumente; nur ein leerer Arbeitsbereich kann gelöscht werden.","workspaceCleanupPending": "Seine gelöschten Dokumente werden noch eine Weile aufbewahrt, bevor sie endgültig verschwinden. Versuche es danach erneut.","shareOpenedInBrowser": "Im Browser geöffnet",- "openInDesktopApp": "In der Desktop-App öffnen"+ "openInDesktopApp": "In der Desktop-App öffnen",+ "versionHistory": "Versionsverlauf",+ "closeVersionHistory": "Versionsverlauf schließen",+ "currentVersion": "Aktuelle Version",+ "addToVersionHistory": "Zum Versionsverlauf hinzufügen",+ "editVersionInfo": "Versionsinfo bearbeiten",+ "versionTitle": "Titel",+ "versionDescription": "Beschreibe, was sich geändert hat",+ "restoreVersion": "Diese Version wiederherstellen",+ "duplicateVersion": "Duplizieren",+ "deleteVersionInfo": "Versionsinfo löschen",+ "versionOptions": "Weitere Optionen für die Version",+ "versionFilter": "Versionen filtern",+ "versionsAll": "Alle",+ "versionsOnlyYours": "Nur deine",+ "showAutosaveVersions": "Automatisch gespeicherte Versionen anzeigen",+ "restoredVersion": "Wiederhergestellte Version: {name}",+ "restoredVersionUnnamed": "Wiederhergestellte Version",+ "viewingVersion": "{name} wird angezeigt",+ "olderVersions": "Ältere Versionen anzeigen",+ "noVersions": "Keine Versionen",+ "versionsFailed": "Der Versionsverlauf konnte nicht geladen werden.",+ "versionFailed": "Diese Version konnte nicht geöffnet werden.",+ "versionChangeFailed": "Der Versionsverlauf konnte nicht geändert werden.",+ "versionCopyName": "{name} (Kopie)"}diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex 79cb1cdf2..9a7e06566 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Auswahl als .fig exportieren","togglePreview": "Vorschau","browseFiles": "Dateien durchsuchen…",- "saveTo": "Speichern in…"+ "saveTo": "Speichern in…",+ "showVersionHistory": "Versionsverlauf anzeigen",+ "saveToVersionHistory": "Im Versionsverlauf speichern…"}diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonindex 2adc2fa9a..b37367d44 100644--- a/packages/vue/src/i18n/locales/es/cloud/editor.json+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -274,5 +274,29 @@"workspaceNotEmpty": "Elimina o mueve primero sus documentos; solo se puede eliminar un espacio vacío.","workspaceCleanupPending": "Sus documentos eliminados se conservan un tiempo antes de borrarse definitivamente. Vuelve a intentarlo después.","shareOpenedInBrowser": "Abierto en el navegador",- "openInDesktopApp": "Abrir en la aplicación de escritorio"+ "openInDesktopApp": "Abrir en la aplicación de escritorio",+ "versionHistory": "Historial de versiones",+ "closeVersionHistory": "Cerrar historial de versiones",+ "currentVersion": "Versión actual",+ "addToVersionHistory": "Añadir al historial de versiones",+ "editVersionInfo": "Editar información de la versión",+ "versionTitle": "Título",+ "versionDescription": "Describe qué ha cambiado",+ "restoreVersion": "Restaurar esta versión",+ "duplicateVersion": "Duplicar",+ "deleteVersionInfo": "Eliminar información de la versión",+ "versionOptions": "Más opciones de la versión",+ "versionFilter": "Filtrar versiones",+ "versionsAll": "Todas",+ "versionsOnlyYours": "Solo las tuyas",+ "showAutosaveVersions": "Mostrar versiones guardadas automáticamente",+ "restoredVersion": "Versión restaurada: {name}",+ "restoredVersionUnnamed": "Versión restaurada",+ "viewingVersion": "Viendo {name}",+ "olderVersions": "Mostrar versiones anteriores",+ "noVersions": "No hay versiones",+ "versionsFailed": "No se pudo cargar el historial de versiones.",+ "versionFailed": "No se pudo abrir esta versión.",+ "versionChangeFailed": "No se pudo cambiar el historial de versiones.",+ "versionCopyName": "{name} (copia)"}diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex a9e610833..73d863bb5 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Exportar selección como .fig","togglePreview": "Vista previa","browseFiles": "Explorar archivos…",- "saveTo": "Guardar en…"+ "saveTo": "Guardar en…",+ "showVersionHistory": "Mostrar historial de versiones",+ "saveToVersionHistory": "Guardar en el historial de versiones…"}diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonindex dd9c30a11..58a3d19ee 100644--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -274,5 +274,29 @@"workspaceNotEmpty": "Supprimez ou déplacez d’abord ses documents ; seul un espace vide peut être supprimé.","workspaceCleanupPending": "Ses documents supprimés sont conservés un temps avant de disparaître définitivement. Réessayez ensuite.","shareOpenedInBrowser": "Ouvert dans le navigateur",- "openInDesktopApp": "Ouvrir dans l’application de bureau"+ "openInDesktopApp": "Ouvrir dans l’application de bureau",+ "versionHistory": "Historique des versions",+ "closeVersionHistory": "Fermer l’historique des versions",+ "currentVersion": "Version actuelle",+ "addToVersionHistory": "Ajouter à l’historique des versions",+ "editVersionInfo": "Modifier les infos de la version",+ "versionTitle": "Titre",+ "versionDescription": "Décrivez ce qui a changé",+ "restoreVersion": "Restaurer cette version",+ "duplicateVersion": "Dupliquer",+ "deleteVersionInfo": "Supprimer les infos de la version",+ "versionOptions": "Plus d’options pour la version",+ "versionFilter": "Filtrer les versions",+ "versionsAll": "Toutes",+ "versionsOnlyYours": "Seulement les vôtres",+ "showAutosaveVersions": "Afficher les versions enregistrées automatiquement",+ "restoredVersion": "Version restaurée : {name}",+ "restoredVersionUnnamed": "Version restaurée",+ "viewingVersion": "Affichage de {name}",+ "olderVersions": "Afficher les versions plus anciennes",+ "noVersions": "Aucune version",+ "versionsFailed": "Impossible de charger l’historique des versions.",+ "versionFailed": "Impossible d’ouvrir cette version.",+ "versionChangeFailed": "Impossible de modifier l’historique des versions.",+ "versionCopyName": "{name} (copie)"}diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex e38138351..ac4d8a80b 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Exporter la sélection en .fig","togglePreview": "Aperçu","browseFiles": "Parcourir les fichiers…",- "saveTo": "Enregistrer dans…"+ "saveTo": "Enregistrer dans…",+ "showVersionHistory": "Afficher l’historique des versions",+ "saveToVersionHistory": "Enregistrer dans l’historique des versions…"}diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonindex b0b03c9a6..a883fd551 100644--- a/packages/vue/src/i18n/locales/it/cloud/editor.json+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -274,5 +274,29 @@"workspaceNotEmpty": "Prima elimina o sposta i suoi documenti; si può eliminare solo un’area vuota.","workspaceCleanupPending": "I suoi documenti eliminati vengono conservati per un po’ prima di sparire del tutto. Riprova dopo.","shareOpenedInBrowser": "Aperto nel browser",- "openInDesktopApp": "Apri nell’app desktop"+ "openInDesktopApp": "Apri nell’app desktop",+ "versionHistory": "Cronologia versioni",+ "closeVersionHistory": "Chiudi cronologia versioni",+ "currentVersion": "Versione attuale",+ "addToVersionHistory": "Aggiungi alla cronologia versioni",+ "editVersionInfo": "Modifica info versione",+ "versionTitle": "Titolo",+ "versionDescription": "Descrivi cosa è cambiato",+ "restoreVersion": "Ripristina questa versione",+ "duplicateVersion": "Duplica",+ "deleteVersionInfo": "Elimina info versione",+ "versionOptions": "Altre opzioni per la versione",+ "versionFilter": "Filtra versioni",+ "versionsAll": "Tutte",+ "versionsOnlyYours": "Solo le tue",+ "showAutosaveVersions": "Mostra versioni salvate automaticamente",+ "restoredVersion": "Versione ripristinata: {name}",+ "restoredVersionUnnamed": "Versione ripristinata",+ "viewingVersion": "Visualizzazione di {name}",+ "olderVersions": "Mostra versioni precedenti",+ "noVersions": "Nessuna versione",+ "versionsFailed": "Impossibile caricare la cronologia versioni.",+ "versionFailed": "Impossibile aprire questa versione.",+ "versionChangeFailed": "Impossibile modificare la cronologia versioni.",+ "versionCopyName": "{name} (copia)"}diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex a48d8d538..9d56292f4 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Esporta selezione come .fig","togglePreview": "Anteprima","browseFiles": "Sfoglia file…",- "saveTo": "Salva in…"+ "saveTo": "Salva in…",+ "showVersionHistory": "Mostra cronologia versioni",+ "saveToVersionHistory": "Salva nella cronologia versioni…"}diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonindex 955ff0215..8d2779584 100644--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -271,5 +271,29 @@"workspaceNotEmpty": "先にドキュメントを削除するか移動してください。削除できるのは空のワークスペースだけです。","workspaceCleanupPending": "削除されたドキュメントは完全に消えるまでしばらく保管されます。その後にもう一度お試しください。","shareOpenedInBrowser": "ブラウザーで開きました",- "openInDesktopApp": "デスクトップアプリで開く"+ "openInDesktopApp": "デスクトップアプリで開く",+ "versionHistory": "バージョン履歴",+ "closeVersionHistory": "バージョン履歴を閉じる",+ "currentVersion": "現在のバージョン",+ "addToVersionHistory": "バージョン履歴に追加",+ "editVersionInfo": "バージョン情報を編集",+ "versionTitle": "タイトル",+ "versionDescription": "変更内容を説明",+ "restoreVersion": "このバージョンを復元",+ "duplicateVersion": "複製",+ "deleteVersionInfo": "バージョン情報を削除",+ "versionOptions": "バージョンのその他のオプション",+ "versionFilter": "バージョンを絞り込む",+ "versionsAll": "すべて",+ "versionsOnlyYours": "自分のみ",+ "showAutosaveVersions": "自動保存バージョンを表示",+ "restoredVersion": "復元したバージョン: {name}",+ "restoredVersionUnnamed": "復元したバージョン",+ "viewingVersion": "{name} を表示中",+ "olderVersions": "以前のバージョンを表示",+ "noVersions": "バージョンがありません",+ "versionsFailed": "バージョン履歴を読み込めませんでした。",+ "versionFailed": "このバージョンを開けませんでした。",+ "versionChangeFailed": "バージョン履歴を変更できませんでした。",+ "versionCopyName": "{name}(コピー)"}diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex 47bf8171c..13036c22d 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "選択範囲を .fig としてエクスポート","togglePreview": "プレビュー","browseFiles": "ファイルを表示…",- "saveTo": "保存先を選んで保存…"+ "saveTo": "保存先を選んで保存…",+ "showVersionHistory": "バージョン履歴を表示",+ "saveToVersionHistory": "バージョン履歴に保存…"}diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonindex 56f331d53..26a96ca16 100644--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -277,5 +277,29 @@"workspaceNotEmpty": "Najpierw usuń lub przenieś jego dokumenty; usunąć można tylko pusty obszar.","workspaceCleanupPending": "Usunięte dokumenty są jeszcze przez jakiś czas przechowywane. Spróbuj ponownie później.","shareOpenedInBrowser": "Otwarto w przeglądarce",- "openInDesktopApp": "Otwórz w aplikacji na komputer"+ "openInDesktopApp": "Otwórz w aplikacji na komputer",+ "versionHistory": "Historia wersji",+ "closeVersionHistory": "Zamknij historię wersji",+ "currentVersion": "Bieżąca wersja",+ "addToVersionHistory": "Dodaj do historii wersji",+ "editVersionInfo": "Edytuj informacje o wersji",+ "versionTitle": "Tytuł",+ "versionDescription": "Opisz, co się zmieniło",+ "restoreVersion": "Przywróć tę wersję",+ "duplicateVersion": "Duplikuj",+ "deleteVersionInfo": "Usuń informacje o wersji",+ "versionOptions": "Więcej opcji wersji",+ "versionFilter": "Filtruj wersje",+ "versionsAll": "Wszystkie",+ "versionsOnlyYours": "Tylko twoje",+ "showAutosaveVersions": "Pokaż wersje zapisane automatycznie",+ "restoredVersion": "Przywrócona wersja: {name}",+ "restoredVersionUnnamed": "Przywrócona wersja",+ "viewingVersion": "Wyświetlanie: {name}",+ "olderVersions": "Pokaż starsze wersje",+ "noVersions": "Brak wersji",+ "versionsFailed": "Nie udało się wczytać historii wersji.",+ "versionFailed": "Nie udało się otworzyć tej wersji.",+ "versionChangeFailed": "Nie udało się zmienić historii wersji.",+ "versionCopyName": "{name} (kopia)"}diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex 236484ed6..f95edc62e 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Eksportuj zaznaczenie jako .fig","togglePreview": "Podgląd","browseFiles": "Przeglądaj pliki…",- "saveTo": "Zapisz w…"+ "saveTo": "Zapisz w…",+ "showVersionHistory": "Pokaż historię wersji",+ "saveToVersionHistory": "Zapisz w historii wersji…"}diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonindex b9b44b2ce..dfcdd7490 100644--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -277,5 +277,29 @@"workspaceNotEmpty": "Сначала удалите или перенесите его документы: удалить можно только пустое пространство.","workspaceCleanupPending": "Удалённые документы ещё какое-то время хранятся, прежде чем исчезнуть окончательно. Попробуйте позже.","shareOpenedInBrowser": "Открыто в браузере",- "openInDesktopApp": "Открыть в приложении для компьютера"+ "openInDesktopApp": "Открыть в приложении для компьютера",+ "versionHistory": "История версий",+ "closeVersionHistory": "Закрыть историю версий",+ "currentVersion": "Текущая версия",+ "addToVersionHistory": "Добавить в историю версий",+ "editVersionInfo": "Изменить сведения о версии",+ "versionTitle": "Название",+ "versionDescription": "Опишите, что изменилось",+ "restoreVersion": "Восстановить эту версию",+ "duplicateVersion": "Дублировать",+ "deleteVersionInfo": "Удалить сведения о версии",+ "versionOptions": "Другие действия с версией",+ "versionFilter": "Фильтр версий",+ "versionsAll": "Все",+ "versionsOnlyYours": "Только ваши",+ "showAutosaveVersions": "Показывать автосохранённые версии",+ "restoredVersion": "Восстановленная версия: {name}",+ "restoredVersionUnnamed": "Восстановленная версия",+ "viewingVersion": "Просмотр: {name}",+ "olderVersions": "Показать более старые версии",+ "noVersions": "Нет версий",+ "versionsFailed": "Не удалось загрузить историю версий.",+ "versionFailed": "Не удалось открыть эту версию.",+ "versionChangeFailed": "Не удалось изменить историю версий.",+ "versionCopyName": "{name} (копия)"}diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex ccc6e765c..ee5f6aa27 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "Экспортировать выделение как .fig","togglePreview": "Просмотр","browseFiles": "Обзор файлов…",- "saveTo": "Сохранить в…"+ "saveTo": "Сохранить в…",+ "showVersionHistory": "Показать историю версий",+ "saveToVersionHistory": "Сохранить в историю версий…"}diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonindex aa4ba3c4f..f55100f7b 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -271,5 +271,29 @@"workspaceNotEmpty": "请先删除或移走其中的文档;只能删除空的工作区。","workspaceCleanupPending": "已删除的文档会保留一段时间后才彻底清除。请在那之后再试。","shareOpenedInBrowser": "已在浏览器中打开",- "openInDesktopApp": "在桌面应用中打开"+ "openInDesktopApp": "在桌面应用中打开",+ "versionHistory": "版本历史",+ "closeVersionHistory": "关闭版本历史",+ "currentVersion": "当前版本",+ "addToVersionHistory": "添加到版本历史",+ "editVersionInfo": "编辑版本信息",+ "versionTitle": "标题",+ "versionDescription": "描述更改内容",+ "restoreVersion": "恢复此版本",+ "duplicateVersion": "创建副本",+ "deleteVersionInfo": "删除版本信息",+ "versionOptions": "版本的更多选项",+ "versionFilter": "筛选版本",+ "versionsAll": "全部",+ "versionsOnlyYours": "仅限我的",+ "showAutosaveVersions": "显示自动保存的版本",+ "restoredVersion": "已恢复的版本:{name}",+ "restoredVersionUnnamed": "已恢复的版本",+ "viewingVersion": "正在查看 {name}",+ "olderVersions": "显示更早的版本",+ "noVersions": "没有版本",+ "versionsFailed": "无法加载版本历史。",+ "versionFailed": "无法打开此版本。",+ "versionChangeFailed": "无法更改版本历史。",+ "versionCopyName": "{name}(副本)"}diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex 6bf77b130..d14915713 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -80,5 +80,7 @@"exportSelectionAsFig": "将所选内容导出为 .fig","togglePreview": "预览","browseFiles": "浏览文件…",- "saveTo": "保存到…"+ "saveTo": "保存到…",+ "showVersionHistory": "显示版本历史",+ "saveToVersionHistory": "保存到版本历史…"}diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsindex 41765965d..48c250108 100644--- a/packages/vue/src/i18n/messages/cloud/editor.ts+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -325,7 +325,33 @@ export const cloudMessageDefaults = {syncError: 'Could not upload changes',shareLinkFailed: 'This link doesn’t open a document. Ask for a new one.',shareOpenedInBrowser: 'Opened in the browser',- openInDesktopApp: 'Open in the desktop app'+ openInDesktopApp: 'Open in the desktop app',++ // Version history+ versionHistory: 'Version history',+ closeVersionHistory: 'Close version history',+ currentVersion: 'Current version',+ addToVersionHistory: 'Add to version history',+ editVersionInfo: 'Edit version info',+ versionTitle: 'Title',+ versionDescription: 'Describe what changed',+ restoreVersion: 'Restore this version',+ duplicateVersion: 'Duplicate',+ deleteVersionInfo: 'Delete version info',+ versionOptions: 'More options for version',+ versionFilter: 'Filter versions',+ versionsAll: 'All',+ versionsOnlyYours: 'Only yours',+ showAutosaveVersions: 'Show autosave versions',+ restoredVersion: params('Restored version: {name}'),+ restoredVersionUnnamed: 'Restored version',+ viewingVersion: params('Viewing {name}'),+ olderVersions: 'Show older versions',+ noVersions: 'No versions to show',+ versionsFailed: 'Couldn’t load the version history.',+ versionFailed: 'Couldn’t open this version.',+ versionChangeFailed: 'Couldn’t change the version history.',+ versionCopyName: params('{name} (copy)')} as constexport const cloudMessages = i18n('cloud', cloudMessageDefaults)diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex c268ea1e6..c2d1d9f37 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -15,6 +15,8 @@ export const menuMessageDefaults = {save: 'Save',saveAs: 'Save as…',saveTo: 'Save to…',+ showVersionHistory: 'Show version history',+ saveToVersionHistory: 'Save to version history…',exportSelection: 'Export selection…',exportSelectionAsPNG: 'Export selection as PNG',exportSelectionAsSVG: 'Export selection as SVG',diff --git a/src/app/cloud/integration/index.ts b/src/app/cloud/integration/index.tsindex 828f54c08..3d6574c3f 100644--- a/src/app/cloud/integration/index.ts+++ b/src/app/cloud/integration/index.ts@@ -10,6 +10,13 @@ export { isCloudBinding } from '../documents/status'export { cloudSaveDestinations, cloudUploadFailure, signInToSaveTo } from '../documents/save'export { useHomeCloud } from '../home'export { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'+export {+ isVersionHistoryOpen,+ openVersionDialog,+ openVersionHistory,+ shownEditorStore,+ versionPreviewKey+} from '../versions/history'/** This build has Cloud; whether it shows depends on the server's listing or a preview. */export const CLOUD_INCLUDED: boolean = truediff --git a/src/app/cloud/integration/off/index.ts b/src/app/cloud/integration/off/index.tsindex 19dbc77b2..220988e4a 100644--- a/src/app/cloud/integration/off/index.ts+++ b/src/app/cloud/integration/off/index.ts@@ -24,6 +24,21 @@ export function isCloudBinding(): boolean {return false}+export function isVersionHistoryOpen(): boolean {+ return false+}++export const openVersionDialog = noop+export const openVersionHistory = noop++export function shownEditorStore<Store>(store: Store): Store {+ return store+}++export function versionPreviewKey(): string {+ return ''+}+export async function cloudSaveDestinations(): Promise<SaveDestination[]> {return []}diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.tsindex bc81aee72..44b52f027 100644--- a/src/app/cloud/rooms/live.ts+++ b/src/app/cloud/rooms/live.ts@@ -2,16 +2,21 @@ import { shallowRef, watch } from 'vue'import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'-import { openDocumentRoom, roomForStore } from '@/app/collab/rooms'+import { leaveRoom, openDocumentRoom, roomForStore } from '@/app/collab/rooms'import type { RoomSession } from '@/app/collab/session'import type { JoinCollabRoom } from '@/app/collab/transport'import { createCloudRelayJoin } from '@/app/collab/transport/cloud'import type { EditorStore } from '@/app/editor/session'import { createStorageAdapter } from '@/app/integrations/storage'import { getLocalCanvasStore } from '@/app/storage/local-store'-import { dropCanvasUploads, kickSyncEngine, replaceStoredVersion } from '@/app/storage/sync'+import {+ adoptStoredVersion,+ dropCanvasUploads,+ kickSyncEngine,+ replaceStoredVersion+} from '@/app/storage/sync'import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'-import { allTabs, getTabForStore, getTabsSnapshot } from '@/app/tabs'+import { allTabs, getTabForStore, getTabsSnapshot, reloadStorageDocumentInTab } from '@/app/tabs'import { isCloudBinding } from '../documents/status'import { cloudConnections } from '../sessions/connection'@@ -62,9 +67,15 @@ async function catchUpWithServer(store: EditorStore): Promise<void> {/*** Keeps this tab saving only while it is the room's saver. A tab that stops drops its queued* uploads, since the room holds those edits; the saver overwrites a revision it conflicts with,- * since the room's document already has every edit in it.+ * since the room's document already has every edit in it, unless that revision is a restore,+ * which moves the room on instead.*/-function followSaver(store: EditorStore, session: RoomSession, canSave: boolean): () => void {+function followSaver(+ store: EditorStore,+ session: RoomSession,+ canSave: boolean,+ roomIsCurrent: () => Promise<boolean>+): () => void {let saving: boolean | null = nullconst documentId = () => store.getStorageBinding()?.documentId ?? null@@ -80,6 +91,7 @@ function followSaver(store: EditorStore, session: RoomSession, canSave: boolean)await dropCanvasUploads(id)return}+ if (!(await roomIsCurrent())) returnawait catchUpWithServer(store).catch(() => undefined)// Only a stored document saves without asking where; the room never adds a file prompt.if (store.getStorageBinding() && store.hasUnsavedChanges()) await store.saveFigFile()@@ -88,7 +100,7 @@ function followSaver(store: EditorStore, session: RoomSession, canSave: boolean)async function settleConflict(id: string) {if (!saving) returnconst meta = await getLocalCanvasStore().getMeta(id)- if (meta?.syncStatus !== 'conflict') return+ if (meta?.syncStatus !== 'conflict' || !(await roomIsCurrent())) returnawait replaceStoredVersion(id)await kickSyncEngine()}@@ -125,6 +137,12 @@ export function openCloudDocumentRoom(permission: 'edit' | 'view'/** A guest from a link edits but has no account to save with. */guest?: boolean+ /**+ * Whether the document is still in this room; false once it was restored to a version, when+ * the room is left for `onRestored` to move the tab on.+ */+ roomIsCurrent?: () => Promise<boolean>+ onRestored?: () => void}) {const canEdit = options.permission === 'edit'@@ -139,7 +157,12 @@ export function openCloudDocumentRoom(stopSynced()if (canEdit && !session.roomHasDocument()) session.shareDocument()})- const stopSaver = followSaver(store, session, canSave)+ // Unsure whether the document moved on, the saver waits rather than overwrite a restore.+ const stopSaver = followSaver(store, session, canSave, async () => {+ const current = options.roomIsCurrent ? await options.roomIsCurrent().catch(() => null) : true+ if (current === false) options.onRestored?.()+ return current === true+ })return {session,stop() {@@ -158,7 +181,8 @@ export function openCloudDocumentRoom(export function cloudRelayTransport(url: string,first: CollaborationTicket,- next: () => Promise<CollaborationTicket>+ next: () => Promise<CollaborationTicket>,+ onRestored?: () => void): JoinCollabRoom {let unused: CollaborationTicket | null = firstreturn createCloudRelayJoin({@@ -166,16 +190,26 @@ export function cloudRelayTransport(async ticket() {const ticket = unused ?? (await next())unused = null+ // A restore moves the document to a new room; this one has nothing left to join.+ if (ticket.roomId !== first.roomId) return nullreturn { token: ticket.token, expiresAt: ticket.expiresAt }- }+ },+ onRestored})}+/** Each tab's live Cloud room, stopped when the tab closes or the room starts over. */+const liveRooms = new Map<EditorStore, { stop(): void }>()+/** Leaves the room's saving and status behind once its tab closes. */export function stopWithTab(store: EditorStore, room: { stop(): void }): void {+ liveRooms.set(store, room)const stopLeaving = watch(allTabs, () => {if (roomForStore(store)) return- room.stop()+ if (liveRooms.get(store) === room) {+ liveRooms.delete(store)+ room.stop()+ }stopLeaving()})}@@ -196,12 +230,14 @@ export async function startCloudRoom(store: EditorStore): Promise<void> {// The document may have moved, or its tab closed, while the ticket was on its way.const current = store.getStorageBinding() === binding && getTabForStore(store)if (first.provider !== 'relay' || !first.serverURL || !current) return+ const nextTicket = () => target.client.getCollaborationTicket(binding.documentId)+ const restart = () => void restartCloudRoom(store)const room = openCloudDocumentRoom(store, {roomId: first.roomId,- transport: cloudRelayTransport(first.serverURL, first, () =>- target.client.getCollaborationTicket(binding.documentId)- ),- permission: first.permission+ transport: cloudRelayTransport(first.serverURL, first, nextTicket, restart),+ permission: first.permission,+ roomIsCurrent: async () => (await nextTicket()).roomId === first.roomId,+ onRestored: restart})stopWithTab(store, room)} finally {@@ -209,6 +245,29 @@ export async function startCloudRoom(store: EditorStore): Promise<void> {}}+const restarting = new WeakSet<EditorStore>()++/**+ * Moves a tab to its document's new room after the document was restored to a version: the old+ * room's edits are left behind, the tab shows the restored document, and it joins again.+ */+export async function restartCloudRoom(store: EditorStore): Promise<void> {+ const binding = store.getStorageBinding()+ if (!binding || restarting.has(store)) return+ restarting.add(store)+ try {+ liveRooms.get(store)?.stop()+ liveRooms.delete(store)+ const session = roomForStore(store)+ if (session) leaveRoom(session)+ // The tab shows what it downloaded: another tab of the document may still write the local copy.+ await reloadStorageDocumentInTab(store, await adoptStoredVersion(binding.documentId))+ await startCloudRoom(store)+ } finally {+ restarting.delete(store)+ }+}+/** Starts the room of every open Cloud document, as tabs open and documents move to Cloud. */export function watchCloudRooms(): () => void {return watch(diff --git a/src/app/cloud/versions/actions.ts b/src/app/cloud/versions/actions.tsnew file mode 100644index 000000000..94a31f9ce--- /dev/null+++ b/src/app/cloud/versions/actions.ts@@ -0,0 +1,90 @@+import type {+ DocumentVersion,+ DocumentVersions,+ SaveDocumentVersionInput,+ UpdateDocumentVersionInput+} from '@open-pencil/cloud/contract'++import type { EditorStore } from '@/app/editor/session'+import { followUpload, kickSyncEngine } from '@/app/storage/sync'+import { openStorageDocumentInNewTab } from '@/app/tabs'++import { restartCloudRoom } from '../rooms/live'+import { cloudShareTarget } from '../sharing/document'+import { closeVersionHistory, versionHistoryOf } from './history'++function targetOf(store: EditorStore) {+ const document = versionHistoryOf(store)?.store ?? store+ const binding = document.getStorageBinding()+ const target = binding && cloudShareTarget(binding)+ if (!binding || !target) throw new Error('This document is not on a Cloud server')+ return { document, binding, target }+}++/** Who is signed in to the document's server, for the history's "Only yours". */+export function versionHistoryAccountId(store: EditorStore): string | null {+ const binding = (versionHistoryOf(store)?.store ?? store).getStorageBinding()+ return (binding && cloudShareTarget(binding)?.accountId) ?? null+}++/** A page of the document's history, newest first, older than `before` when given. */+export async function listVersions(store: EditorStore, before?: string): Promise<DocumentVersions> {+ const { target } = targetOf(store)+ return target.client.listDocumentVersions(target.documentId, { before })+}++/**+ * Names the document as it is now. The saver's unsaved edits are uploaded first, so the version+ * holds what is on screen.+ */+export async function saveVersion(+ store: EditorStore,+ input: SaveDocumentVersionInput+): Promise<DocumentVersion> {+ const { document, target } = targetOf(store)+ if (document.state.autosaveEnabled && document.hasUnsavedChanges()) {+ await document.saveFigFile()+ await kickSyncEngine()+ if ((await followUpload(target.documentId)) !== 'uploaded') {+ throw new Error('The document could not be saved before naming the version')+ }+ }+ return target.client.saveDocumentVersion(target.documentId, input)+}++/** Renames a version, or with a null name deletes its info and leaves an autosave. */+export async function editVersion(+ store: EditorStore,+ version: DocumentVersion,+ input: UpdateDocumentVersionInput+): Promise<DocumentVersion> {+ const { target } = targetOf(store)+ return target.client.updateDocumentVersion(target.documentId, version.id, input)+}++/**+ * Makes a version the document again, as Figma's Restore this version: the history closes and+ * the tab, with everyone else in the room, moves on to the restored document.+ */+export async function restoreVersion(store: EditorStore, version: DocumentVersion): Promise<void> {+ const { document, target } = targetOf(store)+ await target.client.restoreDocumentVersion(target.documentId, version.id)+ closeVersionHistory(document)+ await restartCloudRoom(document)+}++/** Copies a version into a new document beside this one and opens it. */+export async function duplicateVersion(+ store: EditorStore,+ version: DocumentVersion,+ name: string+): Promise<void> {+ const { binding, target } = targetOf(store)+ const copy = await target.client.duplicateDocumentVersion(target.documentId, version.id, {+ name+ })+ await openStorageDocumentInNewTab(+ { id: copy.id, name: copy.name, updatedAt: copy.updatedAt, revision: copy.currentRevisionId },+ binding+ )+}diff --git a/src/app/cloud/versions/history.ts b/src/app/cloud/versions/history.tsnew file mode 100644index 000000000..c02397c24--- /dev/null+++ b/src/app/cloud/versions/history.ts@@ -0,0 +1,178 @@+import { shallowRef } from 'vue'++import type { DocumentVersion } from '@open-pencil/cloud/contract'++import { createEditorStore, type EditorStore } from '@/app/editor/session'+import { downloadCloudRevision } from '@/app/integrations/storage/cloud/download'+import { storageFetch } from '@/app/integrations/storage/s3/fetch'+import { readFigBytes } from '@/app/tabs'++import { cloudShareTarget } from '../sharing/document'++/** An earlier version shown in place of the document, in an editor of its own. */+export type VersionPreview = { version: DocumentVersion; store: EditorStore }++/**+ * A tab's open version history. The document is read-only while it is open, as in Figma; a+ * previewed version gets its own read-only editor, so the document and its room carry on beneath.+ */+export type VersionHistory = {+ store: EditorStore+ /** Whether the document was read-only before, as for a viewer, to put back on closing. */+ wasReadOnly: boolean+ preview: VersionPreview | null+ /** The version being opened for preview. */+ opening: string | null+ /** Whether the last preview could not be opened. */+ failed: boolean+}++const histories = shallowRef<ReadonlyMap<EditorStore, VersionHistory>>(new Map())++/** The version info dialog: naming the document as it is now, or editing a version's info. */+export type VersionDialog = { store: EditorStore; version: DocumentVersion | null }+export const versionDialog = shallowRef<VersionDialog | null>(null)++/** Bumped when this window changes the history, so an open list loads it again. */+export const versionListRevision = shallowRef(0)+/** Each tab's preview download in flight, keyed by its document. */+const previewLoads = new Map<EditorStore, AbortController>()++function update(store: EditorStore, next: VersionHistory | null) {+ const map = new Map(histories.value)+ if (next) map.set(store, next)+ else map.delete(store)+ histories.value = map+}++/** The open history that `store` is the document or the previewed version of. */+export function versionHistoryOf(store: EditorStore): VersionHistory | undefined {+ const own = histories.value.get(store)+ if (own) return own+ for (const history of histories.value.values()) {+ if (history.preview?.store === store) return history+ }+ return undefined+}++export function isVersionHistoryOpen(store: EditorStore): boolean {+ return versionHistoryOf(store) !== undefined+}++/** Opens the version info dialog, as Save to version history or a version's Edit version info. */+export function openVersionDialog(+ store: EditorStore,+ version: DocumentVersion | null = null+): void {+ versionDialog.value = { store: versionHistoryOf(store)?.store ?? store, version }+}++/** A key that changes whenever the tab of `store` shows another version or the document again. */+export function versionPreviewKey(store: EditorStore): string {+ return histories.value.get(store)?.preview?.version.id ?? ''+}++/** What the tab of `store` shows: the previewed version while there is one, else the document. */+export function shownEditorStore(store: EditorStore): EditorStore {+ return histories.value.get(store)?.preview?.store ?? store+}++function endPreview(history: VersionHistory) {+ previewLoads.get(history.store)?.abort()+ previewLoads.delete(history.store)+ const preview = history.preview+ if (!preview) return+ preview.store.preparationController.dispose()+ preview.store.dispose()+}++export function openVersionHistory(store: EditorStore): void {+ if (histories.value.has(store)) return+ update(store, {+ store,+ wasReadOnly: store.state.readOnly,+ preview: null,+ opening: null,+ failed: false+ })+ store.setReadOnly(true)+}++export function closeVersionHistory(store: EditorStore): void {+ const history = versionHistoryOf(store)+ if (!history) return+ endPreview(history)+ update(history.store, null)+ history.store.setReadOnly(history.wasReadOnly)+}++/** Back to the document as it is now, keeping the history open. */+export function showCurrentVersion(store: EditorStore): void {+ const history = versionHistoryOf(store)+ if (!history) return+ endPreview(history)+ update(history.store, { ...history, preview: null, opening: null, failed: false })+}++/**+ * Shows an earlier version where the document was, on the same page and at the same view where+ * the version has that page.+ */+export async function previewVersion(store: EditorStore, version: DocumentVersion): Promise<void> {+ const history = versionHistoryOf(store)+ const binding = history?.store.getStorageBinding()+ const target = binding && cloudShareTarget(binding)+ if (!history || !target) return+ if (version.current) {+ showCurrentVersion(store)+ return+ }+ previewLoads.get(history.store)?.abort()+ const load = new AbortController()+ previewLoads.set(history.store, load)+ update(history.store, { ...history, opening: version.id, failed: false })+ const document = history.store+ let preview: EditorStore+ try {+ const download = await target.client.getDocumentVersion(target.documentId, version.id)+ const bytes = await downloadCloudRevision(download, storageFetch, { signal: load.signal })+ const name = document.state.documentName+ preview = createEditorStore(await readFigBytes(bytes, name, load.signal))+ preview.state.documentName = name+ preview.setReadOnly(true)+ } catch (error) {+ if (load.signal.aborted) return+ update(history.store, { ...history, opening: null, failed: true })+ console.warn('[Cloud] Opening a version failed:', error)+ return+ }+ if (load.signal.aborted) {+ preview.dispose()+ return+ }+ previewLoads.delete(document)+ const current = versionHistoryOf(document)+ if (!current) {+ preview.dispose()+ return+ }+ endPreview(current)+ update(document, { ...current, preview: { version, store: preview }, opening: null })+ // The version still shows where the document's page is missing or does not open.+ void keepPlace(preview, document).catch(() => undefined)+}++/**+ * Once the version shows, it opens at the document's view, on the page in the same place in its+ * page list; a `.fig` read gives every page a new ID, so the place is what they share.+ */+async function keepPlace(preview: EditorStore, document: EditorStore) {+ const { currentPageId, panX, panY, zoom } = document.state+ const index = document.graph.getPages().findIndex((page) => page.id === currentPageId)+ const page = index === -1 ? undefined : preview.graph.getPages().at(index)+ if (!page) return+ await preview.canvasReady+ if (preview.state.currentPageId !== page.id) await preview.switchPage(page.id)+ Object.assign(preview.state, { panX, panY, zoom })+ preview.requestRepaint()+}diff --git a/src/app/cloud/versions/list.ts b/src/app/cloud/versions/list.tsnew file mode 100644index 000000000..69bb20b26--- /dev/null+++ b/src/app/cloud/versions/list.ts@@ -0,0 +1,106 @@+import { computed, effectScope, ref, shallowRef, watch } from 'vue'++import type { DocumentVersion } from '@open-pencil/cloud/contract'++import type { EditorStore } from '@/app/editor/session'++import { cloudRoomPermissions } from '../rooms/live'+import { listVersions, versionHistoryAccountId } from './actions'+import { isVersionHistoryOpen, versionHistoryOf, versionListRevision } from './history'++export type VersionList = ReturnType<typeof createVersionList>++/**+ * Each open history's list. Choosing a version remounts the workspace, and the list keeps its+ * filters, loaded pages, and scroll position across that.+ */+const lists = new Map<EditorStore, VersionList>()++function createVersionList(document: EditorStore) {+ const versions = shallowRef<DocumentVersion[]>([])+ const nextCursor = ref<string | null>(null)+ const loading = ref(false)+ const failed = ref(false)+ const onlyYours = ref(false)+ const showAutosaves = ref(true)+ const scrollTop = ref(0)+ let generation = 0++ async function load(before?: string) {+ const current = ++generation+ loading.value = true+ failed.value = false+ try {+ const page = await listVersions(document, before)+ if (current !== generation) return+ versions.value = before ? [...versions.value, ...page.versions] : page.versions+ nextCursor.value = page.nextCursor+ } catch (error) {+ if (current !== generation) return+ failed.value = true+ console.warn('[Cloud] Loading the version history failed:', error)+ } finally {+ if (current === generation) loading.value = false+ }+ }++ watch(versionListRevision, () => void load(), { immediate: true })++ const accountId = computed(() => versionHistoryAccountId(document))+ const byId = computed(() => new Map(versions.value.map((version) => [version.id, version])))+ /** A restore reads as a named entry, as Figma lists "Restored version: …". */+ const isNamed = (version: DocumentVersion) =>+ version.kind === 'named' || version.restoredFromVersionId !== null+ const listed = computed(() =>+ versions.value.filter(+ (version) =>+ (showAutosaves.value || isNamed(version)) &&+ (!onlyYours.value || version.createdBy.id === accountId.value)+ )+ )+ const canEdit = computed(() => cloudRoomPermissions.value.get(document) !== 'view')++ return {+ document,+ versions: listed,+ nextCursor,+ loading,+ failed,+ onlyYours,+ showAutosaves,+ scrollTop,+ canEdit,+ isNamed,+ restoredFrom: (version: DocumentVersion) =>+ version.restoredFromVersionId ? byId.value.get(version.restoredFromVersionId) : undefined,+ loadOlder: () => (nextCursor.value ? load(nextCursor.value) : Promise.resolve()),+ reload: () => load()+ }+}++/**+ * The document's history as the panel lists it, newest first and a page at a time, with Figma's+ * filters: everyone's versions or only yours, and autosaves shown or hidden. It lasts until the+ * history closes.+ */+export function useVersionList(shown: EditorStore): VersionList {+ const document = versionHistoryOf(shown)?.store ?? shown+ const existing = lists.get(document)+ if (existing) return existing+ const scope = effectScope(true)+ const list = scope.run(() => {+ watch(+ () => isVersionHistoryOpen(document),+ (open) => {+ if (open) return+ lists.delete(document)+ scope.stop()+ },+ { flush: 'sync' }+ )+ return createVersionList(document)+ })+ if (!list) throw new Error('The version list could not be created')+ lists.set(document, list)+ return list+}diff --git a/src/app/collab/transport/cloud.ts b/src/app/collab/transport/cloud.tsindex e9888db96..250878705 100644--- a/src/app/collab/transport/cloud.ts+++ b/src/app/collab/transport/cloud.ts@@ -21,8 +21,13 @@ export type CloudRelayTicket = { token: string; expiresAt: string }export type CloudRelayOptions = {/** The relay's WebSocket URL from the ticket. */url: string- /** Issues a fresh ticket for the room, on connecting and before the current one expires. */- ticket: (roomId: string) => Promise<CloudRelayTicket>+ /**+ * Issues a fresh ticket for the room, on connecting and before the current one expires, or+ * null once the document has moved to another room.+ */+ ticket: (roomId: string) => Promise<CloudRelayTicket | null>+ /** The document was restored to a version and its room started over; this one is done. */+ onRestored?: () => voidcreateSocket?: (url: string) => WebSocket/** How long to wait before reconnection attempt `attempt`, counting from zero. */reconnectDelayMs?: (attempt: number) => number@@ -64,6 +69,8 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRlet socket: WebSocket | null = nulllet welcomed = falselet left = false+ /** Set once the relay or a ticket says the document was restored, which ends the room once. */+ let ended = falselet attempt = 0let refreshTimer: ReturnType<typeof setTimeout> | undefinedlet ticketExpiresAt = 0@@ -77,6 +84,10 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRtry {const next = await options.ticket(roomId)if (left) return+ if (!next) {+ restored()+ return+ }send({ type: 'auth', token: next.token })scheduleRefresh(next)} catch (error) {@@ -137,8 +148,22 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRattempt += 1}+ /** The room this transport serves is over; whoever opened it moves to the new one. */+ function restored() {+ if (ended) return+ ended = true+ clearTimeout(refreshTimer)+ clearTimeout(reconnectTimer)+ // Nothing more goes to the old room, whoever moves on to the new one.+ const current = socket+ socket = null+ current?.close(1000, 'The document was restored')+ forgetPeers()+ options.onRestored?.()+ }+async function connect() {- let ticket: CloudRelayTicket+ let ticket: CloudRelayTicket | nulltry {ticket = await options.ticket(roomId)} catch (error) {@@ -147,14 +172,19 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRreturn}if (left) return+ if (!ticket) {+ restored()+ return+ }+ const issued = ticketconst next = createSocket(options.url)next.binaryType = 'arraybuffer'socket = next// A socket that was replaced or left behind by `leave()` no longer speaks for this room.next.addEventListener('open', () => {if (socket !== next) return- send({ type: 'auth', token: ticket.token })- scheduleRefresh(ticket)+ send({ type: 'auth', token: issued.token })+ scheduleRefresh(issued)})next.addEventListener('message', (event: MessageEvent<ArrayBuffer>) => {if (socket === next) handleFrame(event.data)@@ -164,6 +194,10 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRsocket = nullclearTimeout(refreshTimer)forgetPeers()+ if (event.code === RELAY_CLOSE.restored) {+ restored()+ return+ }if (FINAL_CLOSE_CODES.has(event.code)) {report('The collaboration relay refused this peer:', event.reason || event.code)returndiff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsindex 598f33428..7d4745576 100644--- a/src/app/shell/keyboard/registry.ts+++ b/src/app/shell/keyboard/registry.ts@@ -5,6 +5,7 @@ import { onScopeDispose } from 'vue'import { editorCommandMetadata } from '@open-pencil/vue'import type { EditorCommandId } from '@open-pencil/vue'+import { isCloudBinding, openVersionDialog } from '@/app/cloud/integration'import { useComments } from '@/app/comments/use'import {copySelectionProperties,@@ -190,6 +191,13 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {keys: appMenuTinykeysShortcut('save-as') ?? '$mod+Shift+KeyS',run: ({ store }) => void store.saveFigFileAs()},+ {+ id: 'save-version',+ keys: appMenuTinykeysShortcut('save-version') ?? '$mod+Alt+KeyS',+ run: ({ store }) => {+ if (isCloudBinding(store.getStorageBinding())) openVersionDialog(store)+ }+ },...commandShortcuts('selection.ungroup', 'edit.redo'),{id: 'toggle-preview',diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex b14963f5f..c7e31cc12 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -110,6 +110,8 @@ export function useAppMenu() {save: 'save','save-as': 'saveAs','save-to': 'saveTo',+ 'save-version': 'saveToVersionHistory',+ 'version-history': 'showVersionHistory','export-selection': 'exportSelection',autosave: 'autosave',close: 'closeTab',diff --git a/src/app/shell/menu/features.ts b/src/app/shell/menu/features.tsindex dc2c4220a..c4f096b82 100644--- a/src/app/shell/menu/features.ts+++ b/src/app/shell/menu/features.ts@@ -1,5 +1,6 @@import { computed, watch } from 'vue'+import { isCloudBinding } from '@/app/cloud/integration'import { useEditorStore } from '@/app/editor/active-store'import { isTauri } from '@/app/tauri/env'@@ -9,7 +10,9 @@ const store = useEditorStore()const available: Record<AppMenuFeature, () => boolean> = {// Cloud and storage documents always save; auto-save is a choice only for a file on disk.- 'local-file': () => store.hasWritableSource() && !store.getStorageBinding()+ 'local-file': () => store.hasWritableSource() && !store.getStorageBinding(),+ // Version history lives on the Cloud server that keeps the document.+ 'cloud-document': () => isCloudBinding(store.getStorageBinding())}/** Whether a menu item that waits for a feature shows; items without one always do. */diff --git a/src/app/shell/menu/save-actions.ts b/src/app/shell/menu/save-actions.tsindex 8e0640c94..a4dc1f2d6 100644--- a/src/app/shell/menu/save-actions.ts+++ b/src/app/shell/menu/save-actions.ts@@ -1,3 +1,4 @@+import { openVersionDialog, openVersionHistory } from '@/app/cloud/integration'import type { EditorStore } from '@/app/editor/active-store'import { openSaveTo } from '@/app/storage/save-to/session'@@ -5,6 +6,8 @@ export function createSaveMenuActions(store: EditorStore) {return {save: () => void store.saveFigFile(),'save-as': () => void store.saveFigFileAs(),- 'save-to': () => void openSaveTo(store)+ 'save-to': () => void openSaveTo(store),+ 'save-version': () => openVersionDialog(store),+ 'version-history': () => openVersionHistory(store)}}diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex 4a196524c..135a9e83e 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -35,7 +35,7 @@ export type AppMenuHandler = 'editor' | 'shell'/** A feature an item waits for: it shows only while the feature is available (`./features`). *//** Items shown only for a document backed by a file on disk. */-export type AppMenuFeature = 'local-file'+export type AppMenuFeature = 'local-file' | 'cloud-document'export interface AppMenuActionItem {type?: 'item'@@ -88,6 +88,13 @@ export const APP_MENU_SCHEMA = [{ id: 'save', label: 'Save', shortcut: 'MOD+S' },{ id: 'save-as', label: 'Save As…', shortcut: 'MOD+SHIFT+S' },{ id: 'save-to', label: 'Save To…' },+ {+ id: 'save-version',+ label: 'Save to Version History…',+ shortcut: 'ALT+MOD+S',+ feature: 'cloud-document'+ },+ { id: 'version-history', label: 'Show Version History', feature: 'cloud-document' },{ type: 'separator' },{id: 'export-selection',diff --git a/src/app/storage/sync/conflicts.ts b/src/app/storage/sync/conflicts.tsindex 0a9871e9d..ac21ccde9 100644--- a/src/app/storage/sync/conflicts.ts+++ b/src/app/storage/sync/conflicts.ts@@ -37,7 +37,18 @@ export async function dropCanvasUploads(canvasId: string): Promise<void> {/** Discards this device's edits and takes the provider's newer revision. */export async function takeStoredVersion(canvasId: string): Promise<void> {- const { meta } = await conflictedCanvas(canvasId)+ await conflictedCanvas(canvasId)+ await adoptStoredVersion(canvasId)+}++/**+ * Makes the provider's current revision this device's copy, dropping queued uploads, as after+ * the document was restored to a version elsewhere. Returns the bytes, which another tab of the+ * document may overwrite in the local copy at any moment.+ */+export async function adoptStoredVersion(canvasId: string): Promise<Uint8Array> {+ const meta = await getLocalCanvasStore().getMeta(canvasId)+ if (!meta) throw new Error('This device has no copy of the document')const location = storageLocationOf(meta)const content = await createStorageAdapter(location).getDocument(canvasId)await dropCanvasUploads(canvasId)@@ -50,6 +61,7 @@ export async function takeStoredVersion(canvasId: string): Promise<void> {remoteRevision: content.revision})emitStorageWorkspaceEvent({ ...location, documentId: canvasId, kind: 'changed' })+ return content.bytes}/**diff --git a/src/app/storage/sync/index.ts b/src/app/storage/sync/index.tsindex d6077bc02..2f1447ed6 100644--- a/src/app/storage/sync/index.ts+++ b/src/app/storage/sync/index.ts@@ -7,6 +7,7 @@ export {resumeStorageSync} from './engine'export {+ adoptStoredVersion,dropCanvasUploads,keepBothVersions,replaceStoredVersion,diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 5683c6bba..6c3f407ce 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -312,18 +312,22 @@ function failPreparation(})}+/** A `.fig` file named after its document, holding a copy of the bytes. */+function figFile(bytes: Uint8Array, name: string): File {+ const copy = new Uint8Array(bytes.byteLength)+ copy.set(bytes)+ return new File([copy.buffer], `${name}.fig`, { type: 'application/octet-stream' })+}+async function showStorageDocument(store: EditorStore,binding: StorageDocumentBinding,document: StorageDocument,- load: DocumentLoadSession+ load: DocumentLoadSession,+ given?: Uint8Array): Promise<void> {- const bytes = await readStorageDocument(binding, document, load)- const fileBytes = new Uint8Array(bytes.byteLength)- fileBytes.set(bytes)- const file = new File([fileBytes.buffer], `${document.name}.fig`, {- type: 'application/octet-stream'- })+ const bytes = given ?? (await readStorageDocument(binding, document, load))+ const file = figFile(bytes, document.name)load.update({ phase: 'decoding', detail: document.name })const imported = await readFigForTab(file, load.signal)await showImportedGraph(@@ -334,8 +338,26 @@ async function showStorageDocument()}-/** Shows what this device now holds for a tab's stored document, as after a conflict. */-export async function reloadStorageDocumentInTab(store: EditorStore): Promise<void> {+/**+ * Reads a `.fig` file's bytes as a tab opens them, laid out and ready to show, for an editor of+ * its own such as an earlier version's preview.+ */+export function readFigBytes(+ bytes: Uint8Array,+ name: string,+ signal?: AbortSignal+): Promise<SceneGraph> {+ return readFigForTab(figFile(bytes, name), signal)+}++/**+ * Shows what this device now holds for a tab's stored document, as after a conflict, or `bytes`+ * just taken from its storage.+ */+export async function reloadStorageDocumentInTab(+ store: EditorStore,+ bytes?: Uint8Array+): Promise<void> {const binding = store.getStorageBinding()if (!binding) returnconst name = store.state.documentName@@ -345,7 +367,8 @@ export async function reloadStorageDocumentInTab(store: EditorStore): Promise<vostore,binding,{ id: binding.documentId, name, updatedAt: new Date().toISOString() },- load+ load,+ bytes)load.complete()} catch (error) {diff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vueindex 5ada7442a..7fe3c67fb 100644--- a/src/components/PropertiesPanel.vue+++ b/src/components/PropertiesPanel.vue@@ -5,8 +5,10 @@ import { computed } from 'vue'import { useDesignCheckMessages, useI18n } from '@open-pencil/vue'import { useAIChat } from '@/app/ai/chat/use'+import { isVersionHistoryOpen } from '@/app/cloud/integration'import { useEditorStore } from '@/app/editor/active-store'import { countIssues } from '@/app/editor/design-check/issues'+import { CloudVersionHistory } from '@/components/cloud/integration'import { propertiesTabs } from '@/theme/panel/properties-tabs'import ChatPanel from './ChatPanel.vue'@@ -24,6 +26,8 @@ const store = useEditorStore()const tabStyles = propertiesTabs()/** The Comment tool turns the sidebar into the comments list, as in Figma; the tabs keep their state. */const commenting = computed(() => store.state.activeTool === 'COMMENT')+/** Version history takes the sidebar while it is open, for the document and a version alike. */+const history = computed(() => isVersionHistoryOpen(store))/** Errors and warnings on the current page; suggestions do not earn an indicator. */const problemCount = computed(() => {@@ -40,8 +44,13 @@ const problemCount = computed(() => {class="flex min-w-0 flex-1 flex-col overflow-hidden border-l border-border bg-panel"style="contain: paint layout style">- <CommentsPanel v-if="commenting" />- <TabsRoot v-show="!commenting" v-model="activeTab" class="flex min-h-0 flex-1 flex-col">+ <CloudVersionHistory v-if="history" />+ <CommentsPanel v-else-if="commenting" />+ <TabsRoot+ v-show="!commenting && !history"+ v-model="activeTab"+ class="flex min-h-0 flex-1 flex-col"+ ><TabsList :class="tabStyles.list()"><TabsTriggervalue="design"diff --git a/src/components/cloud/integration/index.ts b/src/components/cloud/integration/index.tsindex 42fd05178..f12a8c7e7 100644--- a/src/components/cloud/integration/index.ts+++ b/src/components/cloud/integration/index.ts@@ -9,3 +9,5 @@ export { default as CloudSettingsSection } from '@/components/settings/cloud/Cloexport { default as CloudHosts } from '../CloudHosts.vue'export { default as CloudShareButton } from '../share/CloudShareButton.vue'export { default as CloudDocumentStatusHost } from '../status/CloudDocumentStatusHost.vue'+export { default as CloudVersionDialog } from '../versions/CloudVersionDialog.vue'+export { default as CloudVersionHistory } from '../versions/CloudVersionHistory.vue'diff --git a/src/components/cloud/integration/off.ts b/src/components/cloud/integration/off.tsindex 687792bbf..cb278e7f5 100644--- a/src/components/cloud/integration/off.ts+++ b/src/components/cloud/integration/off.ts@@ -11,3 +11,5 @@ export const CloudSettingsSection = absent('CloudSettingsSection')export const CloudHosts = absent('CloudHosts')export const CloudShareButton = absent('CloudShareButton')export const CloudDocumentStatusHost = absent('CloudDocumentStatusHost')+export const CloudVersionDialog = absent('CloudVersionDialog')+export const CloudVersionHistory = absent('CloudVersionHistory')diff --git a/src/components/cloud/versions/CloudVersionDialog.vue b/src/components/cloud/versions/CloudVersionDialog.vuenew file mode 100644index 000000000..d6ace09ec--- /dev/null+++ b/src/components/cloud/versions/CloudVersionDialog.vue@@ -0,0 +1,113 @@+<script setup lang="ts">+import { computed, ref, watch } from 'vue'++import {+ DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH,+ DOCUMENT_VERSION_NAME_MAX_LENGTH+} from '@open-pencil/cloud/contract'+import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import { editVersion, saveVersion } from '@/app/cloud/versions/actions'+import { versionDialog, versionListRevision } from '@/app/cloud/versions/history'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppDialogBody from '@/components/ui/dialog/AppDialogBody.vue'+import AppDialogFooter from '@/components/ui/dialog/AppDialogFooter.vue'+import AppDialogHeader from '@/components/ui/dialog/AppDialogHeader.vue'+import AppDialogRoot from '@/components/ui/dialog/AppDialogRoot.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import AppTextarea from '@/components/ui/input/AppTextarea.vue'+import { cloudVersions } from '@/theme/cloud/versions'++/**+ * Figma's Add to version history: a title and what changed, for the document as it is now, or+ * as Edit version info for a version already in the history.+ */+const t = useCloudMessages()+const common = useCommonMessages()+const ui = cloudVersions()+const name = ref('')+const description = ref('')+const busy = ref(false)+const failed = ref(false)++const open = computed({+ get: () => versionDialog.value !== null,+ set: (value) => {+ if (!value) versionDialog.value = null+ }+})+const editing = computed(() => versionDialog.value?.version ?? null)+const trimmed = computed(() => name.value.trim())++watch(versionDialog, (dialog) => {+ name.value = dialog?.version?.name ?? ''+ description.value = dialog?.version?.description ?? ''+ failed.value = false+})++async function submit() {+ const dialog = versionDialog.value+ if (!dialog || !trimmed.value) return+ busy.value = true+ failed.value = false+ const input = { name: trimmed.value, description: description.value.trim() }+ try {+ if (dialog.version) await editVersion(dialog.store, dialog.version, input)+ else await saveVersion(dialog.store, input)+ versionListRevision.value+++ versionDialog.value = null+ } catch (error) {+ console.warn('[Cloud] Saving to the version history failed:', error)+ failed.value = true+ } finally {+ busy.value = false+ }+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader+ :heading="editing ? t.editVersionInfo : t.addToVersionHistory"+ :close-label="common.close"+ />+ <AppDialogBody>+ <form id="cloud-version" :class="ui.form()" novalidate @submit.prevent="submit">+ <label for="cloud-version-title" :class="ui.label()">{{ t.versionTitle }}</label>+ <AppInput+ id="cloud-version-title"+ v-model="name"+ autofocus+ :maxlength="DOCUMENT_VERSION_NAME_MAX_LENGTH"+ :disabled="busy"+ :placeholder="t.versionTitle"+ />+ <label for="cloud-version-description" :class="ui.label()">+ {{ t.versionDescription }}+ </label>+ <AppTextarea+ id="cloud-version-description"+ v-model="description"+ :maxlength="DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH"+ :disabled="busy"+ :placeholder="t.versionDescription"+ />+ <AppAlert v-if="failed" tone="error" :heading="t.versionChangeFailed" />+ </form>+ </AppDialogBody>+ <AppDialogFooter>+ <AppButton @click="open = false">{{ common.cancel }}</AppButton>+ <AppButton+ type="submit"+ form="cloud-version"+ color="primary"+ variant="solid"+ :loading="busy"+ :disabled="!trimmed"+ >+ {{ common.save }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/versions/CloudVersionHistory.vue b/src/components/cloud/versions/CloudVersionHistory.vuenew file mode 100644index 000000000..1beb21775--- /dev/null+++ b/src/components/cloud/versions/CloudVersionHistory.vue@@ -0,0 +1,260 @@+<script setup lang="ts">+import {+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuItemIndicator,+ DropdownMenuPortal,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed, onMounted, useTemplateRef } from 'vue'++import type { DocumentVersion } from '@open-pencil/cloud/contract'+import { useCloudMessages, useI18n } from '@open-pencil/vue'++import { duplicateVersion, editVersion, restoreVersion } from '@/app/cloud/versions/actions'+import {+ closeVersionHistory,+ openVersionDialog,+ previewVersion,+ showCurrentVersion,+ versionHistoryOf,+ versionListRevision+} from '@/app/cloud/versions/history'+import { useVersionList } from '@/app/cloud/versions/list'+import { useEditorStore } from '@/app/editor/active-store'+import { toast } from '@/app/shell/ui'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'+import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'+import PanelHeader from '@/components/ui/panel/PanelHeader.vue'+import { cloudVersions } from '@/theme/cloud/versions'++import CloudVersionListItem from './CloudVersionListItem.vue'++/**+ * Version history, taking the right sidebar as in Figma: Current version first, then the+ * document's versions, newest first. Choosing one shows it read-only in place of the document.+ */+const shown = useEditorStore()+const t = useCloudMessages()+const { locale } = useI18n()+const ui = cloudVersions()+const menuCls = useMenuUI({ content: 'min-w-52', item: 'justify-start gap-2' })+const filterItem = menuItem({ justify: 'start', class: 'relative pl-7' })++const list = useVersionList(shown)+const listElement = useTemplateRef<HTMLUListElement>('listElement')+// Choosing a version remounts the panel; it opens where the list was scrolled.+onMounted(() => {+ if (listElement.value) listElement.value.scrollTop = list.scrollTop.value+})+function rememberScroll() {+ list.scrollTop.value = listElement.value?.scrollTop ?? 0+}+const history = computed(() => versionHistoryOf(shown))+const selectedId = computed(() => history.value?.preview?.version.id ?? null)++/** An autosave goes by when it was made, as Figma titles it: the time today, else with the date. */+const TODAY_FORMAT: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: '2-digit' }+const EARLIER_FORMAT: Intl.DateTimeFormatOptions = {+ ...TODAY_FORMAT,+ month: 'short',+ day: 'numeric'+}++function autosaveTitle(at: string) {+ const time = new Date(at)+ const today = new Date().toDateString() === time.toDateString()+ return new Intl.DateTimeFormat(locale.value, today ? TODAY_FORMAT : EARLIER_FORMAT).format(time)+}++function titleOf(version: DocumentVersion) {+ if (version.name) return version.name+ if (version.restoredFromVersionId) {+ const source = list.restoredFrom(version)?.name+ return source ? t.value.restoredVersion({ name: source }) : t.value.restoredVersionUnnamed+ }+ return autosaveTitle(version.createdAt)+}++function descriptionOf(version: DocumentVersion) {+ return version.description ?? list.restoredFrom(version)?.description ?? null+}++async function select(version: DocumentVersion) {+ await previewVersion(shown, version)+ const history = versionHistoryOf(shown)+ if (history?.failed) toast.error(t.value.versionFailed)+ else if (history?.preview?.version.id === version.id) {+ toast.info(t.value.viewingVersion({ name: titleOf(version) }))+ }+}++async function run(action: () => Promise<unknown>) {+ try {+ await action()+ versionListRevision.value+++ } catch (error) {+ console.warn('[Cloud] Changing the version history failed:', error)+ toast.error(t.value.versionChangeFailed)+ }+}++const restore = (version: DocumentVersion) => run(() => restoreVersion(shown, version))+const duplicate = (version: DocumentVersion) =>+ run(() =>+ duplicateVersion(+ shown,+ version,+ t.value.versionCopyName({ name: list.document.state.documentName })+ )+ )+const deleteInfo = (version: DocumentVersion) =>+ run(() => editVersion(shown, version, { name: null, description: '' }))++function setScope(value: unknown) {+ list.onlyYours.value = value === 'yours'+}+</script>++<template>+ <section :class="ui.panel()" :aria-label="t.versionHistory" data-slot="version-history">+ <PanelHeader>+ <template #icon><icon-lucide-history class="size-3.5" /></template>+ {{ t.versionHistory }}+ <template #actions>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton+ :label="t.versionFilter"+ :active="list.onlyYours.value || !list.showAutosaves.value"+ >+ <icon-lucide-list-filter class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4">+ <MenuScrollArea>+ <DropdownMenuRadioGroup+ :model-value="list.onlyYours.value ? 'yours' : 'all'"+ @update:model-value="setScope"+ >+ <DropdownMenuRadioItem value="all" :class="filterItem">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ t.versionsAll }}+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="yours" :class="filterItem">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ t.versionsOnlyYours }}+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator :class="menuCls.separator" />+ <DropdownMenuCheckboxItem v-model="list.showAutosaves.value" :class="filterItem">+ <DropdownMenuItemIndicator :class="ui.menuIndicator()">+ <icon-lucide-check class="size-3.5" />+ </DropdownMenuItemIndicator>+ {{ t.showAutosaveVersions }}+ </DropdownMenuCheckboxItem>+ </MenuScrollArea>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ <IconButton+ v-if="list.canEdit.value"+ :label="t.addToVersionHistory"+ @click="openVersionDialog(shown)"+ >+ <icon-lucide-plus class="size-3.5" />+ </IconButton>+ <IconButton :label="t.closeVersionHistory" @click="closeVersionHistory(shown)">+ <icon-lucide-x class="size-3.5" />+ </IconButton>+ </template>+ </PanelHeader>++ <ul+ ref="listElement"+ :class="ui.list()"+ :aria-label="t.versionHistory"+ @scroll="rememberScroll"+ >+ <CloudVersionListItem+ :label="t.currentVersion"+ current+ :selected="selectedId === null"+ :last="list.versions.value.length === 0"+ @select="showCurrentVersion(shown)"+ />+ <CloudVersionListItem+ v-for="(version, index) in list.versions.value"+ :key="version.id"+ :label="titleOf(version)"+ :description="descriptionOf(version)"+ :author="version.createdBy.name"+ :at="version.createdAt"+ :named="list.isNamed(version)"+ :selected="selectedId === version.id"+ :last="index === list.versions.value.length - 1"+ @select="select(version)"+ >+ <template v-if="list.canEdit.value" #actions>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="t.versionOptions">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4">+ <MenuScrollArea>+ <DropdownMenuItem+ :class="menuCls.item"+ @select="openVersionDialog(shown, version)"+ >+ {{ version.name ? t.editVersionInfo : t.addToVersionHistory }}+ </DropdownMenuItem>+ <DropdownMenuItem+ v-if="!version.current"+ :class="menuCls.item"+ @select="restore(version)"+ >+ {{ t.restoreVersion }}+ </DropdownMenuItem>+ <DropdownMenuItem :class="menuCls.item" @select="duplicate(version)">+ {{ t.duplicateVersion }}+ </DropdownMenuItem>+ <DropdownMenuItem+ v-if="version.name"+ :class="menuCls.item"+ @select="deleteInfo(version)"+ >+ {{ t.deleteVersionInfo }}+ </DropdownMenuItem>+ </MenuScrollArea>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </template>+ </CloudVersionListItem>+ </ul>+ <p v-if="list.failed.value" :class="ui.status()" role="alert">{{ t.versionsFailed }}</p>+ <p v-else-if="!list.loading.value && list.versions.value.length === 0" :class="ui.status()">+ {{ t.noVersions }}+ </p>+ <div v-if="list.nextCursor.value" :class="ui.more()">+ <AppButton size="sm" :loading="list.loading.value" @click="list.loadOlder()">+ {{ t.olderVersions }}+ </AppButton>+ </div>+ </section>+</template>diff --git a/src/components/cloud/versions/CloudVersionListItem.vue b/src/components/cloud/versions/CloudVersionListItem.vuenew file mode 100644index 000000000..ae59820fb--- /dev/null+++ b/src/components/cloud/versions/CloudVersionListItem.vue@@ -0,0 +1,58 @@+<script setup lang="ts">+import CommentTime from '@/components/comments/CommentTime.vue'+import { cloudVersions } from '@/theme/cloud/versions'++/**+ * An entry on the history's timeline. A named version shows a ring, an autosave a dot, as in+ * Figma; the line runs on to the next entry unless this is the last one.+ */+const {+ label,+ description = null,+ author = null,+ at = null,+ named = false,+ selected = false,+ last = false,+ current = false+} = defineProps<{+ label: string+ description?: string | null+ author?: string | null+ at?: string | null+ named?: boolean+ selected?: boolean+ last?: boolean+ /** The Current version entry, which names the document as it is now. */+ current?: boolean+}>()++const emit = defineEmits<{ select: [] }>()+defineSlots<{ actions?(): unknown }>()++const ui = cloudVersions()+</script>++<template>+ <li data-slot="version-list-item" :data-selected="selected || undefined" :class="ui.item()">+ <button+ type="button"+ :class="ui.itemButton()"+ :data-selected="selected || undefined"+ :aria-current="selected || undefined"+ @click="emit('select')"+ >+ <span :class="ui.marker()" aria-hidden="true">+ <span v-if="!last" :class="ui.line()" />+ <span :class="named || current ? ui.ring() : ui.dot()" />+ </span>+ <span :class="ui.body()">+ <span :class="current ? ui.current() : ui.title()">{{ label }}</span>+ <span v-if="description" :class="ui.description()">{{ description }}</span>+ <span v-if="author" :class="ui.author()">{{ author }}</span>+ <CommentTime v-if="at && named" :at="at" :class="ui.time()" />+ </span>+ </button>+ <span v-if="$slots.actions" :class="ui.actions()"><slot name="actions" /></span>+ </li>+</template>diff --git a/src/theme/cloud/versions.ts b/src/theme/cloud/versions.tsnew file mode 100644index 000000000..6769f8d56--- /dev/null+++ b/src/theme/cloud/versions.ts@@ -0,0 +1,30 @@+import { tv } from 'tailwind-variants'++/** Version history in the right sidebar: the document's versions on a timeline, as in Figma. */+export const cloudVersions = tv({+ slots: {+ panel: 'flex min-h-0 flex-1 flex-col',+ list: 'scrollbar-thin min-h-0 flex-1 overflow-y-auto py-1',+ item: 'group/item relative px-2',+ // The line between markers runs through the gutter beside each entry.+ itemButton:+ 'grid w-full cursor-pointer grid-cols-[24px_minmax(0,1fr)] gap-x-2 rounded-md px-1 py-1.5 pr-8 text-left text-xs outline-none hover:bg-hover focus-visible:bg-hover data-[selected]:bg-panel-selected-muted',+ marker: 'relative flex justify-center pt-0.5',+ ring: 'relative z-10 size-4 rounded-full border-2 border-muted bg-panel group-data-[selected]/item:border-accent',+ dot: 'relative z-10 mt-1 size-2 rounded-full bg-muted group-data-[selected]/item:bg-accent',+ line: 'absolute top-0 bottom-[-0.75rem] left-1/2 w-px -translate-x-1/2 bg-border',+ body: 'flex min-w-0 flex-col gap-0.5',+ title: 'min-w-0 truncate font-semibold text-surface',+ current: 'min-w-0 truncate font-semibold text-surface group-data-[selected]/item:text-accent',+ description: 'line-clamp-3 min-w-0 break-words text-surface/80',+ author: 'min-w-0 truncate text-[11px] text-muted',+ time: 'text-[11px] text-muted',+ actions:+ 'invisible absolute top-1.5 right-3 group-focus-within/item:visible group-hover/item:visible group-data-[selected]/item:visible group-data-[menu-open]/item:visible',+ more: 'flex justify-center px-3 py-2',+ status: 'px-4 py-3 text-xs text-muted',+ menuIndicator: 'absolute left-2',+ form: 'flex flex-col gap-3',+ label: 'sr-only'+ }+})diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex e4008f560..a1c393c9a 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { useHead } from '@unhead/vue'import { useEventListener, whenever } from '@vueuse/core'-import { onMounted, onUnmounted, provide, ref } from 'vue'+import { computed, onMounted, onUnmounted, provide, ref, watch } from 'vue'import { useRoute, useRouter } from 'vue-router'import { useI18n } from '@open-pencil/vue'@@ -14,6 +14,7 @@ import { exposeAutomationTestRequests } from '@/app/automation/bridge/test-hooksimport { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'import { startWebMCP } from '@/app/automation/webmcp/runtime'import { exposeCollaborationActions } from '@/app/browser-bridge'+import { shownEditorStore, versionPreviewKey } from '@/app/cloud/integration'import { useJoinRoom } from '@/app/collab/join'import { bindDesktopRoomLinks } from '@/app/collab/room/links'import { syncRoomRoute } from '@/app/collab/route'@@ -22,6 +23,7 @@ import { openDemoDocument } from '@/app/demo/document'import type { PendingOpenFile } from '@/app/document/io/pending-open'import { openPendingFiles } from '@/app/document/io/pending-open'import { openWebLinkFromLocation, withoutWebLinkParams } from '@/app/document/io/web-link'+import { setActiveEditorStore } from '@/app/editor/active-store'import { focusNodesByName } from '@/app/editor/selection/focus'import { notificationMessages } from '@/app/i18n/notifications'import { appRuntimeConfig } from '@/app/runtime/config'@@ -42,6 +44,7 @@ import {import { isTauri } from '@/app/tauri/env'import { offerUsageStatsPrompt, startSharing } from '@/app/telemetry'import ColorSpaceBanner from '@/components/canvas/ColorSpaceBanner.vue'+import { CloudVersionDialog } from '@/components/cloud/integration'import CommandPalette from '@/components/commands/CommandPalette.vue'import EditorWorkspace from '@/components/editor/EditorWorkspace.vue'import FileApiBanner from '@/components/FileApiBanner.vue'@@ -52,6 +55,25 @@ import TabBar from '@/components/TabBar.vue'import { IS_BROWSER } from '@/constants'const route = useRoute()+/**+ * The active tab as it shows: a version of its document being previewed takes the document's+ * place, in a workspace of its own, until the history goes back to the document.+ */+const shown = computed(() => {+ const tab = activeTab.value+ if (!tab) return null+ return {+ tab: { ...tab, store: shownEditorStore(tab.store) },+ key: tab.id + versionPreviewKey(tab.store)+ }+})+// Shortcuts, menus, and the clipboard act on what the tab shows.+watch(+ () => shown.value?.tab.store,+ (store) => {+ if (store) setActiveEditorStore(store)+ }+)const router = useRouter()const createdInitialTab = tabCount() === 0const shouldCreateHome =@@ -251,10 +273,7 @@ onUnmounted(() => {<CommandPalette /><TabBar /><HomeWorkspace v-show="activeTab?.kind === 'home'" @new-document="createDocumentInCurrentTab" />- <EditorWorkspace- v-if="activeTab && activeTab.kind !== 'home'"- :key="activeTab.id"- :tab="activeTab"- />+ <CloudVersionDialog />+ <EditorWorkspace v-if="shown && shown.tab.kind !== 'home'" :key="shown.key" :tab="shown.tab" /></div></template>diff --git a/tests/app/cloud/versions/history.test.ts b/tests/app/cloud/versions/history.test.tsnew file mode 100644index 000000000..c22f36344--- /dev/null+++ b/tests/app/cloud/versions/history.test.ts@@ -0,0 +1,47 @@+import 'fake-indexeddb/auto'+import { describe, expect, test } from 'bun:test'++import {+ closeVersionHistory,+ isVersionHistoryOpen,+ openVersionDialog,+ openVersionHistory,+ shownEditorStore,+ versionDialog,+ versionPreviewKey+} from '@/app/cloud/versions/history'+import { createEditorStore } from '@/app/editor/session/create'++// Figma desktop, version history (2026-10-17): the file is read-only while the panel is open,+// even on Current version, and editable again once it closes.++describe('version history', () => {+ test('keeps the document read-only while it is open', () => {+ const store = createEditorStore()+ openVersionHistory(store)+ expect(isVersionHistoryOpen(store)).toBe(true)+ expect(store.state.readOnly).toBe(true)+ expect(shownEditorStore(store)).toBe(store)+ expect(versionPreviewKey(store)).toBe('')++ closeVersionHistory(store)+ expect(isVersionHistoryOpen(store)).toBe(false)+ expect(store.state.readOnly).toBe(false)+ })++ test('leaves a viewer’s document read-only after closing', () => {+ const store = createEditorStore()+ store.setReadOnly(true)+ openVersionHistory(store)+ closeVersionHistory(store)+ expect(store.state.readOnly).toBe(true)+ })++ test('opens the version dialog for the document, without opening the history', () => {+ const store = createEditorStore()+ openVersionDialog(store)+ expect(versionDialog.value).toEqual({ store, version: null })+ expect(isVersionHistoryOpen(store)).toBe(false)+ versionDialog.value = null+ })+})diff --git a/tests/app/cloud/versions/list.test.ts b/tests/app/cloud/versions/list.test.tsnew file mode 100644index 000000000..7f91605a4--- /dev/null+++ b/tests/app/cloud/versions/list.test.ts@@ -0,0 +1,25 @@+import 'fake-indexeddb/auto'+import { describe, expect, test } from 'bun:test'++import { closeVersionHistory, openVersionHistory } from '@/app/cloud/versions/history'+import { useVersionList } from '@/app/cloud/versions/list'+import { createEditorStore } from '@/app/editor/session/create'++describe('version list', () => {+ test('lasts while the history is open, so a remounted panel keeps its place', () => {+ const store = createEditorStore()+ openVersionHistory(store)+ const list = useVersionList(store)+ list.onlyYours.value = true+ list.scrollTop.value = 240+ expect(useVersionList(store)).toBe(list)++ closeVersionHistory(store)+ openVersionHistory(store)+ const reopened = useVersionList(store)+ expect(reopened).not.toBe(list)+ expect(reopened.onlyYours.value).toBe(false)+ expect(reopened.scrollTop.value).toBe(0)+ closeVersionHistory(store)+ })+})diff --git a/tests/app/collab/transport/cloud.test.ts b/tests/app/collab/transport/cloud.test.tsindex 10a9551b9..3034cfab9 100644--- a/tests/app/collab/transport/cloud.test.ts+++ b/tests/app/collab/transport/cloud.test.ts@@ -43,15 +43,23 @@ async function settle() {for (let index = 0; index < 5; index++) await Promise.resolve()}-function room(options: { failTicket?: (attempt: number) => boolean } = {}) {+function room(+ options: {+ failTicket?: (attempt: number) => boolean+ /** The document moved to another room by this ticket request. */+ movedAt?: number+ } = {}+) {const sockets: FakeSocket[] = []let tickets = 0+ let restored = 0const errors: unknown[] = []const join = createCloudRelayJoin({url: 'wss://cloud.example.com/api/collaboration/relay',ticket: async () => {tickets += 1if (options.failTicket?.(tickets)) throw new Error('Ticket endpoint unavailable')+ if (options.movedAt !== undefined && tickets >= options.movedAt) return nullreturn { token: `ticket-${tickets}`, expiresAt: new Date(Date.now() + 300_000).toISOString() }},createSocket: () => {@@ -60,14 +68,25 @@ function room(options: { failTicket?: (attempt: number) => boolean } = {}) {return asDouble<WebSocket>(socket)},reconnectDelayMs: () => 0,- onError: (_message, error) => errors.push(error)+ onError: (_message, error) => errors.push(error),+ onRestored: () => {+ restored += 1+ }})const transport = join('cloud:room:0')const joined: string[] = []const left: string[] = []transport.onPeerJoin((peerId) => joined.push(peerId))transport.onPeerLeave((peerId) => left.push(peerId))- return { transport, sockets, joined, left, errors, tickets: () => tickets }+ return {+ transport,+ sockets,+ joined,+ left,+ errors,+ tickets: () => tickets,+ restored: () => restored+ }}describe('Cloud relay transport', () => {@@ -154,6 +173,63 @@ describe('Cloud relay transport', () => {}})+ test('moves on, without reconnecting, once the relay says the document was restored', async () => {+ const { sockets, restored, errors } = room()+ await settle()+ sockets[0]?.open()+ sockets[0]?.close(RELAY_CLOSE.restored, 'The document was restored')+ await settle()+ expect(restored()).toBe(1)+ expect(sockets).toHaveLength(1)+ expect(errors).toEqual([])+ })++ test('moves on when a fresh ticket is for the document’s new room', async () => {+ const { sockets, restored } = room({ movedAt: 2 })+ await settle()+ sockets[0]?.open()+ sockets[0]?.close(1006, 'Connection lost')+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ await settle()+ expect(restored()).toBe(1)+ expect(sockets).toHaveLength(1)+ })++ test('moves on once when the relay and a refreshed ticket both say so', async () => {+ jest.useFakeTimers()+ try {+ const { sockets, restored } = room({ movedAt: 2 })+ await settle()+ sockets[0]?.open()+ // The refresh is waiting on its ticket as the relay closes the room.+ jest.advanceTimersByTime(240_000)+ sockets[0]?.close(RELAY_CLOSE.restored, 'The document was restored')+ await settle()+ expect(restored()).toBe(1)+ } finally {+ jest.useRealTimers()+ }+ })++ test('closes its socket when a refreshed ticket is for the document’s new room', async () => {+ jest.useFakeTimers()+ try {+ const { sockets, left, restored } = room({ movedAt: 2 })+ await settle()+ sockets[0]?.open()+ sockets[0]?.receive({ type: 'welcome', peerId: 'me', peers: ['server', 'alice'] })+ jest.advanceTimersByTime(240_000)+ await settle()+ expect(restored()).toBe(1)+ expect(sockets[0]?.readyState).toBe(WebSocket.CLOSED)+ expect(left).toEqual(['server', 'alice'])+ } finally {+ jest.useRealTimers()+ }+ })+test('leaving closes the socket and never reconnects', async () => {const { transport, sockets } = room()await settle()