AI-native design editor. Open-source Figma alternative.
feat: give Cloud documents and their versions addresses and copyable links (#1285)
Danila Poyarkovfb14323a8476
diff --git a/changes/1069/added.md b/changes/1069/added.mdindex 2b69c3329..c8924a64c 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. **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.+- 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. In the web app the address bar shows the open Cloud document, and the version being looked at, so a reload or the address reopens it for anyone with access, and a version's **Copy link** copies that address. 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/packages/cloud/src/client/api.ts b/packages/cloud/src/client/api.tsindex 5a6b0f37e..61616dfc3 100644--- a/packages/cloud/src/client/api.ts+++ b/packages/cloud/src/client/api.ts@@ -11,6 +11,7 @@ import {documentInvitationSchema,documentShareSchema,documentSummarySchema,+ documentVersionDownloadSchema,documentVersionResponseSchema,documentVersionsSchema,restoredDocumentSchema,@@ -36,6 +37,7 @@ import {type DocumentShare,type DocumentSummary,type DocumentVersion,+ type DocumentVersionDownload,type DocumentVersions,type DuplicateDocumentVersionInput,type SaveDocumentVersionInput,@@ -493,15 +495,17 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio)return response.version},- async getDocumentVersion(documentId: string, versionId: string): Promise<DocumentDownload> {- const response = await parseResponse(+ async getDocumentVersion(+ documentId: string,+ versionId: string+ ): Promise<DocumentVersionDownload> {+ return parseResponse(client.documents[':documentId'].versions[':versionId'].$get({param: { documentId, versionId }}),- downloadResponseSchema,+ documentVersionDownloadSchema,options.onDiagnostic)- return response.document},async restoreDocumentVersion(documentId: string, versionId: string) {return parseResponse(diff --git a/packages/cloud/src/client/index.ts b/packages/cloud/src/client/index.tsindex 7bf404eb4..edc5951f7 100644--- a/packages/cloud/src/client/index.ts+++ b/packages/cloud/src/client/index.ts@@ -1,5 +1,12 @@export { cloudEditorReturnURL, cloudSignInURL } from './auth/navigation'-export { cloudDesktopLinkURL, cloudRedirectPath, cloudShareURL, type CloudLinkKind } from './links'+export {+ cloudDesktopLinkURL,+ cloudDocumentPath,+ cloudDocumentURL,+ cloudRedirectPath,+ cloudShareURL,+ type CloudLinkKind+} from './links'export {CloudAPIError,createCloudAPIClient,diff --git a/packages/cloud/src/client/links.ts b/packages/cloud/src/client/links.tsindex 92070cd10..eeee165cf 100644--- a/packages/cloud/src/client/links.ts+++ b/packages/cloud/src/client/links.ts@@ -1,24 +1,49 @@import type { CloudDiscovery } from '#cloud/contract'/** Canonical web links come from the owning instance, never the caller's window. */-export function cloudShareURL(- discovery: CloudDiscovery,- serverURL: string,- shareId: string,- secret: string-): string {+function editorURL(discovery: CloudDiscovery, path: string, serverURL: string): URL {if (!discovery.appURL) throw new Error('This instance does not advertise a public editor URL')const url = new URL(discovery.appURL)if (url.protocol !== 'https:' && url.protocol !== 'http:') {throw new Error('The public editor URL must use HTTP or HTTPS')}- url.pathname = `/cloud/share/${encodeURIComponent(shareId)}`+ url.pathname = pathurl.search = ''+ url.hash = ''url.searchParams.set('server', serverURL)+ return url+}++export function cloudShareURL(+ discovery: CloudDiscovery,+ serverURL: string,+ shareId: string,+ secret: string+): string {+ const url = editorURL(discovery, `/cloud/share/${encodeURIComponent(shareId)}`, serverURL)url.hash = secretreturn url.href}+/**+ * A document's address for its members, `/cloud/documents/:id?server=…`, or one of its versions+ * with `&version=…`. It carries no secret: whoever opens it signs in, and the server decides.+ */+export function cloudDocumentURL(+ discovery: CloudDiscovery,+ serverURL: string,+ documentId: string,+ versionId: string | null = null+): string {+ const url = editorURL(discovery, cloudDocumentPath(documentId), serverURL)+ if (versionId) url.searchParams.set('version', versionId)+ return url.href+}++export function cloudDocumentPath(documentId: string): string {+ return `/cloud/documents/${encodeURIComponent(documentId)}`+}+/** The two kinds of Cloud link that carry a secret: invitations and documents shared by link. */export type CloudLinkKind = 'invitations' | 'share'diff --git a/packages/cloud/src/contract/versions.ts b/packages/cloud/src/contract/versions.tsindex d197dea6e..6d6f441ee 100644--- a/packages/cloud/src/contract/versions.ts+++ b/packages/cloud/src/contract/versions.ts@@ -1,6 +1,6 @@import * as v from 'valibot'-import { documentSummarySchema } from './documents'+import { documentDownloadSchema, documentSummarySchema } from './documents'/** How long a version's name may be; the history list shows the start of longer ones. */export const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100@@ -65,6 +65,12 @@ export const duplicateDocumentVersionSchema = v.object({export type DuplicateDocumentVersionInput = v.InferOutput<typeof duplicateDocumentVersionSchema>export const documentVersionResponseSchema = v.object({ version: documentVersionSchema })+/** A version with where to download it, so a link to it can show it without the history. */+export const documentVersionDownloadSchema = v.object({+ document: documentDownloadSchema,+ version: documentVersionSchema+})+export type DocumentVersionDownload = v.InferOutput<typeof documentVersionDownloadSchema>export const restoredDocumentSchema = v.object({document: documentSummarySchema,version: documentVersionSchemadiff --git a/packages/cloud/src/server/documents/versions/routes.ts b/packages/cloud/src/server/documents/versions/routes.tsindex 173b216ef..dec2aba08 100644--- a/packages/cloud/src/server/documents/versions/routes.ts+++ b/packages/cloud/src/server/documents/versions/routes.ts@@ -71,13 +71,13 @@ export function createDocumentVersionRoutes(service: DocumentVersionService) {).get('/documents/:documentId/versions/:versionId', (context) =>answer(context, async () =>- context.json({- document: await service.download(+ context.json(+ await service.download(context.get('actor').userId,context.req.param('documentId'),context.req.param('versionId'))- })+ ))).post('/documents/:documentId/versions/:versionId/restore', (context) =>diff --git a/packages/cloud/src/server/documents/versions/service.ts b/packages/cloud/src/server/documents/versions/service.tsindex 9aa70e2cf..542be76d6 100644--- a/packages/cloud/src/server/documents/versions/service.ts+++ b/packages/cloud/src/server/documents/versions/service.ts@@ -1,5 +1,5 @@import type {- DocumentDownload,+ DocumentVersionDownload,DocumentSummary,DocumentVersion,DocumentVersions,@@ -228,20 +228,23 @@ export function createDocumentVersionService(userId: string,documentId: string,versionId: string- ): Promise<DocumentDownload> {+ ): Promise<DocumentVersionDownload> {const { document, start } = await openHistory(userId, documentId, false)const version = await findVersion(documentId, versionId, start)const stored = await storedRevision(database, version.revisionId)return {- document: documentSummary(document),- revisionId: version.revisionId,- byteSize: Number(stored.byteSize),- checksum: stored.checksum,- contentType: stored.contentType,- download: await objects.createDownload({- key: stored.objectKey,- expiresAt: new Date(Date.now() + DOWNLOAD_LIFETIME_MS)- })+ document: {+ document: documentSummary(document),+ revisionId: version.revisionId,+ byteSize: Number(stored.byteSize),+ checksum: stored.checksum,+ contentType: stored.contentType,+ download: await objects.createDownload({+ key: stored.objectKey,+ expiresAt: new Date(Date.now() + DOWNLOAD_LIFETIME_MS)+ })+ },+ version: versionOf(version, document.currentRevisionId)}},diff --git a/packages/cloud/tests/client/links.test.ts b/packages/cloud/tests/client/links.test.tsindex b0de08b22..a0b132cf9 100644--- a/packages/cloud/tests/client/links.test.ts+++ b/packages/cloud/tests/client/links.test.ts@@ -1,6 +1,11 @@import { expect, test } from 'bun:test'-import { cloudDesktopLinkURL, cloudRedirectPath, cloudShareURL } from '#cloud/client'+import {+ cloudDesktopLinkURL,+ cloudDocumentURL,+ cloudRedirectPath,+ cloudShareURL+} from '#cloud/client'import type { CloudDiscovery } from '#cloud/contract'const discovery: CloudDiscovery = {@@ -31,6 +36,23 @@ test('sharing rejects absent or non-web editor URLs', () => {).toThrow()})+test('a document or version address names its server and carries no secret', () => {+ const document = new URL(cloudDocumentURL(discovery, 'https://company.example', 'doc-id'))+ expect(document.origin).toBe('https://editor.company.example')+ expect(document.pathname).toBe('/cloud/documents/doc-id')+ expect(document.searchParams.get('server')).toBe('https://company.example')+ expect(document.searchParams.has('version')).toBe(false)+ expect(document.hash).toBe('')++ const version = new URL(+ cloudDocumentURL(discovery, 'https://company.example', 'doc-id', 'version-id')+ )+ expect(version.searchParams.get('version')).toBe('version-id')++ const anchored = { ...discovery, appURL: 'https://editor.company.example/#welcome' }+ expect(new URL(cloudDocumentURL(anchored, 'https://company.example', 'doc-id')).hash).toBe('')+})+test('authentication continuation stays on the issuing origin', () => {expect(cloudRedirectPath('/cloud/device?user_code=ABCD')).toBe('/cloud/device?user_code=ABCD')for (const input of [diff --git a/packages/cloud/tests/integration/server/documents/versions.test.ts b/packages/cloud/tests/integration/server/documents/versions.test.tsindex 53c1a034c..465dd9a61 100644--- a/packages/cloud/tests/integration/server/documents/versions.test.ts+++ b/packages/cloud/tests/integration/server/documents/versions.test.ts@@ -270,11 +270,16 @@ describe('Cloud version history', () => {[restored.version.id, original.id].map(async (versionId) =>responseJSON(await context.request(`/documents/${context.documentId}/versions/${versionId}`),- v.object({ document: v.object({ download: v.object({ url: v.string() }) }) })+ v.object({+ document: v.object({ download: v.object({ url: v.string() }) }),+ version: v.object({ id: v.string() })+ }))))expect(restoredDownload?.document.download.url).toBe(originalDownload?.document.download.url)+ // Each comes with its version, so a link to one can show it without the history.+ expect(originalDownload?.version.id).toBe(original.id)const usage = await context.runtime.database.selectFrom('workspaceStorageUsage').select('committedBytes')diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 9e98c9338..231033e25 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -69,6 +69,12 @@ keeps on its own, and versions someone named (`document_version`, one per revisithe right sidebar, as Figma does. Choosing a version shows it in a read-only editor of its own inplace of the document, whose room keeps syncing underneath; Save to version history (⌥⌘S) namesthe document once the saver's edits are uploaded.+- A document's address is `/cloud/documents/:id?server=…`, with `&version=…` for a version; the+ editor keeps the address bar on the active tab's document and the version it shows, and a+ version's Copy link builds the address on the server's advertised editor URL. The address carries+ no secret: opening it signs in to the named server, one the app already knows or the official one,+ and the server's access rules decide. Fetching a version returns the version with its download, so+ a link can show it without paging the history.- 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 053acf04e..c386ac18c 100644--- a/packages/docs/user-guide/openpencil-cloud.md+++ b/packages/docs/user-guide/openpencil-cloud.md@@ -79,8 +79,13 @@ Choose **File → Show version history** to list a document's versions in the ri- 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.+- **Copy link** in the same menu copies a link that opens the document with that version shown.-People who can only view see the history but can't change it.+People who can only view see the history and can copy links, but can't change it.++## Document Links++In the web app, the address bar shows the Cloud document you're looking at, and the version you have open in the history, so you can reload or pass the address on. Opening it signs you in to the document's server if needed, then opens the document for anyone with access to it. A link to a server you have never used only names the server; connect to it in **Settings → Cloud** first.## Share a Documentdiff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonindex 67ec79f3f..dc9d75842 100644--- a/packages/vue/src/i18n/locales/de/cloud/editor.json+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -216,6 +216,8 @@"syncConflict": "Auch anderswo bearbeitet – wähle, welche Version du behalten möchtest","syncError": "Änderungen konnten nicht hochgeladen werden","shareLinkFailed": "Dieser Link öffnet kein Dokument. Bitte um einen neuen.",+ "documentLinkFailed": "Dieses Dokument konnte nicht geöffnet werden. Bitte die Person, der es gehört, um Zugriff.",+ "documentLinkUnknownServer": "Melde dich zuerst bei {host} an, um diesen Link zu öffnen.","connectServerHeading": "Server deines Teams verbinden","connectServerDescription": "Gib die Adresse ein, die dein Team für OpenPencil Cloud nutzt.","checkingServer": "Server wird geprüft…",diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonindex b37367d44..d75e90734 100644--- a/packages/vue/src/i18n/locales/es/cloud/editor.json+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -216,6 +216,8 @@"syncConflict": "También se ha editado en otro sitio: elige qué versión conservar","syncError": "No se pudieron subir los cambios","shareLinkFailed": "Este enlace no abre ningún documento. Pide uno nuevo.",+ "documentLinkFailed": "No se pudo abrir este documento. Pide acceso a su propietario.",+ "documentLinkUnknownServer": "Inicia sesión en {host} para abrir este enlace.","connectServerHeading": "Conecta el servidor de tu equipo","connectServerDescription": "Escribe la dirección que usa tu equipo para OpenPencil Cloud.","checkingServer": "Comprobando el servidor…",diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonindex 58a3d19ee..be79cfa5a 100644--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -216,6 +216,8 @@"syncConflict": "Modifié ailleurs aussi — choisissez la version à conserver","syncError": "Impossible d’envoyer les modifications","shareLinkFailed": "Ce lien n’ouvre aucun document. Demandez-en un nouveau.",+ "documentLinkFailed": "Impossible d’ouvrir ce document. Demandez l’accès à son propriétaire.",+ "documentLinkUnknownServer": "Connectez-vous d’abord à {host} pour ouvrir ce lien.","connectServerHeading": "Connecter le serveur de votre équipe","connectServerDescription": "Saisissez l’adresse que votre équipe utilise pour OpenPencil Cloud.","checkingServer": "Vérification du serveur…",diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonindex a883fd551..e48e0e6ab 100644--- a/packages/vue/src/i18n/locales/it/cloud/editor.json+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -216,6 +216,8 @@"syncConflict": "Modificato anche altrove: scegli quale versione mantenere","syncError": "Impossibile caricare le modifiche","shareLinkFailed": "Questo link non apre un documento. Chiedine uno nuovo.",+ "documentLinkFailed": "Impossibile aprire questo documento. Chiedi l’accesso al proprietario.",+ "documentLinkUnknownServer": "Accedi prima a {host} per aprire questo link.","connectServerHeading": "Collega il server del tuo team","connectServerDescription": "Inserisci l’indirizzo che il tuo team usa per OpenPencil Cloud.","checkingServer": "Verifica del server…",diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonindex 8d2779584..6397b1261 100644--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -213,6 +213,8 @@"syncConflict": "他の場所でも編集されました。残すバージョンを選んでください","syncError": "変更をアップロードできませんでした","shareLinkFailed": "このリンクではドキュメントを開けません。新しいリンクを依頼してください。",+ "documentLinkFailed": "このドキュメントを開けませんでした。オーナーにアクセス権を依頼してください。",+ "documentLinkUnknownServer": "このリンクを開くには、先に {host} にサインインしてください。","connectServerHeading": "チームのサーバーに接続","connectServerDescription": "チームが OpenPencil Cloud に使っているアドレスを入力してください。","checkingServer": "サーバーを確認しています…",diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonindex 26a96ca16..0e791227f 100644--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -219,6 +219,8 @@"syncConflict": "Edytowano też gdzie indziej — wybierz, którą wersję zachować","syncError": "Nie udało się przesłać zmian","shareLinkFailed": "Ten link nie otwiera dokumentu. Poproś o nowy.",+ "documentLinkFailed": "Nie udało się otworzyć tego dokumentu. Poproś właściciela o dostęp.",+ "documentLinkUnknownServer": "Najpierw zaloguj się do {host}, aby otworzyć ten link.","connectServerHeading": "Połącz serwer zespołu","connectServerDescription": "Wpisz adres, którego zespół używa dla OpenPencil Cloud.","checkingServer": "Sprawdzanie serwera…",diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonindex dfcdd7490..2a0ef7b1c 100644--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -219,6 +219,8 @@"syncConflict": "Изменено и в другом месте — выберите, какую версию оставить","syncError": "Не удалось загрузить изменения","shareLinkFailed": "Эта ссылка не открывает документ. Попросите новую.",+ "documentLinkFailed": "Не удалось открыть документ. Попросите доступ у владельца.",+ "documentLinkUnknownServer": "Сначала войдите на {host}, чтобы открыть эту ссылку.","connectServerHeading": "Подключите сервер команды","connectServerDescription": "Введите адрес, который ваша команда использует для OpenPencil Cloud.","checkingServer": "Проверяем сервер…",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonindex f55100f7b..7f4e3c225 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -213,6 +213,8 @@"syncConflict": "其他地方也有编辑——请选择要保留的版本","syncError": "无法上传更改","shareLinkFailed": "此链接无法打开文档。请索取新链接。",+ "documentLinkFailed": "无法打开此文档。请向所有者申请访问权限。",+ "documentLinkUnknownServer": "请先登录 {host},再打开此链接。","connectServerHeading": "连接团队的服务器","connectServerDescription": "输入团队用于 OpenPencil Cloud 的地址。","checkingServer": "正在检查服务器…",diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsindex 48c250108..acb53e83f 100644--- a/packages/vue/src/i18n/messages/cloud/editor.ts+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -324,6 +324,8 @@ export const cloudMessageDefaults = {syncConflict: 'Edited elsewhere too — choose which version to keep',syncError: 'Could not upload changes',shareLinkFailed: 'This link doesn’t open a document. Ask for a new one.',+ documentLinkFailed: 'Couldn’t open this document. Ask its owner for access.',+ documentLinkUnknownServer: params('Sign in to {host} first to open this link.'),shareOpenedInBrowser: 'Opened in the browser',openInDesktopApp: 'Open in the desktop app',diff --git a/src/app/cloud/documents/link.ts b/src/app/cloud/documents/link.tsnew file mode 100644index 000000000..6f9ed2ace--- /dev/null+++ b/src/app/cloud/documents/link.ts@@ -0,0 +1,168 @@+import { useSessionStorage } from '@vueuse/core'+import * as v from 'valibot'+import { ref, watch } from 'vue'++import { cloudDocumentPath, cloudDocumentURL } from '@open-pencil/cloud/client'+import { cloudMessages } from '@open-pencil/vue'++import type { EditorStore } from '@/app/editor/session'+import { toast } from '@/app/shell/ui'+import { openStorageDocumentInNewTab } from '@/app/tabs'+import { IS_BROWSER, OFFICIAL_CLOUD_URL } from '@/constants'++import { cloudSignedIn, openCloudConnect } from '../connect/flow'+import { cloudServerHost, normalizeCloudServerURL } from '../servers/address'+import { addCloudServer, cloudServers, findCloudServer } from '../servers/store'+import { cloudAPIClient, cloudConnection } from '../sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'+import { openVersionHistory, previewVersion, versionHistoryOf } from '../versions/history'+import { isCloudBinding } from './status'++/**+ * A document's address for its members, `/cloud/documents/:id?server=…`, with `&version=…` for+ * one of its versions. Unlike invitations and share links it carries no secret: the server+ * decides whether whoever signs in may open it.+ */+export type CloudDocumentLink = { documentId: string; server: string; versionId: string | null }++const CLOUD_DOCUMENT_PATH = /^\/cloud\/documents\/([^/]+)$/++const linkSchema = v.object({+ documentId: v.string(),+ server: v.string(),+ versionId: v.nullable(v.string())+})++/** The link this tab is opening while it signs in, kept for the tab so it survives leaving. */+const stored = IS_BROWSER+ ? useSessionStorage<string | null>('open-pencil:cloud-document-link', null)+ : ref<string | null>(null)++/** The document link a web address carries, if it is one. */+export function readCloudDocumentLink(url: URL): CloudDocumentLink | null {+ const [, id] = url.pathname.match(CLOUD_DOCUMENT_PATH) ?? []+ const server = url.searchParams.get('server')+ if (!id || !server) return null+ try {+ return {+ documentId: decodeURIComponent(id),+ server,+ versionId: url.searchParams.get('version')+ }+ } catch {+ // A broken escape such as `%E0` is no link; it must not stop the app from starting.+ return null+ }+}++/**+ * What the tab of `store` has at its address: its Cloud document, and the version shown in place+ * of it. Null for anything else, or while signed out of its server.+ */+export function cloudDocumentAddress(+ store: EditorStore+): { path: string; query: Record<string, string> } | null {+ const history = versionHistoryOf(store)+ const binding = (history?.store ?? store).getStorageBinding()+ if (!binding || !isCloudBinding(binding) || !binding.profileId) return null+ const server = findCloudServer(binding.profileId)+ if (!server) return null+ const version = history?.preview?.version.id+ return {+ path: cloudDocumentPath(binding.documentId),+ query: version ? { server: server.url, version } : { server: server.url }+ }+}++/** Where links to the document in `store` go: its server, while that advertises an editor. */+function linkTarget(store: EditorStore) {+ const binding = (versionHistoryOf(store)?.store ?? store).getStorageBinding()+ const server = binding?.profileId ? findCloudServer(binding.profileId) : null+ const discovery = server ? cloudConnection(server.id).discovery : null+ return binding && server && discovery?.appURL ? { binding, server, discovery } : null+}++/** Whether versions of the document in `store` can be linked to. */+export function canLinkToVersions(store: EditorStore): boolean {+ return linkTarget(store) !== null+}++/** The link to copy for a version of the document in `store`, on its server's own editor. */+export function cloudVersionLinkURL(store: EditorStore, versionId: string): string | null {+ const target = linkTarget(store)+ if (!target) return null+ const { binding, server, discovery } = target+ return cloudDocumentURL(discovery, server.url, binding.documentId, versionId)+}++/**+ * Opens a document link: the document in a tab, and the version in the history when the link+ * names one. Signed out, it signs in first and picks the link up again after. A server this app+ * never used is only named, not added, so a link alone never connects it anywhere new.+ */+export async function openCloudDocumentLink(link: CloudDocumentLink): Promise<void> {+ const messages = cloudMessages.get()+ const url = normalizeCloudServerURL(link.server)+ if (!url) {+ toast.error(messages.documentLinkFailed)+ return+ }+ let server = cloudServers.value.find((candidate) => candidate.url === url) ?? null+ if (!server && url === OFFICIAL_CLOUD_URL)+ server = await addCloudServer({ kind: 'official', url })+ if (!server) {+ toast.error(messages.documentLinkUnknownServer({ host: cloudServerHost(url) }))+ return+ }+ const connection = cloudConnection(server.id)+ if (connection.state !== 'signed-in' || !connection.discovery) {+ stored.value = JSON.stringify(link satisfies CloudDocumentLink)+ openCloudConnect({ serverId: server.id })+ return+ }+ stored.value = null+ const client = cloudAPIClient(server, connection.discovery)+ const download = await client.getDocument(link.documentId).catch(() => null)+ if (!download) {+ toast.error(messages.documentLinkFailed)+ return+ }+ const { document } = download+ // Opening reports its own failure.+ const store = await openStorageDocumentInNewTab(+ {+ id: document.id,+ name: document.name,+ updatedAt: document.updatedAt,+ revision: document.currentRevisionId+ },+ {+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: server.id,+ containerId: document.workspaceId+ }+ ).catch(() => null)+ if (!store || !link.versionId) return+ const shown = await client.getDocumentVersion(document.id, link.versionId).catch(() => null)+ if (shown) {+ openVersionHistory(store)+ await previewVersion(store, shown.version)+ }+ if (!shown || versionHistoryOf(store)?.failed) toast.error(messages.versionFailed)+}++/** Drops a link kept while signing in, as when the tab opens with another one. */+export function forgetCloudDocumentLink(): void {+ stored.value = null+}++/** Picks a document link back up once signing in for it finished. */+export function resumeCloudDocumentLink(): () => void {+ return watch(cloudSignedIn, (signedIn) => {+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), linkSchema), stored.value ?? '')+ if (!signedIn || !parsed.success) return+ const url = normalizeCloudServerURL(parsed.output.server)+ if (url !== findCloudServer(signedIn.serverId)?.url) return+ void openCloudDocumentLink(parsed.output)+ })+}diff --git a/src/app/cloud/integration/index.ts b/src/app/cloud/integration/index.tsindex 3d6574c3f..a84f34f52 100644--- a/src/app/cloud/integration/index.ts+++ b/src/app/cloud/integration/index.ts@@ -6,6 +6,7 @@import { watchCloudRooms } from '../rooms/live'import { startCloudSessions } from '../sessions/startup'+export { cloudDocumentAddress } from '../documents/link'export { isCloudBinding } from '../documents/status'export { cloudSaveDestinations, cloudUploadFailure, signInToSaveTo } from '../documents/save'export { useHomeCloud } from '../home'diff --git a/src/app/cloud/integration/off/index.ts b/src/app/cloud/integration/off/index.tsindex 220988e4a..5099b8bfa 100644--- a/src/app/cloud/integration/off/index.ts+++ b/src/app/cloud/integration/off/index.ts@@ -24,6 +24,10 @@ export function isCloudBinding(): boolean {return false}+export function cloudDocumentAddress(): { path: string; query: Record<string, string> } | null {+ return null+}+export function isVersionHistoryOpen(): boolean {return false}diff --git a/src/app/cloud/sessions/startup.ts b/src/app/cloud/sessions/startup.tsindex 3f00b4069..73ae153a0 100644--- a/src/app/cloud/sessions/startup.ts+++ b/src/app/cloud/sessions/startup.ts@@ -1,5 +1,11 @@import { checkCloudAvailability } from '../availability'import { cloudSignedIn } from '../connect/flow'+import {+ forgetCloudDocumentLink,+ openCloudDocumentLink,+ readCloudDocumentLink,+ resumeCloudDocumentLink+} from '../documents/link'import { resumeCloudInvitation } from '../invitations/flow'import { bindDesktopCloudLinks, openCloudLink, readCloudLink } from '../links'import { cloudServers, findCloudServer } from '../servers/store'@@ -8,15 +14,20 @@ import { takePendingCloudSignIn } from './sign-in'/*** Checks every known server once the app starts, finishes a sign-in this tab left for the- * server's pages to do, and opens an invitation or a shared link the tab was opened with, or the- * desktop app was sent. The link's secret is taken out of the address at once.+ * server's pages to do, and opens an invitation, a shared link, or a document link the tab was+ * opened with, or the desktop app was sent. A link's secret is taken out of the address at once.*/export async function startCloudSessions(options: {/** Leaves a Cloud link's address, so its secret is not kept in history. */leaveLinkAddress(): Promise<unknown>}): Promise<void> {void checkCloudAvailability(globalThis.location.href)- const link = readCloudLink(new URL(globalThis.location.href))+ const address = new URL(globalThis.location.href)+ const link = readCloudLink(address)+ const documentLink = readCloudDocumentLink(address)+ // The link the tab opens with is the one to open, not one kept from an earlier sign-in.+ if (documentLink) forgetCloudDocumentLink()+ resumeCloudDocumentLink()if (link) await options.leaveLinkAddress()const pending = takePendingCloudSignIn()await Promise.all(cloudServers.value.map((server) => refreshCloudConnection(server)))@@ -24,5 +35,6 @@ export async function startCloudSessions(options: {if (server) cloudSignedIn.value = { serverId: server.id }if (link?.kind !== 'invitations') resumeCloudInvitation()if (link) await openCloudLink(link)+ if (documentLink) await openCloudDocumentLink(documentLink)await bindDesktopCloudLinks()}diff --git a/src/app/cloud/versions/history.ts b/src/app/cloud/versions/history.tsindex c02397c24..f988f3482 100644--- a/src/app/cloud/versions/history.ts+++ b/src/app/cloud/versions/history.ts@@ -134,7 +134,10 @@ export async function previewVersion(store: EditorStore, version: DocumentVersioconst document = history.storelet preview: EditorStoretry {- const download = await target.client.getDocumentVersion(target.documentId, version.id)+ const { document: download } = await target.client.getDocumentVersion(+ target.documentId,+ version.id+ )const bytes = await downloadCloudRevision(download, storageFetch, { signal: load.signal })const name = document.state.documentNamepreview = createEditorStore(await readFigBytes(bytes, name, load.signal))diff --git a/src/app/collab/route.ts b/src/app/collab/route.tsdeleted file mode 100644index 3ff501ef4..000000000--- a/src/app/collab/route.ts+++ /dev/null@@ -1,38 +0,0 @@-import { watch } from 'vue'-import type { RouteLocationNormalizedLoaded, Router } from 'vue-router'--import { isRoomId } from '@/app/collab/room/id'-import { activeRoom } from '@/app/collab/rooms'--export const SHARE_ROUTE_PREFIX = '/share/'--export function shareRoutePath(roomId: string): string {- return `${SHARE_ROUTE_PREFIX}${roomId}`-}--/**- * The path for the active tab's room: its share link, or `/` after leaving a share link. Only- * peer-to-peer rooms have share links; a Cloud document's room is the server's relay channel, so- * its ID never goes in the address.- */-export function roomPathFor(roomId: string | null, currentPath: string): string {- if (roomId && isRoomId(roomId)) return shareRoutePath(roomId)- return currentPath.startsWith(SHARE_ROUTE_PREFIX) ? '/' : currentPath-}--/**- * Keeps the address bar on the active tab's room: `/share/<id>` while a shared room's tab is- * active, and back to `/` when the active tab is not in one, so a reload or a copied URL opens what is- * on screen.- */-export function syncRoomRoute(router: Router, route: RouteLocationNormalizedLoaded): () => void {- return watch(- () => activeRoom.value?.roomId ?? null,- (roomId) => {- const path = roomPathFor(roomId, route.path)- if (path === route.path) return- void router.replace({ path, query: route.query, hash: route.hash })- },- { immediate: true }- )-}diff --git a/src/app/tabs/address.ts b/src/app/tabs/address.tsnew file mode 100644index 000000000..ea33faced--- /dev/null+++ b/src/app/tabs/address.ts@@ -0,0 +1,62 @@+import { isEqual, omit } from 'es-toolkit'+import { watch } from 'vue'+import type { LocationQuery, RouteLocationNormalizedLoaded, Router } from 'vue-router'++import { cloudDocumentAddress } from '@/app/cloud/integration'+import { isRoomId } from '@/app/collab/room/id'+import { activeRoom } from '@/app/collab/rooms'++import { activeTab } from './index'++export const SHARE_ROUTE_PREFIX = '/share/'+const CLOUD_DOCUMENT_PREFIX = '/cloud/documents/'+/** The query a Cloud document's address adds, and leaving it takes away. */+const CLOUD_DOCUMENT_QUERY = ['server', 'version']++export type TabAddress = { path: string; query: LocationQuery }++export function shareRoutePath(roomId: string): string {+ return `${SHARE_ROUTE_PREFIX}${roomId}`+}++/**+ * The address for the active tab: its Cloud document's, its shared room's link, or `/` after+ * leaving either. A Cloud document's room is the server's relay channel, so its ID never goes in+ * the address. On `opening`, a document address stays for startup to open.+ */+export function tabAddressFor(+ roomId: string | null,+ cloud: { path: string; query: Record<string, string> } | null,+ current: TabAddress,+ opening = false+): TabAddress {+ const query = omit(current.query, CLOUD_DOCUMENT_QUERY)+ if (cloud) return { path: cloud.path, query: { ...query, ...cloud.query } }+ if (roomId && isRoomId(roomId)) return { path: shareRoutePath(roomId), query }+ if (current.path.startsWith(SHARE_ROUTE_PREFIX)) return { path: '/', query }+ if (current.path.startsWith(CLOUD_DOCUMENT_PREFIX) && !opening) return { path: '/', query }+ return current+}++/**+ * Keeps the address bar on the active tab: its Cloud document, with the version it shows, or its+ * shared room, and back to `/` for anything else, so a reload or a copied URL opens what is on+ * screen.+ */+export function syncTabAddress(router: Router, route: RouteLocationNormalizedLoaded): () => void {+ let opening = true+ return watch(+ () => {+ const store = activeTab.value?.store+ return [activeRoom.value?.roomId ?? null, store ? cloudDocumentAddress(store) : null] as const+ },+ ([roomId, cloud]) => {+ const current = { path: route.path, query: route.query }+ const next = tabAddressFor(roomId, cloud, current, opening)+ opening = false+ if (next.path === current.path && isEqual(next.query, current.query)) return+ void router.replace({ ...next, hash: route.hash })+ },+ { immediate: true }+ )+}diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 6c3f407ce..ab61d340c 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -380,7 +380,7 @@ export async function reloadStorageDocumentInTab(export async function openStorageDocumentInNewTab(document: StorageDocument,location: StorageLocation = { providerId: activeStorageProviderID.value }-): Promise<void> {+): Promise<EditorStore> {const binding: StorageDocumentBinding = {...storageLocationOf(location),documentId: document.id@@ -389,7 +389,7 @@ export async function openStorageDocumentInNewTab(if (existing) {switchTab(existing.id)rememberRecentStorageDocument(binding, document.name)- return+ return existing.store}const { store, created } = reusableTabStore()@@ -427,6 +427,7 @@ export async function openStorageDocumentInNewTab(} finally {if (succeeded) load.complete()}+ return store}export async function openFileInNewTab(diff --git a/src/components/cloud/versions/CloudVersionHistory.vue b/src/components/cloud/versions/CloudVersionHistory.vueindex 1beb21775..dcf8662f2 100644--- a/src/components/cloud/versions/CloudVersionHistory.vue+++ b/src/components/cloud/versions/CloudVersionHistory.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { useClipboard } from '@vueuse/core'import {DropdownMenuCheckboxItem,DropdownMenuContent,@@ -16,6 +17,7 @@ import { computed, onMounted, useTemplateRef } from 'vue'import type { DocumentVersion } from '@open-pencil/cloud/contract'import { useCloudMessages, useI18n } from '@open-pencil/vue'+import { canLinkToVersions, cloudVersionLinkURL } from '@/app/cloud/documents/link'import { duplicateVersion, editVersion, restoreVersion } from '@/app/cloud/versions/actions'import {closeVersionHistory,@@ -118,6 +120,17 @@ const duplicate = (version: DocumentVersion) =>const deleteInfo = (version: DocumentVersion) =>run(() => editVersion(shown, version, { name: null, description: '' }))+const { copy } = useClipboard({ legacy: true })+// A server that advertises no editor has no address to link to.+const linkable = computed(() => canLinkToVersions(shown))++async function copyLink(version: DocumentVersion) {+ const url = cloudVersionLinkURL(shown, version.id)+ if (!url) return+ await copy(url)+ toast.info(t.value.shareLinkCopied)+}+function setScope(value: unknown) {list.onlyYours.value = value === 'yours'}@@ -207,7 +220,7 @@ function setScope(value: unknown) {:last="index === list.versions.value.length - 1"@select="select(version)">- <template v-if="list.canEdit.value" #actions>+ <template v-if="list.canEdit.value || linkable" #actions><DropdownMenuRoot :modal="false"><DropdownMenuTrigger as-child><IconButton :label="t.versionOptions">@@ -217,28 +230,37 @@ function setScope(value: unknown) {<DropdownMenuPortal><DropdownMenuContent :class="menuCls.content" align="end" :side-offset="4"><MenuScrollArea>+ <template v-if="list.canEdit.value">+ <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>+ </template><DropdownMenuItem+ v-if="linkable":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)"+ @select="copyLink(version)">- {{ t.deleteVersionInfo }}+ {{ t.shareCopyLink }}</DropdownMenuItem></MenuScrollArea></DropdownMenuContent>diff --git a/src/router.ts b/src/router.tsindex feefe326d..36b53b3ee 100644--- a/src/router.ts+++ b/src/router.ts@@ -20,7 +20,9 @@ const router = createRouter({{ path: '/share/:roomId', component: WorkspaceView },// Cloud invitations and links; the app takes their secret out of the address on start.{ path: '/cloud/invitations/:invitationId', component: WorkspaceView },- { path: '/cloud/share/:shareId', component: WorkspaceView }+ { path: '/cloud/share/:shareId', component: WorkspaceView },+ // A Cloud document, or one of its versions, for whoever signs in with access to it.+ { path: '/cloud/documents/:documentId', component: WorkspaceView }]})diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex a1c393c9a..063e967d8 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -17,7 +17,6 @@ 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'import { COLLAB_KEY, useCollab } from '@/app/collab/use'import { openDemoDocument } from '@/app/demo/document'import type { PendingOpenFile } from '@/app/document/io/pending-open'@@ -41,6 +40,7 @@ import {tabCount,type Tab} from '@/app/tabs'+import { syncTabAddress } from '@/app/tabs/address'import { isTauri } from '@/app/tauri/env'import { offerUsageStatsPrompt, startSharing } from '@/app/telemetry'import ColorSpaceBanner from '@/components/canvas/ColorSpaceBanner.vue'@@ -139,7 +139,7 @@ const collab = useCollab()provide(COLLAB_KEY, collab)exposeCollaborationActions(collab, joinRoomFromInput)exposeAutomationTestRequests()-syncRoomRoute(router, route)+syncTabAddress(router, route)useEventListener(document,diff --git a/tests/app/cloud/documents/link.test.ts b/tests/app/cloud/documents/link.test.tsnew file mode 100644index 000000000..3990cefc3--- /dev/null+++ b/tests/app/cloud/documents/link.test.ts@@ -0,0 +1,29 @@+import 'fake-indexeddb/auto'+import { describe, expect, test } from 'bun:test'++import { readCloudDocumentLink } from '@/app/cloud/documents/link'++const SERVER = 'https://cloud.example.com'+const DOCUMENT = '1413785f-37aa-4935-8bfb-e2cd81a035cf'++describe('Cloud document links', () => {+ test('an address names the document, its server, and the version it shows', () => {+ const base = `https://openpencil.dev/cloud/documents/${DOCUMENT}?server=${SERVER}`+ expect(readCloudDocumentLink(new URL(base))).toEqual({+ documentId: DOCUMENT,+ server: SERVER,+ versionId: null+ })+ expect(readCloudDocumentLink(new URL(`${base}&version=v1`))?.versionId).toBe('v1')+ })++ test('an address without a server or with a broken escape is no link', () => {+ expect(+ readCloudDocumentLink(new URL(`https://openpencil.dev/cloud/documents/${DOCUMENT}`))+ ).toBeNull()+ expect(+ readCloudDocumentLink(new URL(`https://openpencil.dev/cloud/documents/%E0?server=${SERVER}`))+ ).toBeNull()+ expect(readCloudDocumentLink(new URL(`https://openpencil.dev/?server=${SERVER}`))).toBeNull()+ })+})diff --git a/tests/app/collab/route.test.ts b/tests/app/collab/route.test.tsdeleted file mode 100644index cdae035dc..000000000--- a/tests/app/collab/route.test.ts+++ /dev/null@@ -1,23 +0,0 @@-import { describe, expect, test } from 'bun:test'--import { roomPathFor } from '@/app/collab/route'--const roomId = 'abcdefghijklmnopqrstuvwxyz012345'--describe('room address', () => {- test('shows a shared room as its share link', () => {- expect(roomPathFor(roomId, '/')).toBe(`/share/${roomId}`)- })-- test('keeps a Cloud document room out of the address', () => {- expect(roomPathFor('cloud:1413785f-37aa-4935-8bfb-e2cd81a035cf:0', '/')).toBe('/')- expect(roomPathFor('cloud:1413785f-37aa-4935-8bfb-e2cd81a035cf:0', `/share/${roomId}`)).toBe(- '/'- )- })-- test('leaves a share link for the home address when no room is active', () => {- expect(roomPathFor(null, `/share/${roomId}`)).toBe('/')- expect(roomPathFor(null, '/demo')).toBe('/demo')- })-})diff --git a/tests/app/tabs/address.test.ts b/tests/app/tabs/address.test.tsnew file mode 100644index 000000000..2c94e0568--- /dev/null+++ b/tests/app/tabs/address.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'bun:test'++import { tabAddressFor } from '@/app/tabs/address'++const roomId = 'abcdefghijklmnopqrstuvwxyz012345'+const cloudRoomId = 'cloud:1413785f-37aa-4935-8bfb-e2cd81a035cf:0'+const home = { path: '/', query: {} }+const document = {+ path: '/cloud/documents/1413785f-37aa-4935-8bfb-e2cd81a035cf',+ query: { server: 'https://cloud.example.com' }+}++describe('tab address', () => {+ test('shows a shared room as its share link', () => {+ expect(tabAddressFor(roomId, null, home).path).toBe(`/share/${roomId}`)+ })++ test('takes a document’s server and version off when a room’s tab comes up', () => {+ const shown = {+ path: document.path,+ query: { ...document.query, version: 'v1', cloud: 'preview' }+ }+ expect(tabAddressFor(roomId, null, shown)).toEqual({+ path: `/share/${roomId}`,+ query: { cloud: 'preview' }+ })+ })++ test('shows a Cloud document at its address, not its room', () => {+ expect(tabAddressFor(cloudRoomId, document, home)).toEqual(document)+ expect(tabAddressFor(cloudRoomId, null, { path: `/share/${roomId}`, query: {} }).path).toBe('/')+ })++ test('names the version shown, keeping the rest of the query', () => {+ const version = { ...document, query: { ...document.query, version: 'v1' } }+ expect(tabAddressFor(cloudRoomId, version, { path: '/', query: { cloud: 'preview' } })).toEqual(+ { path: version.path, query: { cloud: 'preview', ...version.query } }+ )+ expect(+ tabAddressFor(cloudRoomId, document, { path: version.path, query: version.query })+ ).toEqual(document)+ })++ test('leaves a share link or a document for the home address when the tab has neither', () => {+ expect(tabAddressFor(null, null, { path: `/share/${roomId}`, query: {} }).path).toBe('/')+ expect(tabAddressFor(null, null, { path: document.path, query: document.query })).toEqual(home)+ expect(tabAddressFor(null, null, { path: '/demo', query: {} }).path).toBe('/demo')+ })++ test('keeps the document address the app opened with, for startup to open', () => {+ const opened = { path: document.path, query: document.query }+ expect(tabAddressFor(null, null, opened, true)).toEqual(opened)+ })+})