AI-native design editor. Open-source Figma alternative.
feat(cloud): use Cloud documents from the editor (#1069)
Danila Poyarkov46b509e008a1
diff --git a/changes/1069/added.md b/changes/1069/added.mdnew file mode 100644index 000000000..28a1b3a50--- /dev/null+++ b/changes/1069/added.md@@ -0,0 +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. 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. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud`.diff --git a/changes/1069/changed.md b/changes/1069/changed.mdnew file mode 100644index 000000000..482b72619--- /dev/null+++ b/changes/1069/changed.md@@ -0,0 +1 @@+- Home lists places in a sidebar: Recent files, the storage bucket, and the Cloud workspaces of the server you connect each have their own page instead of sharing one, and phones get the same places in a menu above the documents.diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdindex 95f5fa0e8..65fa03ab8 100644--- a/desktop/AGENTS.md+++ b/desktop/AGENTS.md@@ -11,6 +11,7 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j- The Software Update window is a second webview labelled `updater` that loads `updater.html` (`src/updater.ts`), never the editor's `index.html`; its own capability, `desktop/capabilities/updater.json`, grants only checking, installing, restarting, closing, and opening links. It owns no documents, so before a restart or a Windows install it asks the editor window over `updater:restart-request` to run the Quit approval (`src/app/shell/updater/approvals.ts`, `tests/app/shell/updater/session.test.ts`).- Never click Install in a `tauri dev` build: the updater unpacks the release next to the running binary, which there is `desktop/target/debug`.- `desktop/generated/menu.json` is produced by `bun run generate:tauri-menu` from `src/app/shell/menu/schema.ts`; do not edit or import it directly.+- A menu entry with a `feature` in the schema is built only while the frontend names that feature through `set_native_menu_features` (`src/app/shell/menu/features.ts`); every rebuild keeps the check states the menu had (`desktop/src/menu.rs`).- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex 4cb929905..c2335d661 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -17,8 +17,8 @@"label": "Open Recent"},{- "id": "open-storage-workspace",- "label": "Open Storage Workspace…"+ "id": "browse-files",+ "label": "Browse Files…"},{"id": "open-tour",@@ -38,8 +38,8 @@"accelerator": "CmdOrCtrl+Shift+S"},{- "id": "save-to-storage",- "label": "Save to Storage…"+ "id": "save-to",+ "label": "Save To…"},{"type": "separator"@@ -73,7 +73,8 @@{"id": "autosave","label": "Autosave",- "checkbox": true+ "checkbox": true,+ "feature": "local-file"},{"id": "close",diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 8071484e5..5652d6582 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -17,7 +17,10 @@ use deep_link::path_matches_suffix;use fig_container::build_fig_file;use fonts::{list_system_fonts, load_system_font};use http::{cancel_http_request, proxy_http_request, ProxyHttpRequests};-use menu::{install_app_menu, native_menu_checked, set_native_menu_checked};+use menu::{+ install_app_menu, native_menu_checked, set_native_menu_checked, set_native_menu_features,+ update_app_menu, NativeMenuInputs, NativeMenuState,+};use menu_events::handle_menu_event;use std::{path::{Path, PathBuf},@@ -89,7 +92,7 @@ fn sharing_disabled_by_env() -> bool {#[tauri::command]fn set_recent_files(app: tauri::AppHandle, paths: Vec<String>) -> Result<(), String> {- install_app_menu(&app, &paths).map_err(|error| error.to_string())+ update_app_menu(&app, |inputs| inputs.recent_files = paths)}/// Name of the MCP entry point installed by `@open-pencil/mcp`.@@ -361,6 +364,7 @@ pub fn run() {.manage(PendingOpen(Mutex::new(Vec::new()))).manage(ProxyHttpRequests::default()).manage(PendingRooms(Mutex::new(Vec::new())))+ .manage(NativeMenuState(Mutex::new(NativeMenuInputs::default()))).invoke_handler(tauri::generate_handler![agents::agent_lookup,build_fig_file,@@ -378,6 +382,7 @@ pub fn run() {proxy_http_request,cancel_http_request,set_recent_files,+ set_native_menu_features,native_menu_checked,set_native_menu_checked,take_pending_open,@@ -433,7 +438,10 @@ pub fn run() {queue_deep_links(app.handle(), urls);}- Ok(install_app_menu(app.handle(), &[])?)+ Ok(install_app_menu(+ app.handle(),+ &NativeMenuInputs::default(),+ )?)}).build(tauri::generate_context!()).expect("error while building tauri application")diff --git a/desktop/src/menu.rs b/desktop/src/menu.rsindex 6002d3101..974b00389 100644--- a/desktop/src/menu.rs+++ b/desktop/src/menu.rs@@ -1,5 +1,7 @@use serde::Deserialize;+use std::collections::HashMap;use std::path::Path;+use std::sync::Mutex;use tauri::menu::{CheckMenuItemBuilder, MenuBuilder, MenuItemBuilder, MenuItemKind, Submenu, SubmenuBuilder,};@@ -22,10 +24,27 @@ struct MenuEntry {accelerator: Option<String>,#[serde(default)]checkbox: bool,+ /// A feature the frontend turns on before the item shows (`set_native_menu_features`).+ feature: Option<String>,#[serde(default)]sub: Vec<MenuEntry>,}+/// What the schema menu is built from besides the schema: recent files and enabled features.+#[derive(Default)]+pub struct NativeMenuInputs {+ pub recent_files: Vec<String>,+ pub features: Vec<String>,+}++pub struct NativeMenuState(pub Mutex<NativeMenuInputs>);++/// What one build reads: the inputs, and the check states the menu being replaced had.+struct MenuBuild<'a> {+ inputs: &'a NativeMenuInputs,+ checked: HashMap<String, bool>,+}+#[cfg(target_os = "macos")]#[derive(Deserialize)]struct AppMenuItem {@@ -54,10 +73,16 @@ fn app_menu_file() -> tauri::Result<AppMenuFile> {/// The macOS application menu holds Settings…, so the schema's copy is left out there, along/// with a separator it would leave at the end of its menu.-fn platform_entries(items: &[MenuEntry]) -> Vec<&MenuEntry> {+fn platform_entries<'a>(items: &'a [MenuEntry], features: &[String]) -> Vec<&'a MenuEntry> {let mut entries: Vec<&MenuEntry> = items.iter().filter(|entry| !(cfg!(target_os = "macos") && entry.id.as_deref() == Some("settings")))+ .filter(|entry| {+ entry+ .feature+ .as_ref()+ .is_none_or(|feature| features.contains(feature))+ }).collect();while entries.last()@@ -72,11 +97,11 @@ fn build_submenu<R: tauri::Runtime>(app: &tauri::AppHandle<R>,label: &str,items: &[MenuEntry],- recent_files: &[String],+ build: &MenuBuild,) -> tauri::Result<Submenu<R>> {let mut builder = SubmenuBuilder::new(app, label);- for entry in platform_entries(items) {+ for entry in platform_entries(items, &build.inputs.features) {if entry.r#type.as_deref() == Some("separator") {builder = builder.separator();continue;@@ -84,12 +109,12 @@ fn build_submenu<R: tauri::Runtime>(let label = entry.label.as_deref().unwrap_or_default();if entry.id.as_deref() == Some("open-recent") {- let submenu = build_recent_files_submenu(app, label, recent_files)?;+ let submenu = build_recent_files_submenu(app, label, &build.inputs.recent_files)?;builder = builder.item(&submenu);continue;}if !entry.sub.is_empty() {- let submenu = build_submenu(app, label, &entry.sub, recent_files)?;+ let submenu = build_submenu(app, label, &entry.sub, build)?;builder = builder.item(&submenu);continue;}@@ -114,7 +139,13 @@ fn build_submenu<R: tauri::Runtime>(}if entry.checkbox {- let mut item = CheckMenuItemBuilder::new(label).checked(true);+ // A rebuild keeps what the menu it replaces had checked.+ let checked = entry+ .id+ .as_ref()+ .and_then(|id| build.checked.get(id).copied())+ .unwrap_or(true);+ let mut item = CheckMenuItemBuilder::new(label).checked(checked);if let Some(id) = &entry.id {item = item.id(id);}@@ -184,15 +215,44 @@ fn build_recent_files_submenu<R: tauri::Runtime>(fn build_schema_menus<R: tauri::Runtime>(app: &tauri::AppHandle<R>,- recent_files: &[String],+ build: &MenuBuild,) -> tauri::Result<Vec<Submenu<R>>> {let groups: Vec<MenuGroup> = serde_json::from_str(include_str!("../generated/menu.json"))?;groups.iter()- .map(|group| build_submenu(app, &group.label, &group.items, recent_files))+ .map(|group| build_submenu(app, &group.label, &group.items, build)).collect()}+fn collect_checked<R: tauri::Runtime>(+ items: Vec<MenuItemKind<R>>,+ checked: &mut HashMap<String, bool>,+) {+ for item in items {+ match &item {+ MenuItemKind::Check(check) => {+ if let Ok(state) = check.is_checked() {+ checked.insert(item.id().0.clone(), state);+ }+ }+ MenuItemKind::Submenu(submenu) => {+ if let Ok(children) = submenu.items() {+ collect_checked(children, checked);+ }+ }+ _ => {}+ }+ }+}++fn current_checked<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> HashMap<String, bool> {+ let mut checked = HashMap::new();+ if let Some(items) = app.menu().and_then(|menu| menu.items().ok()) {+ collect_checked(items, &mut checked);+ }+ checked+}+fn find_menu_item<R: tauri::Runtime>(items: Vec<MenuItemKind<R>>,id: &str,@@ -247,8 +307,12 @@ pub fn set_native_menu_checked<R: tauri::Runtime>(pub fn install_app_menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>,- recent_files: &[String],+ inputs: &NativeMenuInputs,) -> tauri::Result<()> {+ let build = MenuBuild {+ inputs,+ checked: current_checked(app),+ };#[cfg(target_os = "macos")]let app_menu = {let items = app_menu_file()?;@@ -285,7 +349,7 @@ pub fn install_app_menu<R: tauri::Runtime>(.build()?};- let schema_menus = build_schema_menus(app, recent_files)?;+ let schema_menus = build_schema_menus(app, &build)?;let mut builder = MenuBuilder::new(app);#[cfg(target_os = "macos")]@@ -300,3 +364,25 @@ pub fn install_app_menu<R: tauri::Runtime>(app.set_menu(builder.build()?)?;Ok(())}++/// Rebuilds the menu after one of its inputs changed.+pub fn update_app_menu<R: tauri::Runtime>(+ app: &tauri::AppHandle<R>,+ change: impl FnOnce(&mut NativeMenuInputs),+) -> Result<(), String> {+ let state = tauri::Manager::state::<NativeMenuState>(app);+ let mut inputs = state+ .0+ .lock()+ .map_err(|_| "Menu state is unavailable".to_string())?;+ change(&mut inputs);+ install_app_menu(app, &inputs).map_err(|error| error.to_string())+}++#[tauri::command]+pub fn set_native_menu_features<R: tauri::Runtime>(+ app: tauri::AppHandle<R>,+ features: Vec<String>,+) -> Result<(), String> {+ update_app_menu(&app, |inputs| inputs.features = features)+}diff --git a/packages/cloud/src/client/auth/navigation.ts b/packages/cloud/src/client/auth/navigation.tsindex 0b386eb43..815ecf1ef 100644--- a/packages/cloud/src/client/auth/navigation.ts+++ b/packages/cloud/src/client/auth/navigation.ts@@ -1,5 +1,7 @@import type { CloudDiscovery } from '#cloud/contract'+import type { CloudSocialProvider } from './client'+/** The instance owns authentication; only its configured editor may receive the return. */export function cloudEditorReturnURL(discovery: CloudDiscovery, value: string): string {if (!discovery.appURL) throw new Error('This instance does not advertise a public editor URL')@@ -17,11 +19,23 @@ export function cloudEditorReturnURL(discovery: CloudDiscovery, value: string):return destination.href}-export function cloudSignInURL(discovery: CloudDiscovery, returnURL: string): string {+/**+ * The server's sign-in page, coming back to `returnURL` on its editor afterwards. A `provider`+ * starts that provider's sign-in at once, while the server's pages still handle two-step sign-in+ * and approval before the return.+ */+export function cloudSignInURL(+ discovery: CloudDiscovery,+ returnURL: string,+ provider?: CloudSocialProvider+): string {const destination = cloudEditorReturnURL(discovery, returnURL)const continuation = new URL('/auth/return', discovery.authURL)continuation.searchParams.set('editor', destination)const signIn = new URL('/auth/sign-in', discovery.authURL)signIn.searchParams.set('redirect', `${continuation.pathname}${continuation.search}`)+ if (provider && discovery.authentication.socialProviders.includes(provider)) {+ signIn.searchParams.set('provider', provider)+ }return signIn.href}diff --git a/packages/cloud/src/client/discovery.ts b/packages/cloud/src/client/discovery.tsindex 49c98513e..97da125e6 100644--- a/packages/cloud/src/client/discovery.ts+++ b/packages/cloud/src/client/discovery.ts@@ -1,4 +1,10 @@-import { CLOUD_DISCOVERY_PATH, parseCloudDiscovery, type CloudDiscovery } from '#cloud/contract'+import {+ CLOUD_DISCOVERY_PATH,+ CLOUD_PROTOCOL_VERSION,+ cloudDiscoverySchema,+ type CloudDiscovery+} from '#cloud/contract'+import * as v from 'valibot'const DISCOVERY_TIMEOUT_MS = 10_000@@ -9,25 +15,39 @@ export type DiscoverCloudOptions = {signal?: AbortSignal}+/**+ * Why a server could not be used: the address is not a web address, nothing answered, something+ * answered but not as OpenPencil Cloud, or it speaks another protocol version.+ */+export type CloudDiscoveryFailure = 'invalid-address' | 'unreachable' | 'not-cloud' | 'outdated'+export class CloudClientError extends Error {constructor(message: string,- override readonly cause?: unknown+ override readonly cause?: unknown,+ readonly reason: CloudDiscoveryFailure = 'unreachable') {super(message)this.name = 'CloudClientError'}}+const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}))+const protocolSchema = v.looseObject({ protocolVersion: v.string() })+function discoveryURL(serverURL: string): URL {let url: URLtry {url = new URL(serverURL)} catch (error) {- throw new CloudClientError('OpenPencil server URL is invalid', error)+ throw new CloudClientError('OpenPencil server URL is invalid', error, 'invalid-address')}if (url.protocol !== 'https:' && url.protocol !== 'http:') {- throw new CloudClientError('OpenPencil server URL must use HTTP or HTTPS')+ throw new CloudClientError(+ 'OpenPencil server URL must use HTTP or HTTPS',+ undefined,+ 'invalid-address'+ )}url.pathname = CLOUD_DISCOVERY_PATHurl.search = ''@@ -35,6 +55,24 @@ function discoveryURL(serverURL: string): URL {return url}+function parseDiscoveryBody(text: string): CloudDiscovery {+ const body = v.safeParse(discoveryBodySchema, text)+ if (!body.success) {+ throw new CloudClientError('OpenPencil server discovery is not JSON', body.issues, 'not-cloud')+ }+ const discovery = v.safeParse(cloudDiscoverySchema, body.output)+ if (discovery.success) return discovery.output+ const protocol = v.safeParse(protocolSchema, body.output)+ const outdated = protocol.success && protocol.output.protocolVersion !== CLOUD_PROTOCOL_VERSION+ throw new CloudClientError(+ outdated+ ? `OpenPencil server speaks protocol ${protocol.output.protocolVersion}`+ : 'OpenPencil server discovery is invalid',+ discovery.issues,+ outdated ? 'outdated' : 'not-cloud'+ )+}+export async function discoverCloud(serverURL: string,options: DiscoverCloudOptions = {}@@ -50,9 +88,13 @@ export async function discoverCloud(signal})if (!response.ok) {- throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`)+ throw new CloudClientError(+ `OpenPencil server discovery failed with HTTP ${response.status}`,+ undefined,+ response.status >= 500 ? 'unreachable' : 'not-cloud'+ )}- return parseCloudDiscovery(await response.json())+ return parseDiscoveryBody(await response.text())} catch (error) {if (error instanceof CloudClientError) throw errorif (signal.aborted) {diff --git a/packages/cloud/src/client/index.ts b/packages/cloud/src/client/index.tsindex db6426f2a..77f65ff3a 100644--- a/packages/cloud/src/client/index.ts+++ b/packages/cloud/src/client/index.ts@@ -32,6 +32,7 @@ export {} from './device-authorization'export {CloudClientError,+ type CloudDiscoveryFailure,discoverCloud,type CloudFetch,type DiscoverCloudOptionsdiff --git a/packages/cloud/src/server/sharing/contracts.ts b/packages/cloud/src/server/sharing/contracts.tsindex bc3016a4c..0b6c22556 100644--- a/packages/cloud/src/server/sharing/contracts.ts+++ b/packages/cloud/src/server/sharing/contracts.ts@@ -22,8 +22,13 @@ export function shareContract(row: {revokedAt: Date | string | nulllastUsedAt: Date | string | null}): DocumentShare {+ // Rows carry the secret's hash; responses name each field so it never goes out.return {- ...row,+ id: row.id,+ documentId: row.documentId,+ permission: row.permission,+ roomEpoch: row.roomEpoch,+ createdBy: row.createdBy,createdAt: dateString(row.createdAt) ?? '',updatedAt: dateString(row.updatedAt) ?? '',expiresAt: dateString(row.expiresAt),@@ -42,7 +47,11 @@ export function grantContract(row: {updatedAt: Date | string}): DocumentGrant {return {- ...row,+ id: row.id,+ documentId: row.documentId,+ userId: row.userId,+ permission: row.permission,+ createdBy: row.createdBy,createdAt: dateString(row.createdAt) ?? '',updatedAt: dateString(row.updatedAt) ?? ''}diff --git a/packages/cloud/tests/client/auth/navigation.test.ts b/packages/cloud/tests/client/auth/navigation.test.tsindex fa9705119..f99d2b115 100644--- a/packages/cloud/tests/client/auth/navigation.test.ts+++ b/packages/cloud/tests/client/auth/navigation.test.ts@@ -41,3 +41,14 @@ test('return navigation rejects foreign origins and userinfo and strips fragmentcloudSignInURL({ ...discovery, appURL: undefined }, 'https://editor.example')).toThrow()})++test('a chosen provider rides along only when the server offers it', () => {+ const social = {+ ...discovery,+ authentication: { ...discovery.authentication, socialProviders: ['google' as const] }+ }+ const google = new URL(cloudSignInURL(social, 'https://editor.example/', 'google'))+ expect(google.searchParams.get('provider')).toBe('google')+ const apple = new URL(cloudSignInURL(social, 'https://editor.example/', 'apple'))+ expect(apple.searchParams.has('provider')).toBe(false)+})diff --git a/packages/cloud/tests/client/discovery.test.ts b/packages/cloud/tests/client/discovery.test.tsindex 3966d1951..db0b2662d 100644--- a/packages/cloud/tests/client/discovery.test.ts+++ b/packages/cloud/tests/client/discovery.test.ts@@ -60,3 +60,29 @@ describe('discoverCloud', () => {await expect(request).rejects.toBeInstanceOf(CloudClientError)})})++describe('discovery failures', () => {+ async function reason(fetch: () => Promise<Response>, url = 'https://cloud.example.com') {+ try {+ await discoverCloud(url, { fetch })+ } catch (error) {+ return error instanceof CloudClientError ? error.reason : 'other'+ }+ return 'none'+ }++ test('say whether the address, the network, or the server is the problem', async () => {+ expect(await reason(async () => Response.json(discovery), 'not a url')).toBe('invalid-address')+ expect(await reason(() => Promise.reject(new TypeError('fetch failed')))).toBe('unreachable')+ expect(await reason(async () => new Response(null, { status: 502 }))).toBe('unreachable')+ expect(await reason(async () => new Response(null, { status: 404 }))).toBe('not-cloud')+ expect(await reason(async () => new Response('<!doctype html>'))).toBe('not-cloud')+ expect(await reason(async () => Response.json({ name: 'something else' }))).toBe('not-cloud')+ })++ test('tell a server on another protocol version from one that is not Cloud', async () => {+ expect(await reason(async () => Response.json({ ...discovery, protocolVersion: '2' }))).toBe(+ 'outdated'+ )+ })+})diff --git a/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts b/packages/cloud/tests/integration/server/sharing/capabilities/service.test.tsindex 7aca20284..ae37fba2d 100644--- a/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts+++ b/packages/cloud/tests/integration/server/sharing/capabilities/service.test.ts@@ -15,6 +15,8 @@ describe('document sharing capabilities integration', () => {permission: 'view'})expect(capability.secret).toMatch(/^[0-9a-f]{48}$/)+ // What goes out names the share; its stored hash stays on the server.+ expect(Object.keys(capability.share)).not.toContain('secretHash')expect(capability.path).toBe(`/share/${capability.share.id}#${capability.secret}`)const stored = await context.runtime.database.selectFrom('documentShare')diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.tsindex 8347c1f96..bc47f121b 100644--- a/packages/core/src/text/web-fonts.ts+++ b/packages/core/src/text/web-fonts.ts@@ -30,6 +30,25 @@ export const DEFAULT_WEB_FONT_PROVIDER_SETTINGS: Record<WebFontProviderId, booleexport type WebFontFetch = (url: string, init?: RequestInit) => Promise<Response>+/**+ * Hosts the font providers' metadata and stylesheet requests go to. Only these are proxied while+ * a provider resolves; the app's other requests in that window keep their own fetch.+ */+const WEB_FONT_PROVIDER_HOSTS = new Set([+ 'api.fontshare.com',+ 'api.fontsource.org',+ 'cdn.jsdelivr.net',+ 'fonts.bunny.net',+ 'fonts.google.com',+ 'fonts.googleapis.com'+])++function isWebFontProviderURL(value: string): boolean {+ if (!URL.canParse(value)) return false+ const url = new URL(value)+ return url.protocol === 'https:' && WEB_FONT_PROVIDER_HOSTS.has(url.hostname)+}+const DEFAULT_WEB_FONT_SUBSETS = ['latin','latin-ext',@@ -281,7 +300,7 @@ export class WebFontResolver {const originalFetch = globalThis.fetchconst proxyFetch = (input: RequestInfo | URL, init?: RequestInit) => {const url = typeof input === 'string' || input instanceof URL ? input.toString() : input.url- if (url.startsWith('https://') || url.startsWith('http://')) {+ if (isWebFontProviderURL(url)) {signal?.throwIfAborted()return (this.remoteFetch?.(url, { ...init, signal: signal ?? init?.signal }) ??diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsindex 24af7cf71..ae4bebfe5 100644--- a/packages/docs/.vitepress/labels.ts+++ b/packages/docs/.vitepress/labels.ts@@ -17,6 +17,7 @@ export interface SidebarLabels {components: stringvariables: stringcheckingDesigns: string+ openPencilCloud: stringcloudStorage: stringoverview: stringgettingStarted: string@@ -170,6 +171,7 @@ export const EN: SidebarLabels = {components: 'Components',variables: 'Variables',checkingDesigns: 'Checking Designs',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Cloud Storage',icons: 'Icons',overview: 'Overview',@@ -199,6 +201,7 @@ export const DE: SidebarLabels = {components: 'Komponenten',variables: 'Variablen',checkingDesigns: 'Designs prüfen',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Cloud-Speicher',icons: 'Symbole',overview: 'Überblick',@@ -228,6 +231,7 @@ export const IT: SidebarLabels = {components: 'Componenti',variables: 'Variabili',checkingDesigns: 'Verificare i design',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Archiviazione cloud',icons: 'Icone',overview: 'Panoramica',@@ -257,6 +261,7 @@ export const FR: SidebarLabels = {components: 'Composants',variables: 'Variables',checkingDesigns: 'Vérifier les designs',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Stockage cloud',icons: 'Icônes',overview: 'Vue d’ensemble',@@ -286,6 +291,7 @@ export const ES: SidebarLabels = {components: 'Componentes',variables: 'Variables',checkingDesigns: 'Revisar diseños',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Almacenamiento en la nube',icons: 'Iconos',overview: 'Resumen',@@ -315,6 +321,7 @@ export const PL: SidebarLabels = {components: 'Komponenty',variables: 'Zmienne',checkingDesigns: 'Sprawdzanie projektów',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Przechowywanie w chmurze',icons: 'Ikony',overview: 'Przegląd',@@ -344,6 +351,7 @@ export const RU: SidebarLabels = {components: 'Компоненты',variables: 'Переменные',checkingDesigns: 'Проверка дизайна',+ openPencilCloud: 'OpenPencil Cloud',cloudStorage: 'Облачное хранилище',icons: 'Иконки',overview: 'Обзор',diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex 0e50366ec..3dbb1964c 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -43,6 +43,7 @@ export const userGuideSidebar = ({ text: labels.layers, link: `${prefix}/user-guide/layers-and-pages` },{ text: labels.exporting, link: `${prefix}/user-guide/exporting` },// English only until translated; locales link to the canonical page.+ { text: labels.openPencilCloud, link: '/user-guide/openpencil-cloud' },{ text: labels.cloudStorage, link: '/user-guide/cloud-storage' },],},diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 9a63d43d5..7acd2c9d3 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -59,6 +59,11 @@ link, and the strongest source wins. Revoking one source leaves access inheritedDocuments granted to someone outside their own workspaces are listed for them separately, so aclient can show what was shared with them.+Workspace administrators invite people by email with a role. Workspace invitations use the same+`/cloud/invitations/:id` link as document invitations: preview and accept look for a workspace+invitation first and fall back to a document one, so email, the desktop handoff, and the editor's+invitation dialog serve both. A workspace with members always keeps an administrator.+Database rows use UUIDs. Capability secrets and invitation tokens are random hex; only their SHA-256digests are stored, and they travel in URL fragments so they never reach access logs or `Referer`headers. Invitation continuations through OAuth are single-use compact JWE.@@ -111,12 +116,13 @@ either role: the first operator is approved and promoted through the `admin` com## PortalThe server shows its own pages on its public address: sign-in and sign-up, email verification,-password reset, two-step sign-in, desktop sign-in approval, account security, and the-administration console. They are a separate Vite entry, `cloud.html`, in the app project, so they-reuse the editor's components and theme without loading the editor; `bun run build:cloud-portal`-writes them to `dist-cloud-portal/`. The editor, on the web and on the desktop, never embeds these-pages; it opens them in a browser and gets the person back through `/auth/return` or the device-code.+password reset, two-step sign-in, desktop sign-in approval, account security, and the administration+console. They are a separate Vite entry, `cloud.html`, in the app project, so they reuse the+editor's components and theme without loading the editor; `bun run build:cloud-portal` writes them+to `dist-cloud-portal/`. The editor never embeds these pages; when it needs them, for a social+provider or a second sign-in step, it opens them in a browser and gets the person back through+`/auth/return` or the device code. A verification link started in the editor lands on+`/auth/verified`, which sends the person back to the editor.`CLOUD_PORTAL_PAGE_ROOTS` in the contract lists the page paths, and every runtime serves`cloud.html` at and below them with `frame-ancestors 'none'`, so the approval page cannot be@@ -124,6 +130,26 @@ framed. The Node runtime serves the build named by `OPENPENCIL_CLOUD_PORTAL_DIR`pages before the API and portal assets only where the API returns 404. `bun run cloud:dev` keeps awatched portal build next to the server.+## Editor client++The editor treats each Cloud server as a profile of the `openpencil-cloud` storage provider, with a+workspace as the container, so the sync engine, recent files, and tabs handle Cloud documents the+way they handle a bucket. A server's id is hex from its address, which also names its credentials.+Email and password sign in inside the connect dialog wherever the server accepts the editor's+requests, which is the desktop app and the server's own editor address; the session's bearer token+goes in the credential store. Social providers and accounts with two-step sign-in finish in the+browser: the server's own editor address leaves for its pages and comes back, and the desktop app+approves a device code. Each connection tells a signed-in account from one waiting for approval, one+whose sign-in expired, and one never signed in.++Saves name the revision they were edited from, so a write over someone else's newer revision+becomes a conflict to resolve. Opening a Cloud document also joins its room on the relay. An empty+room takes the first editor's document once the relay has answered; a tab that opened the stored+file takes the room's copy when the room already has one, because each read of a `.fig` gives the+layers new IDs. One signed-in editor, the one with the lowest presence client, saves for the room;+the others drop their queued uploads and count their edits as saved. Guests who open a link join+the room with the link's permission and never save.+## ConfigurationOperators author one schema-versioned TOML file. It owns URLs, trusted origins and proxies,@@ -172,3 +198,81 @@ Nodemailer; `email.transport = "none"` disables delivery.`bun run test:cloud` type-checks the package and runs unit and integration tests. The end-to-endrunners start PostgreSQL and SeaweedFS (or Garage) in an isolated Compose project, exercise presignedand multipart uploads and the full revision flow, and remove the project afterwards.++## Decisions++Choices made while porting Cloud, with what was rejected and why. Add new entries at the end with+their date; revise an entry only by adding one that supersedes it.++**2026-10 · A relay instead of Hocuspocus.** The relay speaks the same room messages as Trystero, so+local and Cloud documents share one sync implementation. A Hocuspocus server would have needed a+second provider in the editor and its own authorization hooks for tickets and viewer filtering.++**2026-10 · The portal is a second Vite entry served only by the server.** Sign-in, approval, and+administration pages reuse the editor's components and theme without shipping in the editor+bundle, and a self-hosted server serves pages that match its own version. Pages inside the editor+would put the approval page under an origin the server does not control; a separate frontend+package would have duplicated the UI kit.++**2026-10 · Rooms are live whenever a Cloud document is open, and one editor saves.** Every open+tab joins the room, and the signed-in editor with the lowest presence client uploads for everyone,+so two people editing together never conflict with each other. Joining only on demand left+concurrent saves to the conflict dialog; building files on the server from the room's Yjs state+needs a headless `.fig` writer on the server, which is a later step.++**2026-10 · A tab takes the room's copy when the room has one.** Reading a `.fig` gives layers new+IDs, so two tabs that read the same file cannot merge their Yjs states. The first editor seeds an+empty room only after the relay answers, and later tabs adopt the room root.++**2026-10 · Redirect sign-in only on the server's own editor address.** There the session cookie is+first-party and the server can send the person back to the same tab. The desktop app and editors on+other origins approve a device code instead of relying on third-party cookies or custom URL+schemes.++**2026-10 · Link secrets stay on the device that created them.** The server stores only digests,+like every capability secret, so a leaked database does not open documents. Other devices offer+**Reset link**, which rotates the secret, instead of a server that can hand the link back.++**2026-10 · Guests never save, and viewers are not locked yet.** A link opens a room with the link's+permission but no account to save under, so a signed-in editor saves for guests. The relay already+drops a viewer's document updates; locking the canvas for viewers needs a read-only mode in Core and+is a follow-up.++**2026-10 · Save to Cloud copies rather than moves.** The local file keeps its last saved contents+and the tab moves to the Cloud document, matching **Save to storage**. Moving would delete a file+the person may still open elsewhere.++**2026-10 · Home is split into places.** Recent files, each server's workspaces, documents shared+with the person, and the storage bucket are separate places in a sidebar, so Cloud does not crowd+the local file list and one server's workspaces show at a time.++**2026-10 · Cloud entry points wait for the official server's listing.** Settings → OpenPencil Cloud+and Save to Cloud stay hidden until `cloud.openpencil.dev` answers discovery with a `listing` whose+minimum editor version this editor meets, a server is already connected on the device, or someone+opened the editor with `?cloud=preview`. Launching, or pulling back, is a change to that server's+config rather than an editor release, and a launch that needs a client change sets the minimum to the+release that has it. A separate flags file or a third-party flag service would be one more thing to+deploy for one switch.++**2026-10 · Email and password sign in inside the editor.** The connect dialog signs in, signs up,+and waits for the verification link itself, and keeps a bearer token, so no cookie has to cross+from the server's address to the editor's; Safari treats sibling `.localhost` hosts as separate+sites and dropped that cookie. Signing in on the server's pages stays for social providers and the+second sign-in step, which need the server's own origin. This supersedes the redirect decision for+email and password.++**2026-10 · Settings → Cloud is always there.** Before the hosted service opens, its card holds the+waitlist, which used to sit under Storage, and a team's own server can be connected at any time.+This supersedes hiding Settings and Save to Cloud until the official server's listing.++**2026-10 · Every account starts with a workspace, and Save to asks only when there is a choice.**+An active account with no workspace gets one of its own when it first asks for its status, under a+slug fixed per person so concurrent requests make one. Save to goes straight to the only workspace+or bucket a document can go to, and New design creates in the place Home shows, so neither asks a+question with one answer. A setup step that makes people name a first workspace would stop them+before they have anything to put in it.++**2026-10 · Workspace invitations share the document invitation link.** Previewing an invitation+says whether it is for a document or a workspace, so one link format, one email path, and one+editor dialog cover both, and the desktop app's link handling needs no new kind. Invitation+continuations through OAuth stay document-only; the editor keeps a pending invitation itself.diff --git a/packages/docs/user-guide/cloud-storage.md b/packages/docs/user-guide/cloud-storage.mdindex ac31f5265..fae853848 100644--- a/packages/docs/user-guide/cloud-storage.md+++ b/packages/docs/user-guide/cloud-storage.md@@ -9,7 +9,7 @@ OpenPencil can keep documents in a bucket you own on any S3-compatible service:## Connect a Bucket-Open **Settings → Cloud storage**, select **S3 storage**, and fill in:+Open **Settings → Storage**, select **S3 storage**, and fill in:| Field | What to enter || --------------------- | --------------------------------------------------------------------------------- |@@ -52,9 +52,9 @@ Set it in the AWS console under the bucket's **Permissions → Cross-origin reso## Save a Document to Storage-Open or create a document, then choose **File → Save to storage…**. The document is saved into the bucket and the tab stays bound to it: **Save** and auto-save now write to storage instead of a local file. A local `.fig` you had open keeps its last saved contents.+Open or create a document, then choose **File → Save to…**. With no Cloud workspace to choose from, the document is saved straight into the bucket; otherwise pick the bucket from the list. The tab stays bound to it: **Save** and auto-save now write to storage instead of a local file. A local `.fig` you had open keeps its last saved contents.-To open stored documents, choose **File → Open storage workspace…**. The workspace lists every document in the bucket with a preview read from the document itself, so listing a large file downloads only its embedded thumbnail.+To open stored documents, select your bucket in Home's sidebar; **File → Browse files…** opens Home where you left it. **New design** with the bucket selected creates a document in it. Home lists every document in the bucket with a preview read from the document itself, so listing a large file downloads only its embedded thumbnail.## How Saving Worksdiff --git a/packages/docs/user-guide/index.md b/packages/docs/user-guide/index.mdindex 845888808..4292939df 100644--- a/packages/docs/user-guide/index.md+++ b/packages/docs/user-guide/index.md@@ -29,6 +29,7 @@ Throughout this guide, keyboard shortcuts use Mac notation: <kbd>⌘</kbd> = <kb- [Layers & Pages](./layers-and-pages) — the layers panel, pages, and properties panel- [Context Menu](./context-menu) — right-click actions for clipboard, grouping, components, and more- [Exporting](./exporting) — image export and .fig file operations+- [OpenPencil Cloud](./openpencil-cloud) — documents on OpenPencil Cloud or your team's server, shared and edited together- [Cloud Storage](./cloud-storage) — documents and libraries in your own S3-compatible bucket## Advanced Featuresdiff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.mdnew file mode 100644index 000000000..1f0a9671e--- /dev/null+++ b/packages/docs/user-guide/openpencil-cloud.md@@ -0,0 +1,92 @@+---+title: OpenPencil Cloud+description: Keep documents on OpenPencil Cloud or your team's own server, share them, and edit them together.+---++# OpenPencil Cloud++OpenPencil Cloud keeps documents on a server so they follow you across devices and several people can edit them at once. Use the hosted service at `cloud.openpencil.dev` or a server your team runs itself. Cloud is optional: documents on your device and in your own [storage bucket](./cloud-storage) work the same with or without it.++## Connect a Server++Open **Settings → Cloud**. Until the hosted service opens, its card there takes your email for the waitlist; **Your team's server** asks for the address your team uses. OpenPencil checks that the address answers as an OpenPencil Cloud server before asking you to sign in, and says when nothing answers, when the address belongs to something else, or when the server runs a version this app doesn't support.++The ways to sign in come from the server: Google, Apple, or email and password.++- Email and password work right in the dialog, in the desktop app and in the web app at the server's own editor address. **Create an account** asks for your name, email, and a password of at least 8 characters, twice. The server emails you a link; open it, come back to OpenPencil, and signing in finishes by itself.+- Google and Apple, and accounts with two-step sign-in, finish in your browser: in the web app at the server's own editor address you come back to the same tab, and the desktop app shows a code to check against the browser's before you approve it.++Servers that review new accounts say so before you sign up. Until an administrator approves you, Settings shows that your account is waiting.++Each server in **Settings → Cloud** shows who is signed in to it:++- **Sign-in expired** keeps your account, so **Sign in** goes back to the same one.+- **Account and security** in the server's **…** menu opens the server's own account page, where you change your password, two-step sign-in, and passkeys.+- **Sign out** ends the session on the server. If the server can't be reached, you stay signed in so you can try again.+- **Disconnect server** signs you out and forgets the server on this device; your documents stay on it, and you can connect again anytime. It warns you when documents still have changes that haven't reached the server, because disconnecting discards them.++The desktop app keeps its sign-in in the system credential store. In the browser, a sign-in through the server's page lasts as long as the server's session; a sign-in with a code follows **Settings → General → Remember API keys on this device**.++## Find Documents on Home++Home lists places in a sidebar: **Recent**, the workspaces of the server Home shows, **Shared with you**, and your storage bucket. On a phone the same places are in a menu above the documents. With more than one server connected, choose which one Home shows with **Show on Home** in Settings.++A workspace lists its documents with where each one stands, how much of the workspace's storage they use, and your role in it. Every account starts with a workspace of its own. **New design** creates a document in the workspace you are looking at, and says which one; in **Shared with you** it creates in your own workspace, and in Recent, or a workspace you can only view, it creates a file on your device. **Shared with you** lists documents people invited you to in workspaces you are not a member of.++## Work in a Team Workspace++Every account starts with a workspace of its own. To work with a team, select **+** beside **OpenPencil Cloud** in Home's sidebar, name the workspace, and you administer it. **Members** in the workspace's header lists who is in it:++- Admins rename the workspace, invite people by email as an admin, editor, or viewer, change roles, and remove people. Editors and admins change documents; viewers only look.+- An invitation arrives by email. If the server doesn't send email, copy the invitation link from the dialog and pass it on. Invitations expire after seven days, and inviting the same address again replaces the earlier one.+- Anyone can leave a workspace, except its last admin: make someone else an admin first.+- Admins can delete a workspace once it holds no documents. Deleted documents are kept for a while before they are gone for good, and the workspace can be deleted after that.++Opening a workspace invitation works like a document invitation: sign in with the invited address, choose **Join workspace**, and Home shows the workspace.++## Save a Document to Cloud++Open or create a document, then choose **File → Save to…**. When there is only one place it can go, it is saved there under its current name; with several workspaces, or a storage bucket too, pick one, and the last place you used is chosen first. Workspaces where you can only view are listed but can't be chosen. The Cloud copy opens in the same tab and saves as you work. A file you had open on your device keeps its last saved contents.++Saving can fail when the file is over the size the workspace allows, when the workspace is out of space, or when you are offline. Nothing changes on your device in those cases.++## Where a Document Stands++A Cloud document saves as you work, and the tab's dot shows edits that haven't reached the server yet, as it does for any file. When something needs you, a status appears beside the name; select it to see the workspace and server, and what you can do next.++| State | What it means |+| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |+| **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. |++## When a Document Changed in Two Places++This happens when you edited a document offline, or before you joined a session, while someone else saved a newer version. Nothing is lost until you choose. Select the status beside the name, then **Choose a version**:++- **Keep both** leaves the newer version as it is and saves yours next to it as "(your copy)"; the tab moves to your copy.+- **Use the Cloud version** discards the changes on this device and shows the newer version.+- **Replace it with your version** uploads yours over the newer one for everyone.++**Decide later** keeps both versions until you come back to it.++## Share a Document++Select **Share** on a Cloud document.++- Invite people by email with **Can edit** or **Can view**. They get an email with a link, and the invitation expires after seven days. Change someone's access or remove it from the list.+- Everyone in the document's workspace has the access the workspace gives them.+- Under **General access**, **Anyone with the link** lets people open the document without an account, with **Can view** or **Can edit**. Some workspaces' plans turn links off, and the dialog says so.++The server keeps only a fingerprint of each link, so a link can be copied only on the device that created it. On other devices, **Reset link** makes a new one you can copy; the old link stops working.++## Open an Invitation++An invitation link opens OpenPencil with who invited you, to which document, and on which server. If you have never used that server, OpenPencil warns you to sign in only if you trust it. Sign in with the address the invitation was sent to; if you are signed in as someone else, choose **Use another account**. Once you accept, the document opens and stays under **Shared with you** on Home.++## Edit Together++Opening a Cloud document joins its live session: everyone who has it open sees each other's cursors and edits as they happen. One person's app saves the document for everyone, so editing together never makes your changes conflict with someone else's.++People who open a link without an account join under the name OpenPencil gives them, or the one they chose. They edit when the link allows it, but their app never saves to the server; someone signed in who can edit saves for them.diff --git a/packages/vue/AGENTS.md b/packages/vue/AGENTS.mdindex 1f4e6c553..8116ce8f9 100644--- a/packages/vue/AGENTS.md+++ b/packages/vue/AGENTS.md@@ -28,7 +28,7 @@ The app's `DesignPanel` retains at most one selection-property subtree through `- Commands use `packages/vue/src/editor/commands/registry.ts` for shortcuts, bindings, and menu IDs. Store portable tokens (`MOD+D`) and format them at render time; labels and translations never contain shortcuts.- Canvas menu structure lives in `packages/vue/src/editor/menu-model/canvas.ts`; the app's `CanvasMenu.vue` renders it.- `useEditorEvent(event, handler)` in `packages/vue/src/editor/events/use.ts` wraps the editor event bus.-- i18n uses narrow product-domain catalogs under `packages/vue/src/i18n/messages/` with matching locale files. Inspect existing domains instead of adding generic UI/component namespaces; prefer narrow `use*Messages()` composables over aggregate `useI18n()`. `bun run check:i18n` enforces structure, placeholder parity, and reviewed translation baselines; remove stale baseline identities when fixing existing debt.+- i18n uses narrow product-domain catalogs under `packages/vue/src/i18n/messages/` with matching locale files; namespaces of one domain share a folder (`messages/cloud/editor.ts`, `locales/<locale>/cloud/editor.json`) mapped in `LOCALE_FILE_NAMES` (`tools/checks/i18n/src/check-locales.ts`). Inspect existing domains instead of adding generic UI/component namespaces; prefer narrow `use*Messages()` composables over aggregate `useI18n()`. `bun run check:i18n` enforces structure, placeholder parity, and reviewed translation baselines; remove stale baseline identities when fixing existing debt.## Documentationdiff --git a/packages/vue/src/i18n/index.ts b/packages/vue/src/i18n/index.tsindex bdfcf9af2..afafb1bfd 100644--- a/packages/vue/src/i18n/index.ts+++ b/packages/vue/src/i18n/index.ts@@ -26,6 +26,7 @@ export {useStorageMessages,useToolMessages,useUpdateMessages,+ useCloudMessages,useCloudPortalMessages,useVariableMessages,useVariableTypeMessagesdiff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonnew file mode 100644index 000000000..2135f2412--- /dev/null+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -0,0 +1,276 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Weiter",+ "tryAgain": "Erneut versuchen",+ "signIn": "Anmelden",+ "signOut": "Abmelden",+ "workspace": "Arbeitsbereich",+ "server": "Server",+ "share": "Teilen",+ "viewOnly": "Nur ansehen",+ "canEdit": "Kann bearbeiten",+ "canView": "Kann ansehen",+ "roleViewer": "Betrachter",+ "roleEditor": "Bearbeiter",+ "roleAdmin": "Administrator",+ "changedInTwoPlaces": "„{name}“ wurde an zwei Stellen geändert",+ "conflictDescription": "Jemand hat eine neuere Version gespeichert, während du noch nicht gesendete Änderungen hattest. Bis du dich entscheidest, geht nichts verloren.",+ "connectHeading": "Mit OpenPencil Cloud verbinden",+ "connectDescription": "Halte Dateien auf allen Geräten synchron und lade andere ein, gemeinsam mit dir zu bearbeiten.",+ "deviceHeading": "Im Browser bestätigen",+ "deviceDescription": "Genehmige diese Anmeldung auf {host}.",+ "deviceDescriptionNoHost": "Genehmige diese Anmeldung auf dem Server.",+ "officialDescription": "Gehostet von OpenPencil · {host}",+ "selfHostedLabel": "Server deines Teams",+ "selfHostedDescription": "Eine selbst gehostete OpenPencil Cloud",+ "serverAddress": "Serveradresse",+ "errorInvalidAddressHeading": "Gib die Webadresse des Servers ein",+ "errorInvalidAddressDescription": "Verwende die Adresse, die dir dein Team gegeben hat, z. B. https://cloud.example.com.",+ "errorUnreachableHeading": "Dieser Server ist nicht erreichbar",+ "errorUnreachableDescription": "Prüfe die Adresse und deine Verbindung und versuche es dann erneut.",+ "errorNotCloudHeading": "Das ist kein OpenPencil-Cloud-Server",+ "errorNotCloudDescription": "Unter dieser Adresse antwortet etwas, aber nicht OpenPencil Cloud. Frag dein Team nach der richtigen.",+ "errorOutdatedHeading": "Dieser Server braucht ein Update",+ "errorOutdatedDescription": "Er läuft mit einer älteren Version von OpenPencil Cloud, als diese App unterstützt.",+ "errorDeniedHeading": "Anmeldung abgelehnt",+ "errorDeniedDescription": "Die Anfrage wurde im Browser abgelehnt. Starte die Anmeldung erneut.",+ "errorExpiredHeading": "Der Code ist abgelaufen",+ "errorExpiredDescription": "Er wurde nicht rechtzeitig genehmigt. Starte erneut, um einen neuen zu erhalten.",+ "errorSignInFailedHeading": "Anmeldung fehlgeschlagen",+ "errorSignInFailedDescription": "Der Server hat die Anmeldung nicht abgeschlossen. Versuche es gleich noch einmal.",+ "continueWithGoogle": "Weiter mit Google",+ "continueWithApple": "Weiter mit Apple",+ "continueWithEmail": "Weiter mit E-Mail",+ "signInNoteDesktop": "Dein Browser öffnet sich, um die Anmeldung abzuschließen; danach kehrst du hierher zurück.",+ "signInNoteBrowser": "Nach der Anmeldung kehrst du zu diesem Tab zurück.",+ "yourCode": "Dein Code",+ "copyCode": "Code kopieren",+ "deviceWaiting": "Warten auf deine Genehmigung… Der Code läuft in {duration} ab.",+ "openBrowserAgain": "Browser erneut öffnen",+ "accountPending": "Dein Konto auf {host} wartet auf die Genehmigung durch einen Administrator.",+ "signedInAs": "Bei {host} angemeldet als {email}.",+ "invitationUnavailableHeading": "Diese Einladung kann nicht verwendet werden",+ "invitationOpening": "Einladung wird geöffnet",+ "invitedYou": "{name} hat dich eingeladen",+ "invitationEditDescription": "Zum Bearbeiten eines Dokuments auf {host}.",+ "invitationViewDescription": "Zum Ansehen eines Dokuments auf {host}.",+ "invitationChecking": "Einladung wird geprüft…",+ "invitationUnavailableDescription": "Sie ist abgelaufen, wurde zurückgezogen oder bereits angenommen. Bitte {name} um eine neue.",+ "invitationUnavailableDescriptionNoName": "Sie ist abgelaufen, wurde zurückgezogen oder bereits angenommen. Bitte die Person, die sie gesendet hat, um eine neue.",+ "invitationSentTo": "Gesendet an {recipient}",+ "invitationExpiresIn": "Läuft in {duration} ab",+ "unknownServerHeading": "Du hast {host} noch nie verwendet",+ "unknownServerDescription": "Melde dich nur an, wenn du diesem Server vertraust. Er speichert das Dokument und sieht deine Änderungen.",+ "invitationSignInHeading": "Bei {host} anmelden",+ "invitationSignInDescription": "Verwende das Konto, an das diese Einladung gesendet wurde. Das Dokument öffnet sich direkt danach.",+ "wrongAccountHeading": "Diese Einladung gilt für ein anderes Konto",+ "wrongAccountDescription": "Du bist als {email} angemeldet. Melde dich mit {recipient} an, um sie zu öffnen.",+ "notNow": "Nicht jetzt",+ "signInToOpen": "Zum Öffnen anmelden",+ "useAnotherAccount": "Anderes Konto verwenden",+ "openDocument": "Dokument öffnen",+ "saveHeading": "Speicherort wählen",+ "saveDescription": "Halte dieses Design auf allen Geräten synchron und teile es mit anderen.",+ "saveName": "Name",+ "saveQuotaHeading": "Dieser Arbeitsbereich hat keinen Speicherplatz mehr",+ "saveQuotaDescription": "Gib Speicherplatz frei oder wähle einen anderen Arbeitsbereich.",+ "saveOfflineHeading": "Du bist offline",+ "saveOfflineDescription": "Stelle eine Internetverbindung her, um in der Cloud zu speichern. Auf diesem Gerät hat sich nichts geändert.",+ "saveFailedHeading": "Speichern fehlgeschlagen",+ "saveFailedDescription": "Der Server hat die Datei nicht angenommen. Versuche es gleich noch einmal.",+ "saveUploading": "Wird hochgeladen… {sent} von {total}",+ "saveTooLargeHeading": "Diese Datei ist zu groß für diesen Server",+ "saveTooLargeDescription": "Er nimmt Dateien bis {limit} an. Entferne ungenutzte Bilder oder Seiten und versuche es dann erneut.",+ "saveNote": "Die gespeicherte Kopie öffnet sich in diesem Tab und speichert beim Arbeiten. Die Datei auf diesem Gerät bleibt unverändert.",+ "shareHeading": "„{name}“ teilen",+ "shareDescriptionInWorkspace": "In {workspace} auf OpenPencil Cloud",+ "shareDescription": "Auf OpenPencil Cloud",+ "shareAddPeople": "Personen per E-Mail hinzufügen",+ "shareEmailAddress": "E-Mail-Adresse",+ "shareNewPeoplePermission": "Berechtigung für neue Personen",+ "shareInvite": "Einladen",+ "sharePeopleWithAccess": "Personen mit Zugriff",+ "shareYou": "(du)",+ "shareInvited": "Eingeladen",+ "shareInvitationExpires": "Einladung läuft ab: {date}",+ "shareAccessFor": "Zugriff für {name}",+ "shareOwner": "Eigentümer",+ "shareRemoveAccess": "Zugriff entfernen",+ "shareEveryoneIn": "Alle in {workspace}",+ "shareMemberCount": {+ "one": "{count} Mitglied",+ "many": "{count} Mitglieder"+ },+ "shareWorkspacePermissionTip": "Vom Arbeitsbereich festgelegt; ändere es in den Einstellungen des Arbeitsbereichs",+ "shareGeneralAccess": "Allgemeiner Zugriff",+ "shareRestricted": "Nur Personen mit Zugriff",+ "shareAnyoneWithLink": "Jeder mit dem Link",+ "shareLinkDetail": "Jeder, der den Link hat, kann diese Datei ohne Anmeldung öffnen.",+ "shareRestrictedDetail": "Nur die oben genannten Personen und der Arbeitsbereich können diese Datei öffnen.",+ "shareRestrictedNoLinksDetail": "Nur die oben genannten Personen und der Arbeitsbereich können diese Datei öffnen. Links sind für diesen Arbeitsbereich deaktiviert.",+ "shareLinkPermission": "Linkberechtigung",+ "shareCannotManage": "Nur der Eigentümer und Bearbeiter können ändern, wer Zugriff hat.",+ "shareResetLinkTip": "Dieser Link wurde auf einem anderen Gerät erstellt. Beim Zurücksetzen entsteht ein neuer Link, und der alte funktioniert nicht mehr.",+ "shareResetLink": "Link zurücksetzen",+ "shareLinkCopied": "Link kopiert",+ "shareCopyLink": "Link kopieren",+ "shareLoadFailed": "Die Zugriffsliste konnte nicht geladen werden. Prüfe deine Verbindung und versuche es erneut.",+ "shareChangeFailed": "Die Änderung wurde nicht übernommen. Versuche es gleich noch einmal.",+ "conflictKeepBoth": "Beide behalten",+ "conflictKeepBothDescription": "Die Cloud-Version bleibt „{name}“. Deine wird daneben als „{copyName}“ gespeichert.",+ "conflictUseCloud": "Cloud-Version verwenden",+ "conflictUseCloudDescription": "Deine nicht gesendeten Änderungen auf diesem Gerät werden verworfen.",+ "conflictUseMine": "Durch deine Version ersetzen",+ "conflictUseMineDescriptionBy": "Die neuesten Änderungen von {name} werden für alle ersetzt.",+ "conflictUseMineDescription": "Die neuere Version auf dem Server wird für alle ersetzt.",+ "conflictConfirmUseCloud": "Cloud-Version verwenden",+ "conflictConfirmUseMine": "Durch meine ersetzen",+ "conflictYourVersion": "Deine Version",+ "conflictCloudVersion": "Cloud-Version",+ "conflictWhichVersion": "Welche Version behalten",+ "conflictDecideLater": "Später entscheiden",+ "conflictYourCopyName": "{name} (deine Kopie)",+ "conflictYouOnThisDevice": "Du, auf diesem Gerät",+ "conflictResolveFailed": "Der Konflikt konnte nicht gelöst werden. Deine Änderungen sind weiterhin auf diesem Gerät.",+ "statusViewOnlyDetail": "Du kannst dich umsehen und anderen folgen; deine Änderungen erreichen niemanden.",+ "statusSavedTo": "In {workspace} gespeichert",+ "statusSavedAgo": "Gespeichert {time}",+ "statusUpToDate": "Aktuell",+ "statusSaving": "Wird gespeichert…",+ "statusUploadingTo": "Wird in {workspace} hochgeladen",+ "statusSavedOnDevice": "Auf diesem Gerät gespeichert",+ "statusUploadsSoon": "Wird gleich hochgeladen",+ "statusOfflineDetail": "Du bist offline. Änderungen werden hochgeladen, sobald du wieder verbunden bist.",+ "statusConflict": "An zwei Stellen geändert",+ "statusConflictDetail": "Jemand hat eine neuere Version gespeichert, während du bearbeitet hast. Wähle, welche du behalten möchtest.",+ "statusErrorDetail": "Deine Änderungen sind auf diesem Gerät sicher.",+ "statusResolve": "Lösen",+ "statusChooseVersion": "Version wählen",+ "statusOpenWorkspace": "Arbeitsbereich öffnen",+ "settingsDescription": "Server, mit denen diese App Dokumente synchronisiert. Die Startseite zeigt jeweils die Arbeitsbereiche eines Servers.",+ "settingsEmptyDescription": "Halte Dateien auf allen Geräten synchron und bearbeite sie gemeinsam mit anderen. Dokumente auf diesem Gerät bleiben, wo sie sind.",+ "settingsConnectServer": "Server verbinden",+ "settingsOfficialDescription": "Gehostet von OpenPencil, keine Einrichtung nötig.",+ "settingsSelfHostedDescription": "Eine selbst gehostete OpenPencil Cloud unter der Adresse, die dein Team verwendet.",+ "settingsOnHome": "Auf der Startseite",+ "settingsSignInExpired": "Anmeldung abgelaufen",+ "settingsSignInExpiredFor": "Anmeldung für {email} abgelaufen",+ "settingsSignedOut": "Abgemeldet",+ "settingsWaitingForApproval": "Wartet darauf, dass ein Administrator dein Konto genehmigt",+ "settingsAccessClosed": "Ein Administrator hat deinen Zugang abgelehnt oder entzogen",+ "settingsOptionsFor": "Optionen für {host}",+ "settingsAccountAndSecurity": "Konto und Sicherheit",+ "settingsShowOnHome": "Auf der Startseite anzeigen",+ "settingsDisconnectServer": "Server trennen",+ "settingsSignOutFailed": "Abmelden fehlgeschlagen. Prüfe deine Verbindung und versuche es erneut.",+ "settingsDisconnectHeading": "{host} trennen?",+ "settingsDisconnectDescription": "Du wirst abgemeldet, und seine Arbeitsbereiche verschwinden auf diesem Gerät von der Startseite. Deine Dokumente bleiben auf dem Server, und du kannst dich jederzeit wieder verbinden.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Du wirst abgemeldet, und seine Arbeitsbereiche verschwinden auf diesem Gerät von der Startseite. {count} Dokument hat Änderungen, die den Server noch nicht erreicht haben; beim Trennen gehen sie verloren.",+ "many": "Du wirst abgemeldet, und seine Arbeitsbereiche verschwinden auf diesem Gerät von der Startseite. {count} Dokumente haben Änderungen, die den Server noch nicht erreicht haben; beim Trennen gehen sie verloren."+ },+ "settingsDisconnect": "Trennen",+ "settingsDisconnectAndDiscard": "Trennen und Änderungen verwerfen",+ "homeLocations": "Orte",+ "homeRecent": "Zuletzt verwendet",+ "homeAccount": "Konto: {email}",+ "homeAccountSettings": "Kontoeinstellungen",+ "homeConnectAnotherServer": "Weiteren Server verbinden…",+ "homeAttentionTip": "Eine Datei hier erfordert eine Entscheidung",+ "homeNeedsAttention": "Erfordert Aufmerksamkeit",+ "homeSharedWithYou": "Mit dir geteilt",+ "homeSharedSubtitle": "Dateien, zu denen du eingeladen wurdest",+ "homeSharedBy": "Geteilt von {name}",+ "homeSignIn": "Anmelden…",+ "homeStorage": "Speicher",+ "homeStorageSettings": "Speichereinstellungen",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "{used} belegt",+ "homeUsageOf": "{used} von {total}",+ "homeWorkspaceStorage": "Speicher des Arbeitsbereichs, {usage}",+ "homeView": "Ansicht",+ "homeGrid": "Raster",+ "homeList": "Liste",+ "homeOfflineHeading": "Du bist offline",+ "homeOfflineDescription": "Das sind die auf diesem Gerät gespeicherten Dateien. Änderungen werden hochgeladen, sobald du wieder verbunden bist.",+ "homeLoadFailedHeading": "Dieser Arbeitsbereich konnte nicht geladen werden",+ "homeLoadFailedDescription": "Der Server hat nicht geantwortet. Auf diesem Gerät gespeicherte Dateien werden weiterhin angezeigt.",+ "homeConflicts": {+ "one": "{count} Datei wurde an zwei Stellen geändert",+ "many": "{count} Dateien wurden an zwei Stellen geändert"+ },+ "homeReview": "Prüfen",+ "homeLoadingFiles": "Dateien werden geladen",+ "homeEmptyWorkspace": "Noch keine Dateien in {workspace}",+ "homeEmptyWorkspaceDescription": "Erstelle hier ein Design oder speichere eine geöffnete Datei über das Menü „Datei“ in diesem Arbeitsbereich.",+ "homeNothingShared": "Noch nichts mit dir geteilt",+ "homeNothingSharedDescription": "Dateien, zu denen du eingeladen wirst, erscheinen hier.",+ "homeNewDesign": "Neues Design",+ "homeViewOnlyTip": "Du kannst diese Datei ansehen",+ "homeSharedTip": "Mit Personen außerhalb des Arbeitsbereichs geteilt",+ "homeShared": "Geteilt",+ "syncSynced": "In der Cloud gespeichert",+ "syncUploading": "Änderungen werden hochgeladen…",+ "syncPending": "Änderungen auf diesem Gerät gespeichert, Upload ausstehend",+ "syncOffline": "Offline – Änderungen werden auf diesem Gerät gespeichert",+ "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.",+ "connectServerHeading": "Server deines Teams verbinden",+ "connectServerDescription": "Gib die Adresse ein, die dein Team für OpenPencil Cloud nutzt.",+ "checkingServer": "Server wird geprüft…",+ "signInHeading": "Bei {name} anmelden",+ "onHost": "Auf {host}.",+ "verifyDescription": "Wir haben einen Link an {email} gesendet.",+ "verifyNote": "Öffne den Link in der E-Mail und komm dann hierher zurück. Die Anmeldung wird automatisch abgeschlossen.",+ "verifyNotYet": "Deine E-Mail-Adresse ist noch nicht bestätigt. Öffne den Link in der E-Mail und versuche es dann erneut.",+ "verifyNoEmail": "Keine E-Mail?",+ "settingsTitle": "Cloud",+ "saveWhere": "Ort",+ "saveAction": "Speichern",+ "saveStorageGroup": "Speicher",+ "invitationWorkspaceDescription": "Um einem Arbeitsbereich auf {host} beizutreten.",+ "joinWorkspace": "Arbeitsbereich beitreten",+ "homeNewWorkspace": "Neuer Arbeitsbereich",+ "homeMembers": "Mitglieder",+ "newWorkspaceHeading": "Neuer Arbeitsbereich",+ "newWorkspaceDescription": "Ein Ort für Designs mit deinem Team. Du bestimmst, wer beitritt.",+ "workspaceName": "Name des Arbeitsbereichs",+ "workspaceNamePlaceholder": "Designteam",+ "createWorkspace": "Arbeitsbereich erstellen",+ "renameWorkspace": "Umbenennen",+ "membersDescription": "Alle hier sehen die Dokumente des Arbeitsbereichs; Bearbeiter und Admins ändern sie.",+ "invitePeople": "Personen einladen",+ "inviteEmail": "E-Mail-Adresse",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Rolle",+ "invite": "Einladen",+ "invitationSentNote": "Wir haben die Einladung per E-Mail gesendet. Wenn dieser Server keine E-Mails sendet, teile stattdessen diesen Link.",+ "copyInvitationLink": "Einladungslink kopieren",+ "membersLoading": "Mitglieder werden geladen…",+ "memberRole": "Rolle von {name}",+ "removeMember": "{name} entfernen",+ "pendingInvitations": "Wartet auf Beitritt",+ "revokeInvitation": "Zurückziehen",+ "leaveWorkspace": "Arbeitsbereich verlassen",+ "workspaceAlreadyMember": "Diese Person ist bereits in diesem Arbeitsbereich.",+ "workspaceLastAdmin": "Ein Arbeitsbereich braucht einen Admin. Mach zuerst jemand anderen zum Admin.",+ "workspaceForbidden": "Nur Admins dieses Arbeitsbereichs können das tun.",+ "workspaceNotFound": "Dieser Arbeitsbereich oder diese Einladung ist nicht mehr da. Schließe dies und versuche es erneut.",+ "workspaceFailed": "Der Arbeitsbereich konnte nicht geändert werden. Versuche es gleich noch einmal.",+ "unknownServerWorkspaceDescription": "Melde dich nur an, wenn du diesem Server vertraust. Er speichert die Dokumente des Arbeitsbereichs und sieht deine Änderungen.",+ "leaveWorkspaceHeading": "{workspace} verlassen?",+ "leaveWorkspaceDescription": "Du verlierst den Zugriff auf die Dokumente, sofern sie nicht direkt mit dir geteilt wurden. Ein Admin kann dich wieder einladen.",+ "removeMemberHeading": "{name} aus {workspace} entfernen?",+ "removeMemberDescription": "Die Person verliert den Zugriff auf die Dokumente, sofern sie nicht direkt geteilt wurden. Du kannst sie wieder einladen.",+ "removeMemberConfirm": "Entfernen",+ "deleteWorkspace": "Arbeitsbereich löschen",+ "deleteWorkspaceHeading": "{workspace} löschen?",+ "deleteWorkspaceDescription": "Alle verlieren den Zugriff und seine Einladungen funktionieren nicht mehr. Nur ein leerer Arbeitsbereich kann gelöscht werden.",+ "deleteWorkspaceTypeName": "Gib zur Bestätigung „{workspace}“ ein.",+ "dangerZone": "Gefahrenbereich",+ "leaveWorkspaceShort": "Verlassen",+ "deleteWorkspaceShort": "Löschen",+ "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."+}diff --git a/packages/vue/src/i18n/locales/de/cloud-portal.json b/packages/vue/src/i18n/locales/de/cloud/portal.jsonsimilarity index 94%rename from packages/vue/src/i18n/locales/de/cloud-portal.jsonrename to packages/vue/src/i18n/locales/de/cloud/portal.jsonindex 171f5966b..f00e77947 100644--- a/packages/vue/src/i18n/locales/de/cloud-portal.json+++ b/packages/vue/src/i18n/locales/de/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Hilfe","loading": "Wird geladen…","unavailableTitle": "Dieser Server antwortet nicht","unavailableDescription": "Prüfe die Adresse oder versuche es gleich noch einmal.","tryAgain": "Erneut versuchen","signInTitle": "Bei OpenPencil Cloud anmelden","signUpTitle": "Konto erstellen",- "signInWelcome": "Willkommen zurück.",- "signUpDescription": "Erstelle ein Konto auf diesem Server.","returnsTo": "Danach geht es zurück zu {destination}.","returnsToDesktop": "der OpenPencil-App","returnsToEditor": "dem Editor",@@ -23,7 +22,7 @@"signIn": "Anmelden","createAccount": "Konto erstellen","haveAccount": "Du hast schon ein Konto?",- "newHere": "Neu hier?",+ "newHere": "Neu bei OpenPencil Cloud?","createAnAccount": "Konto erstellen","approvalTitle": "Neue Konten werden von einem Administrator geprüft","approvalDescription": "Du kannst dich anmelden, sobald deine Anfrage genehmigt ist. Wir benachrichtigen dich per E-Mail.",@@ -235,5 +234,14 @@"errorNotAllowed": "Dazu bist du nicht berechtigt.","errorNetwork": "Der Server ist nicht erreichbar. Prüfe deine Verbindung.","errorAlreadyDecided": "Über diese Anfrage wurde bereits entschieden. Aktualisiere die Seite, um das Ergebnis zu sehen.",- "passwordResetSent": "Wir haben dir einen Link zum Festlegen eines Passworts gesendet."+ "passwordResetSent": "Wir haben dir einen Link zum Festlegen eines Passworts gesendet.",+ "repeatPassword": "Passwort wiederholen",+ "errorNameRequired": "Gib deinen Namen ein.",+ "errorEmailRequired": "Gib deine E-Mail-Adresse ein.",+ "errorEmailInvalid": "Gib eine E-Mail-Adresse wie [email protected] ein.",+ "errorPasswordRequired": "Gib dein Passwort ein.",+ "errorPasswordTooShort": "Verwende mindestens {count} Zeichen.",+ "errorPasswordsDiffer": "Die Passwörter stimmen nicht überein.",+ "verifiedTitle": "E-Mail bestätigt",+ "verifiedDescription": "Geh zurück zu OpenPencil, um die Anmeldung abzuschließen. Du kannst diesen Tab schließen."}diff --git a/packages/vue/src/i18n/locales/de/common.json b/packages/vue/src/i18n/locales/de/common.jsonindex 8aa8ccd8e..2904ccbc4 100644--- a/packages/vue/src/i18n/locales/de/common.json+++ b/packages/vue/src/i18n/locales/de/common.json@@ -38,5 +38,7 @@"tokens": "Token","clear": "Löschen","dismiss": "Schließen",- "browserSupport": "Browser-Unterstützung prüfen"+ "browserSupport": "Browser-Unterstützung prüfen",+ "showPassword": "Passwort anzeigen",+ "hidePassword": "Passwort verbergen"}diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.jsonindex e4d97cde5..8557648d9 100644--- a/packages/vue/src/i18n/locales/de/files.json+++ b/packages/vue/src/i18n/locales/de/files.json@@ -25,5 +25,6 @@"newDesign": "Neues Design","noMatchingFiles": "Keine Dateien entsprechen „{query}“.","saveAsPrompt": "Speichern unter:",- "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden."+ "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden.",+ "newDesignIn": "Neues Design in {place}"}diff --git a/packages/vue/src/i18n/locales/de/index.ts b/packages/vue/src/i18n/locales/de/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/de/index.ts+++ b/packages/vue/src/i18n/locales/de/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex 05bdfb4d0..6c4eb1281 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -7,11 +7,9 @@"text": "Text","new": "Neu","open": "Öffnen…",- "openStorageWorkspace": "Speicher-Arbeitsbereich öffnen…","openTour": "Rundgang öffnen","save": "Speichern","saveAs": "Speichern unter…",- "saveToStorage": "Im Speicher-Arbeitsbereich speichern…","exportSelection": "Auswahl exportieren…","autosave": "Automatisch in Datei speichern","copy": "Kopieren",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Auswahl als SVG exportieren","exportSelectionAsPPTX": "Auswahl als PPTX exportieren","exportSelectionAsFig": "Auswahl als .fig exportieren",- "togglePreview": "Vorschau"+ "togglePreview": "Vorschau",+ "browseFiles": "Dateien durchsuchen…",+ "saveTo": "Speichern in…"}diff --git a/packages/vue/src/i18n/locales/de/settings.json b/packages/vue/src/i18n/locales/de/settings.jsonindex 4a8e373b8..795f8390b 100644--- a/packages/vue/src/i18n/locales/de/settings.json+++ b/packages/vue/src/i18n/locales/de/settings.json@@ -22,7 +22,8 @@"media": "Medien","mcp": "MCP","toolAccess": "Werkzeugzugriff",- "storage": "Cloud-Speicher",+ "storage": "Speicher",+ "cloud": "Cloud","animations": "Animationen","animationsSystem": "Systemeinstellung","animationsOff": "Aus",diff --git a/packages/vue/src/i18n/locales/de/variables.json b/packages/vue/src/i18n/locales/de/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/de/variables.jsonrename to packages/vue/src/i18n/locales/de/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/de/variable-types.json b/packages/vue/src/i18n/locales/de/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/de/variable-types.jsonrename to packages/vue/src/i18n/locales/de/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonnew file mode 100644index 000000000..9bf5bf7bf--- /dev/null+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -0,0 +1,276 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Continuar",+ "tryAgain": "Reintentar",+ "signIn": "Iniciar sesión",+ "signOut": "Cerrar sesión",+ "workspace": "Espacio de trabajo",+ "server": "Servidor",+ "share": "Compartir",+ "viewOnly": "Solo lectura",+ "canEdit": "Puede editar",+ "canView": "Puede ver",+ "roleViewer": "Lector",+ "roleEditor": "Editor",+ "roleAdmin": "Administrador",+ "changedInTwoPlaces": "«{name}» se ha cambiado en dos sitios",+ "conflictDescription": "Alguien guardó una versión más reciente mientras tenías cambios sin enviar. No se pierde nada hasta que elijas.",+ "connectHeading": "Conectar con OpenPencil Cloud",+ "connectDescription": "Mantén tus archivos sincronizados entre dispositivos e invita a otras personas a editar contigo.",+ "deviceHeading": "Confirma en tu navegador",+ "deviceDescription": "Aprueba este inicio de sesión en {host}.",+ "deviceDescriptionNoHost": "Aprueba este inicio de sesión en el servidor.",+ "officialDescription": "Alojado por OpenPencil · {host}",+ "selfHostedLabel": "El servidor de tu equipo",+ "selfHostedDescription": "Un OpenPencil Cloud autoalojado",+ "serverAddress": "Dirección del servidor",+ "errorInvalidAddressHeading": "Introduce la dirección web del servidor",+ "errorInvalidAddressDescription": "Usa la dirección que te ha dado tu equipo, por ejemplo https://cloud.example.com.",+ "errorUnreachableHeading": "No se pudo conectar con este servidor",+ "errorUnreachableDescription": "Comprueba la dirección y tu conexión, y vuelve a intentarlo.",+ "errorNotCloudHeading": "Este no es un servidor de OpenPencil Cloud",+ "errorNotCloudDescription": "La dirección ha respondido, pero no como OpenPencil Cloud. Pide a tu equipo la correcta.",+ "errorOutdatedHeading": "Este servidor necesita una actualización",+ "errorOutdatedDescription": "Ejecuta una versión de OpenPencil Cloud más antigua de la que admite esta app.",+ "errorDeniedHeading": "Se ha denegado el inicio de sesión",+ "errorDeniedDescription": "La solicitud se rechazó en el navegador. Empieza de nuevo para iniciar sesión.",+ "errorExpiredHeading": "El código ha caducado",+ "errorExpiredDescription": "No se aprobó a tiempo. Empieza de nuevo para obtener otro.",+ "errorSignInFailedHeading": "No se pudo iniciar sesión",+ "errorSignInFailedDescription": "El servidor no terminó de iniciar tu sesión. Inténtalo de nuevo en un momento.",+ "continueWithGoogle": "Continuar con Google",+ "continueWithApple": "Continuar con Apple",+ "continueWithEmail": "Continuar con correo",+ "signInNoteDesktop": "Se abrirá tu navegador para terminar de iniciar sesión y después volverás aquí.",+ "signInNoteBrowser": "Volverás a esta pestaña después de iniciar sesión.",+ "yourCode": "Tu código",+ "copyCode": "Copiar código",+ "deviceWaiting": "Esperando tu aprobación… El código caduca en {duration}.",+ "openBrowserAgain": "Abrir el navegador de nuevo",+ "accountPending": "Tu cuenta en {host} está pendiente de que un administrador la apruebe.",+ "signedInAs": "Has iniciado sesión en {host} como {email}.",+ "invitationUnavailableHeading": "Esta invitación no se puede usar",+ "invitationOpening": "Abriendo la invitación",+ "invitedYou": "{name} te ha invitado",+ "invitationEditDescription": "A editar un documento en {host}.",+ "invitationViewDescription": "A ver un documento en {host}.",+ "invitationChecking": "Comprobando la invitación…",+ "invitationUnavailableDescription": "Ha caducado, se ha retirado o ya se aceptó. Pide una nueva a {name}.",+ "invitationUnavailableDescriptionNoName": "Ha caducado, se ha retirado o ya se aceptó. Pide una nueva a quien te la envió.",+ "invitationSentTo": "Enviada a {recipient}",+ "invitationExpiresIn": "Caduca en {duration}",+ "unknownServerHeading": "No has usado {host} antes",+ "unknownServerDescription": "Inicia sesión solo si confías en este servidor. Guarda el documento y ve tus cambios.",+ "invitationSignInHeading": "Inicia sesión en {host}",+ "invitationSignInDescription": "Usa la cuenta a la que se envió esta invitación. El documento se abrirá justo después.",+ "wrongAccountHeading": "Esta invitación es para otra cuenta",+ "wrongAccountDescription": "Has iniciado sesión como {email}. Inicia sesión con {recipient} para abrirla.",+ "notNow": "Ahora no",+ "signInToOpen": "Iniciar sesión para abrir",+ "useAnotherAccount": "Usar otra cuenta",+ "openDocument": "Abrir documento",+ "saveHeading": "Elige dónde guardar",+ "saveDescription": "Mantén este diseño sincronizado entre dispositivos y compártelo con otras personas.",+ "saveName": "Nombre",+ "saveQuotaHeading": "Este espacio de trabajo no tiene espacio libre",+ "saveQuotaDescription": "Libera espacio o elige otro espacio de trabajo.",+ "saveOfflineHeading": "No tienes conexión",+ "saveOfflineDescription": "Conéctate a internet para guardar en la nube. No ha cambiado nada en este dispositivo.",+ "saveFailedHeading": "No se pudo guardar",+ "saveFailedDescription": "El servidor no aceptó el archivo. Inténtalo de nuevo en un momento.",+ "saveUploading": "Subiendo… {sent} de {total}",+ "saveTooLargeHeading": "Este archivo es demasiado grande para este servidor",+ "saveTooLargeDescription": "Admite archivos de hasta {limit}. Elimina imágenes o páginas que no uses y vuelve a intentarlo.",+ "saveNote": "La copia guardada se abre en esta pestaña y se guarda mientras trabajas. El archivo de este dispositivo no cambia.",+ "shareHeading": "Compartir «{name}»",+ "shareDescriptionInWorkspace": "En {workspace} de OpenPencil Cloud",+ "shareDescription": "En OpenPencil Cloud",+ "shareAddPeople": "Añadir personas por correo",+ "shareEmailAddress": "Correo electrónico",+ "shareNewPeoplePermission": "Permiso para las personas nuevas",+ "shareInvite": "Invitar",+ "sharePeopleWithAccess": "Personas con acceso",+ "shareYou": "(tú)",+ "shareInvited": "Invitado",+ "shareInvitationExpires": "La invitación caduca el {date}",+ "shareAccessFor": "Acceso de {name}",+ "shareOwner": "Propietario",+ "shareRemoveAccess": "Retirar acceso",+ "shareEveryoneIn": "Todos en {workspace}",+ "shareMemberCount": {+ "one": "{count} miembro",+ "many": "{count} miembros"+ },+ "shareWorkspacePermissionTip": "Lo define el espacio de trabajo; cámbialo en sus ajustes",+ "shareGeneralAccess": "Acceso general",+ "shareRestricted": "Solo personas con acceso",+ "shareAnyoneWithLink": "Cualquiera con el enlace",+ "shareLinkDetail": "Cualquiera que tenga el enlace puede abrir este archivo sin iniciar sesión.",+ "shareRestrictedDetail": "Solo las personas y el espacio de trabajo indicados arriba pueden abrir este archivo.",+ "shareRestrictedNoLinksDetail": "Solo las personas y el espacio de trabajo indicados arriba pueden abrir este archivo. Los enlaces están desactivados en este espacio de trabajo.",+ "shareLinkPermission": "Permiso del enlace",+ "shareCannotManage": "Solo el propietario y los editores pueden cambiar quién tiene acceso.",+ "shareResetLinkTip": "Este enlace se creó en otro dispositivo. Al restablecerlo se crea un enlace nuevo y el anterior deja de funcionar.",+ "shareResetLink": "Restablecer enlace",+ "shareLinkCopied": "Enlace copiado",+ "shareCopyLink": "Copiar enlace",+ "shareLoadFailed": "No se pudo cargar quién tiene acceso. Comprueba tu conexión y vuelve a intentarlo.",+ "shareChangeFailed": "Ese cambio no se ha aplicado. Inténtalo de nuevo en un momento.",+ "conflictKeepBoth": "Conservar ambas",+ "conflictKeepBothDescription": "La versión de la nube se queda como «{name}». La tuya se guarda a su lado como «{copyName}».",+ "conflictUseCloud": "Usar la versión de la nube",+ "conflictUseCloudDescription": "Se descartan tus cambios sin enviar de este dispositivo.",+ "conflictUseMine": "Reemplazarla por tu versión",+ "conflictUseMineDescriptionBy": "Los últimos cambios de {name} se reemplazan para todos.",+ "conflictUseMineDescription": "La versión más reciente del servidor se reemplaza para todos.",+ "conflictConfirmUseCloud": "Usar versión de la nube",+ "conflictConfirmUseMine": "Reemplazar por la mía",+ "conflictYourVersion": "Tu versión",+ "conflictCloudVersion": "Versión de la nube",+ "conflictWhichVersion": "Qué versión conservar",+ "conflictDecideLater": "Decidir más tarde",+ "conflictYourCopyName": "{name} (tu copia)",+ "conflictYouOnThisDevice": "Tú, en este dispositivo",+ "conflictResolveFailed": "No se pudo resolver el conflicto. Tus cambios siguen en este dispositivo.",+ "statusViewOnlyDetail": "Puedes explorar y seguir a otros; tus cambios no llegarán a nadie.",+ "statusSavedTo": "Guardado en {workspace}",+ "statusSavedAgo": "Guardado {time}",+ "statusUpToDate": "Actualizado",+ "statusSaving": "Guardando…",+ "statusUploadingTo": "Subiendo a {workspace}",+ "statusSavedOnDevice": "Guardado en este dispositivo",+ "statusUploadsSoon": "Se subirá en un momento",+ "statusOfflineDetail": "No tienes conexión. Los cambios se subirán cuando vuelvas a conectarte.",+ "statusConflict": "Cambiado en dos sitios",+ "statusConflictDetail": "Alguien guardó una versión más reciente mientras editabas. Elige cuál conservar.",+ "statusErrorDetail": "Tus cambios están a salvo en este dispositivo.",+ "statusResolve": "Resolver",+ "statusChooseVersion": "Elegir una versión",+ "statusOpenWorkspace": "Abrir espacio de trabajo",+ "settingsDescription": "Servidores con los que esta app sincroniza documentos. Inicio muestra los espacios de trabajo de un servidor cada vez.",+ "settingsEmptyDescription": "Mantén tus archivos sincronizados entre dispositivos y edítalos con otras personas. Los documentos de este dispositivo se quedan donde están.",+ "settingsConnectServer": "Conectar un servidor",+ "settingsOfficialDescription": "Alojado por OpenPencil, sin nada que configurar.",+ "settingsSelfHostedDescription": "Un OpenPencil Cloud autoalojado, en la dirección que usa tu equipo.",+ "settingsOnHome": "En Inicio",+ "settingsSignInExpired": "La sesión ha caducado",+ "settingsSignInExpiredFor": "La sesión de {email} ha caducado",+ "settingsSignedOut": "Sesión cerrada",+ "settingsWaitingForApproval": "Esperando a que un administrador apruebe tu cuenta",+ "settingsAccessClosed": "Un administrador ha rechazado o retirado tu acceso",+ "settingsOptionsFor": "Opciones de {host}",+ "settingsAccountAndSecurity": "Cuenta y seguridad",+ "settingsShowOnHome": "Mostrar en Inicio",+ "settingsDisconnectServer": "Desconectar servidor",+ "settingsSignOutFailed": "No se pudo cerrar sesión. Comprueba tu conexión y vuelve a intentarlo.",+ "settingsDisconnectHeading": "¿Desconectar {host}?",+ "settingsDisconnectDescription": "Se cerrará tu sesión y sus espacios de trabajo desaparecerán de Inicio en este dispositivo. Tus documentos se quedan en el servidor y puedes volver a conectarte cuando quieras.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Se cerrará tu sesión y sus espacios de trabajo desaparecerán de Inicio en este dispositivo. {count} documento tiene cambios que aún no llegaron al servidor; al desconectar se descartan.",+ "many": "Se cerrará tu sesión y sus espacios de trabajo desaparecerán de Inicio en este dispositivo. {count} documentos tienen cambios que aún no llegaron al servidor; al desconectar se descartan."+ },+ "settingsDisconnect": "Desconectar",+ "settingsDisconnectAndDiscard": "Desconectar y descartar cambios",+ "homeLocations": "Ubicaciones",+ "homeRecent": "Recientes",+ "homeAccount": "Cuenta: {email}",+ "homeAccountSettings": "Ajustes de la cuenta",+ "homeConnectAnotherServer": "Conectar otro servidor…",+ "homeAttentionTip": "Un archivo de aquí necesita que elijas",+ "homeNeedsAttention": "Requiere atención",+ "homeSharedWithYou": "Compartido contigo",+ "homeSharedSubtitle": "Archivos a los que te han invitado",+ "homeSharedBy": "Compartido por {name}",+ "homeSignIn": "Iniciar sesión…",+ "homeStorage": "Almacenamiento",+ "homeStorageSettings": "Ajustes de almacenamiento",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "{used} usados",+ "homeUsageOf": "{used} de {total}",+ "homeWorkspaceStorage": "Almacenamiento del espacio de trabajo, {usage}",+ "homeView": "Vista",+ "homeGrid": "Cuadrícula",+ "homeList": "Lista",+ "homeOfflineHeading": "No tienes conexión",+ "homeOfflineDescription": "Estos son los archivos guardados en este dispositivo. Los cambios se subirán cuando vuelvas a conectarte.",+ "homeLoadFailedHeading": "No se pudo cargar este espacio de trabajo",+ "homeLoadFailedDescription": "El servidor no ha respondido. Los archivos guardados en este dispositivo siguen en la lista.",+ "homeConflicts": {+ "one": "{count} archivo se ha cambiado en dos sitios",+ "many": "{count} archivos se han cambiado en dos sitios"+ },+ "homeReview": "Revisar",+ "homeLoadingFiles": "Cargando archivos",+ "homeEmptyWorkspace": "Aún no hay archivos en {workspace}",+ "homeEmptyWorkspaceDescription": "Crea un diseño aquí o guarda un archivo abierto en este espacio de trabajo desde el menú Archivo.",+ "homeNothingShared": "Aún no se ha compartido nada contigo",+ "homeNothingSharedDescription": "Aquí aparecerán los archivos a los que te inviten.",+ "homeNewDesign": "Nuevo diseño",+ "homeViewOnlyTip": "Puedes ver este archivo",+ "homeSharedTip": "Compartido con personas de fuera del espacio de trabajo",+ "homeShared": "Compartido",+ "syncSynced": "Guardado en la nube",+ "syncUploading": "Subiendo cambios…",+ "syncPending": "Cambios guardados en este dispositivo, pendientes de subir",+ "syncOffline": "Sin conexión: los cambios se guardan en este dispositivo",+ "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.",+ "connectServerHeading": "Conecta el servidor de tu equipo",+ "connectServerDescription": "Escribe la dirección que usa tu equipo para OpenPencil Cloud.",+ "checkingServer": "Comprobando el servidor…",+ "signInHeading": "Inicia sesión en {name}",+ "onHost": "En {host}.",+ "verifyDescription": "Enviamos un enlace a {email}.",+ "verifyNote": "Abre el enlace del correo y vuelve aquí. El inicio de sesión termina solo.",+ "verifyNotYet": "Tu correo aún no está confirmado. Abre el enlace del correo y vuelve a intentarlo.",+ "verifyNoEmail": "¿No te llegó?",+ "settingsTitle": "Nube",+ "saveWhere": "Ubicación",+ "saveAction": "Guardar",+ "saveStorageGroup": "Almacenamiento",+ "invitationWorkspaceDescription": "Para unirte a un espacio de trabajo en {host}.",+ "joinWorkspace": "Unirse al espacio",+ "homeNewWorkspace": "Nuevo espacio de trabajo",+ "homeMembers": "Miembros",+ "newWorkspaceHeading": "Nuevo espacio de trabajo",+ "newWorkspaceDescription": "Un lugar para guardar diseños con tu equipo. Tú decides quién se une.",+ "workspaceName": "Nombre del espacio",+ "workspaceNamePlaceholder": "Equipo de diseño",+ "createWorkspace": "Crear espacio",+ "renameWorkspace": "Renombrar",+ "membersDescription": "Todos aquí ven los documentos del espacio; los editores y administradores los cambian.",+ "invitePeople": "Invitar personas",+ "inviteEmail": "Correo electrónico",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Rol",+ "invite": "Invitar",+ "invitationSentNote": "Enviamos la invitación por correo. Si este servidor no envía correos, comparte este enlace.",+ "copyInvitationLink": "Copiar enlace de invitación",+ "membersLoading": "Cargando miembros…",+ "memberRole": "Rol de {name}",+ "removeMember": "Quitar a {name}",+ "pendingInvitations": "Pendientes de unirse",+ "revokeInvitation": "Retirar",+ "leaveWorkspace": "Salir del espacio",+ "workspaceAlreadyMember": "Ya está en este espacio de trabajo.",+ "workspaceLastAdmin": "Un espacio necesita un administrador. Haz administrador a otra persona primero.",+ "workspaceForbidden": "Solo los administradores del espacio pueden hacerlo.",+ "workspaceNotFound": "Este espacio o invitación ya no existe. Cierra esto e inténtalo de nuevo.",+ "workspaceFailed": "No se pudo cambiar el espacio. Inténtalo de nuevo en un momento.",+ "unknownServerWorkspaceDescription": "Inicia sesión solo si confías en este servidor. Guarda los documentos del espacio y ve tus cambios.",+ "leaveWorkspaceHeading": "¿Salir de {workspace}?",+ "leaveWorkspaceDescription": "Pierdes el acceso a sus documentos salvo los compartidos directamente contigo. Un administrador puede volver a invitarte.",+ "removeMemberHeading": "¿Quitar a {name} de {workspace}?",+ "removeMemberDescription": "Pierde el acceso a sus documentos salvo los compartidos directamente. Puedes volver a invitarla.",+ "removeMemberConfirm": "Quitar",+ "deleteWorkspace": "Eliminar espacio",+ "deleteWorkspaceHeading": "¿Eliminar {workspace}?",+ "deleteWorkspaceDescription": "Todos pierden el acceso y sus invitaciones dejan de funcionar. Solo se puede eliminar un espacio vacío.",+ "deleteWorkspaceTypeName": "Para confirmar, escribe «{workspace}».",+ "dangerZone": "Zona de peligro",+ "leaveWorkspaceShort": "Salir",+ "deleteWorkspaceShort": "Eliminar",+ "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."+}diff --git a/packages/vue/src/i18n/locales/es/cloud-portal.json b/packages/vue/src/i18n/locales/es/cloud/portal.jsonsimilarity index 95%rename from packages/vue/src/i18n/locales/es/cloud-portal.jsonrename to packages/vue/src/i18n/locales/es/cloud/portal.jsonindex 79c078c9c..0c0b6781a 100644--- a/packages/vue/src/i18n/locales/es/cloud-portal.json+++ b/packages/vue/src/i18n/locales/es/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Ayuda","loading": "Cargando…","unavailableTitle": "Este servidor no responde","unavailableDescription": "Comprueba la dirección o inténtalo de nuevo en un momento.","tryAgain": "Reintentar","signInTitle": "Inicia sesión en OpenPencil Cloud","signUpTitle": "Crea tu cuenta",- "signInWelcome": "Hola de nuevo.",- "signUpDescription": "Crea una cuenta en este servidor.","returnsTo": "Después volverás a {destination}.","returnsToDesktop": "la app de OpenPencil","returnsToEditor": "el editor",@@ -23,7 +22,7 @@"signIn": "Iniciar sesión","createAccount": "Crear cuenta","haveAccount": "¿Ya tienes una cuenta?",- "newHere": "¿Eres nuevo?",+ "newHere": "¿Eres nuevo en OpenPencil Cloud?","createAnAccount": "Crea una cuenta","approvalTitle": "Un administrador revisa las cuentas nuevas","approvalDescription": "Podrás iniciar sesión cuando se apruebe tu solicitud. Te avisaremos por correo.",@@ -235,5 +234,14 @@"errorNotAllowed": "No tienes permiso para hacer eso.","errorNetwork": "No se pudo conectar con el servidor. Comprueba tu conexión.","errorAlreadyDecided": "Alguien ya ha resuelto esta solicitud. Actualiza para verla.",- "passwordResetSent": "Te hemos enviado un enlace para establecer una contraseña."+ "passwordResetSent": "Te hemos enviado un enlace para establecer una contraseña.",+ "repeatPassword": "Repite la contraseña",+ "errorNameRequired": "Escribe tu nombre.",+ "errorEmailRequired": "Escribe tu correo electrónico.",+ "errorEmailInvalid": "Escribe un correo como [email protected].",+ "errorPasswordRequired": "Escribe tu contraseña.",+ "errorPasswordTooShort": "Usa al menos {count} caracteres.",+ "errorPasswordsDiffer": "Las contraseñas no coinciden.",+ "verifiedTitle": "Correo confirmado",+ "verifiedDescription": "Vuelve a OpenPencil para terminar de iniciar sesión. Puedes cerrar esta pestaña."}diff --git a/packages/vue/src/i18n/locales/es/common.json b/packages/vue/src/i18n/locales/es/common.jsonindex 04c528464..e1afff928 100644--- a/packages/vue/src/i18n/locales/es/common.json+++ b/packages/vue/src/i18n/locales/es/common.json@@ -38,5 +38,7 @@"tokens": "tokens","clear": "Limpiar","dismiss": "Descartar",- "browserSupport": "Consultar compatibilidad"+ "browserSupport": "Consultar compatibilidad",+ "showPassword": "Mostrar contraseña",+ "hidePassword": "Ocultar contraseña"}diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.jsonindex 7f318bd51..3fc286f86 100644--- a/packages/vue/src/i18n/locales/es/files.json+++ b/packages/vue/src/i18n/locales/es/files.json@@ -25,5 +25,6 @@"newDesign": "Nuevo diseño","noMatchingFiles": "Ningún archivo coincide con «{query}».","saveAsPrompt": "Guardar como:",- "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar."+ "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar.",+ "newDesignIn": "Nuevo diseño en {place}"}diff --git a/packages/vue/src/i18n/locales/es/index.ts b/packages/vue/src/i18n/locales/es/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/es/index.ts+++ b/packages/vue/src/i18n/locales/es/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex 34a1879a1..05703ad8f 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -7,11 +7,9 @@"text": "Texto","new": "Nuevo","open": "Abrir…",- "openStorageWorkspace": "Abrir espacio de almacenamiento…","openTour": "Abrir el recorrido","save": "Guardar","saveAs": "Guardar como…",- "saveToStorage": "Guardar en el espacio de almacenamiento…","exportSelection": "Exportar selección…","autosave": "Guardado automático en archivo","copy": "Copiar",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Exportar selección como SVG","exportSelectionAsPPTX": "Exportar selección como PPTX","exportSelectionAsFig": "Exportar selección como .fig",- "togglePreview": "Vista previa"+ "togglePreview": "Vista previa",+ "browseFiles": "Explorar archivos…",+ "saveTo": "Guardar en…"}diff --git a/packages/vue/src/i18n/locales/es/settings.json b/packages/vue/src/i18n/locales/es/settings.jsonindex 107405b8d..81ccd12f5 100644--- a/packages/vue/src/i18n/locales/es/settings.json+++ b/packages/vue/src/i18n/locales/es/settings.json@@ -22,7 +22,8 @@"media": "Multimedia","mcp": "MCP","toolAccess": "Acceso a herramientas",- "storage": "Almacenamiento en la nube",+ "storage": "Almacenamiento",+ "cloud": "Nube","animations": "Animaciones","animationsSystem": "Seguir al sistema","animationsOff": "Desactivadas",diff --git a/packages/vue/src/i18n/locales/es/variables.json b/packages/vue/src/i18n/locales/es/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/es/variables.jsonrename to packages/vue/src/i18n/locales/es/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/es/variable-types.json b/packages/vue/src/i18n/locales/es/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/es/variable-types.jsonrename to packages/vue/src/i18n/locales/es/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonnew file mode 100644index 000000000..8f99dde53--- /dev/null+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -0,0 +1,276 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Continuer",+ "tryAgain": "Réessayer",+ "signIn": "Se connecter",+ "signOut": "Se déconnecter",+ "workspace": "Espace de travail",+ "server": "Serveur",+ "share": "Partager",+ "viewOnly": "Lecture seule",+ "canEdit": "Peut modifier",+ "canView": "Peut consulter",+ "roleViewer": "Lecteur",+ "roleEditor": "Éditeur",+ "roleAdmin": "Administrateur",+ "changedInTwoPlaces": "« {name} » a été modifié à deux endroits",+ "conflictDescription": "Quelqu’un a enregistré une version plus récente alors que vous aviez des modifications non envoyées. Rien n’est perdu tant que vous n’avez pas choisi.",+ "connectHeading": "Se connecter à OpenPencil Cloud",+ "connectDescription": "Synchronisez vos fichiers sur tous vos appareils et invitez d’autres personnes à les modifier avec vous.",+ "deviceHeading": "Confirmez dans votre navigateur",+ "deviceDescription": "Approuvez cette connexion sur {host}.",+ "deviceDescriptionNoHost": "Approuvez cette connexion sur le serveur.",+ "officialDescription": "Hébergé par OpenPencil · {host}",+ "selfHostedLabel": "Le serveur de votre équipe",+ "selfHostedDescription": "Un OpenPencil Cloud auto-hébergé",+ "serverAddress": "Adresse du serveur",+ "errorInvalidAddressHeading": "Saisissez l’adresse web du serveur",+ "errorInvalidAddressDescription": "Utilisez l’adresse fournie par votre équipe, par exemple https://cloud.example.com.",+ "errorUnreachableHeading": "Impossible de joindre ce serveur",+ "errorUnreachableDescription": "Vérifiez l’adresse et votre connexion, puis réessayez.",+ "errorNotCloudHeading": "Ce n’est pas un serveur OpenPencil Cloud",+ "errorNotCloudDescription": "L’adresse a répondu, mais pas en tant qu’OpenPencil Cloud. Demandez la bonne adresse à votre équipe.",+ "errorOutdatedHeading": "Ce serveur doit être mis à jour",+ "errorOutdatedDescription": "Il utilise une version d’OpenPencil Cloud plus ancienne que celle prise en charge par cette app.",+ "errorDeniedHeading": "Connexion refusée",+ "errorDeniedDescription": "La demande a été refusée dans le navigateur. Recommencez pour vous connecter.",+ "errorExpiredHeading": "Le code a expiré",+ "errorExpiredDescription": "Il n’a pas été approuvé à temps. Recommencez pour en obtenir un nouveau.",+ "errorSignInFailedHeading": "Connexion impossible",+ "errorSignInFailedDescription": "Le serveur n’a pas terminé votre connexion. Réessayez dans un instant.",+ "continueWithGoogle": "Continuer avec Google",+ "continueWithApple": "Continuer avec Apple",+ "continueWithEmail": "Continuer avec un e-mail",+ "signInNoteDesktop": "Votre navigateur s’ouvre pour terminer la connexion, puis vous revenez ici.",+ "signInNoteBrowser": "Vous reviendrez à cet onglet après la connexion.",+ "yourCode": "Votre code",+ "copyCode": "Copier le code",+ "deviceWaiting": "En attente de votre approbation… Le code expire dans {duration}.",+ "openBrowserAgain": "Rouvrir le navigateur",+ "accountPending": "Votre compte sur {host} attend l’approbation d’un administrateur.",+ "signedInAs": "Connecté à {host} en tant que {email}.",+ "invitationUnavailableHeading": "Cette invitation ne peut pas être utilisée",+ "invitationOpening": "Ouverture de l’invitation",+ "invitedYou": "{name} vous a invité",+ "invitationEditDescription": "À modifier un document sur {host}.",+ "invitationViewDescription": "À consulter un document sur {host}.",+ "invitationChecking": "Vérification de l’invitation…",+ "invitationUnavailableDescription": "Elle a expiré, a été retirée ou a déjà été acceptée. Demandez-en une nouvelle à {name}.",+ "invitationUnavailableDescriptionNoName": "Elle a expiré, a été retirée ou a déjà été acceptée. Demandez-en une nouvelle à la personne qui vous l’a envoyée.",+ "invitationSentTo": "Envoyée à {recipient}",+ "invitationExpiresIn": "Expire dans {duration}",+ "unknownServerHeading": "Vous n’avez jamais utilisé {host}",+ "unknownServerDescription": "Ne vous connectez que si vous faites confiance à ce serveur. Il stocke le document et voit vos modifications.",+ "invitationSignInHeading": "Se connecter à {host}",+ "invitationSignInDescription": "Utilisez le compte auquel cette invitation a été envoyée. Le document s’ouvre juste après.",+ "wrongAccountHeading": "Cette invitation est destinée à un autre compte",+ "wrongAccountDescription": "Vous êtes connecté en tant que {email}. Connectez-vous avec {recipient} pour l’ouvrir.",+ "notNow": "Pas maintenant",+ "signInToOpen": "Se connecter pour ouvrir",+ "useAnotherAccount": "Utiliser un autre compte",+ "openDocument": "Ouvrir le document",+ "saveHeading": "Choisir où enregistrer",+ "saveDescription": "Synchronisez ce design sur tous vos appareils et partagez-le avec d’autres personnes.",+ "saveName": "Nom",+ "saveQuotaHeading": "Cet espace de travail est plein",+ "saveQuotaDescription": "Libérez de l’espace ou choisissez un autre espace de travail.",+ "saveOfflineHeading": "Vous êtes hors ligne",+ "saveOfflineDescription": "Connectez-vous à internet pour enregistrer dans le cloud. Rien n’a changé sur cet appareil.",+ "saveFailedHeading": "Échec de l’enregistrement",+ "saveFailedDescription": "Le serveur n’a pas accepté le fichier. Réessayez dans un instant.",+ "saveUploading": "Envoi… {sent} sur {total}",+ "saveTooLargeHeading": "Ce fichier est trop volumineux pour ce serveur",+ "saveTooLargeDescription": "Il accepte les fichiers jusqu’à {limit}. Supprimez les images ou pages inutilisées, puis réessayez.",+ "saveNote": "La copie enregistrée s’ouvre dans cet onglet et s’enregistre pendant que vous travaillez. Le fichier sur cet appareil reste tel quel.",+ "shareHeading": "Partager « {name} »",+ "shareDescriptionInWorkspace": "Dans {workspace} sur OpenPencil Cloud",+ "shareDescription": "Sur OpenPencil Cloud",+ "shareAddPeople": "Ajouter des personnes par e-mail",+ "shareEmailAddress": "Adresse e-mail",+ "shareNewPeoplePermission": "Autorisation des nouvelles personnes",+ "shareInvite": "Inviter",+ "sharePeopleWithAccess": "Personnes ayant accès",+ "shareYou": "(vous)",+ "shareInvited": "Invité",+ "shareInvitationExpires": "Expiration de l’invitation : {date}",+ "shareAccessFor": "Accès de {name}",+ "shareOwner": "Propriétaire",+ "shareRemoveAccess": "Retirer l’accès",+ "shareEveryoneIn": "Tous les membres de {workspace}",+ "shareMemberCount": {+ "one": "{count} membre",+ "many": "{count} membres"+ },+ "shareWorkspacePermissionTip": "Défini par l’espace de travail ; modifiez-le dans ses paramètres",+ "shareGeneralAccess": "Accès général",+ "shareRestricted": "Uniquement les personnes ayant accès",+ "shareAnyoneWithLink": "Toute personne disposant du lien",+ "shareLinkDetail": "Toute personne disposant du lien peut ouvrir ce fichier sans se connecter.",+ "shareRestrictedDetail": "Seuls les personnes et l’espace de travail ci-dessus peuvent ouvrir ce fichier.",+ "shareRestrictedNoLinksDetail": "Seuls les personnes et l’espace de travail ci-dessus peuvent ouvrir ce fichier. Les liens sont désactivés pour cet espace de travail.",+ "shareLinkPermission": "Autorisation du lien",+ "shareCannotManage": "Seuls le propriétaire et les éditeurs peuvent modifier qui a accès.",+ "shareResetLinkTip": "Ce lien a été créé sur un autre appareil. Le réinitialiser crée un nouveau lien, et l’ancien cesse de fonctionner.",+ "shareResetLink": "Réinitialiser le lien",+ "shareLinkCopied": "Lien copié",+ "shareCopyLink": "Copier le lien",+ "shareLoadFailed": "Impossible de charger la liste des accès. Vérifiez votre connexion et réessayez.",+ "shareChangeFailed": "Cette modification n’a pas abouti. Réessayez dans un instant.",+ "conflictKeepBoth": "Conserver les deux",+ "conflictKeepBothDescription": "La version du cloud reste « {name} ». La vôtre est enregistrée à côté sous le nom « {copyName} ».",+ "conflictUseCloud": "Utiliser la version du cloud",+ "conflictUseCloudDescription": "Vos modifications non envoyées sur cet appareil sont abandonnées.",+ "conflictUseMine": "La remplacer par votre version",+ "conflictUseMineDescriptionBy": "Les dernières modifications de {name} sont remplacées pour tout le monde.",+ "conflictUseMineDescription": "La version plus récente sur le serveur est remplacée pour tout le monde.",+ "conflictConfirmUseCloud": "Utiliser la version du cloud",+ "conflictConfirmUseMine": "Remplacer par la mienne",+ "conflictYourVersion": "Votre version",+ "conflictCloudVersion": "Version du cloud",+ "conflictWhichVersion": "Version à conserver",+ "conflictDecideLater": "Décider plus tard",+ "conflictYourCopyName": "{name} (votre copie)",+ "conflictYouOnThisDevice": "Vous, sur cet appareil",+ "conflictResolveFailed": "Impossible de résoudre le conflit. Vos modifications sont toujours sur cet appareil.",+ "statusViewOnlyDetail": "Vous pouvez explorer et suivre les autres ; vos modifications n’atteindront personne.",+ "statusSavedTo": "Enregistré dans {workspace}",+ "statusSavedAgo": "Enregistré {time}",+ "statusUpToDate": "À jour",+ "statusSaving": "Enregistrement…",+ "statusUploadingTo": "Envoi vers {workspace}",+ "statusSavedOnDevice": "Enregistré sur cet appareil",+ "statusUploadsSoon": "Envoi dans un instant",+ "statusOfflineDetail": "Vous êtes hors ligne. Les modifications seront envoyées à la reconnexion.",+ "statusConflict": "Modifié à deux endroits",+ "statusConflictDetail": "Quelqu’un a enregistré une version plus récente pendant que vous modifiiez. Choisissez celle à conserver.",+ "statusErrorDetail": "Vos modifications sont en sécurité sur cet appareil.",+ "statusResolve": "Résoudre",+ "statusChooseVersion": "Choisir une version",+ "statusOpenWorkspace": "Ouvrir l’espace de travail",+ "settingsDescription": "Serveurs avec lesquels cette app synchronise les documents. L’accueil affiche les espaces de travail d’un seul serveur à la fois.",+ "settingsEmptyDescription": "Synchronisez vos fichiers sur tous vos appareils et modifiez-les avec d’autres personnes. Les documents de cet appareil restent où ils sont.",+ "settingsConnectServer": "Connecter un serveur",+ "settingsOfficialDescription": "Hébergé par OpenPencil, rien à configurer.",+ "settingsSelfHostedDescription": "Un OpenPencil Cloud auto-hébergé, à l’adresse utilisée par votre équipe.",+ "settingsOnHome": "Affiché sur l’accueil",+ "settingsSignInExpired": "Connexion expirée",+ "settingsSignInExpiredFor": "Connexion expirée pour {email}",+ "settingsSignedOut": "Déconnecté",+ "settingsWaitingForApproval": "En attente de l’approbation de votre compte par un administrateur",+ "settingsAccessClosed": "Un administrateur a refusé ou retiré votre accès",+ "settingsOptionsFor": "Options pour {host}",+ "settingsAccountAndSecurity": "Compte et sécurité",+ "settingsShowOnHome": "Afficher sur l’accueil",+ "settingsDisconnectServer": "Déconnecter le serveur",+ "settingsSignOutFailed": "Impossible de se déconnecter. Vérifiez votre connexion et réessayez.",+ "settingsDisconnectHeading": "Déconnecter {host} ?",+ "settingsDisconnectDescription": "Vous êtes déconnecté et ses espaces de travail quittent l’accueil sur cet appareil. Vos documents restent sur le serveur, et vous pouvez vous reconnecter à tout moment.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Vous êtes déconnecté et ses espaces de travail quittent l’accueil sur cet appareil. {count} document a des modifications qui n’ont pas encore atteint le serveur ; la déconnexion les supprime.",+ "many": "Vous êtes déconnecté et ses espaces de travail quittent l’accueil sur cet appareil. {count} documents ont des modifications qui n’ont pas encore atteint le serveur ; la déconnexion les supprime."+ },+ "settingsDisconnect": "Déconnecter",+ "settingsDisconnectAndDiscard": "Déconnecter et abandonner les modifications",+ "homeLocations": "Emplacements",+ "homeRecent": "Récents",+ "homeAccount": "Compte : {email}",+ "homeAccountSettings": "Paramètres du compte",+ "homeConnectAnotherServer": "Connecter un autre serveur…",+ "homeAttentionTip": "Un fichier ici demande un choix",+ "homeNeedsAttention": "À traiter",+ "homeSharedWithYou": "Partagés avec vous",+ "homeSharedSubtitle": "Fichiers auxquels on vous a invité",+ "homeSharedBy": "Partagé par {name}",+ "homeSignIn": "Se connecter…",+ "homeStorage": "Stockage",+ "homeStorageSettings": "Paramètres de stockage",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "{used} utilisés",+ "homeUsageOf": "{used} sur {total}",+ "homeWorkspaceStorage": "Stockage de l’espace de travail, {usage}",+ "homeView": "Affichage",+ "homeGrid": "Grille",+ "homeList": "Liste",+ "homeOfflineHeading": "Vous êtes hors ligne",+ "homeOfflineDescription": "Voici les fichiers enregistrés sur cet appareil. Les modifications seront envoyées à la reconnexion.",+ "homeLoadFailedHeading": "Impossible de charger cet espace de travail",+ "homeLoadFailedDescription": "Le serveur n’a pas répondu. Les fichiers enregistrés sur cet appareil restent affichés.",+ "homeConflicts": {+ "one": "{count} fichier a été modifié à deux endroits",+ "many": "{count} fichiers ont été modifiés à deux endroits"+ },+ "homeReview": "Examiner",+ "homeLoadingFiles": "Chargement des fichiers",+ "homeEmptyWorkspace": "Aucun fichier dans {workspace} pour le moment",+ "homeEmptyWorkspaceDescription": "Créez un design ici, ou enregistrez un fichier ouvert dans cet espace de travail depuis le menu Fichier.",+ "homeNothingShared": "Rien n’a encore été partagé avec vous",+ "homeNothingSharedDescription": "Les fichiers auxquels on vous invite apparaissent ici.",+ "homeNewDesign": "Nouveau design",+ "homeViewOnlyTip": "Vous pouvez consulter ce fichier",+ "homeSharedTip": "Partagé avec des personnes extérieures à l’espace de travail",+ "homeShared": "Partagé",+ "syncSynced": "Enregistré dans le cloud",+ "syncUploading": "Envoi des modifications…",+ "syncPending": "Modifications enregistrées sur cet appareil, en attente d’envoi",+ "syncOffline": "Hors ligne — les modifications sont enregistrées sur cet appareil",+ "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.",+ "connectServerHeading": "Connecter le serveur de votre équipe",+ "connectServerDescription": "Saisissez l’adresse que votre équipe utilise pour OpenPencil Cloud.",+ "checkingServer": "Vérification du serveur…",+ "signInHeading": "Se connecter à {name}",+ "onHost": "Sur {host}.",+ "verifyDescription": "Nous avons envoyé un lien à {email}.",+ "verifyNote": "Ouvrez le lien de l’e-mail, puis revenez ici. La connexion se termine d’elle-même.",+ "verifyNotYet": "Votre adresse n’est pas encore confirmée. Ouvrez le lien de l’e-mail, puis réessayez.",+ "verifyNoEmail": "Pas d’e-mail ?",+ "settingsTitle": "Cloud",+ "saveWhere": "Emplacement",+ "saveAction": "Enregistrer",+ "saveStorageGroup": "Stockage",+ "invitationWorkspaceDescription": "Pour rejoindre un espace de travail sur {host}.",+ "joinWorkspace": "Rejoindre l’espace",+ "homeNewWorkspace": "Nouvel espace de travail",+ "homeMembers": "Membres",+ "newWorkspaceHeading": "Nouvel espace de travail",+ "newWorkspaceDescription": "Un endroit pour garder vos designs avec votre équipe. Vous choisissez qui la rejoint.",+ "workspaceName": "Nom de l’espace",+ "workspaceNamePlaceholder": "Équipe design",+ "createWorkspace": "Créer l’espace",+ "renameWorkspace": "Renommer",+ "membersDescription": "Tout le monde ici voit les documents de l’espace ; les éditeurs et admins les modifient.",+ "invitePeople": "Inviter des personnes",+ "inviteEmail": "Adresse e-mail",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Rôle",+ "invite": "Inviter",+ "invitationSentNote": "Nous avons envoyé l’invitation par e-mail. Si ce serveur n’envoie pas d’e-mails, partagez plutôt ce lien.",+ "copyInvitationLink": "Copier le lien d’invitation",+ "membersLoading": "Chargement des membres…",+ "memberRole": "Rôle de {name}",+ "removeMember": "Retirer {name}",+ "pendingInvitations": "En attente",+ "revokeInvitation": "Retirer",+ "leaveWorkspace": "Quitter l’espace",+ "workspaceAlreadyMember": "Cette personne fait déjà partie de l’espace.",+ "workspaceLastAdmin": "Un espace a besoin d’un admin. Nommez d’abord quelqu’un d’autre admin.",+ "workspaceForbidden": "Seuls les admins de l’espace peuvent le faire.",+ "workspaceNotFound": "Cet espace ou cette invitation n’existe plus. Fermez et réessayez.",+ "workspaceFailed": "Impossible de modifier l’espace. Réessayez dans un instant.",+ "unknownServerWorkspaceDescription": "Ne vous connectez que si vous faites confiance à ce serveur. Il stocke les documents de l’espace et voit vos modifications.",+ "leaveWorkspaceHeading": "Quitter {workspace} ?",+ "leaveWorkspaceDescription": "Vous perdez l’accès à ses documents, sauf ceux partagés directement avec vous. Un admin peut vous réinviter.",+ "removeMemberHeading": "Retirer {name} de {workspace} ?",+ "removeMemberDescription": "Cette personne perd l’accès à ses documents, sauf ceux partagés directement. Vous pouvez la réinviter.",+ "removeMemberConfirm": "Retirer",+ "deleteWorkspace": "Supprimer l’espace",+ "deleteWorkspaceHeading": "Supprimer {workspace} ?",+ "deleteWorkspaceDescription": "Tout le monde perd l’accès et ses invitations cessent de fonctionner. Seul un espace vide peut être supprimé.",+ "deleteWorkspaceTypeName": "Pour confirmer, saisissez « {workspace} ».",+ "dangerZone": "Zone de danger",+ "leaveWorkspaceShort": "Quitter",+ "deleteWorkspaceShort": "Supprimer",+ "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."+}diff --git a/packages/vue/src/i18n/locales/fr/cloud-portal.json b/packages/vue/src/i18n/locales/fr/cloud/portal.jsonsimilarity index 95%rename from packages/vue/src/i18n/locales/fr/cloud-portal.jsonrename to packages/vue/src/i18n/locales/fr/cloud/portal.jsonindex 8267dec20..713eac237 100644--- a/packages/vue/src/i18n/locales/fr/cloud-portal.json+++ b/packages/vue/src/i18n/locales/fr/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Aide","loading": "Chargement…","unavailableTitle": "Ce serveur ne répond pas","unavailableDescription": "Vérifiez l’adresse ou réessayez dans un instant.","tryAgain": "Réessayer","signInTitle": "Se connecter à OpenPencil Cloud","signUpTitle": "Créer votre compte",- "signInWelcome": "Bon retour parmi nous.",- "signUpDescription": "Créez un compte sur ce serveur.","returnsTo": "Vous reviendrez ensuite à {destination}.","returnsToDesktop": "l’app OpenPencil","returnsToEditor": "l’éditeur",@@ -23,7 +22,7 @@"signIn": "Se connecter","createAccount": "Créer le compte","haveAccount": "Vous avez déjà un compte ?",- "newHere": "Nouveau ici ?",+ "newHere": "Nouveau sur OpenPencil Cloud ?","createAnAccount": "Créer un compte","approvalTitle": "Un administrateur examine les nouveaux comptes","approvalDescription": "Vous pourrez vous connecter une fois votre demande approuvée. Nous vous préviendrons par e-mail.",@@ -235,5 +234,14 @@"errorNotAllowed": "Vous n’avez pas l’autorisation de faire cela.","errorNetwork": "Impossible de joindre le serveur. Vérifiez votre connexion.","errorAlreadyDecided": "Quelqu’un a déjà statué sur cette demande. Actualisez pour voir la décision.",- "passwordResetSent": "Nous vous avons envoyé par e-mail un lien pour définir un mot de passe."+ "passwordResetSent": "Nous vous avons envoyé par e-mail un lien pour définir un mot de passe.",+ "repeatPassword": "Répétez le mot de passe",+ "errorNameRequired": "Saisissez votre nom.",+ "errorEmailRequired": "Saisissez votre adresse e-mail.",+ "errorEmailInvalid": "Saisissez une adresse comme [email protected].",+ "errorPasswordRequired": "Saisissez votre mot de passe.",+ "errorPasswordTooShort": "Utilisez au moins {count} caractères.",+ "errorPasswordsDiffer": "Les mots de passe ne correspondent pas.",+ "verifiedTitle": "Adresse confirmée",+ "verifiedDescription": "Revenez à OpenPencil pour terminer la connexion. Vous pouvez fermer cet onglet."}diff --git a/packages/vue/src/i18n/locales/fr/common.json b/packages/vue/src/i18n/locales/fr/common.jsonindex eefb19751..e62208ad8 100644--- a/packages/vue/src/i18n/locales/fr/common.json+++ b/packages/vue/src/i18n/locales/fr/common.json@@ -38,5 +38,7 @@"tokens": "jetons","clear": "Effacer","dismiss": "Ignorer",- "browserSupport": "Vérifier la compatibilité"+ "browserSupport": "Vérifier la compatibilité",+ "showPassword": "Afficher le mot de passe",+ "hidePassword": "Masquer le mot de passe"}diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.jsonindex 58435d75c..5313f0be1 100644--- a/packages/vue/src/i18n/locales/fr/files.json+++ b/packages/vue/src/i18n/locales/fr/files.json@@ -25,5 +25,6 @@"newDesign": "Nouveau design","noMatchingFiles": "Aucun fichier ne correspond à « {query} ».","saveAsPrompt": "Enregistrer sous :",- "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place."+ "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place.",+ "newDesignIn": "Nouveau design dans {place}"}diff --git a/packages/vue/src/i18n/locales/fr/index.ts b/packages/vue/src/i18n/locales/fr/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/fr/index.ts+++ b/packages/vue/src/i18n/locales/fr/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex 5ada2dbf9..d3c59f761 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -7,11 +7,9 @@"text": "Texte","new": "Nouveau","open": "Ouvrir…",- "openStorageWorkspace": "Ouvrir l’espace de stockage…","openTour": "Ouvrir la visite","save": "Enregistrer","saveAs": "Enregistrer sous…",- "saveToStorage": "Enregistrer dans l’espace de stockage…","exportSelection": "Exporter la sélection…","autosave": "Enregistrement automatique","copy": "Copier",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Exporter la sélection en SVG","exportSelectionAsPPTX": "Exporter la sélection en PPTX","exportSelectionAsFig": "Exporter la sélection en .fig",- "togglePreview": "Aperçu"+ "togglePreview": "Aperçu",+ "browseFiles": "Parcourir les fichiers…",+ "saveTo": "Enregistrer dans…"}diff --git a/packages/vue/src/i18n/locales/fr/settings.json b/packages/vue/src/i18n/locales/fr/settings.jsonindex 0cf65dc09..e28bcba1f 100644--- a/packages/vue/src/i18n/locales/fr/settings.json+++ b/packages/vue/src/i18n/locales/fr/settings.json@@ -22,7 +22,8 @@"media": "Médias","mcp": "MCP","toolAccess": "Accès aux outils",- "storage": "Stockage cloud",+ "storage": "Stockage",+ "cloud": "Cloud","animations": "Animations","animationsSystem": "Suivre le système","animationsOff": "Désactivées",diff --git a/packages/vue/src/i18n/locales/fr/variables.json b/packages/vue/src/i18n/locales/fr/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/fr/variables.jsonrename to packages/vue/src/i18n/locales/fr/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/fr/variable-types.json b/packages/vue/src/i18n/locales/fr/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/fr/variable-types.jsonrename to packages/vue/src/i18n/locales/fr/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonnew file mode 100644index 000000000..681844d21--- /dev/null+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -0,0 +1,276 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Continua",+ "tryAgain": "Riprova",+ "signIn": "Accedi",+ "signOut": "Esci",+ "workspace": "Area di lavoro",+ "server": "Server",+ "share": "Condividi",+ "viewOnly": "Sola lettura",+ "canEdit": "Può modificare",+ "canView": "Può visualizzare",+ "roleViewer": "Visualizzatore",+ "roleEditor": "Editor",+ "roleAdmin": "Amministratore",+ "changedInTwoPlaces": "«{name}» è stato modificato in due posti",+ "conflictDescription": "Qualcuno ha salvato una versione più recente mentre avevi modifiche non inviate. Non si perde nulla finché non scegli.",+ "connectHeading": "Connettiti a OpenPencil Cloud",+ "connectDescription": "Mantieni i file sincronizzati tra i dispositivi e invita altre persone a modificarli con te.",+ "deviceHeading": "Conferma nel browser",+ "deviceDescription": "Approva questo accesso su {host}.",+ "deviceDescriptionNoHost": "Approva questo accesso sul server.",+ "officialDescription": "Ospitato da OpenPencil · {host}",+ "selfHostedLabel": "Il server del tuo team",+ "selfHostedDescription": "Un OpenPencil Cloud self-hosted",+ "serverAddress": "Indirizzo del server",+ "errorInvalidAddressHeading": "Inserisci l’indirizzo web del server",+ "errorInvalidAddressDescription": "Usa l’indirizzo che ti ha dato il tuo team, ad esempio https://cloud.example.com.",+ "errorUnreachableHeading": "Impossibile raggiungere questo server",+ "errorUnreachableDescription": "Controlla l’indirizzo e la connessione, poi riprova.",+ "errorNotCloudHeading": "Questo non è un server OpenPencil Cloud",+ "errorNotCloudDescription": "L’indirizzo ha risposto, ma non come OpenPencil Cloud. Chiedi al tuo team quello giusto.",+ "errorOutdatedHeading": "Questo server deve essere aggiornato",+ "errorOutdatedDescription": "Usa una versione di OpenPencil Cloud più vecchia di quella supportata da questa app.",+ "errorDeniedHeading": "Accesso negato",+ "errorDeniedDescription": "La richiesta è stata rifiutata nel browser. Ricomincia per accedere.",+ "errorExpiredHeading": "Il codice è scaduto",+ "errorExpiredDescription": "Non è stato approvato in tempo. Ricomincia per ottenerne uno nuovo.",+ "errorSignInFailedHeading": "Accesso non riuscito",+ "errorSignInFailedDescription": "Il server non ha completato l’accesso. Riprova tra un momento.",+ "continueWithGoogle": "Continua con Google",+ "continueWithApple": "Continua con Apple",+ "continueWithEmail": "Continua con email",+ "signInNoteDesktop": "Il browser si apre per completare l’accesso, poi torni qui.",+ "signInNoteBrowser": "Dopo l’accesso tornerai a questa scheda.",+ "yourCode": "Il tuo codice",+ "copyCode": "Copia codice",+ "deviceWaiting": "In attesa della tua approvazione… Il codice scade tra {duration}.",+ "openBrowserAgain": "Riapri il browser",+ "accountPending": "Il tuo account su {host} è in attesa dell’approvazione di un amministratore.",+ "signedInAs": "Accesso a {host} effettuato come {email}.",+ "invitationUnavailableHeading": "Questo invito non può essere usato",+ "invitationOpening": "Apertura dell’invito",+ "invitedYou": "{name} ti ha invitato",+ "invitationEditDescription": "A modificare un documento su {host}.",+ "invitationViewDescription": "A visualizzare un documento su {host}.",+ "invitationChecking": "Verifica dell’invito…",+ "invitationUnavailableDescription": "È scaduto, è stato ritirato o è già stato accettato. Chiedine uno nuovo a {name}.",+ "invitationUnavailableDescriptionNoName": "È scaduto, è stato ritirato o è già stato accettato. Chiedine uno nuovo a chi te l’ha inviato.",+ "invitationSentTo": "Inviato a {recipient}",+ "invitationExpiresIn": "Scade tra {duration}",+ "unknownServerHeading": "Non hai mai usato {host}",+ "unknownServerDescription": "Accedi solo se ti fidi di questo server. Archivia il documento e vede le tue modifiche.",+ "invitationSignInHeading": "Accedi a {host}",+ "invitationSignInDescription": "Usa l’account a cui è stato inviato questo invito. Il documento si apre subito dopo.",+ "wrongAccountHeading": "Questo invito è per un altro account",+ "wrongAccountDescription": "Hai effettuato l’accesso come {email}. Accedi con {recipient} per aprirlo.",+ "notNow": "Non ora",+ "signInToOpen": "Accedi per aprire",+ "useAnotherAccount": "Usa un altro account",+ "openDocument": "Apri documento",+ "saveHeading": "Scegli dove salvare",+ "saveDescription": "Mantieni questo design sincronizzato tra i dispositivi e condividilo con altre persone.",+ "saveName": "Nome",+ "saveQuotaHeading": "Quest’area di lavoro ha esaurito lo spazio",+ "saveQuotaDescription": "Libera spazio o scegli un’altra area di lavoro.",+ "saveOfflineHeading": "Sei offline",+ "saveOfflineDescription": "Connettiti a internet per salvare nel cloud. Su questo dispositivo non è cambiato nulla.",+ "saveFailedHeading": "Impossibile salvare",+ "saveFailedDescription": "Il server non ha accettato il file. Riprova tra un momento.",+ "saveUploading": "Caricamento… {sent} di {total}",+ "saveTooLargeHeading": "Questo file è troppo grande per questo server",+ "saveTooLargeDescription": "Accetta file fino a {limit}. Rimuovi le immagini o le pagine inutilizzate, poi riprova.",+ "saveNote": "La copia salvata si apre in questa scheda e si salva mentre lavori. Il file su questo dispositivo resta com’è.",+ "shareHeading": "Condividi «{name}»",+ "shareDescriptionInWorkspace": "In {workspace} su OpenPencil Cloud",+ "shareDescription": "Su OpenPencil Cloud",+ "shareAddPeople": "Aggiungi persone tramite email",+ "shareEmailAddress": "Indirizzo email",+ "shareNewPeoplePermission": "Autorizzazione per le nuove persone",+ "shareInvite": "Invita",+ "sharePeopleWithAccess": "Persone con accesso",+ "shareYou": "(tu)",+ "shareInvited": "Invitato",+ "shareInvitationExpires": "L’invito scade il {date}",+ "shareAccessFor": "Accesso per {name}",+ "shareOwner": "Proprietario",+ "shareRemoveAccess": "Revoca accesso",+ "shareEveryoneIn": "Tutti in {workspace}",+ "shareMemberCount": {+ "one": "{count} membro",+ "many": "{count} membri"+ },+ "shareWorkspacePermissionTip": "Impostato dall’area di lavoro; modificalo nelle sue impostazioni",+ "shareGeneralAccess": "Accesso generale",+ "shareRestricted": "Solo persone con accesso",+ "shareAnyoneWithLink": "Chiunque abbia il link",+ "shareLinkDetail": "Chiunque abbia il link può aprire questo file senza accedere.",+ "shareRestrictedDetail": "Solo le persone e l’area di lavoro indicate sopra possono aprire questo file.",+ "shareRestrictedNoLinksDetail": "Solo le persone e l’area di lavoro indicate sopra possono aprire questo file. I link sono disattivati per quest’area di lavoro.",+ "shareLinkPermission": "Autorizzazione del link",+ "shareCannotManage": "Solo il proprietario e gli editor possono modificare chi ha accesso.",+ "shareResetLinkTip": "Questo link è stato creato su un altro dispositivo. Reimpostandolo se ne crea uno nuovo e quello vecchio smette di funzionare.",+ "shareResetLink": "Reimposta link",+ "shareLinkCopied": "Link copiato",+ "shareCopyLink": "Copia link",+ "shareLoadFailed": "Impossibile caricare chi ha accesso. Controlla la connessione e riprova.",+ "shareChangeFailed": "La modifica non è andata a buon fine. Riprova tra un momento.",+ "conflictKeepBoth": "Mantieni entrambe",+ "conflictKeepBothDescription": "La versione nel cloud resta «{name}». La tua viene salvata accanto come «{copyName}».",+ "conflictUseCloud": "Usa la versione nel cloud",+ "conflictUseCloudDescription": "Le modifiche non inviate su questo dispositivo vengono scartate.",+ "conflictUseMine": "Sostituiscila con la tua versione",+ "conflictUseMineDescriptionBy": "Le ultime modifiche di {name} vengono sostituite per tutti.",+ "conflictUseMineDescription": "La versione più recente sul server viene sostituita per tutti.",+ "conflictConfirmUseCloud": "Usa versione nel cloud",+ "conflictConfirmUseMine": "Sostituisci con la mia",+ "conflictYourVersion": "La tua versione",+ "conflictCloudVersion": "Versione nel cloud",+ "conflictWhichVersion": "Quale versione mantenere",+ "conflictDecideLater": "Decidi più tardi",+ "conflictYourCopyName": "{name} (la tua copia)",+ "conflictYouOnThisDevice": "Tu, su questo dispositivo",+ "conflictResolveFailed": "Impossibile risolvere il conflitto. Le tue modifiche sono ancora su questo dispositivo.",+ "statusViewOnlyDetail": "Puoi esplorare e seguire gli altri; le tue modifiche non arriveranno a nessuno.",+ "statusSavedTo": "Salvato in {workspace}",+ "statusSavedAgo": "Salvato {time}",+ "statusUpToDate": "Aggiornato",+ "statusSaving": "Salvataggio…",+ "statusUploadingTo": "Caricamento in {workspace}",+ "statusSavedOnDevice": "Salvato su questo dispositivo",+ "statusUploadsSoon": "Caricamento tra un momento",+ "statusOfflineDetail": "Sei offline. Le modifiche verranno caricate quando ti riconnetti.",+ "statusConflict": "Modificato in due posti",+ "statusConflictDetail": "Qualcuno ha salvato una versione più recente mentre modificavi. Scegli quale mantenere.",+ "statusErrorDetail": "Le tue modifiche sono al sicuro su questo dispositivo.",+ "statusResolve": "Risolvi",+ "statusChooseVersion": "Scegli una versione",+ "statusOpenWorkspace": "Apri area di lavoro",+ "settingsDescription": "Server con cui questa app sincronizza i documenti. Home mostra le aree di lavoro di un server alla volta.",+ "settingsEmptyDescription": "Mantieni i file sincronizzati tra i dispositivi e modificali con altre persone. I documenti su questo dispositivo restano dove sono.",+ "settingsConnectServer": "Connetti un server",+ "settingsOfficialDescription": "Ospitato da OpenPencil, nulla da configurare.",+ "settingsSelfHostedDescription": "Un OpenPencil Cloud self-hosted, all’indirizzo usato dal tuo team.",+ "settingsOnHome": "In Home",+ "settingsSignInExpired": "Accesso scaduto",+ "settingsSignInExpiredFor": "Accesso scaduto per {email}",+ "settingsSignedOut": "Disconnesso",+ "settingsWaitingForApproval": "In attesa che un amministratore approvi il tuo account",+ "settingsAccessClosed": "Un amministratore ha rifiutato o revocato il tuo accesso",+ "settingsOptionsFor": "Opzioni per {host}",+ "settingsAccountAndSecurity": "Account e sicurezza",+ "settingsShowOnHome": "Mostra in Home",+ "settingsDisconnectServer": "Disconnetti server",+ "settingsSignOutFailed": "Impossibile uscire. Controlla la connessione e riprova.",+ "settingsDisconnectHeading": "Disconnettere {host}?",+ "settingsDisconnectDescription": "Esci dall’account e le sue aree di lavoro spariscono dalla Home su questo dispositivo. I tuoi documenti restano sul server e puoi riconnetterti quando vuoi.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Esci dall’account e le sue aree di lavoro spariscono dalla Home su questo dispositivo. {count} documento ha modifiche non ancora arrivate al server; disconnettendo vanno perse.",+ "many": "Esci dall’account e le sue aree di lavoro spariscono dalla Home su questo dispositivo. {count} documenti hanno modifiche non ancora arrivate al server; disconnettendo vanno perse."+ },+ "settingsDisconnect": "Disconnetti",+ "settingsDisconnectAndDiscard": "Disconnetti e scarta le modifiche",+ "homeLocations": "Posizioni",+ "homeRecent": "Recenti",+ "homeAccount": "Account: {email}",+ "homeAccountSettings": "Impostazioni account",+ "homeConnectAnotherServer": "Connetti un altro server…",+ "homeAttentionTip": "Un file qui richiede una scelta",+ "homeNeedsAttention": "Richiede attenzione",+ "homeSharedWithYou": "Condivisi con te",+ "homeSharedSubtitle": "File a cui sei stato invitato",+ "homeSharedBy": "Condiviso da {name}",+ "homeSignIn": "Accedi…",+ "homeStorage": "Archiviazione",+ "homeStorageSettings": "Impostazioni di archiviazione",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "{used} utilizzati",+ "homeUsageOf": "{used} di {total}",+ "homeWorkspaceStorage": "Spazio dell’area di lavoro, {usage}",+ "homeView": "Vista",+ "homeGrid": "Griglia",+ "homeList": "Elenco",+ "homeOfflineHeading": "Sei offline",+ "homeOfflineDescription": "Questi sono i file salvati su questo dispositivo. Le modifiche verranno caricate quando ti riconnetti.",+ "homeLoadFailedHeading": "Impossibile caricare quest’area di lavoro",+ "homeLoadFailedDescription": "Il server non ha risposto. I file salvati su questo dispositivo restano in elenco.",+ "homeConflicts": {+ "one": "{count} file è stato modificato in due posti",+ "many": "{count} file sono stati modificati in due posti"+ },+ "homeReview": "Esamina",+ "homeLoadingFiles": "Caricamento file",+ "homeEmptyWorkspace": "Ancora nessun file in {workspace}",+ "homeEmptyWorkspaceDescription": "Crea un design qui o salva un file aperto in quest’area di lavoro dal menu File.",+ "homeNothingShared": "Nessun file condiviso con te",+ "homeNothingSharedDescription": "Qui compaiono i file a cui vieni invitato.",+ "homeNewDesign": "Nuovo design",+ "homeViewOnlyTip": "Puoi visualizzare questo file",+ "homeSharedTip": "Condiviso con persone esterne all’area di lavoro",+ "homeShared": "Condiviso",+ "syncSynced": "Salvato nel cloud",+ "syncUploading": "Caricamento delle modifiche…",+ "syncPending": "Modifiche salvate su questo dispositivo, in attesa di caricamento",+ "syncOffline": "Offline: le modifiche sono salvate su questo dispositivo",+ "syncConflict": "Modificato anche altrove: scegli quale versione mantenere",+ "syncError": "Impossibile caricare le modifiche",+ "shareLinkFailed": "Questo link non apre un documento. Chiedine uno nuovo.",+ "connectServerHeading": "Collega il server del tuo team",+ "connectServerDescription": "Inserisci l’indirizzo che il tuo team usa per OpenPencil Cloud.",+ "checkingServer": "Verifica del server…",+ "signInHeading": "Accedi a {name}",+ "onHost": "Su {host}.",+ "verifyDescription": "Abbiamo inviato un link a {email}.",+ "verifyNote": "Apri il link nell’email, poi torna qui. L’accesso si completa da solo.",+ "verifyNotYet": "La tua email non è ancora confermata. Apri il link nell’email, poi riprova.",+ "verifyNoEmail": "Nessuna email?",+ "settingsTitle": "Cloud",+ "saveWhere": "Posizione",+ "saveAction": "Salva",+ "saveStorageGroup": "Archiviazione",+ "invitationWorkspaceDescription": "Per entrare in un’area di lavoro su {host}.",+ "joinWorkspace": "Entra nell’area",+ "homeNewWorkspace": "Nuova area di lavoro",+ "homeMembers": "Membri",+ "newWorkspaceHeading": "Nuova area di lavoro",+ "newWorkspaceDescription": "Un posto per i design del tuo team. Decidi tu chi entra.",+ "workspaceName": "Nome dell’area",+ "workspaceNamePlaceholder": "Team design",+ "createWorkspace": "Crea area",+ "renameWorkspace": "Rinomina",+ "membersDescription": "Tutti qui vedono i documenti dell’area; editor e admin li modificano.",+ "invitePeople": "Invita persone",+ "inviteEmail": "Indirizzo email",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Ruolo",+ "invite": "Invita",+ "invitationSentNote": "Abbiamo inviato l’invito via email. Se questo server non invia email, condividi questo link.",+ "copyInvitationLink": "Copia link di invito",+ "membersLoading": "Caricamento dei membri…",+ "memberRole": "Ruolo di {name}",+ "removeMember": "Rimuovi {name}",+ "pendingInvitations": "In attesa di entrare",+ "revokeInvitation": "Ritira",+ "leaveWorkspace": "Lascia l’area",+ "workspaceAlreadyMember": "È già in quest’area di lavoro.",+ "workspaceLastAdmin": "Un’area ha bisogno di un admin. Prima rendi admin qualcun altro.",+ "workspaceForbidden": "Solo gli admin dell’area possono farlo.",+ "workspaceNotFound": "Quest’area o invito non esiste più. Chiudi e riprova.",+ "workspaceFailed": "Impossibile modificare l’area. Riprova tra poco.",+ "unknownServerWorkspaceDescription": "Accedi solo se ti fidi di questo server. Conserva i documenti dell’area e vede le tue modifiche.",+ "leaveWorkspaceHeading": "Lasciare {workspace}?",+ "leaveWorkspaceDescription": "Perdi l’accesso ai suoi documenti, salvo quelli condivisi direttamente con te. Un admin può invitarti di nuovo.",+ "removeMemberHeading": "Rimuovere {name} da {workspace}?",+ "removeMemberDescription": "Perde l’accesso ai documenti, salvo quelli condivisi direttamente. Puoi invitarla di nuovo.",+ "removeMemberConfirm": "Rimuovi",+ "deleteWorkspace": "Elimina area",+ "deleteWorkspaceHeading": "Eliminare {workspace}?",+ "deleteWorkspaceDescription": "Tutti perdono l’accesso e i suoi inviti smettono di funzionare. Si può eliminare solo un’area vuota.",+ "deleteWorkspaceTypeName": "Per confermare, digita «{workspace}».",+ "dangerZone": "Zona pericolosa",+ "leaveWorkspaceShort": "Esci",+ "deleteWorkspaceShort": "Elimina",+ "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."+}diff --git a/packages/vue/src/i18n/locales/it/cloud-portal.json b/packages/vue/src/i18n/locales/it/cloud/portal.jsonsimilarity index 95%rename from packages/vue/src/i18n/locales/it/cloud-portal.jsonrename to packages/vue/src/i18n/locales/it/cloud/portal.jsonindex 18f078a9a..f1c732aee 100644--- a/packages/vue/src/i18n/locales/it/cloud-portal.json+++ b/packages/vue/src/i18n/locales/it/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Aiuto","loading": "Caricamento…","unavailableTitle": "Questo server non risponde","unavailableDescription": "Controlla l’indirizzo o riprova tra un momento.","tryAgain": "Riprova","signInTitle": "Accedi a OpenPencil Cloud","signUpTitle": "Crea il tuo account",- "signInWelcome": "Bentornato.",- "signUpDescription": "Crea un account su questo server.","returnsTo": "Poi tornerai a {destination}.","returnsToDesktop": "l’app OpenPencil","returnsToEditor": "l’editor",@@ -23,7 +22,7 @@"signIn": "Accedi","createAccount": "Crea account","haveAccount": "Hai già un account?",- "newHere": "Sei nuovo?",+ "newHere": "Nuovo su OpenPencil Cloud?","createAnAccount": "Crea un account","approvalTitle": "Un amministratore esamina i nuovi account","approvalDescription": "Potrai accedere quando la tua richiesta sarà approvata. Ti avviseremo via email.",@@ -235,5 +234,14 @@"errorNotAllowed": "Non hai l’autorizzazione per farlo.","errorNetwork": "Impossibile raggiungere il server. Controlla la connessione.","errorAlreadyDecided": "Qualcuno ha già deciso su questa richiesta. Aggiorna per vederla.",- "passwordResetSent": "Ti abbiamo inviato via email un link per impostare una password."+ "passwordResetSent": "Ti abbiamo inviato via email un link per impostare una password.",+ "repeatPassword": "Ripeti la password",+ "errorNameRequired": "Inserisci il tuo nome.",+ "errorEmailRequired": "Inserisci il tuo indirizzo email.",+ "errorEmailInvalid": "Inserisci un indirizzo come [email protected].",+ "errorPasswordRequired": "Inserisci la password.",+ "errorPasswordTooShort": "Usa almeno {count} caratteri.",+ "errorPasswordsDiffer": "Le password non coincidono.",+ "verifiedTitle": "Email confermata",+ "verifiedDescription": "Torna a OpenPencil per completare l’accesso. Puoi chiudere questa scheda."}diff --git a/packages/vue/src/i18n/locales/it/common.json b/packages/vue/src/i18n/locales/it/common.jsonindex 574154d8f..ddb3b892a 100644--- a/packages/vue/src/i18n/locales/it/common.json+++ b/packages/vue/src/i18n/locales/it/common.json@@ -38,5 +38,7 @@"tokens": "token","clear": "Cancella","dismiss": "Chiudi",- "browserSupport": "Verifica il supporto"+ "browserSupport": "Verifica il supporto",+ "showPassword": "Mostra password",+ "hidePassword": "Nascondi password"}diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.jsonindex d48e3cd68..317d3096b 100644--- a/packages/vue/src/i18n/locales/it/files.json+++ b/packages/vue/src/i18n/locales/it/files.json@@ -25,5 +25,6 @@"newDesign": "Nuovo design","noMatchingFiles": "Nessun file corrisponde a «{query}».","saveAsPrompt": "Salva con nome:",- "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente."+ "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente.",+ "newDesignIn": "Nuovo design in {place}"}diff --git a/packages/vue/src/i18n/locales/it/index.ts b/packages/vue/src/i18n/locales/it/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/it/index.ts+++ b/packages/vue/src/i18n/locales/it/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 944af19ff..71f0c6733 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -7,11 +7,9 @@"text": "Testo","new": "Nuovo","open": "Apri…",- "openStorageWorkspace": "Apri area di archiviazione…","openTour": "Apri il tour","save": "Salva","saveAs": "Salva con nome…",- "saveToStorage": "Salva nell’area di archiviazione…","exportSelection": "Esporta selezione…","autosave": "Salvataggio automatico su file","copy": "Copia",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Esporta selezione come SVG","exportSelectionAsPPTX": "Esporta selezione come PPTX","exportSelectionAsFig": "Esporta selezione come .fig",- "togglePreview": "Anteprima"+ "togglePreview": "Anteprima",+ "browseFiles": "Sfoglia file…",+ "saveTo": "Salva in…"}diff --git a/packages/vue/src/i18n/locales/it/settings.json b/packages/vue/src/i18n/locales/it/settings.jsonindex 38a2dfab9..925f108a4 100644--- a/packages/vue/src/i18n/locales/it/settings.json+++ b/packages/vue/src/i18n/locales/it/settings.json@@ -22,7 +22,8 @@"media": "Media","mcp": "MCP","toolAccess": "Accesso agli strumenti",- "storage": "Archiviazione cloud",+ "storage": "Archiviazione",+ "cloud": "Cloud","animations": "Animazioni","animationsSystem": "Segui il sistema","animationsOff": "Disattivate",diff --git a/packages/vue/src/i18n/locales/it/variables.json b/packages/vue/src/i18n/locales/it/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/it/variables.jsonrename to packages/vue/src/i18n/locales/it/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/it/variable-types.json b/packages/vue/src/i18n/locales/it/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/it/variable-types.jsonrename to packages/vue/src/i18n/locales/it/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonnew file mode 100644index 000000000..085011f81--- /dev/null+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -0,0 +1,273 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "続行",+ "tryAgain": "もう一度試す",+ "signIn": "サインイン",+ "signOut": "サインアウト",+ "workspace": "ワークスペース",+ "server": "サーバー",+ "share": "共有",+ "viewOnly": "閲覧のみ",+ "canEdit": "編集可能",+ "canView": "閲覧可能",+ "roleViewer": "閲覧者",+ "roleEditor": "編集者",+ "roleAdmin": "管理者",+ "changedInTwoPlaces": "「{name}」が2か所で変更されました",+ "conflictDescription": "未送信の変更があるあいだに、誰かが新しいバージョンを保存しました。選択するまで何も失われません。",+ "connectHeading": "OpenPencil Cloud に接続",+ "connectDescription": "デバイス間でファイルを同期し、他の人を招待して一緒に編集できます。",+ "deviceHeading": "ブラウザで確認してください",+ "deviceDescription": "{host} でこのサインインを承認してください。",+ "deviceDescriptionNoHost": "サーバーでこのサインインを承認してください。",+ "officialDescription": "OpenPencil がホスト · {host}",+ "selfHostedLabel": "チームのサーバー",+ "selfHostedDescription": "セルフホストの OpenPencil Cloud",+ "serverAddress": "サーバーのアドレス",+ "errorInvalidAddressHeading": "サーバーのウェブアドレスを入力してください",+ "errorInvalidAddressDescription": "チームから伝えられたアドレス(例:https://cloud.example.com)を入力してください。",+ "errorUnreachableHeading": "このサーバーに接続できませんでした",+ "errorUnreachableDescription": "アドレスと接続を確認して、もう一度お試しください。",+ "errorNotCloudHeading": "これは OpenPencil Cloud のサーバーではありません",+ "errorNotCloudDescription": "このアドレスは応答しましたが、OpenPencil Cloud ではありませんでした。正しいアドレスをチームに確認してください。",+ "errorOutdatedHeading": "このサーバーはアップデートが必要です",+ "errorOutdatedDescription": "このアプリが対応しているより古いバージョンの OpenPencil Cloud が動作しています。",+ "errorDeniedHeading": "サインインが拒否されました",+ "errorDeniedDescription": "ブラウザでリクエストが拒否されました。もう一度サインインを始めてください。",+ "errorExpiredHeading": "コードの有効期限が切れました",+ "errorExpiredDescription": "時間内に承認されませんでした。もう一度始めて、新しいコードを取得してください。",+ "errorSignInFailedHeading": "サインインできませんでした",+ "errorSignInFailedDescription": "サーバーでサインインが完了しませんでした。しばらくしてからもう一度お試しください。",+ "continueWithGoogle": "Google で続行",+ "continueWithApple": "Apple で続行",+ "continueWithEmail": "メールアドレスで続行",+ "signInNoteDesktop": "ブラウザが開くのでサインインを完了し、その後ここに戻ってください。",+ "signInNoteBrowser": "サインイン後、このタブに戻ります。",+ "yourCode": "あなたのコード",+ "copyCode": "コードをコピー",+ "deviceWaiting": "承認を待っています… コードの有効期限まであと{duration}です。",+ "openBrowserAgain": "ブラウザをもう一度開く",+ "accountPending": "{host} のアカウントは管理者の承認待ちです。",+ "signedInAs": "{host} に {email} としてサインインしています。",+ "invitationUnavailableHeading": "この招待は使用できません",+ "invitationOpening": "招待を開いています",+ "invitedYou": "{name} さんから招待が届きました",+ "invitationEditDescription": "{host} のドキュメントを編集するための招待です。",+ "invitationViewDescription": "{host} のドキュメントを閲覧するための招待です。",+ "invitationChecking": "招待を確認しています…",+ "invitationUnavailableDescription": "有効期限が切れたか、取り消されたか、すでに承諾されています。{name} さんに新しい招待を依頼してください。",+ "invitationUnavailableDescriptionNoName": "有効期限が切れたか、取り消されたか、すでに承諾されています。送信者に新しい招待を依頼してください。",+ "invitationSentTo": "{recipient} 宛て",+ "invitationExpiresIn": "有効期限まであと{duration}",+ "unknownServerHeading": "{host} を使うのは初めてです",+ "unknownServerDescription": "信頼できるサーバーの場合だけサインインしてください。サーバーはドキュメントを保存し、あなたの編集内容を見ることができます。",+ "invitationSignInHeading": "{host} にサインイン",+ "invitationSignInDescription": "この招待が送られたアカウントを使ってください。サインインするとすぐにドキュメントが開きます。",+ "wrongAccountHeading": "この招待は別のアカウント宛てです",+ "wrongAccountDescription": "{email} でサインインしています。開くには {recipient} でサインインしてください。",+ "notNow": "今はしない",+ "signInToOpen": "サインインして開く",+ "useAnotherAccount": "別のアカウントを使う",+ "openDocument": "ドキュメントを開く",+ "saveHeading": "保存先を選択",+ "saveDescription": "このデザインをデバイス間で同期し、他の人と共有できます。",+ "saveName": "名前",+ "saveQuotaHeading": "このワークスペースの容量が不足しています",+ "saveQuotaDescription": "空き容量を増やすか、別のワークスペースを選択してください。",+ "saveOfflineHeading": "オフラインです",+ "saveOfflineDescription": "クラウドに保存するにはインターネットに接続してください。このデバイスでは何も変更されていません。",+ "saveFailedHeading": "保存できませんでした",+ "saveFailedDescription": "サーバーがファイルを受け付けませんでした。しばらくしてからもう一度お試しください。",+ "saveUploading": "アップロード中… {sent} / {total}",+ "saveTooLargeHeading": "このファイルはこのサーバーには大きすぎます",+ "saveTooLargeDescription": "このサーバーで扱えるファイルは {limit} までです。使っていない画像やページを削除してから、もう一度お試しください。",+ "saveNote": "保存したコピーはこのタブで開き、作業しながら保存されます。このデバイスのファイルはそのままです。",+ "shareHeading": "「{name}」を共有",+ "shareDescriptionInWorkspace": "OpenPencil Cloud の {workspace}",+ "shareDescription": "OpenPencil Cloud 上",+ "shareAddPeople": "メールアドレスでユーザーを追加",+ "shareEmailAddress": "メールアドレス",+ "shareNewPeoplePermission": "追加するユーザーの権限",+ "shareInvite": "招待",+ "sharePeopleWithAccess": "アクセスできるユーザー",+ "shareYou": "(あなた)",+ "shareInvited": "招待済み",+ "shareInvitationExpires": "招待の有効期限:{date}",+ "shareAccessFor": "{name} のアクセス権",+ "shareOwner": "オーナー",+ "shareRemoveAccess": "アクセスを削除",+ "shareEveryoneIn": "{workspace} の全員",+ "shareMemberCount": {+ "many": "メンバー {count} 人"+ },+ "shareWorkspacePermissionTip": "ワークスペースで設定されています。変更するにはワークスペースの設定を開いてください",+ "shareGeneralAccess": "一般的なアクセス",+ "shareRestricted": "アクセス権のあるユーザーのみ",+ "shareAnyoneWithLink": "リンクを知っている全員",+ "shareLinkDetail": "リンクを知っている人は誰でも、サインインせずにこのファイルを開けます。",+ "shareRestrictedDetail": "このファイルを開けるのは、上記のユーザーとワークスペースだけです。",+ "shareRestrictedNoLinksDetail": "このファイルを開けるのは、上記のユーザーとワークスペースだけです。このワークスペースではリンクがオフになっています。",+ "shareLinkPermission": "リンクの権限",+ "shareCannotManage": "アクセスできるユーザーを変更できるのは、オーナーと編集者だけです。",+ "shareResetLinkTip": "このリンクは別のデバイスで作成されました。リセットすると新しいリンクが作成され、古いリンクは使えなくなります。",+ "shareResetLink": "リンクをリセット",+ "shareLinkCopied": "リンクをコピーしました",+ "shareCopyLink": "リンクをコピー",+ "shareLoadFailed": "アクセスできるユーザーを読み込めませんでした。接続を確認して、もう一度お試しください。",+ "shareChangeFailed": "変更を反映できませんでした。しばらくしてからもう一度お試しください。",+ "conflictKeepBoth": "両方を残す",+ "conflictKeepBothDescription": "クラウドのバージョンは「{name}」のまま残り、あなたのバージョンはその隣に「{copyName}」として保存されます。",+ "conflictUseCloud": "クラウドのバージョンを使う",+ "conflictUseCloudDescription": "このデバイスの未送信の変更は破棄されます。",+ "conflictUseMine": "あなたのバージョンで置き換える",+ "conflictUseMineDescriptionBy": "{name} さんの最新の変更が、全員に対して置き換えられます。",+ "conflictUseMineDescription": "サーバー上の新しいバージョンが、全員に対して置き換えられます。",+ "conflictConfirmUseCloud": "クラウドのバージョンを使用",+ "conflictConfirmUseMine": "自分のバージョンで置き換え",+ "conflictYourVersion": "あなたのバージョン",+ "conflictCloudVersion": "クラウドのバージョン",+ "conflictWhichVersion": "残すバージョン",+ "conflictDecideLater": "あとで決める",+ "conflictYourCopyName": "{name}(あなたのコピー)",+ "conflictYouOnThisDevice": "このデバイスのあなた",+ "conflictResolveFailed": "競合を解決できませんでした。変更はこのデバイスに残っています。",+ "statusViewOnlyDetail": "閲覧や他の人のフォローはできますが、変更は誰にも届きません。",+ "statusSavedTo": "{workspace} に保存済み",+ "statusSavedAgo": "{time}に保存",+ "statusUpToDate": "最新の状態",+ "statusSaving": "保存中…",+ "statusUploadingTo": "{workspace} にアップロード中",+ "statusSavedOnDevice": "このデバイスに保存済み",+ "statusUploadsSoon": "まもなくアップロードされます",+ "statusOfflineDetail": "オフラインです。再接続すると変更がアップロードされます。",+ "statusConflict": "2か所で変更されました",+ "statusConflictDetail": "編集中に誰かが新しいバージョンを保存しました。残すバージョンを選んでください。",+ "statusErrorDetail": "変更はこのデバイスに安全に保存されています。",+ "statusResolve": "解決",+ "statusChooseVersion": "バージョンを選択",+ "statusOpenWorkspace": "ワークスペースを開く",+ "settingsDescription": "このアプリがドキュメントを同期するサーバーです。ホームには一度に1つのサーバーのワークスペースが表示されます。",+ "settingsEmptyDescription": "デバイス間でファイルを同期し、他の人と一緒に編集できます。このデバイスのドキュメントはそのまま残ります。",+ "settingsConnectServer": "サーバーに接続",+ "settingsOfficialDescription": "OpenPencil がホストするため、設定は不要です。",+ "settingsSelfHostedDescription": "チームが使用しているアドレスにある、セルフホストの OpenPencil Cloud です。",+ "settingsOnHome": "ホームに表示中",+ "settingsSignInExpired": "サインインの有効期限切れ",+ "settingsSignInExpiredFor": "{email} のサインインの有効期限が切れました",+ "settingsSignedOut": "サインアウト済み",+ "settingsWaitingForApproval": "管理者によるアカウントの承認待ち",+ "settingsAccessClosed": "管理者がアクセスを却下または削除しました",+ "settingsOptionsFor": "{host} のオプション",+ "settingsAccountAndSecurity": "アカウントとセキュリティ",+ "settingsShowOnHome": "ホームに表示",+ "settingsDisconnectServer": "サーバーとの接続を解除",+ "settingsSignOutFailed": "サインアウトできませんでした。接続を確認して、もう一度お試しください。",+ "settingsDisconnectHeading": "{host} との接続を解除しますか?",+ "settingsDisconnectDescription": "サインアウトされ、このデバイスのホームからワークスペースが消えます。ドキュメントはサーバーに残り、いつでも再接続できます。",+ "settingsDisconnectUnsavedDescription": {+ "many": "サインアウトされ、このデバイスのホームからワークスペースが消えます。{count} 件のドキュメントにまだサーバーに届いていない変更があり、接続を解除すると破棄されます。"+ },+ "settingsDisconnect": "接続を解除",+ "settingsDisconnectAndDiscard": "接続を解除して変更を破棄",+ "homeLocations": "場所",+ "homeRecent": "最近",+ "homeAccount": "アカウント:{email}",+ "homeAccountSettings": "アカウント設定",+ "homeConnectAnotherServer": "別のサーバーに接続…",+ "homeAttentionTip": "選択が必要なファイルがあります",+ "homeNeedsAttention": "要対応",+ "homeSharedWithYou": "あなたと共有",+ "homeSharedSubtitle": "招待されたファイル",+ "homeSharedBy": "{name} さんが共有",+ "homeSignIn": "サインイン…",+ "homeStorage": "ストレージ",+ "homeStorageSettings": "ストレージ設定",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "{used} 使用中",+ "homeUsageOf": "{used} / {total}",+ "homeWorkspaceStorage": "ワークスペースのストレージ:{usage}",+ "homeView": "表示",+ "homeGrid": "グリッド",+ "homeList": "リスト",+ "homeOfflineHeading": "オフラインです",+ "homeOfflineDescription": "このデバイスに保存されているファイルです。再接続すると変更がアップロードされます。",+ "homeLoadFailedHeading": "このワークスペースを読み込めませんでした",+ "homeLoadFailedDescription": "サーバーが応答しませんでした。このデバイスに保存されたファイルは引き続き表示されます。",+ "homeConflicts": {+ "many": "{count} 件のファイルが2か所で変更されました"+ },+ "homeReview": "確認",+ "homeLoadingFiles": "ファイルを読み込み中",+ "homeEmptyWorkspace": "{workspace} にはまだファイルがありません",+ "homeEmptyWorkspaceDescription": "ここでデザインを作成するか、「ファイル」メニューから開いているファイルをこのワークスペースに保存してください。",+ "homeNothingShared": "共有されたファイルはまだありません",+ "homeNothingSharedDescription": "招待されたファイルはここに表示されます。",+ "homeNewDesign": "新規デザイン",+ "homeViewOnlyTip": "このファイルは閲覧のみ可能です",+ "homeSharedTip": "ワークスペース外のユーザーと共有中",+ "homeShared": "共有中",+ "syncSynced": "クラウドに保存済み",+ "syncUploading": "変更をアップロード中…",+ "syncPending": "変更はこのデバイスに保存済みで、アップロード待ちです",+ "syncOffline": "オフライン:変更はこのデバイスに保存されています",+ "syncConflict": "他の場所でも編集されました。残すバージョンを選んでください",+ "syncError": "変更をアップロードできませんでした",+ "shareLinkFailed": "このリンクではドキュメントを開けません。新しいリンクを依頼してください。",+ "connectServerHeading": "チームのサーバーに接続",+ "connectServerDescription": "チームが OpenPencil Cloud に使っているアドレスを入力してください。",+ "checkingServer": "サーバーを確認しています…",+ "signInHeading": "{name} にサインイン",+ "onHost": "{host} 上。",+ "verifyDescription": "{email} にリンクを送信しました。",+ "verifyNote": "メールのリンクを開いてから、ここに戻ってください。サインインは自動で完了します。",+ "verifyNotYet": "メールアドレスはまだ確認されていません。メールのリンクを開いてから、もう一度お試しください。",+ "verifyNoEmail": "メールが届かない場合",+ "settingsTitle": "クラウド",+ "saveWhere": "場所",+ "saveAction": "保存",+ "saveStorageGroup": "ストレージ",+ "invitationWorkspaceDescription": "{host} のワークスペースに参加します。",+ "joinWorkspace": "ワークスペースに参加",+ "homeNewWorkspace": "新規ワークスペース",+ "homeMembers": "メンバー",+ "newWorkspaceHeading": "新規ワークスペース",+ "newWorkspaceDescription": "チームとデザインを置く場所です。参加者はあなたが管理します。",+ "workspaceName": "ワークスペース名",+ "workspaceNamePlaceholder": "デザインチーム",+ "createWorkspace": "ワークスペースを作成",+ "renameWorkspace": "名前を変更",+ "membersDescription": "ここにいる全員がワークスペースのドキュメントを閲覧でき、編集者と管理者は変更できます。",+ "invitePeople": "メンバーを招待",+ "inviteEmail": "メールアドレス",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "役割",+ "invite": "招待",+ "invitationSentNote": "招待をメールで送信しました。このサーバーがメールを送信しない場合は、このリンクを共有してください。",+ "copyInvitationLink": "招待リンクをコピー",+ "membersLoading": "メンバーを読み込んでいます…",+ "memberRole": "{name} の役割",+ "removeMember": "{name} を削除",+ "pendingInvitations": "参加待ち",+ "revokeInvitation": "取り消す",+ "leaveWorkspace": "ワークスペースから退出",+ "workspaceAlreadyMember": "すでにこのワークスペースのメンバーです。",+ "workspaceLastAdmin": "ワークスペースには管理者が必要です。先に別のメンバーを管理者にしてください。",+ "workspaceForbidden": "この操作はワークスペースの管理者のみ行えます。",+ "workspaceNotFound": "このワークスペースまたは招待はもうありません。閉じてもう一度お試しください。",+ "workspaceFailed": "ワークスペースを変更できませんでした。しばらくしてからもう一度お試しください。",+ "unknownServerWorkspaceDescription": "このサーバーを信頼できる場合のみサインインしてください。ワークスペースのドキュメントを保存し、あなたの編集内容を見ることができます。",+ "leaveWorkspaceHeading": "{workspace} から退出しますか?",+ "leaveWorkspaceDescription": "直接共有されたものを除き、ドキュメントにアクセスできなくなります。管理者が再度招待できます。",+ "removeMemberHeading": "{name} を {workspace} から削除しますか?",+ "removeMemberDescription": "直接共有されたものを除き、ドキュメントにアクセスできなくなります。再度招待できます。",+ "removeMemberConfirm": "削除",+ "deleteWorkspace": "ワークスペースを削除",+ "deleteWorkspaceHeading": "{workspace} を削除しますか?",+ "deleteWorkspaceDescription": "全員がアクセスできなくなり、招待も無効になります。削除できるのは空のワークスペースだけです。",+ "deleteWorkspaceTypeName": "確認のため「{workspace}」と入力してください。",+ "dangerZone": "危険な操作",+ "leaveWorkspaceShort": "退出",+ "deleteWorkspaceShort": "削除",+ "workspaceNotEmpty": "先にドキュメントを削除するか移動してください。削除できるのは空のワークスペースだけです。",+ "workspaceCleanupPending": "削除されたドキュメントは完全に消えるまでしばらく保管されます。その後にもう一度お試しください。"+}diff --git a/packages/vue/src/i18n/locales/ja/cloud-portal.json b/packages/vue/src/i18n/locales/ja/cloud/portal.jsonsimilarity index 94%rename from packages/vue/src/i18n/locales/ja/cloud-portal.jsonrename to packages/vue/src/i18n/locales/ja/cloud/portal.jsonindex a2eb0cfb8..3d4536a96 100644--- a/packages/vue/src/i18n/locales/ja/cloud-portal.json+++ b/packages/vue/src/i18n/locales/ja/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "ヘルプ","loading": "読み込み中…","unavailableTitle": "このサーバーが応答していません","unavailableDescription": "アドレスを確認するか、しばらくしてからもう一度お試しください。","tryAgain": "もう一度試す","signInTitle": "OpenPencil Cloud にサインイン","signUpTitle": "アカウントを作成",- "signInWelcome": "おかえりなさい。",- "signUpDescription": "このサーバーにアカウントを作成します。","returnsTo": "完了すると{destination}に戻ります。","returnsToDesktop": "OpenPencil アプリ","returnsToEditor": "エディター",@@ -23,7 +22,7 @@"signIn": "サインイン","createAccount": "アカウントを作成","haveAccount": "アカウントをお持ちですか?",- "newHere": "初めてですか?",+ "newHere": "OpenPencil Cloud は初めてですか?","createAnAccount": "アカウントを作成","approvalTitle": "新しいアカウントは管理者が審査します","approvalDescription": "リクエストが承認されるとサインインできます。承認されたらメールでお知らせします。",@@ -231,5 +230,14 @@"errorNotAllowed": "この操作を行う権限がありません。","errorNetwork": "サーバーに接続できませんでした。接続を確認してください。","errorAlreadyDecided": "このリクエストはすでに他の人が対応しました。更新して確認してください。",- "passwordResetSent": "パスワードを設定するためのリンクをメールでお送りしました。"+ "passwordResetSent": "パスワードを設定するためのリンクをメールでお送りしました。",+ "repeatPassword": "パスワード(確認)",+ "errorNameRequired": "名前を入力してください。",+ "errorEmailRequired": "メールアドレスを入力してください。",+ "errorEmailInvalid": "[email protected] のようなメールアドレスを入力してください。",+ "errorPasswordRequired": "パスワードを入力してください。",+ "errorPasswordTooShort": "{count}文字以上にしてください。",+ "errorPasswordsDiffer": "パスワードが一致しません。",+ "verifiedTitle": "メールアドレスを確認しました",+ "verifiedDescription": "OpenPencil に戻ってサインインを完了してください。このタブは閉じてかまいません。"}diff --git a/packages/vue/src/i18n/locales/ja/common.json b/packages/vue/src/i18n/locales/ja/common.jsonindex d0082666a..b561bec02 100644--- a/packages/vue/src/i18n/locales/ja/common.json+++ b/packages/vue/src/i18n/locales/ja/common.json@@ -38,5 +38,7 @@"tokens": "トークン","clear": "クリア","dismiss": "閉じる",- "browserSupport": "ブラウザーの対応状況を確認"+ "browserSupport": "ブラウザーの対応状況を確認",+ "showPassword": "パスワードを表示",+ "hidePassword": "パスワードを隠す"}diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.jsonindex 7fbc163c8..7d4e6093a 100644--- a/packages/vue/src/i18n/locales/ja/files.json+++ b/packages/vue/src/i18n/locales/ja/files.json@@ -25,5 +25,6 @@"newDesign": "新しいデザイン","noMatchingFiles": "「{query}」に一致するファイルはありません。","saveAsPrompt": "名前を付けて保存:",- "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。"+ "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。",+ "newDesignIn": "{place} に新規デザイン"}diff --git a/packages/vue/src/i18n/locales/ja/index.ts b/packages/vue/src/i18n/locales/ja/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/ja/index.ts+++ b/packages/vue/src/i18n/locales/ja/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex e42ffe0c9..315784623 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -7,11 +7,9 @@"text": "テキスト","new": "新規作成","open": "開く…",- "openStorageWorkspace": "ストレージワークスペースを開く…","openTour": "ツアーを開く","save": "保存","saveAs": "名前を付けて保存…",- "saveToStorage": "ストレージに保存…","exportSelection": "選択範囲をエクスポート…","autosave": "ファイルに自動保存","copy": "コピー",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "選択範囲を SVG としてエクスポート","exportSelectionAsPPTX": "選択範囲を PPTX としてエクスポート","exportSelectionAsFig": "選択範囲を .fig としてエクスポート",- "togglePreview": "プレビュー"+ "togglePreview": "プレビュー",+ "browseFiles": "ファイルを表示…",+ "saveTo": "保存先を選んで保存…"}diff --git a/packages/vue/src/i18n/locales/ja/settings.json b/packages/vue/src/i18n/locales/ja/settings.jsonindex b44ed31af..26b7dd8c4 100644--- a/packages/vue/src/i18n/locales/ja/settings.json+++ b/packages/vue/src/i18n/locales/ja/settings.json@@ -22,7 +22,8 @@"media": "メディア","mcp": "MCP","toolAccess": "ツールへのアクセス",- "storage": "クラウドストレージ",+ "storage": "ストレージ",+ "cloud": "クラウド","animations": "アニメーション","animationsSystem": "システム設定に従う","animationsOff": "オフ",diff --git a/packages/vue/src/i18n/locales/ja/variables.json b/packages/vue/src/i18n/locales/ja/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/ja/variables.jsonrename to packages/vue/src/i18n/locales/ja/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/ja/variable-types.json b/packages/vue/src/i18n/locales/ja/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/ja/variable-types.jsonrename to packages/vue/src/i18n/locales/ja/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonnew file mode 100644index 000000000..9453b047a--- /dev/null+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -0,0 +1,279 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Dalej",+ "tryAgain": "Spróbuj ponownie",+ "signIn": "Zaloguj się",+ "signOut": "Wyloguj się",+ "workspace": "Obszar roboczy",+ "server": "Serwer",+ "share": "Udostępnij",+ "viewOnly": "Tylko podgląd",+ "canEdit": "Może edytować",+ "canView": "Może wyświetlać",+ "roleViewer": "Przeglądający",+ "roleEditor": "Edytujący",+ "roleAdmin": "Administrator",+ "changedInTwoPlaces": "Dokument „{name}” został zmieniony w dwóch miejscach",+ "conflictDescription": "Ktoś zapisał nowszą wersję, zanim Twoje zmiany zostały wysłane. Dopóki nie wybierzesz, nic nie przepadnie.",+ "connectHeading": "Połącz z OpenPencil Cloud",+ "connectDescription": "Synchronizuj pliki między urządzeniami i zapraszaj innych do wspólnej edycji.",+ "deviceHeading": "Potwierdź w przeglądarce",+ "deviceDescription": "Zatwierdź to logowanie na {host}.",+ "deviceDescriptionNoHost": "Zatwierdź to logowanie na serwerze.",+ "officialDescription": "Serwer OpenPencil · {host}",+ "selfHostedLabel": "Serwer Twojego zespołu",+ "selfHostedDescription": "Własny serwer OpenPencil Cloud",+ "serverAddress": "Adres serwera",+ "errorInvalidAddressHeading": "Wpisz adres internetowy serwera",+ "errorInvalidAddressDescription": "Użyj adresu podanego przez Twój zespół, np. https://cloud.example.com.",+ "errorUnreachableHeading": "Nie udało się połączyć z tym serwerem",+ "errorUnreachableDescription": "Sprawdź adres i połączenie, a następnie spróbuj ponownie.",+ "errorNotCloudHeading": "To nie jest serwer OpenPencil Cloud",+ "errorNotCloudDescription": "Pod tym adresem coś odpowiada, ale nie OpenPencil Cloud. Zapytaj zespół o właściwy adres.",+ "errorOutdatedHeading": "Ten serwer wymaga aktualizacji",+ "errorOutdatedDescription": "Działa na nim starsza wersja OpenPencil Cloud, niż obsługuje ta aplikacja.",+ "errorDeniedHeading": "Odrzucono logowanie",+ "errorDeniedDescription": "Prośba została odrzucona w przeglądarce. Zacznij od nowa, aby się zalogować.",+ "errorExpiredHeading": "Kod wygasł",+ "errorExpiredDescription": "Nie został zatwierdzony na czas. Zacznij od nowa, aby otrzymać nowy.",+ "errorSignInFailedHeading": "Nie udało się zalogować",+ "errorSignInFailedDescription": "Serwer nie dokończył logowania. Spróbuj ponownie za chwilę.",+ "continueWithGoogle": "Kontynuuj z Google",+ "continueWithApple": "Kontynuuj z Apple",+ "continueWithEmail": "Kontynuuj przez e-mail",+ "signInNoteDesktop": "Aby dokończyć logowanie, otworzy się przeglądarka, a potem wrócisz tutaj.",+ "signInNoteBrowser": "Po zalogowaniu wrócisz do tej karty.",+ "yourCode": "Twój kod",+ "copyCode": "Kopiuj kod",+ "deviceWaiting": "Czekamy na zatwierdzenie… Kod wygaśnie za {duration}.",+ "openBrowserAgain": "Otwórz przeglądarkę ponownie",+ "accountPending": "Twoje konto na {host} czeka na zatwierdzenie przez administratora.",+ "signedInAs": "Zalogowano do {host} jako {email}.",+ "invitationUnavailableHeading": "Tego zaproszenia nie można użyć",+ "invitationOpening": "Otwieranie zaproszenia",+ "invitedYou": "{name} zaprasza Cię",+ "invitationEditDescription": "Do edycji dokumentu na {host}.",+ "invitationViewDescription": "Do wyświetlenia dokumentu na {host}.",+ "invitationChecking": "Sprawdzanie zaproszenia…",+ "invitationUnavailableDescription": "Wygasło, zostało wycofane lub już przyjęte. Poproś użytkownika {name} o nowe.",+ "invitationUnavailableDescriptionNoName": "Wygasło, zostało wycofane lub już przyjęte. Poproś osobę, która je wysłała, o nowe.",+ "invitationSentTo": "Wysłano do {recipient}",+ "invitationExpiresIn": "Wygasa za {duration}",+ "unknownServerHeading": "Pierwszy raz łączysz się z {host}",+ "unknownServerDescription": "Loguj się tylko wtedy, gdy ufasz temu serwerowi. Przechowuje on dokument i widzi Twoje zmiany.",+ "invitationSignInHeading": "Zaloguj się do {host}",+ "invitationSignInDescription": "Użyj konta, na które wysłano zaproszenie. Dokument otworzy się zaraz potem.",+ "wrongAccountHeading": "To zaproszenie jest dla innego konta",+ "wrongAccountDescription": "Zalogowano jako {email}. Aby je otworzyć, zaloguj się jako {recipient}.",+ "notNow": "Nie teraz",+ "signInToOpen": "Zaloguj się, aby otworzyć",+ "useAnotherAccount": "Użyj innego konta",+ "openDocument": "Otwórz dokument",+ "saveHeading": "Wybierz miejsce zapisu",+ "saveDescription": "Synchronizuj ten projekt między urządzeniami i udostępniaj go innym.",+ "saveName": "Nazwa",+ "saveQuotaHeading": "W tym obszarze roboczym zabrakło miejsca",+ "saveQuotaDescription": "Zwolnij trochę miejsca lub wybierz inny obszar roboczy.",+ "saveOfflineHeading": "Jesteś offline",+ "saveOfflineDescription": "Połącz się z internetem, aby zapisać w chmurze. Na tym urządzeniu nic się nie zmieniło.",+ "saveFailedHeading": "Nie udało się zapisać",+ "saveFailedDescription": "Serwer nie przyjął pliku. Spróbuj ponownie za chwilę.",+ "saveUploading": "Przesyłanie… {sent} z {total}",+ "saveTooLargeHeading": "Ten plik jest za duży dla tego serwera",+ "saveTooLargeDescription": "Serwer przyjmuje pliki do {limit}. Usuń nieużywane obrazy lub strony i spróbuj ponownie.",+ "saveNote": "Zapisana kopia otwiera się w tej karcie i zapisuje się podczas pracy. Plik na tym urządzeniu pozostaje bez zmian.",+ "shareHeading": "Udostępnij „{name}”",+ "shareDescriptionInWorkspace": "W obszarze {workspace} w OpenPencil Cloud",+ "shareDescription": "W OpenPencil Cloud",+ "shareAddPeople": "Dodaj osoby przez e-mail",+ "shareEmailAddress": "Adres e-mail",+ "shareNewPeoplePermission": "Uprawnienia nowych osób",+ "shareInvite": "Zaproś",+ "sharePeopleWithAccess": "Osoby z dostępem",+ "shareYou": "(ty)",+ "shareInvited": "Zaproszenie wysłane",+ "shareInvitationExpires": "Zaproszenie wygasa {date}",+ "shareAccessFor": "Dostęp: {name}",+ "shareOwner": "Właściciel",+ "shareRemoveAccess": "Odbierz dostęp",+ "shareEveryoneIn": "Wszyscy w obszarze {workspace}",+ "shareMemberCount": {+ "one": "{count} osoba",+ "few": "{count} osoby",+ "many": "{count} osób"+ },+ "shareWorkspacePermissionTip": "Ustawiane przez obszar roboczy; zmień to w jego ustawieniach",+ "shareGeneralAccess": "Dostęp ogólny",+ "shareRestricted": "Tylko osoby z dostępem",+ "shareAnyoneWithLink": "Każdy, kto ma link",+ "shareLinkDetail": "Każdy, kto ma link, może otworzyć ten plik bez logowania.",+ "shareRestrictedDetail": "Ten plik mogą otworzyć tylko osoby i obszar roboczy wymienione powyżej.",+ "shareRestrictedNoLinksDetail": "Ten plik mogą otworzyć tylko osoby i obszar roboczy wymienione powyżej. Linki są wyłączone w tym obszarze roboczym.",+ "shareLinkPermission": "Uprawnienia linku",+ "shareCannotManage": "Tylko właściciel i edytujący mogą zmieniać dostęp.",+ "shareResetLinkTip": "Ten link został utworzony na innym urządzeniu. Zresetowanie go utworzy nowy link, a stary przestanie działać.",+ "shareResetLink": "Zresetuj link",+ "shareLinkCopied": "Skopiowano link",+ "shareCopyLink": "Kopiuj link",+ "shareLoadFailed": "Nie udało się wczytać listy osób z dostępem. Sprawdź połączenie i spróbuj ponownie.",+ "shareChangeFailed": "Nie udało się wprowadzić zmiany. Spróbuj ponownie za chwilę.",+ "conflictKeepBoth": "Zachowaj obie",+ "conflictKeepBothDescription": "Wersja w chmurze pozostanie jako „{name}”. Twoja zostanie zapisana obok jako „{copyName}”.",+ "conflictUseCloud": "Użyj wersji z chmury",+ "conflictUseCloudDescription": "Niewysłane zmiany na tym urządzeniu zostaną odrzucone.",+ "conflictUseMine": "Zastąp ją swoją wersją",+ "conflictUseMineDescriptionBy": "Najnowsze zmiany autorstwa {name} zostaną zastąpione u wszystkich.",+ "conflictUseMineDescription": "Nowsza wersja na serwerze zostanie zastąpiona u wszystkich.",+ "conflictConfirmUseCloud": "Użyj z chmury",+ "conflictConfirmUseMine": "Zastąp swoją",+ "conflictYourVersion": "Twoja wersja",+ "conflictCloudVersion": "Wersja w chmurze",+ "conflictWhichVersion": "Którą wersję zachować",+ "conflictDecideLater": "Zdecyduj później",+ "conflictYourCopyName": "{name} (Twoja kopia)",+ "conflictYouOnThisDevice": "Ty, na tym urządzeniu",+ "conflictResolveFailed": "Nie udało się rozwiązać konfliktu. Twoje zmiany nadal są na tym urządzeniu.",+ "statusViewOnlyDetail": "Możesz przeglądać i obserwować innych; Twoje zmiany do nikogo nie dotrą.",+ "statusSavedTo": "Zapisano w {workspace}",+ "statusSavedAgo": "Zapisano {time}",+ "statusUpToDate": "Aktualne",+ "statusSaving": "Zapisywanie…",+ "statusUploadingTo": "Przesyłanie do {workspace}",+ "statusSavedOnDevice": "Zapisano na tym urządzeniu",+ "statusUploadsSoon": "Przesyłanie za chwilę",+ "statusOfflineDetail": "Jesteś offline. Zmiany zostaną przesłane po ponownym połączeniu.",+ "statusConflict": "Zmieniono w dwóch miejscach",+ "statusConflictDetail": "Ktoś zapisał nowszą wersję podczas Twojej edycji. Wybierz, którą zachować.",+ "statusErrorDetail": "Twoje zmiany są bezpieczne na tym urządzeniu.",+ "statusResolve": "Rozwiąż",+ "statusChooseVersion": "Wybierz wersję",+ "statusOpenWorkspace": "Otwórz obszar roboczy",+ "settingsDescription": "Serwery, z którymi ta aplikacja synchronizuje dokumenty. Strona główna pokazuje obszary robocze jednego serwera naraz.",+ "settingsEmptyDescription": "Synchronizuj pliki między urządzeniami i edytuj je razem z innymi. Dokumenty na tym urządzeniu zostaną na miejscu.",+ "settingsConnectServer": "Połącz serwer",+ "settingsOfficialDescription": "Serwer OpenPencil, bez konfiguracji.",+ "settingsSelfHostedDescription": "Własny serwer OpenPencil Cloud pod adresem używanym przez Twój zespół.",+ "settingsOnHome": "Na stronie głównej",+ "settingsSignInExpired": "Sesja wygasła",+ "settingsSignInExpiredFor": "Sesja wygasła: {email}",+ "settingsSignedOut": "Wylogowano",+ "settingsWaitingForApproval": "Twoje konto czeka na zatwierdzenie przez administratora",+ "settingsAccessClosed": "Administrator odrzucił Twoją prośbę lub odebrał Ci dostęp",+ "settingsOptionsFor": "Opcje: {host}",+ "settingsAccountAndSecurity": "Konto i bezpieczeństwo",+ "settingsShowOnHome": "Pokaż na stronie głównej",+ "settingsDisconnectServer": "Odłącz serwer",+ "settingsSignOutFailed": "Nie udało się wylogować. Sprawdź połączenie i spróbuj ponownie.",+ "settingsDisconnectHeading": "Odłączyć {host}?",+ "settingsDisconnectDescription": "Zostaniesz wylogowany, a jego obszary robocze znikną z ekranu głównego na tym urządzeniu. Twoje dokumenty zostają na serwerze i możesz połączyć się ponownie w każdej chwili.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Zostaniesz wylogowany, a jego obszary robocze znikną z ekranu głównego na tym urządzeniu. {count} dokument ma zmiany, które nie dotarły jeszcze na serwer; odłączenie je odrzuci.",+ "few": "Zostaniesz wylogowany, a jego obszary robocze znikną z ekranu głównego na tym urządzeniu. {count} dokumenty mają zmiany, które nie dotarły jeszcze na serwer; odłączenie je odrzuci.",+ "many": "Zostaniesz wylogowany, a jego obszary robocze znikną z ekranu głównego na tym urządzeniu. {count} dokumentów ma zmiany, które nie dotarły jeszcze na serwer; odłączenie je odrzuci."+ },+ "settingsDisconnect": "Odłącz",+ "settingsDisconnectAndDiscard": "Odłącz i odrzuć zmiany",+ "homeLocations": "Lokalizacje",+ "homeRecent": "Ostatnie",+ "homeAccount": "Konto: {email}",+ "homeAccountSettings": "Ustawienia konta",+ "homeConnectAnotherServer": "Połącz inny serwer…",+ "homeAttentionTip": "Plik w tym miejscu wymaga decyzji",+ "homeNeedsAttention": "Wymaga uwagi",+ "homeSharedWithYou": "Udostępnione Tobie",+ "homeSharedSubtitle": "Pliki, do których Cię zaproszono",+ "homeSharedBy": "Od: {name}",+ "homeSignIn": "Zaloguj się…",+ "homeStorage": "Miejsce na dane",+ "homeStorageSettings": "Ustawienia miejsca na dane",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "Wykorzystano: {used}",+ "homeUsageOf": "{used} z {total}",+ "homeWorkspaceStorage": "Miejsce obszaru roboczego: {usage}",+ "homeView": "Widok",+ "homeGrid": "Siatka",+ "homeList": "Lista",+ "homeOfflineHeading": "Jesteś offline",+ "homeOfflineDescription": "To pliki zapisane na tym urządzeniu. Zmiany zostaną przesłane po ponownym połączeniu.",+ "homeLoadFailedHeading": "Nie udało się wczytać tego obszaru roboczego",+ "homeLoadFailedDescription": "Serwer nie odpowiedział. Pliki zapisane na tym urządzeniu nadal są na liście.",+ "homeConflicts": {+ "one": "{count} plik został zmieniony w dwóch miejscach",+ "few": "{count} pliki zostały zmienione w dwóch miejscach",+ "many": "{count} plików zostało zmienionych w dwóch miejscach"+ },+ "homeReview": "Przejrzyj",+ "homeLoadingFiles": "Ładowanie plików",+ "homeEmptyWorkspace": "W obszarze {workspace} nie ma jeszcze plików",+ "homeEmptyWorkspaceDescription": "Utwórz tu projekt lub zapisz otwarty plik w tym obszarze roboczym z menu „Plik”.",+ "homeNothingShared": "Nikt jeszcze niczego Ci nie udostępnił",+ "homeNothingSharedDescription": "Pojawią się tu pliki, do których ktoś Cię zaprosi.",+ "homeNewDesign": "Nowy projekt",+ "homeViewOnlyTip": "Możesz wyświetlać ten plik",+ "homeSharedTip": "Udostępniony osobom spoza obszaru roboczego",+ "homeShared": "Udostępniony",+ "syncSynced": "Zapisano w chmurze",+ "syncUploading": "Przesyłanie zmian…",+ "syncPending": "Zmiany zapisane na tym urządzeniu czekają na przesłanie",+ "syncOffline": "Offline — zmiany są zapisane na tym urządzeniu",+ "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.",+ "connectServerHeading": "Połącz serwer zespołu",+ "connectServerDescription": "Wpisz adres, którego zespół używa dla OpenPencil Cloud.",+ "checkingServer": "Sprawdzanie serwera…",+ "signInHeading": "Zaloguj się do {name}",+ "onHost": "Na {host}.",+ "verifyDescription": "Wysłaliśmy link na adres {email}.",+ "verifyNote": "Otwórz link z e-maila i wróć tutaj. Logowanie zakończy się samo.",+ "verifyNotYet": "Adres e-mail nie jest jeszcze potwierdzony. Otwórz link z e-maila i spróbuj ponownie.",+ "verifyNoEmail": "Brak e-maila?",+ "settingsTitle": "Chmura",+ "saveWhere": "Lokalizacja",+ "saveAction": "Zapisz",+ "saveStorageGroup": "Magazyn",+ "invitationWorkspaceDescription": "Aby dołączyć do obszaru roboczego na {host}.",+ "joinWorkspace": "Dołącz do obszaru",+ "homeNewWorkspace": "Nowy obszar roboczy",+ "homeMembers": "Członkowie",+ "newWorkspaceHeading": "Nowy obszar roboczy",+ "newWorkspaceDescription": "Miejsce na projekty zespołu. To Ty decydujesz, kto dołącza.",+ "workspaceName": "Nazwa obszaru",+ "workspaceNamePlaceholder": "Zespół projektowy",+ "createWorkspace": "Utwórz obszar",+ "renameWorkspace": "Zmień nazwę",+ "membersDescription": "Wszyscy tutaj widzą dokumenty obszaru; edytorzy i administratorzy je zmieniają.",+ "invitePeople": "Zaproś osoby",+ "inviteEmail": "Adres e-mail",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Rola",+ "invite": "Zaproś",+ "invitationSentNote": "Wysłaliśmy zaproszenie e-mailem. Jeśli ten serwer nie wysyła e-maili, udostępnij ten link.",+ "copyInvitationLink": "Kopiuj link zaproszenia",+ "membersLoading": "Wczytywanie członków…",+ "memberRole": "Rola: {name}",+ "removeMember": "Usuń: {name}",+ "pendingInvitations": "Oczekujące",+ "revokeInvitation": "Wycofaj",+ "leaveWorkspace": "Opuść obszar",+ "workspaceAlreadyMember": "Ta osoba już jest w tym obszarze.",+ "workspaceLastAdmin": "Obszar potrzebuje administratora. Najpierw nadaj tę rolę komuś innemu.",+ "workspaceForbidden": "Tylko administratorzy obszaru mogą to zrobić.",+ "workspaceNotFound": "Ten obszar lub zaproszenie już nie istnieje. Zamknij i spróbuj ponownie.",+ "workspaceFailed": "Nie udało się zmienić obszaru. Spróbuj za chwilę.",+ "unknownServerWorkspaceDescription": "Zaloguj się tylko, jeśli ufasz temu serwerowi. Przechowuje dokumenty obszaru i widzi Twoje zmiany.",+ "leaveWorkspaceHeading": "Opuścić {workspace}?",+ "leaveWorkspaceDescription": "Stracisz dostęp do jego dokumentów, chyba że ktoś udostępnił je bezpośrednio. Administrator może zaprosić Cię ponownie.",+ "removeMemberHeading": "Usunąć {name} z {workspace}?",+ "removeMemberDescription": "Ta osoba straci dostęp do dokumentów, chyba że udostępniono je bezpośrednio. Możesz zaprosić ją ponownie.",+ "removeMemberConfirm": "Usuń",+ "deleteWorkspace": "Usuń obszar",+ "deleteWorkspaceHeading": "Usunąć {workspace}?",+ "deleteWorkspaceDescription": "Wszyscy stracą dostęp, a zaproszenia przestaną działać. Usunąć można tylko pusty obszar.",+ "deleteWorkspaceTypeName": "Aby potwierdzić, wpisz „{workspace}”.",+ "dangerZone": "Strefa zagrożenia",+ "leaveWorkspaceShort": "Opuść",+ "deleteWorkspaceShort": "Usuń",+ "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."+}diff --git a/packages/vue/src/i18n/locales/pl/cloud-portal.json b/packages/vue/src/i18n/locales/pl/cloud/portal.jsonsimilarity index 95%rename from packages/vue/src/i18n/locales/pl/cloud-portal.jsonrename to packages/vue/src/i18n/locales/pl/cloud/portal.jsonindex 8ff3c865d..c71a0755a 100644--- a/packages/vue/src/i18n/locales/pl/cloud-portal.json+++ b/packages/vue/src/i18n/locales/pl/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Pomoc","loading": "Ładowanie…","unavailableTitle": "Ten serwer nie odpowiada","unavailableDescription": "Sprawdź adres lub spróbuj ponownie za chwilę.","tryAgain": "Spróbuj ponownie","signInTitle": "Zaloguj się do OpenPencil Cloud","signUpTitle": "Utwórz konto",- "signInWelcome": "Witaj ponownie.",- "signUpDescription": "Utwórz konto na tym serwerze.","returnsTo": "Następnie wrócisz do {destination}.","returnsToDesktop": "aplikacji OpenPencil","returnsToEditor": "edytora",@@ -23,7 +22,7 @@"signIn": "Zaloguj się","createAccount": "Utwórz konto","haveAccount": "Masz już konto?",- "newHere": "Pierwszy raz tutaj?",+ "newHere": "Pierwszy raz w OpenPencil Cloud?","createAnAccount": "Utwórz konto","approvalTitle": "Nowe konta sprawdza administrator","approvalDescription": "Zalogujesz się, gdy Twoja prośba zostanie zatwierdzona. Powiadomimy Cię o tym e-mailem.",@@ -239,5 +238,14 @@"errorNotAllowed": "Nie masz uprawnień do wykonania tej czynności.","errorNetwork": "Nie udało się połączyć z serwerem. Sprawdź połączenie.","errorAlreadyDecided": "Ktoś już rozpatrzył tę prośbę. Odśwież stronę, aby zobaczyć decyzję.",- "passwordResetSent": "Wysłaliśmy Ci link do ustawienia hasła."+ "passwordResetSent": "Wysłaliśmy Ci link do ustawienia hasła.",+ "repeatPassword": "Powtórz hasło",+ "errorNameRequired": "Wpisz swoje imię.",+ "errorEmailRequired": "Wpisz adres e-mail.",+ "errorEmailInvalid": "Wpisz adres taki jak [email protected].",+ "errorPasswordRequired": "Wpisz hasło.",+ "errorPasswordTooShort": "Użyj co najmniej {count} znaków.",+ "errorPasswordsDiffer": "Hasła się różnią.",+ "verifiedTitle": "Adres e-mail potwierdzony",+ "verifiedDescription": "Wróć do OpenPencil, aby dokończyć logowanie. Możesz zamknąć tę kartę."}diff --git a/packages/vue/src/i18n/locales/pl/common.json b/packages/vue/src/i18n/locales/pl/common.jsonindex 3623318d6..9f0f7c63a 100644--- a/packages/vue/src/i18n/locales/pl/common.json+++ b/packages/vue/src/i18n/locales/pl/common.json@@ -38,5 +38,7 @@"tokens": "tokenów","clear": "Wyczyść","dismiss": "Zamknij",- "browserSupport": "Sprawdź obsługę w przeglądarkach"+ "browserSupport": "Sprawdź obsługę w przeglądarkach",+ "showPassword": "Pokaż hasło",+ "hidePassword": "Ukryj hasło"}diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.jsonindex a5c897258..d5aa1ae4b 100644--- a/packages/vue/src/i18n/locales/pl/files.json+++ b/packages/vue/src/i18n/locales/pl/files.json@@ -25,5 +25,6 @@"newDesign": "Nowy projekt","noMatchingFiles": "Brak plików pasujących do „{query}”.","saveAsPrompt": "Zapisz jako:",- "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu."+ "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu.",+ "newDesignIn": "Nowy projekt w {place}"}diff --git a/packages/vue/src/i18n/locales/pl/index.ts b/packages/vue/src/i18n/locales/pl/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/pl/index.ts+++ b/packages/vue/src/i18n/locales/pl/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex 4d26d3dca..a519fab2e 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -7,11 +7,9 @@"text": "Tekst","new": "Nowy","open": "Otwórz…",- "openStorageWorkspace": "Otwórz obszar przechowywania…","openTour": "Otwórz przewodnik","save": "Zapisz","saveAs": "Zapisz jako…",- "saveToStorage": "Zapisz w obszarze przechowywania…","exportSelection": "Eksportuj zaznaczenie…","autosave": "Automatyczny zapis do pliku","copy": "Kopiuj",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Eksportuj zaznaczenie jako SVG","exportSelectionAsPPTX": "Eksportuj zaznaczenie jako PPTX","exportSelectionAsFig": "Eksportuj zaznaczenie jako .fig",- "togglePreview": "Podgląd"+ "togglePreview": "Podgląd",+ "browseFiles": "Przeglądaj pliki…",+ "saveTo": "Zapisz w…"}diff --git a/packages/vue/src/i18n/locales/pl/settings.json b/packages/vue/src/i18n/locales/pl/settings.jsonindex 7c91d331b..417e31055 100644--- a/packages/vue/src/i18n/locales/pl/settings.json+++ b/packages/vue/src/i18n/locales/pl/settings.json@@ -22,7 +22,8 @@"media": "Media","mcp": "MCP","toolAccess": "Dostęp do narzędzi",- "storage": "Przechowywanie w chmurze",+ "storage": "Przechowywanie",+ "cloud": "Chmura","animations": "Animacje","animationsSystem": "Zgodnie z systemem","animationsOff": "Wyłączone",diff --git a/packages/vue/src/i18n/locales/pl/variables.json b/packages/vue/src/i18n/locales/pl/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/pl/variables.jsonrename to packages/vue/src/i18n/locales/pl/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/pl/variable-types.json b/packages/vue/src/i18n/locales/pl/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/pl/variable-types.jsonrename to packages/vue/src/i18n/locales/pl/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonnew file mode 100644index 000000000..c8dd03a95--- /dev/null+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -0,0 +1,279 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "Продолжить",+ "tryAgain": "Попробовать снова",+ "signIn": "Войти",+ "signOut": "Выйти",+ "workspace": "Рабочее пространство",+ "server": "Сервер",+ "share": "Поделиться",+ "viewOnly": "Только просмотр",+ "canEdit": "Может редактировать",+ "canView": "Может просматривать",+ "roleViewer": "Читатель",+ "roleEditor": "Редактор",+ "roleAdmin": "Администратор",+ "changedInTwoPlaces": "Документ «{name}» изменён в двух местах",+ "conflictDescription": "Кто-то сохранил более новую версию, пока у вас были неотправленные изменения. Пока вы не сделаете выбор, ничего не потеряется.",+ "connectHeading": "Подключение к OpenPencil Cloud",+ "connectDescription": "Синхронизируйте файлы между устройствами и приглашайте людей редактировать вместе с вами.",+ "deviceHeading": "Подтвердите в браузере",+ "deviceDescription": "Одобрите этот вход на {host}.",+ "deviceDescriptionNoHost": "Одобрите этот вход на сервере.",+ "officialDescription": "Сервер OpenPencil · {host}",+ "selfHostedLabel": "Сервер вашей команды",+ "selfHostedDescription": "Собственный сервер OpenPencil Cloud",+ "serverAddress": "Адрес сервера",+ "errorInvalidAddressHeading": "Введите веб-адрес сервера",+ "errorInvalidAddressDescription": "Укажите адрес, который дала ваша команда, например https://cloud.example.com.",+ "errorUnreachableHeading": "Не удалось связаться с сервером",+ "errorUnreachableDescription": "Проверьте адрес и подключение, затем попробуйте снова.",+ "errorNotCloudHeading": "Это не сервер OpenPencil Cloud",+ "errorNotCloudDescription": "По этому адресу что-то отвечает, но это не OpenPencil Cloud. Уточните правильный адрес у команды.",+ "errorOutdatedHeading": "Серверу нужно обновление",+ "errorOutdatedDescription": "На нём работает более старая версия OpenPencil Cloud, чем поддерживает это приложение.",+ "errorDeniedHeading": "Вход отклонён",+ "errorDeniedDescription": "Запрос отклонили в браузере. Начните вход заново.",+ "errorExpiredHeading": "Срок действия кода истёк",+ "errorExpiredDescription": "Его не одобрили вовремя. Начните заново, чтобы получить новый.",+ "errorSignInFailedHeading": "Не удалось войти",+ "errorSignInFailedDescription": "Сервер не завершил вход. Попробуйте чуть позже.",+ "continueWithGoogle": "Продолжить с Google",+ "continueWithApple": "Продолжить с Apple",+ "continueWithEmail": "Войти по почте",+ "signInNoteDesktop": "Чтобы завершить вход, откроется браузер, а затем вы вернётесь сюда.",+ "signInNoteBrowser": "После входа вы вернётесь в эту вкладку.",+ "yourCode": "Ваш код",+ "copyCode": "Скопировать код",+ "deviceWaiting": "Ждём вашего одобрения… Код действует ещё {duration}.",+ "openBrowserAgain": "Открыть браузер снова",+ "accountPending": "Ваш аккаунт на {host} ждёт одобрения администратора.",+ "signedInAs": "Вы вошли на {host} как {email}.",+ "invitationUnavailableHeading": "Это приглашение нельзя использовать",+ "invitationOpening": "Открываем приглашение",+ "invitedYou": "{name} приглашает вас",+ "invitationEditDescription": "Редактировать документ на {host}.",+ "invitationViewDescription": "Просматривать документ на {host}.",+ "invitationChecking": "Проверяем приглашение…",+ "invitationUnavailableDescription": "Срок его действия истёк, его отозвали или уже приняли. Попросите новое у пользователя {name}.",+ "invitationUnavailableDescriptionNoName": "Срок его действия истёк, его отозвали или уже приняли. Попросите новое у того, кто его отправил.",+ "invitationSentTo": "Отправлено на {recipient}",+ "invitationExpiresIn": "Истекает через {duration}",+ "unknownServerHeading": "Вы впервые подключаетесь к {host}",+ "unknownServerDescription": "Входите, только если доверяете этому серверу. Он хранит документ и видит ваши правки.",+ "invitationSignInHeading": "Вход на {host}",+ "invitationSignInDescription": "Используйте аккаунт, на который пришло приглашение. Документ откроется сразу после входа.",+ "wrongAccountHeading": "Это приглашение для другого аккаунта",+ "wrongAccountDescription": "Вы вошли как {email}. Чтобы открыть его, войдите как {recipient}.",+ "notNow": "Не сейчас",+ "signInToOpen": "Войти и открыть",+ "useAnotherAccount": "Использовать другой аккаунт",+ "openDocument": "Открыть документ",+ "saveHeading": "Выберите, куда сохранить",+ "saveDescription": "Синхронизируйте этот дизайн между устройствами и делитесь им с людьми.",+ "saveName": "Название",+ "saveQuotaHeading": "В рабочем пространстве закончилось место",+ "saveQuotaDescription": "Освободите место или выберите другое рабочее пространство.",+ "saveOfflineHeading": "Вы не в сети",+ "saveOfflineDescription": "Подключитесь к интернету, чтобы сохранить в облако. На этом устройстве ничего не изменилось.",+ "saveFailedHeading": "Не удалось сохранить",+ "saveFailedDescription": "Сервер не принял файл. Попробуйте чуть позже.",+ "saveUploading": "Загрузка… {sent} из {total}",+ "saveTooLargeHeading": "Файл слишком большой для этого сервера",+ "saveTooLargeDescription": "Сервер принимает файлы размером до {limit}. Удалите неиспользуемые изображения или страницы и попробуйте снова.",+ "saveNote": "Сохранённая копия откроется в этой вкладке и будет сохраняться по ходу работы. Файл на этом устройстве не изменится.",+ "shareHeading": "Доступ к «{name}»",+ "shareDescriptionInWorkspace": "В пространстве {workspace} в OpenPencil Cloud",+ "shareDescription": "В OpenPencil Cloud",+ "shareAddPeople": "Добавьте людей по почте",+ "shareEmailAddress": "Адрес электронной почты",+ "shareNewPeoplePermission": "Права для новых участников",+ "shareInvite": "Пригласить",+ "sharePeopleWithAccess": "У кого есть доступ",+ "shareYou": "(вы)",+ "shareInvited": "Приглашение отправлено",+ "shareInvitationExpires": "Приглашение истекает {date}",+ "shareAccessFor": "Доступ: {name}",+ "shareOwner": "Владелец",+ "shareRemoveAccess": "Отозвать доступ",+ "shareEveryoneIn": "Все в пространстве {workspace}",+ "shareMemberCount": {+ "one": "{count} участник",+ "few": "{count} участника",+ "many": "{count} участников"+ },+ "shareWorkspacePermissionTip": "Задаётся рабочим пространством; изменить можно в его настройках",+ "shareGeneralAccess": "Общий доступ",+ "shareRestricted": "Только люди с доступом",+ "shareAnyoneWithLink": "Все, у кого есть ссылка",+ "shareLinkDetail": "Любой, у кого есть ссылка, может открыть этот файл без входа.",+ "shareRestrictedDetail": "Открыть этот файл могут только люди и рабочее пространство, указанные выше.",+ "shareRestrictedNoLinksDetail": "Открыть этот файл могут только люди и рабочее пространство, указанные выше. Ссылки в этом рабочем пространстве отключены.",+ "shareLinkPermission": "Права по ссылке",+ "shareCannotManage": "Менять доступ могут только владелец и редакторы.",+ "shareResetLinkTip": "Эта ссылка создана на другом устройстве. При сбросе появится новая ссылка, а старая перестанет работать.",+ "shareResetLink": "Сбросить ссылку",+ "shareLinkCopied": "Ссылка скопирована",+ "shareCopyLink": "Скопировать ссылку",+ "shareLoadFailed": "Не удалось загрузить список доступа. Проверьте подключение и попробуйте снова.",+ "shareChangeFailed": "Изменение не применилось. Попробуйте чуть позже.",+ "conflictKeepBoth": "Оставить обе",+ "conflictKeepBothDescription": "Версия в облаке останется под названием «{name}». Ваша сохранится рядом как «{copyName}».",+ "conflictUseCloud": "Взять версию из облака",+ "conflictUseCloudDescription": "Неотправленные изменения на этом устройстве будут удалены.",+ "conflictUseMine": "Заменить её своей версией",+ "conflictUseMineDescriptionBy": "Последние изменения пользователя {name} будут заменены для всех.",+ "conflictUseMineDescription": "Более новая версия на сервере будет заменена для всех.",+ "conflictConfirmUseCloud": "Взять из облака",+ "conflictConfirmUseMine": "Заменить своей",+ "conflictYourVersion": "Ваша версия",+ "conflictCloudVersion": "Версия в облаке",+ "conflictWhichVersion": "Какую версию оставить",+ "conflictDecideLater": "Решить позже",+ "conflictYourCopyName": "{name} (ваша копия)",+ "conflictYouOnThisDevice": "Вы, на этом устройстве",+ "conflictResolveFailed": "Не удалось разрешить конфликт. Ваши изменения по-прежнему на этом устройстве.",+ "statusViewOnlyDetail": "Можно осматриваться и следить за другими, но ваши изменения никто не увидит.",+ "statusSavedTo": "Сохранено в {workspace}",+ "statusSavedAgo": "Сохранено {time}",+ "statusUpToDate": "Актуальная версия",+ "statusSaving": "Сохранение…",+ "statusUploadingTo": "Загрузка в {workspace}",+ "statusSavedOnDevice": "Сохранено на этом устройстве",+ "statusUploadsSoon": "Скоро загрузится",+ "statusOfflineDetail": "Вы не в сети. Изменения загрузятся, когда подключение восстановится.",+ "statusConflict": "Изменено в двух местах",+ "statusConflictDetail": "Кто-то сохранил более новую версию, пока вы редактировали. Выберите, какую оставить.",+ "statusErrorDetail": "Ваши изменения сохранены на этом устройстве.",+ "statusResolve": "Разрешить",+ "statusChooseVersion": "Выбрать версию",+ "statusOpenWorkspace": "Открыть рабочее пространство",+ "settingsDescription": "Серверы, с которыми приложение синхронизирует документы. На главной показываются рабочие пространства одного сервера.",+ "settingsEmptyDescription": "Синхронизируйте файлы между устройствами и редактируйте их вместе с другими. Документы на этом устройстве останутся на месте.",+ "settingsConnectServer": "Подключить сервер",+ "settingsOfficialDescription": "Сервер OpenPencil, ничего настраивать не нужно.",+ "settingsSelfHostedDescription": "Собственный сервер OpenPencil Cloud по адресу, которым пользуется ваша команда.",+ "settingsOnHome": "На главной",+ "settingsSignInExpired": "Сеанс истёк",+ "settingsSignInExpiredFor": "Сеанс истёк: {email}",+ "settingsSignedOut": "Выход выполнен",+ "settingsWaitingForApproval": "Ваш аккаунт ждёт одобрения администратора",+ "settingsAccessClosed": "Администратор отклонил заявку или закрыл вам доступ",+ "settingsOptionsFor": "Параметры: {host}",+ "settingsAccountAndSecurity": "Аккаунт и безопасность",+ "settingsShowOnHome": "Показывать на главной",+ "settingsDisconnectServer": "Отключить сервер",+ "settingsSignOutFailed": "Не удалось выйти. Проверьте подключение и попробуйте снова.",+ "settingsDisconnectHeading": "Отключить {host}?",+ "settingsDisconnectDescription": "Вы выйдете из аккаунта, а его рабочие пространства исчезнут с главного экрана на этом устройстве. Документы останутся на сервере, подключиться снова можно в любой момент.",+ "settingsDisconnectUnsavedDescription": {+ "one": "Вы выйдете из аккаунта, а его рабочие пространства исчезнут с главного экрана на этом устройстве. В {count} документе есть изменения, которые ещё не дошли до сервера; при отключении они пропадут.",+ "few": "Вы выйдете из аккаунта, а его рабочие пространства исчезнут с главного экрана на этом устройстве. В {count} документах есть изменения, которые ещё не дошли до сервера; при отключении они пропадут.",+ "many": "Вы выйдете из аккаунта, а его рабочие пространства исчезнут с главного экрана на этом устройстве. В {count} документах есть изменения, которые ещё не дошли до сервера; при отключении они пропадут."+ },+ "settingsDisconnect": "Отключить",+ "settingsDisconnectAndDiscard": "Отключить и отменить изменения",+ "homeLocations": "Расположения",+ "homeRecent": "Недавние",+ "homeAccount": "Аккаунт: {email}",+ "homeAccountSettings": "Настройки аккаунта",+ "homeConnectAnotherServer": "Подключить другой сервер…",+ "homeAttentionTip": "Для файла здесь нужно ваше решение",+ "homeNeedsAttention": "Требует внимания",+ "homeSharedWithYou": "Доступные вам",+ "homeSharedSubtitle": "Файлы, в которые вас пригласили",+ "homeSharedBy": "От: {name}",+ "homeSignIn": "Войти…",+ "homeStorage": "Хранилище",+ "homeStorageSettings": "Настройки хранилища",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "Использовано: {used}",+ "homeUsageOf": "{used} из {total}",+ "homeWorkspaceStorage": "Хранилище рабочего пространства: {usage}",+ "homeView": "Вид",+ "homeGrid": "Сетка",+ "homeList": "Список",+ "homeOfflineHeading": "Вы не в сети",+ "homeOfflineDescription": "Здесь файлы, сохранённые на этом устройстве. Изменения загрузятся, когда подключение восстановится.",+ "homeLoadFailedHeading": "Не удалось загрузить рабочее пространство",+ "homeLoadFailedDescription": "Сервер не ответил. Файлы, сохранённые на этом устройстве, по-прежнему в списке.",+ "homeConflicts": {+ "one": "{count} файл изменён в двух местах",+ "few": "{count} файла изменены в двух местах",+ "many": "{count} файлов изменены в двух местах"+ },+ "homeReview": "Просмотреть",+ "homeLoadingFiles": "Загрузка файлов",+ "homeEmptyWorkspace": "В пространстве {workspace} пока нет файлов",+ "homeEmptyWorkspaceDescription": "Создайте здесь дизайн или сохраните открытый файл в это рабочее пространство через меню «Файл».",+ "homeNothingShared": "С вами пока ничем не поделились",+ "homeNothingSharedDescription": "Здесь появятся файлы, в которые вас пригласят.",+ "homeNewDesign": "Новый дизайн",+ "homeViewOnlyTip": "Вы можете просматривать этот файл",+ "homeSharedTip": "Доступен людям вне рабочего пространства",+ "homeShared": "Общий",+ "syncSynced": "Сохранено в облаке",+ "syncUploading": "Загрузка изменений…",+ "syncPending": "Изменения сохранены на этом устройстве и ждут загрузки",+ "syncOffline": "Не в сети — изменения сохранены на этом устройстве",+ "syncConflict": "Изменено и в другом месте — выберите, какую версию оставить",+ "syncError": "Не удалось загрузить изменения",+ "shareLinkFailed": "Эта ссылка не открывает документ. Попросите новую.",+ "connectServerHeading": "Подключите сервер команды",+ "connectServerDescription": "Введите адрес, который ваша команда использует для OpenPencil Cloud.",+ "checkingServer": "Проверяем сервер…",+ "signInHeading": "Вход в {name}",+ "onHost": "На {host}.",+ "verifyDescription": "Мы отправили ссылку на {email}.",+ "verifyNote": "Откройте ссылку из письма и вернитесь сюда. Вход завершится сам.",+ "verifyNotYet": "Почта ещё не подтверждена. Откройте ссылку из письма и попробуйте снова.",+ "verifyNoEmail": "Нет письма?",+ "settingsTitle": "Облако",+ "saveWhere": "Место",+ "saveAction": "Сохранить",+ "saveStorageGroup": "Хранилище",+ "invitationWorkspaceDescription": "Чтобы присоединиться к рабочему пространству на {host}.",+ "joinWorkspace": "Присоединиться",+ "homeNewWorkspace": "Новое рабочее пространство",+ "homeMembers": "Участники",+ "newWorkspaceHeading": "Новое рабочее пространство",+ "newWorkspaceDescription": "Место для дизайнов вашей команды. Вы решаете, кто в нём состоит.",+ "workspaceName": "Название пространства",+ "workspaceNamePlaceholder": "Команда дизайна",+ "createWorkspace": "Создать пространство",+ "renameWorkspace": "Переименовать",+ "membersDescription": "Все участники видят документы пространства; редакторы и администраторы их меняют.",+ "invitePeople": "Пригласить людей",+ "inviteEmail": "Адрес почты",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "Роль",+ "invite": "Пригласить",+ "invitationSentNote": "Мы отправили приглашение по почте. Если этот сервер не отправляет письма, поделитесь этой ссылкой.",+ "copyInvitationLink": "Скопировать ссылку-приглашение",+ "membersLoading": "Загружаем участников…",+ "memberRole": "Роль: {name}",+ "removeMember": "Удалить: {name}",+ "pendingInvitations": "Ждут присоединения",+ "revokeInvitation": "Отозвать",+ "leaveWorkspace": "Покинуть пространство",+ "workspaceAlreadyMember": "Этот человек уже в пространстве.",+ "workspaceLastAdmin": "В пространстве должен быть администратор. Сначала назначьте администратором кого-то другого.",+ "workspaceForbidden": "Это могут делать только администраторы пространства.",+ "workspaceNotFound": "Это пространство или приглашение больше не существует. Закройте окно и попробуйте снова.",+ "workspaceFailed": "Не удалось изменить пространство. Попробуйте чуть позже.",+ "unknownServerWorkspaceDescription": "Входите, только если доверяете этому серверу. Он хранит документы пространства и видит ваши правки.",+ "leaveWorkspaceHeading": "Покинуть {workspace}?",+ "leaveWorkspaceDescription": "Вы потеряете доступ к его документам, если их не поделились с вами напрямую. Администратор может пригласить вас снова.",+ "removeMemberHeading": "Удалить {name} из {workspace}?",+ "removeMemberDescription": "Человек потеряет доступ к документам, если их не поделились с ним напрямую. Его можно пригласить снова.",+ "removeMemberConfirm": "Удалить",+ "deleteWorkspace": "Удалить пространство",+ "deleteWorkspaceHeading": "Удалить {workspace}?",+ "deleteWorkspaceDescription": "Все потеряют доступ, а приглашения перестанут работать. Удалить можно только пустое пространство.",+ "deleteWorkspaceTypeName": "Для подтверждения введите «{workspace}».",+ "dangerZone": "Опасная зона",+ "leaveWorkspaceShort": "Покинуть",+ "deleteWorkspaceShort": "Удалить",+ "workspaceNotEmpty": "Сначала удалите или перенесите его документы: удалить можно только пустое пространство.",+ "workspaceCleanupPending": "Удалённые документы ещё какое-то время хранятся, прежде чем исчезнуть окончательно. Попробуйте позже."+}diff --git a/packages/vue/src/i18n/locales/ru/cloud-portal.json b/packages/vue/src/i18n/locales/ru/cloud/portal.jsonsimilarity index 95%rename from packages/vue/src/i18n/locales/ru/cloud-portal.jsonrename to packages/vue/src/i18n/locales/ru/cloud/portal.jsonindex 7b0585ad2..8458e7345 100644--- a/packages/vue/src/i18n/locales/ru/cloud-portal.json+++ b/packages/vue/src/i18n/locales/ru/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "Справка","loading": "Загрузка…","unavailableTitle": "Сервер не отвечает","unavailableDescription": "Проверьте адрес или попробуйте чуть позже.","tryAgain": "Попробовать снова","signInTitle": "Вход в OpenPencil Cloud","signUpTitle": "Создание аккаунта",- "signInWelcome": "С возвращением.",- "signUpDescription": "Создайте аккаунт на этом сервере.","returnsTo": "Затем вы вернётесь в {destination}.","returnsToDesktop": "приложение OpenPencil","returnsToEditor": "редактор",@@ -23,7 +22,7 @@"signIn": "Войти","createAccount": "Создать аккаунт","haveAccount": "Уже есть аккаунт?",- "newHere": "Впервые здесь?",+ "newHere": "Впервые в OpenPencil Cloud?","createAnAccount": "Создать аккаунт","approvalTitle": "Новые аккаунты проверяет администратор","approvalDescription": "Вы сможете войти, когда заявку одобрят. Мы сообщим об этом по почте.",@@ -239,5 +238,14 @@"errorNotAllowed": "У вас нет прав на это действие.","errorNetwork": "Не удалось связаться с сервером. Проверьте подключение.","errorAlreadyDecided": "По этой заявке уже приняли решение. Обновите страницу, чтобы его увидеть.",- "passwordResetSent": "Мы отправили вам ссылку для установки пароля."+ "passwordResetSent": "Мы отправили вам ссылку для установки пароля.",+ "repeatPassword": "Повторите пароль",+ "errorNameRequired": "Введите имя.",+ "errorEmailRequired": "Введите адрес почты.",+ "errorEmailInvalid": "Введите адрес вида [email protected].",+ "errorPasswordRequired": "Введите пароль.",+ "errorPasswordTooShort": "Минимум символов: {count}.",+ "errorPasswordsDiffer": "Пароли не совпадают.",+ "verifiedTitle": "Почта подтверждена",+ "verifiedDescription": "Вернитесь в OpenPencil, чтобы завершить вход. Эту вкладку можно закрыть."}diff --git a/packages/vue/src/i18n/locales/ru/common.json b/packages/vue/src/i18n/locales/ru/common.jsonindex 46b81d604..97144bd30 100644--- a/packages/vue/src/i18n/locales/ru/common.json+++ b/packages/vue/src/i18n/locales/ru/common.json@@ -38,5 +38,7 @@"tokens": "токенов","clear": "Очистить","dismiss": "Закрыть",- "browserSupport": "Проверить поддержку в браузерах"+ "browserSupport": "Проверить поддержку в браузерах",+ "showPassword": "Показать пароль",+ "hidePassword": "Скрыть пароль"}diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.jsonindex 9352f5d21..d28475a15 100644--- a/packages/vue/src/i18n/locales/ru/files.json+++ b/packages/vue/src/i18n/locales/ru/files.json@@ -25,5 +25,6 @@"newDesign": "Новый дизайн","noMatchingFiles": "Нет файлов по запросу «{query}».","saveAsPrompt": "Сохранить как:",- "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться."+ "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться.",+ "newDesignIn": "Новый дизайн в {place}"}diff --git a/packages/vue/src/i18n/locales/ru/index.ts b/packages/vue/src/i18n/locales/ru/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/ru/index.ts+++ b/packages/vue/src/i18n/locales/ru/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex 99cbb148f..51b9bc9a9 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -7,11 +7,9 @@"text": "Текст","new": "Создать","open": "Открыть…",- "openStorageWorkspace": "Открыть рабочее пространство хранилища…","openTour": "Открыть тур","save": "Сохранить","saveAs": "Сохранить как…",- "saveToStorage": "Сохранить в хранилище…","exportSelection": "Экспорт выделения…","autosave": "Автосохранение в файл","copy": "Копировать",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "Экспортировать выделение как SVG","exportSelectionAsPPTX": "Экспортировать выделение как PPTX","exportSelectionAsFig": "Экспортировать выделение как .fig",- "togglePreview": "Просмотр"+ "togglePreview": "Просмотр",+ "browseFiles": "Обзор файлов…",+ "saveTo": "Сохранить в…"}diff --git a/packages/vue/src/i18n/locales/ru/settings.json b/packages/vue/src/i18n/locales/ru/settings.jsonindex 2d5086cc3..f9bfb44eb 100644--- a/packages/vue/src/i18n/locales/ru/settings.json+++ b/packages/vue/src/i18n/locales/ru/settings.json@@ -22,7 +22,8 @@"media": "Медиа","mcp": "MCP","toolAccess": "Доступ к инструментам",- "storage": "Облачное хранилище",+ "storage": "Хранилище",+ "cloud": "Облако","animations": "Анимации","animationsSystem": "Как в системе","animationsOff": "Выключены",diff --git a/packages/vue/src/i18n/locales/ru/variables.json b/packages/vue/src/i18n/locales/ru/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/ru/variables.jsonrename to packages/vue/src/i18n/locales/ru/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/ru/variable-types.json b/packages/vue/src/i18n/locales/ru/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/ru/variable-types.jsonrename to packages/vue/src/i18n/locales/ru/variables/types.jsondiff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonnew file mode 100644index 000000000..5949c442e--- /dev/null+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -0,0 +1,273 @@+{+ "productName": "OpenPencil Cloud",+ "continue": "继续",+ "tryAgain": "重试",+ "signIn": "登录",+ "signOut": "退出登录",+ "workspace": "工作区",+ "server": "服务器",+ "share": "分享",+ "viewOnly": "仅查看",+ "canEdit": "可编辑",+ "canView": "可查看",+ "roleViewer": "查看者",+ "roleEditor": "编辑者",+ "roleAdmin": "管理员",+ "changedInTwoPlaces": "“{name}”在两处被修改",+ "conflictDescription": "在你还有未上传的更改时,有人保存了更新的版本。在你做出选择之前,不会丢失任何内容。",+ "connectHeading": "连接到 OpenPencil Cloud",+ "connectDescription": "在多台设备间同步文件,并邀请他人与你一起编辑。",+ "deviceHeading": "在浏览器中确认",+ "deviceDescription": "请在 {host} 上批准此次登录。",+ "deviceDescriptionNoHost": "请在服务器上批准此次登录。",+ "officialDescription": "由 OpenPencil 托管 · {host}",+ "selfHostedLabel": "你团队的服务器",+ "selfHostedDescription": "自托管的 OpenPencil Cloud",+ "serverAddress": "服务器地址",+ "errorInvalidAddressHeading": "请输入服务器的网址",+ "errorInvalidAddressDescription": "请使用团队提供的地址,例如 https://cloud.example.com。",+ "errorUnreachableHeading": "无法连接到此服务器",+ "errorUnreachableDescription": "请检查地址和网络连接,然后重试。",+ "errorNotCloudHeading": "这不是 OpenPencil Cloud 服务器",+ "errorNotCloudDescription": "该地址有响应,但不是 OpenPencil Cloud。请向团队索取正确的地址。",+ "errorOutdatedHeading": "此服务器需要更新",+ "errorOutdatedDescription": "它运行的 OpenPencil Cloud 版本低于此应用支持的版本。",+ "errorDeniedHeading": "登录被拒绝",+ "errorDeniedDescription": "请求已在浏览器中被拒绝。请重新开始登录。",+ "errorExpiredHeading": "代码已过期",+ "errorExpiredDescription": "未能及时批准。请重新开始以获取新代码。",+ "errorSignInFailedHeading": "无法登录",+ "errorSignInFailedDescription": "服务器未能完成登录。请稍后重试。",+ "continueWithGoogle": "使用 Google 继续",+ "continueWithApple": "使用 Apple 继续",+ "continueWithEmail": "使用邮箱继续",+ "signInNoteDesktop": "浏览器会打开以完成登录,之后请回到这里。",+ "signInNoteBrowser": "登录后会返回此标签页。",+ "yourCode": "你的代码",+ "copyCode": "复制代码",+ "deviceWaiting": "正在等待你批准… 代码将在 {duration} 后过期。",+ "openBrowserAgain": "重新打开浏览器",+ "accountPending": "你在 {host} 上的账号正在等待管理员批准。",+ "signedInAs": "已以 {email} 身份登录 {host}。",+ "invitationUnavailableHeading": "此邀请无法使用",+ "invitationOpening": "正在打开邀请",+ "invitedYou": "{name} 邀请了你",+ "invitationEditDescription": "邀请你编辑 {host} 上的一个文档。",+ "invitationViewDescription": "邀请你查看 {host} 上的一个文档。",+ "invitationChecking": "正在检查邀请…",+ "invitationUnavailableDescription": "邀请已过期、已撤回或已被接受。请让 {name} 重新发送一份。",+ "invitationUnavailableDescriptionNoName": "邀请已过期、已撤回或已被接受。请让发送者重新发送一份。",+ "invitationSentTo": "已发送给 {recipient}",+ "invitationExpiresIn": "{duration} 后过期",+ "unknownServerHeading": "你之前没有使用过 {host}",+ "unknownServerDescription": "仅在你信任此服务器时登录。它会存储文档,并能看到你的编辑。",+ "invitationSignInHeading": "登录 {host}",+ "invitationSignInDescription": "请使用接收此邀请的账号。登录后文档会立即打开。",+ "wrongAccountHeading": "此邀请属于另一个账号",+ "wrongAccountDescription": "你当前以 {email} 身份登录。请使用 {recipient} 登录以打开它。",+ "notNow": "以后再说",+ "signInToOpen": "登录以打开",+ "useAnotherAccount": "使用其他账号",+ "openDocument": "打开文档",+ "saveHeading": "选择保存位置",+ "saveDescription": "在多台设备间同步此设计,并与他人分享。",+ "saveName": "名称",+ "saveQuotaHeading": "此工作区空间已满",+ "saveQuotaDescription": "请释放一些空间,或选择其他工作区。",+ "saveOfflineHeading": "你已离线",+ "saveOfflineDescription": "请连接互联网以保存到云端。此设备上的内容没有任何更改。",+ "saveFailedHeading": "无法保存",+ "saveFailedDescription": "服务器未接受此文件。请稍后重试。",+ "saveUploading": "正在上传… {sent} / {total}",+ "saveTooLargeHeading": "此文件超出了该服务器的大小限制",+ "saveTooLargeDescription": "此服务器接受的文件最大为 {limit}。请移除未使用的图片或页面,然后重试。",+ "saveNote": "保存的副本会在此标签页中打开,并在你工作时自动保存。此设备上的文件保持不变。",+ "shareHeading": "分享“{name}”",+ "shareDescriptionInWorkspace": "位于 OpenPencil Cloud 的 {workspace} 中",+ "shareDescription": "位于 OpenPencil Cloud",+ "shareAddPeople": "通过邮箱添加成员",+ "shareEmailAddress": "邮箱地址",+ "shareNewPeoplePermission": "新成员的权限",+ "shareInvite": "邀请",+ "sharePeopleWithAccess": "有访问权限的人",+ "shareYou": "(你)",+ "shareInvited": "已邀请",+ "shareInvitationExpires": "邀请过期时间:{date}",+ "shareAccessFor": "{name} 的访问权限",+ "shareOwner": "所有者",+ "shareRemoveAccess": "移除访问权限",+ "shareEveryoneIn": "{workspace} 中的所有人",+ "shareMemberCount": {+ "many": "{count} 名成员"+ },+ "shareWorkspacePermissionTip": "由工作区设置;请在工作区设置中更改",+ "shareGeneralAccess": "常规访问权限",+ "shareRestricted": "仅限有访问权限的人",+ "shareAnyoneWithLink": "任何拥有链接的人",+ "shareLinkDetail": "任何拥有链接的人无需登录即可打开此文件。",+ "shareRestrictedDetail": "只有上方的成员和工作区可以打开此文件。",+ "shareRestrictedNoLinksDetail": "只有上方的成员和工作区可以打开此文件。此工作区已关闭链接分享。",+ "shareLinkPermission": "链接权限",+ "shareCannotManage": "只有所有者和编辑者可以更改访问权限。",+ "shareResetLinkTip": "此链接是在另一台设备上创建的。重置后会生成新链接,旧链接将失效。",+ "shareResetLink": "重置链接",+ "shareLinkCopied": "链接已复制",+ "shareCopyLink": "复制链接",+ "shareLoadFailed": "无法加载访问权限列表。请检查网络连接后重试。",+ "shareChangeFailed": "更改未能生效。请稍后重试。",+ "conflictKeepBoth": "保留两者",+ "conflictKeepBothDescription": "云端版本保留为“{name}”。你的版本会另存为“{copyName}”,放在它旁边。",+ "conflictUseCloud": "使用云端版本",+ "conflictUseCloudDescription": "此设备上未上传的更改将被丢弃。",+ "conflictUseMine": "用你的版本替换",+ "conflictUseMineDescriptionBy": "{name} 的最新更改将被替换,所有人都会受到影响。",+ "conflictUseMineDescription": "服务器上的较新版本将被替换,所有人都会受到影响。",+ "conflictConfirmUseCloud": "使用云端版本",+ "conflictConfirmUseMine": "用我的版本替换",+ "conflictYourVersion": "你的版本",+ "conflictCloudVersion": "云端版本",+ "conflictWhichVersion": "保留哪个版本",+ "conflictDecideLater": "稍后决定",+ "conflictYourCopyName": "{name}(你的副本)",+ "conflictYouOnThisDevice": "你,在此设备上",+ "conflictResolveFailed": "无法解决冲突。你的更改仍保存在此设备上。",+ "statusViewOnlyDetail": "你可以浏览并跟随他人,但你的更改不会传给任何人。",+ "statusSavedTo": "已保存到 {workspace}",+ "statusSavedAgo": "保存于 {time}",+ "statusUpToDate": "已是最新",+ "statusSaving": "正在保存…",+ "statusUploadingTo": "正在上传到 {workspace}",+ "statusSavedOnDevice": "已保存在此设备上",+ "statusUploadsSoon": "即将上传",+ "statusOfflineDetail": "你已离线。重新连接后会上传更改。",+ "statusConflict": "在两处被修改",+ "statusConflictDetail": "你编辑时有人保存了更新的版本。请选择要保留的版本。",+ "statusErrorDetail": "你的更改已安全保存在此设备上。",+ "statusResolve": "解决",+ "statusChooseVersion": "选择版本",+ "statusOpenWorkspace": "打开工作区",+ "settingsDescription": "此应用与之同步文档的服务器。主页一次只显示一个服务器的工作区。",+ "settingsEmptyDescription": "在多台设备间同步文件,并与他人一起编辑。此设备上的文档保持原样。",+ "settingsConnectServer": "连接服务器",+ "settingsOfficialDescription": "由 OpenPencil 托管,无需设置。",+ "settingsSelfHostedDescription": "自托管的 OpenPencil Cloud,使用你团队提供的地址。",+ "settingsOnHome": "显示在主页",+ "settingsSignInExpired": "登录已过期",+ "settingsSignInExpiredFor": "{email} 的登录已过期",+ "settingsSignedOut": "已退出登录",+ "settingsWaitingForApproval": "正在等待管理员批准你的账号",+ "settingsAccessClosed": "管理员拒绝或移除了你的访问权限",+ "settingsOptionsFor": "{host} 的选项",+ "settingsAccountAndSecurity": "账号与安全",+ "settingsShowOnHome": "在主页显示",+ "settingsDisconnectServer": "断开服务器连接",+ "settingsSignOutFailed": "无法退出登录。请检查网络连接后重试。",+ "settingsDisconnectHeading": "断开与 {host} 的连接?",+ "settingsDisconnectDescription": "你将被登出,其工作区会从此设备的主页中移除。你的文档仍保留在服务器上,可以随时重新连接。",+ "settingsDisconnectUnsavedDescription": {+ "many": "你将被登出,其工作区会从此设备的主页中移除。{count} 个文档有尚未同步到服务器的更改;断开连接会丢弃这些更改。"+ },+ "settingsDisconnect": "断开连接",+ "settingsDisconnectAndDiscard": "断开连接并丢弃更改",+ "homeLocations": "位置",+ "homeRecent": "最近",+ "homeAccount": "账号:{email}",+ "homeAccountSettings": "账号设置",+ "homeConnectAnotherServer": "连接其他服务器…",+ "homeAttentionTip": "此处有文件需要你做出选择",+ "homeNeedsAttention": "需要处理",+ "homeSharedWithYou": "与你共享",+ "homeSharedSubtitle": "别人邀请你加入的文件",+ "homeSharedBy": "由 {name} 分享",+ "homeSignIn": "登录…",+ "homeStorage": "存储",+ "homeStorageSettings": "存储设置",+ "homeCloudOnHost": "OpenPencil Cloud · {host}",+ "homeUsageUsed": "已用 {used}",+ "homeUsageOf": "{used} / {total}",+ "homeWorkspaceStorage": "工作区存储,{usage}",+ "homeView": "视图",+ "homeGrid": "网格",+ "homeList": "列表",+ "homeOfflineHeading": "你已离线",+ "homeOfflineDescription": "这些是保存在此设备上的文件。重新连接后会上传更改。",+ "homeLoadFailedHeading": "无法加载此工作区",+ "homeLoadFailedDescription": "服务器没有响应。仍会列出保存在此设备上的文件。",+ "homeConflicts": {+ "many": "{count} 个文件在两处被修改"+ },+ "homeReview": "查看",+ "homeLoadingFiles": "正在加载文件",+ "homeEmptyWorkspace": "{workspace} 中还没有文件",+ "homeEmptyWorkspaceDescription": "在此创建设计,或通过“文件”菜单将打开的文件保存到此工作区。",+ "homeNothingShared": "还没有与你共享的内容",+ "homeNothingSharedDescription": "别人邀请你加入的文件会显示在这里。",+ "homeNewDesign": "新建设计",+ "homeViewOnlyTip": "你对此文件仅有查看权限",+ "homeSharedTip": "已与工作区以外的人共享",+ "homeShared": "已共享",+ "syncSynced": "已保存到云端",+ "syncUploading": "正在上传更改…",+ "syncPending": "更改已保存在此设备上,等待上传",+ "syncOffline": "离线——更改已保存在此设备上",+ "syncConflict": "其他地方也有编辑——请选择要保留的版本",+ "syncError": "无法上传更改",+ "shareLinkFailed": "此链接无法打开文档。请索取新链接。",+ "connectServerHeading": "连接团队的服务器",+ "connectServerDescription": "输入团队用于 OpenPencil Cloud 的地址。",+ "checkingServer": "正在检查服务器…",+ "signInHeading": "登录 {name}",+ "onHost": "在 {host} 上。",+ "verifyDescription": "我们已向 {email} 发送了链接。",+ "verifyNote": "打开邮件中的链接,然后回到这里。登录会自动完成。",+ "verifyNotYet": "你的邮箱尚未确认。打开邮件中的链接后再试一次。",+ "verifyNoEmail": "没有收到邮件?",+ "settingsTitle": "云",+ "saveWhere": "位置",+ "saveAction": "保存",+ "saveStorageGroup": "存储",+ "invitationWorkspaceDescription": "加入 {host} 上的工作区。",+ "joinWorkspace": "加入工作区",+ "homeNewWorkspace": "新建工作区",+ "homeMembers": "成员",+ "newWorkspaceHeading": "新建工作区",+ "newWorkspaceDescription": "与团队存放设计的地方。由你管理谁可以加入。",+ "workspaceName": "工作区名称",+ "workspaceNamePlaceholder": "设计团队",+ "createWorkspace": "创建工作区",+ "renameWorkspace": "重命名",+ "membersDescription": "这里的每个人都能看到工作区的文档;编辑者和管理员可以修改它们。",+ "invitePeople": "邀请成员",+ "inviteEmail": "邮箱地址",+ "inviteEmailPlaceholder": "[email protected]",+ "inviteRole": "角色",+ "invite": "邀请",+ "invitationSentNote": "我们已通过邮件发送邀请。如果此服务器不发送邮件,请改为分享此链接。",+ "copyInvitationLink": "复制邀请链接",+ "membersLoading": "正在加载成员…",+ "memberRole": "{name} 的角色",+ "removeMember": "移除 {name}",+ "pendingInvitations": "等待加入",+ "revokeInvitation": "撤回",+ "leaveWorkspace": "离开工作区",+ "workspaceAlreadyMember": "对方已在此工作区中。",+ "workspaceLastAdmin": "工作区需要一名管理员。请先将其他人设为管理员。",+ "workspaceForbidden": "只有该工作区的管理员可以这样做。",+ "workspaceNotFound": "此工作区或邀请已不存在。请关闭后重试。",+ "workspaceFailed": "无法更改工作区。请稍后重试。",+ "unknownServerWorkspaceDescription": "仅在你信任此服务器时登录。它会存储工作区的文档并能看到你的编辑。",+ "leaveWorkspaceHeading": "离开 {workspace}?",+ "leaveWorkspaceDescription": "除非有人直接与你共享,否则你将无法访问其中的文档。管理员可以再次邀请你。",+ "removeMemberHeading": "将 {name} 从 {workspace} 中移除?",+ "removeMemberDescription": "除非直接共享,对方将无法访问其中的文档。你可以再次邀请对方。",+ "removeMemberConfirm": "移除",+ "deleteWorkspace": "删除工作区",+ "deleteWorkspaceHeading": "删除 {workspace}?",+ "deleteWorkspaceDescription": "所有人都将失去访问权限,其邀请也会失效。只能删除空的工作区。",+ "deleteWorkspaceTypeName": "请输入“{workspace}”以确认。",+ "dangerZone": "危险操作",+ "leaveWorkspaceShort": "退出",+ "deleteWorkspaceShort": "删除",+ "workspaceNotEmpty": "请先删除或移走其中的文档;只能删除空的工作区。",+ "workspaceCleanupPending": "已删除的文档会保留一段时间后才彻底清除。请在那之后再试。"+}diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud-portal.json b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.jsonsimilarity index 94%rename from packages/vue/src/i18n/locales/zh-cn/cloud-portal.jsonrename to packages/vue/src/i18n/locales/zh-cn/cloud/portal.jsonindex 2fe8b5c19..73c9f5106 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud-portal.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json@@ -1,13 +1,12 @@{"productName": "OpenPencil Cloud",+ "help": "帮助","loading": "正在加载…","unavailableTitle": "此服务器没有响应","unavailableDescription": "请检查地址,或稍后重试。","tryAgain": "重试","signInTitle": "登录 OpenPencil Cloud","signUpTitle": "创建账号",- "signInWelcome": "欢迎回来。",- "signUpDescription": "在此服务器上创建账号。","returnsTo": "完成后将返回{destination}。","returnsToDesktop": "OpenPencil 应用","returnsToEditor": "编辑器",@@ -23,7 +22,7 @@"signIn": "登录","createAccount": "创建账号","haveAccount": "已有账号?",- "newHere": "第一次来?",+ "newHere": "初次使用 OpenPencil Cloud?","createAnAccount": "创建账号","approvalTitle": "新账号需经管理员审核","approvalDescription": "申请获批后即可登录。获批时我们会发邮件通知你。",@@ -231,5 +230,14 @@"errorNotAllowed": "你没有执行此操作的权限。","errorNetwork": "无法连接到服务器。请检查网络连接。","errorAlreadyDecided": "已有人处理了此申请。请刷新查看。",- "passwordResetSent": "我们已向你发送设置密码的链接。"+ "passwordResetSent": "我们已向你发送设置密码的链接。",+ "repeatPassword": "再次输入密码",+ "errorNameRequired": "请输入你的名字。",+ "errorEmailRequired": "请输入你的邮箱地址。",+ "errorEmailInvalid": "请输入类似 [email protected] 的邮箱地址。",+ "errorPasswordRequired": "请输入密码。",+ "errorPasswordTooShort": "至少使用 {count} 个字符。",+ "errorPasswordsDiffer": "两次输入的密码不一致。",+ "verifiedTitle": "邮箱已确认",+ "verifiedDescription": "回到 OpenPencil 完成登录。你可以关闭此标签页。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/common.json b/packages/vue/src/i18n/locales/zh-cn/common.jsonindex 03bea28e9..ca3f8db03 100644--- a/packages/vue/src/i18n/locales/zh-cn/common.json+++ b/packages/vue/src/i18n/locales/zh-cn/common.json@@ -38,5 +38,7 @@"tokens": "token","clear": "清除","dismiss": "关闭",- "browserSupport": "查看浏览器支持情况"+ "browserSupport": "查看浏览器支持情况",+ "showPassword": "显示密码",+ "hidePassword": "隐藏密码"}diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.jsonindex 345936a58..3056836c6 100644--- a/packages/vue/src/i18n/locales/zh-cn/files.json+++ b/packages/vue/src/i18n/locales/zh-cn/files.json@@ -25,5 +25,6 @@"newDesign": "新建设计","noMatchingFiles": "没有与“{query}”匹配的文件。","saveAsPrompt": "另存为:",- "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。"+ "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。",+ "newDesignIn": "在 {place} 中新建设计"}diff --git a/packages/vue/src/i18n/locales/zh-cn/index.ts b/packages/vue/src/i18n/locales/zh-cn/index.tsindex e6d27db01..dbb09c01a 100644--- a/packages/vue/src/i18n/locales/zh-cn/index.ts+++ b/packages/vue/src/i18n/locales/zh-cn/index.ts@@ -2,7 +2,8 @@ import type { ComponentsJSON } from '@nanostores/i18n'import ai from './ai.json'import automation from './automation.json'-import cloudPortal from './cloud-portal.json'+import cloud from './cloud/editor.json'+import cloudPortal from './cloud/portal.json'import code from './code.json'import collaboration from './collaboration.json'import commands from './commands.json'@@ -26,12 +27,13 @@ import statuses from './statuses.json'import storage from './storage.json'import tools from './tools.json'import updates from './updates.json'-import variableTypes from './variable-types.json'-import variables from './variables.json'+import variables from './variables/panel.json'+import variableTypes from './variables/types.json'export default {ai,automation,+ cloud,cloudPortal,code,collaboration,diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex b0f04d625..6d08ec7fe 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -7,11 +7,9 @@"text": "文本","new": "新建","open": "打开…",- "openStorageWorkspace": "打开存储工作区…","openTour": "打开导览","save": "保存","saveAs": "另存为…",- "saveToStorage": "保存到存储工作区…","exportSelection": "导出所选内容…","autosave": "自动保存到本地文件","copy": "复制",@@ -78,5 +76,7 @@"exportSelectionAsSVG": "将所选内容导出为 SVG","exportSelectionAsPPTX": "将所选内容导出为 PPTX","exportSelectionAsFig": "将所选内容导出为 .fig",- "togglePreview": "预览"+ "togglePreview": "预览",+ "browseFiles": "浏览文件…",+ "saveTo": "保存到…"}diff --git a/packages/vue/src/i18n/locales/zh-cn/settings.json b/packages/vue/src/i18n/locales/zh-cn/settings.jsonindex cb51364f2..c45c75a6c 100644--- a/packages/vue/src/i18n/locales/zh-cn/settings.json+++ b/packages/vue/src/i18n/locales/zh-cn/settings.json@@ -22,7 +22,8 @@"media": "媒体","mcp": "MCP","toolAccess": "工具访问权限",- "storage": "云存储",+ "storage": "存储",+ "cloud": "云","animations": "动画","animationsSystem": "跟随系统","animationsOff": "关闭",diff --git a/packages/vue/src/i18n/locales/zh-cn/variables.json b/packages/vue/src/i18n/locales/zh-cn/variables/panel.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/zh-cn/variables.jsonrename to packages/vue/src/i18n/locales/zh-cn/variables/panel.jsondiff --git a/packages/vue/src/i18n/locales/zh-cn/variable-types.json b/packages/vue/src/i18n/locales/zh-cn/variables/types.jsonsimilarity index 100%rename from packages/vue/src/i18n/locales/zh-cn/variable-types.jsonrename to packages/vue/src/i18n/locales/zh-cn/variables/types.jsondiff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.tsindex e14f21ffb..932594d11 100644--- a/packages/vue/src/i18n/messages.ts+++ b/packages/vue/src/i18n/messages.ts@@ -1,6 +1,7 @@import { aiMessageDefaults, aiMessages } from '#vue/i18n/messages/ai'import { automationMessageDefaults, automationMessages } from '#vue/i18n/messages/automation'-import { cloudPortalMessageDefaults, cloudPortalMessages } from '#vue/i18n/messages/cloud-portal'+import { cloudMessageDefaults, cloudMessages } from '#vue/i18n/messages/cloud/editor'+import { cloudPortalMessageDefaults, cloudPortalMessages } from '#vue/i18n/messages/cloud/portal'import { codeMessageDefaults, codeMessages } from '#vue/i18n/messages/code'import {collaborationMessageDefaults,@@ -27,11 +28,11 @@ import { statusMessageDefaults, statusMessages } from '#vue/i18n/messages/statusimport { storageMessageDefaults, storageMessages } from '#vue/i18n/messages/storage'import { toolMessageDefaults, toolMessages } from '#vue/i18n/messages/tools'import { updatesMessageDefaults, updatesMessages } from '#vue/i18n/messages/updates'+import { variablesMessageDefaults, variablesMessages } from '#vue/i18n/messages/variables/panel'import {variableTypeMessageDefaults,variableTypeMessages-} from '#vue/i18n/messages/variable-types'-import { variablesMessageDefaults, variablesMessages } from '#vue/i18n/messages/variables'+} from '#vue/i18n/messages/variables/types'export {aiMessages,@@ -59,6 +60,7 @@ export {storageMessages,toolMessages,updatesMessages,+ cloudMessages,cloudPortalMessages,variablesMessages,variableTypeMessages@@ -90,6 +92,7 @@ export const messageDefaults = {storage: storageMessageDefaults,tools: toolMessageDefaults,updates: updatesMessageDefaults,+ cloud: cloudMessageDefaults,cloudPortal: cloudPortalMessageDefaults,variables: variablesMessageDefaults,variableTypes: variableTypeMessageDefaultsdiff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsnew file mode 100644index 000000000..7cb47866c--- /dev/null+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -0,0 +1,329 @@+import { count, params } from '@nanostores/i18n'++import { i18n } from '#vue/i18n/create'++/** Copy for OpenPencil Cloud inside the editor: connecting, sharing, syncing, and Home. */+export const cloudMessageDefaults = {+ productName: 'OpenPencil Cloud',+ continue: 'Continue',+ tryAgain: 'Try again',+ signIn: 'Sign in',+ signOut: 'Sign out',+ workspace: 'Workspace',+ server: 'Server',+ share: 'Share',+ viewOnly: 'View only',+ canEdit: 'Can edit',+ canView: 'Can view',+ roleViewer: 'Viewer',+ roleEditor: 'Editor',+ roleAdmin: 'Admin',+ changedInTwoPlaces: params('“{name}” was changed in two places'),+ conflictDescription:+ 'Someone saved a newer version while you had unsent changes. Nothing is lost until you choose.',++ // Connect+ connectHeading: 'Connect to OpenPencil Cloud',+ connectDescription: 'Keep files in sync across devices and invite people to edit with you.',+ connectServerHeading: 'Connect your team’s server',+ connectServerDescription: 'Enter the address your team uses for OpenPencil Cloud.',+ checkingServer: 'Checking the server…',+ signInHeading: params('Sign in to {name}'),+ onHost: params('On {host}.'),+ verifyDescription: params('We sent a link to {email}.'),+ verifyNote: 'Open the link in that email, then come back here. Signing in finishes on its own.',+ verifyNotYet: 'Your email isn’t confirmed yet. Open the link in the email, then try again.',+ verifyNoEmail: 'No email?',+ deviceHeading: 'Confirm in your browser',+ deviceDescription: params('Approve this sign-in on {host}.'),+ deviceDescriptionNoHost: 'Approve this sign-in on the server.',+ officialDescription: params('Hosted by OpenPencil · {host}'),+ selfHostedLabel: 'Your team’s server',+ selfHostedDescription: 'A self-hosted OpenPencil Cloud',+ serverAddress: 'Server address',+ errorInvalidAddressHeading: 'Enter the server’s web address',+ errorInvalidAddressDescription:+ 'Use the address your team gave you, such as https://cloud.example.com.',+ errorUnreachableHeading: 'Couldn’t reach this server',+ errorUnreachableDescription: 'Check the address and your connection, then try again.',+ errorNotCloudHeading: 'This isn’t an OpenPencil Cloud server',+ errorNotCloudDescription:+ 'The address answered, but not as OpenPencil Cloud. Ask your team for the right one.',+ errorOutdatedHeading: 'This server needs an update',+ errorOutdatedDescription: 'It runs an older version of OpenPencil Cloud than this app supports.',+ errorDeniedHeading: 'Sign-in was denied',+ errorDeniedDescription: 'The request was turned down in the browser. Start again to sign in.',+ errorExpiredHeading: 'The code expired',+ errorExpiredDescription: 'It wasn’t approved in time. Start again to get a new one.',+ errorSignInFailedHeading: 'Couldn’t sign in',+ errorSignInFailedDescription: 'The server didn’t finish signing you in. Try again in a moment.',+ continueWithGoogle: 'Continue with Google',+ continueWithApple: 'Continue with Apple',+ continueWithEmail: 'Continue with email',+ signInNoteDesktop: 'Your browser opens to finish signing in, then you come back here.',+ signInNoteBrowser: 'You come back to this tab after signing in.',+ yourCode: 'Your code',+ copyCode: 'Copy code',+ deviceWaiting: params('Waiting for you to approve… The code expires in {duration}.'),+ openBrowserAgain: 'Open browser again',+ accountPending: params('Your account on {host} is waiting for an administrator to approve it.'),+ signedInAs: params('Signed in to {host} as {email}.'),++ // Invitation+ invitationUnavailableHeading: 'This invitation can’t be used',+ invitationOpening: 'Opening invitation',+ invitedYou: params('{name} invited you'),+ invitationEditDescription: params('To edit a document on {host}.'),+ invitationViewDescription: params('To view a document on {host}.'),+ invitationWorkspaceDescription: params('To join a workspace on {host}.'),+ joinWorkspace: 'Join workspace',+ invitationChecking: 'Checking the invitation…',+ invitationUnavailableDescription: params(+ 'It expired, was withdrawn, or was already accepted. Ask {name} for a new one.'+ ),+ invitationUnavailableDescriptionNoName:+ 'It expired, was withdrawn, or was already accepted. Ask the person who sent it for a new one.',+ invitationSentTo: params('Sent to {recipient}'),+ invitationExpiresIn: params('Expires in {duration}'),+ unknownServerHeading: params('You haven’t used {host} before'),+ unknownServerDescription:+ 'Only sign in if you trust this server. It stores the document and sees your edits.',+ unknownServerWorkspaceDescription:+ 'Only sign in if you trust this server. It stores the workspace’s documents and sees your edits.',+ invitationSignInHeading: params('Sign in to {host}'),+ invitationSignInDescription:+ 'Use the account this invitation was sent to. The document opens right after.',+ wrongAccountHeading: 'This invitation is for another account',+ wrongAccountDescription: params(+ 'You’re signed in as {email}. Sign in with {recipient} to open it.'+ ),+ notNow: 'Not now',+ signInToOpen: 'Sign in to open',+ useAnotherAccount: 'Use another account',+ openDocument: 'Open document',++ // Save+ saveHeading: 'Choose where to save',+ saveDescription: 'Keep this design in sync across devices and share it with people.',+ saveWhere: 'Location',+ saveAction: 'Save',+ saveStorageGroup: 'Storage',+ saveName: 'Name',+ saveQuotaHeading: 'This workspace is out of space',+ saveQuotaDescription: 'Free some space or choose another workspace.',+ saveOfflineHeading: 'You’re offline',+ saveOfflineDescription:+ 'Connect to the internet to save to Cloud. Nothing has changed on this device.',+ saveFailedHeading: 'Couldn’t save',+ saveFailedDescription: 'The server didn’t accept the file. Try again in a moment.',+ saveUploading: params('Uploading… {sent} of {total}'),+ saveTooLargeHeading: 'This file is too large for this server',+ saveTooLargeDescription: params(+ 'It takes files up to {limit}. Remove unused images or pages, then try again.'+ ),+ saveNote:+ 'The saved copy opens in this tab and saves as you work. The file on this device stays as it is.',++ // Share+ shareHeading: params('Share “{name}”'),+ shareDescriptionInWorkspace: params('In {workspace} on OpenPencil Cloud'),+ shareDescription: 'On OpenPencil Cloud',+ shareAddPeople: 'Add people by email',+ shareEmailAddress: 'Email address',+ shareNewPeoplePermission: 'Permission for new people',+ shareInvite: 'Invite',+ sharePeopleWithAccess: 'People with access',+ shareYou: '(you)',+ shareInvited: 'Invited',+ shareInvitationExpires: params('Invitation expires {date}'),+ shareAccessFor: params('Access for {name}'),+ shareOwner: 'Owner',+ shareRemoveAccess: 'Remove access',+ shareEveryoneIn: params('Everyone in {workspace}'),+ shareMemberCount: count({ one: '{count} member', many: '{count} members' }),+ shareWorkspacePermissionTip: 'Set by the workspace; change it in the workspace’s settings',+ shareGeneralAccess: 'General access',+ shareRestricted: 'Only people with access',+ shareAnyoneWithLink: 'Anyone with the link',+ shareLinkDetail: 'Anyone who has the link can open this file without signing in.',+ shareRestrictedDetail: 'Only the people and workspace above can open this file.',+ shareRestrictedNoLinksDetail:+ 'Only the people and workspace above can open this file. Links are turned off for this workspace.',+ shareLinkPermission: 'Link permission',+ shareCannotManage: 'Only the owner and editors can change who has access.',+ shareResetLinkTip:+ 'This link was made on another device. Resetting it makes a new link and the old one stops working.',+ shareResetLink: 'Reset link',+ shareLinkCopied: 'Link copied',+ shareCopyLink: 'Copy link',+ shareLoadFailed: 'Couldn’t load who has access. Check your connection and try again.',+ shareChangeFailed: 'That change didn’t go through. Try again in a moment.',++ // Conflict+ conflictKeepBoth: 'Keep both',+ conflictKeepBothDescription: params(+ 'The Cloud version stays as “{name}”. Yours is saved next to it as “{copyName}”.'+ ),+ conflictUseCloud: 'Use the Cloud version',+ conflictUseCloudDescription: 'Your unsent changes on this device are discarded.',+ conflictUseMine: 'Replace it with your version',+ conflictUseMineDescriptionBy: params('{name}’s latest changes are replaced for everyone.'),+ conflictUseMineDescription: 'The newer version on the server is replaced for everyone.',+ conflictConfirmUseCloud: 'Use Cloud version',+ conflictConfirmUseMine: 'Replace with mine',+ conflictYourVersion: 'Your version',+ conflictCloudVersion: 'Cloud version',+ conflictWhichVersion: 'Which version to keep',+ conflictDecideLater: 'Decide later',+ conflictYourCopyName: params('{name} (your copy)'),+ conflictYouOnThisDevice: 'You, on this device',+ conflictResolveFailed: 'Couldn’t resolve the conflict. Your changes are still on this device.',++ // Status+ statusViewOnlyDetail: 'You can look around and follow others; your changes won’t reach anyone.',+ statusSavedTo: params('Saved to {workspace}'),+ statusSavedAgo: params('Saved {time}'),+ statusUpToDate: 'Up to date',+ statusSaving: 'Saving…',+ statusUploadingTo: params('Uploading to {workspace}'),+ statusSavedOnDevice: 'Saved on this device',+ statusUploadsSoon: 'Uploads in a moment',+ statusOfflineDetail: 'You’re offline. Changes upload when you reconnect.',+ statusConflict: 'Changed in two places',+ statusConflictDetail: 'Someone saved a newer version while you edited. Choose which to keep.',+ statusErrorDetail: 'Your changes are safe on this device.',+ statusResolve: 'Resolve',+ statusChooseVersion: 'Choose a version',+ statusOpenWorkspace: 'Open workspace',++ // Workspaces+ homeNewWorkspace: 'New workspace',+ homeMembers: 'Members',+ newWorkspaceHeading: 'New workspace',+ newWorkspaceDescription: 'A place to keep designs with your team. You manage who joins it.',+ workspaceName: 'Workspace name',+ workspaceNamePlaceholder: 'Design team',+ createWorkspace: 'Create workspace',+ renameWorkspace: 'Rename',+ membersDescription:+ 'Everyone here sees the workspace’s documents; editors and admins change them.',+ invitePeople: 'Invite people',+ inviteEmail: 'Email address',+ inviteEmailPlaceholder: '[email protected]',+ inviteRole: 'Role',+ invite: 'Invite',+ invitationSentNote:+ 'We emailed the invitation. If this server doesn’t send email, share this link with them instead.',+ copyInvitationLink: 'Copy invitation link',+ membersLoading: 'Loading members…',+ memberRole: params('Role of {name}'),+ removeMember: params('Remove {name}'),+ pendingInvitations: 'Waiting to join',+ revokeInvitation: 'Withdraw',+ leaveWorkspace: 'Leave workspace',+ leaveWorkspaceHeading: params('Leave {workspace}?'),+ leaveWorkspaceDescription:+ 'You lose access to its documents unless someone shared them with you directly. An admin can invite you back.',+ removeMemberHeading: params('Remove {name} from {workspace}?'),+ removeMemberDescription:+ 'They lose access to its documents unless someone shared them directly. You can invite them again.',+ removeMemberConfirm: 'Remove',+ deleteWorkspace: 'Delete workspace',+ deleteWorkspaceHeading: params('Delete {workspace}?'),+ deleteWorkspaceDescription:+ 'Everyone loses access and its invitations stop working. Only an empty workspace can be deleted.',+ deleteWorkspaceTypeName: params('To confirm, type “{workspace}”.'),+ dangerZone: 'Danger zone',+ leaveWorkspaceShort: 'Leave',+ deleteWorkspaceShort: 'Delete',+ workspaceNotEmpty: 'Delete or move its documents first; only an empty workspace can be deleted.',+ workspaceCleanupPending:+ 'Its deleted documents are kept for a while before they’re gone for good. Try again after that.',+ workspaceAlreadyMember: 'They’re already in this workspace.',+ workspaceLastAdmin: 'A workspace needs an admin. Make someone else an admin first.',+ workspaceForbidden: 'Only admins of this workspace can do that.',+ workspaceNotFound: 'This workspace or invitation is gone. Close this and try again.',+ workspaceFailed: 'Couldn’t change the workspace. Try again in a moment.',++ // Settings+ settingsTitle: 'Cloud',+ settingsDescription:+ 'Servers this app syncs documents with. Home shows one server’s workspaces at a time.',+ settingsEmptyDescription:+ 'Keep files in sync across devices and edit them with others. Documents on this device stay where they are.',+ settingsConnectServer: 'Connect a server',+ settingsOfficialDescription: 'Hosted by OpenPencil, nothing to set up.',+ settingsSelfHostedDescription: 'A self-hosted OpenPencil Cloud, at the address your team uses.',+ settingsOnHome: 'On Home',+ settingsSignInExpired: 'Sign-in expired',+ settingsSignInExpiredFor: params('Sign-in expired for {email}'),+ settingsSignedOut: 'Signed out',+ settingsWaitingForApproval: 'Waiting for an administrator to approve your account',+ settingsAccessClosed: 'An administrator declined or removed your access',+ settingsOptionsFor: params('Options for {host}'),+ settingsAccountAndSecurity: 'Account and security',+ settingsShowOnHome: 'Show on Home',+ settingsDisconnectServer: 'Disconnect server',+ settingsSignOutFailed: 'Couldn’t sign out. Check your connection and try again.',+ settingsDisconnectHeading: params('Disconnect {host}?'),+ settingsDisconnectDescription:+ 'You’re signed out and its workspaces leave Home on this device. Your documents stay on the server, and you can connect again anytime.',+ settingsDisconnectUnsavedDescription: count({+ one: 'You’re signed out and its workspaces leave Home on this device. {count} document has changes that haven’t reached the server yet; disconnecting discards them.',+ many: 'You’re signed out and its workspaces leave Home on this device. {count} documents have changes that haven’t reached the server yet; disconnecting discards them.'+ }),+ settingsDisconnect: 'Disconnect',+ settingsDisconnectAndDiscard: 'Disconnect and discard changes',++ // Home+ homeLocations: 'Locations',+ homeRecent: 'Recent',+ homeAccount: params('Account: {email}'),+ homeAccountSettings: 'Account settings',+ homeConnectAnotherServer: 'Connect another server…',+ homeAttentionTip: 'A file here needs a choice',+ homeNeedsAttention: 'Needs attention',+ homeSharedWithYou: 'Shared with you',+ homeSharedSubtitle: 'Files people invited you to',+ homeSharedBy: params('Shared by {name}'),+ homeSignIn: 'Sign in…',+ homeStorage: 'Storage',+ homeStorageSettings: 'Storage settings',+ homeCloudOnHost: params('OpenPencil Cloud · {host}'),+ homeUsageUsed: params('{used} used'),+ homeUsageOf: params('{used} of {total}'),+ homeWorkspaceStorage: params('Workspace storage, {usage}'),+ homeView: 'View',+ homeGrid: 'Grid',+ homeList: 'List',+ homeOfflineHeading: 'You’re offline',+ homeOfflineDescription:+ 'These are the files saved on this device. Changes upload when you reconnect.',+ homeLoadFailedHeading: 'Couldn’t load this workspace',+ homeLoadFailedDescription:+ 'The server didn’t answer. Files saved on this device are still listed.',+ homeConflicts: count({+ one: '{count} file was changed in two places',+ many: '{count} files were changed in two places'+ }),+ homeReview: 'Review',+ homeLoadingFiles: 'Loading files',+ homeEmptyWorkspace: params('No files in {workspace} yet'),+ homeEmptyWorkspaceDescription:+ 'Create a design here, or save an open file to this workspace from the File menu.',+ homeNothingShared: 'Nothing shared with you yet',+ homeNothingSharedDescription: 'Files people invite you to show up here.',+ homeNewDesign: 'New design',+ homeViewOnlyTip: 'You can view this file',+ homeSharedTip: 'Shared with people outside the workspace',+ homeShared: 'Shared',+ syncSynced: 'Saved to Cloud',+ syncUploading: 'Uploading changes…',+ syncPending: 'Changes saved on this device, waiting to upload',+ syncOffline: 'Offline — changes are saved on this device',+ 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.'+} as const++export const cloudMessages = i18n('cloud', cloudMessageDefaults)diff --git a/packages/vue/src/i18n/messages/cloud-portal.ts b/packages/vue/src/i18n/messages/cloud/portal.tssimilarity index 95%rename from packages/vue/src/i18n/messages/cloud-portal.tsrename to packages/vue/src/i18n/messages/cloud/portal.tsindex 0f3778961..d8b57078c 100644--- a/packages/vue/src/i18n/messages/cloud-portal.ts+++ b/packages/vue/src/i18n/messages/cloud/portal.ts@@ -5,6 +5,7 @@ import { i18n } from '#vue/i18n/create'/** Copy for the pages a Cloud server shows on its own address. */export const cloudPortalMessageDefaults = {productName: 'OpenPencil Cloud',+ help: 'Help',loading: 'Loading…',unavailableTitle: 'This server isn’t answering',unavailableDescription: 'Check the address, or try again in a moment.',@@ -12,8 +13,6 @@ export const cloudPortalMessageDefaults = {signInTitle: 'Sign in to OpenPencil Cloud',signUpTitle: 'Create your account',- signInWelcome: 'Welcome back.',- signUpDescription: 'Create an account on this server.',returnsTo: params('Then you go back to {destination}.'),returnsToDesktop: 'the OpenPencil app',returnsToEditor: 'the editor',@@ -26,10 +25,19 @@ export const cloudPortalMessageDefaults = {password: 'Password',passwordHint: params('At least {count} characters.'),forgotPassword: 'Forgot password?',+ repeatPassword: 'Repeat password',+ errorNameRequired: 'Enter your name.',+ errorEmailRequired: 'Enter your email address.',+ errorEmailInvalid: 'Enter an email address such as [email protected].',+ errorPasswordRequired: 'Enter your password.',+ errorPasswordTooShort: params('Use at least {count} characters.'),+ errorPasswordsDiffer: 'The passwords don’t match.',+ verifiedTitle: 'Email verified',+ verifiedDescription: 'Go back to OpenPencil to finish signing in. You can close this tab.',signIn: 'Sign in',createAccount: 'Create account',haveAccount: 'Already have an account?',- newHere: 'New here?',+ newHere: 'New to OpenPencil Cloud?',createAnAccount: 'Create an account',approvalTitle: 'An administrator reviews new accounts',approvalDescription: 'You can sign in once your request is approved. We email you when it is.',diff --git a/packages/vue/src/i18n/messages/common.ts b/packages/vue/src/i18n/messages/common.tsindex ea1c9318e..27b59b60c 100644--- a/packages/vue/src/i18n/messages/common.ts+++ b/packages/vue/src/i18n/messages/common.ts@@ -28,6 +28,8 @@ export const commonMessageDefaults = {you: 'You',youSuffix: 'you',connect: 'Connect',+ showPassword: 'Show password',+ hidePassword: 'Hide password',testConnection: 'Test connection',testingConnection: 'Testing…',search: 'Search…',diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.tsindex d12fa54f1..33e8d8918 100644--- a/packages/vue/src/i18n/messages/files.ts+++ b/packages/vue/src/i18n/messages/files.ts@@ -33,6 +33,7 @@ export const filesMessageDefaults = {searchFiles: 'Search files…',searchRecentAndStorageFiles: 'Search recent and storage files…',newDesign: 'New design',+ newDesignIn: params('New design in {place}'),noMatchingFiles: params('No files match “{query}”.'),saveAsPrompt: 'Save as:',browserFileAPINotSupported:diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex c3c13d507..b8ddd18f2 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -10,11 +10,11 @@ export const menuMessageDefaults = {new: 'New',open: 'Open…',- openStorageWorkspace: 'Open storage workspace…',+ browseFiles: 'Browse files…',openTour: 'Open the Tour',save: 'Save',saveAs: 'Save as…',- saveToStorage: 'Save to storage…',+ saveTo: 'Save to…',exportSelection: 'Export selection…',exportSelectionAsPNG: 'Export selection as PNG',exportSelectionAsSVG: 'Export selection as SVG',diff --git a/packages/vue/src/i18n/messages/settings.ts b/packages/vue/src/i18n/messages/settings.tsindex 758634be9..88e9942fb 100644--- a/packages/vue/src/i18n/messages/settings.ts+++ b/packages/vue/src/i18n/messages/settings.ts@@ -72,7 +72,8 @@ export const settingsMessageDefaults = {discardChangesDescription: 'Your unsaved changes will be lost.',keepEditing: 'Keep editing',discard: 'Discard',- storage: 'Cloud storage',+ storage: 'Storage',+ cloud: 'Cloud',mobilePanelNavigation: 'Mobile panel navigation',notifications: 'Notifications'} as constdiff --git a/packages/vue/src/i18n/messages/variables.ts b/packages/vue/src/i18n/messages/variables/panel.tssimilarity index 100%rename from packages/vue/src/i18n/messages/variables.tsrename to packages/vue/src/i18n/messages/variables/panel.tsdiff --git a/packages/vue/src/i18n/messages/variable-types.ts b/packages/vue/src/i18n/messages/variables/types.tssimilarity index 100%rename from packages/vue/src/i18n/messages/variable-types.tsrename to packages/vue/src/i18n/messages/variables/types.tsdiff --git a/packages/vue/src/i18n/useI18n.ts b/packages/vue/src/i18n/useI18n.tsindex 2436dc384..8cacfd239 100644--- a/packages/vue/src/i18n/useI18n.ts+++ b/packages/vue/src/i18n/useI18n.ts@@ -30,6 +30,7 @@ import {storageMessages,toolMessages,updatesMessages,+ cloudMessages,cloudPortalMessages,variablesMessages,variableTypeMessages@@ -64,6 +65,7 @@ export const useStatusMessages = () => useI18nNamespace(statusMessages)export const useStorageMessages = () => useI18nNamespace(storageMessages)export const useToolMessages = () => useI18nNamespace(toolMessages)export const useUpdateMessages = () => useI18nNamespace(updatesMessages)+export const useCloudMessages = () => useI18nNamespace(cloudMessages)export const useCloudPortalMessages = () => useI18nNamespace(cloudPortalMessages)export const useVariableMessages = () => useI18nNamespace(variablesMessages)export const useVariableTypeMessages = () => useI18nNamespace(variableTypeMessages)diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 6f784e562..8b42fedd4 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -26,6 +26,8 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.- Collaboration lives under `src/app/collab/**` on Yjs and awareness over a `CollabRoomTransport`: Trystero for peer-to-peer rooms, the Cloud relay (`transport/cloud.ts`) for Cloud documents. Preserve crypto-safe room IDs and peer cleanup. Room channels are named in `COLLAB_ACTIONS` from `@open-pencil/cloud/contract`, because the relay reads the document ones to persist rooms and drop viewer writes (`tests/integration/collab/cloud-relay.test.ts`).+- Cloud servers are profiles of the `openpencil-cloud` storage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server through `src/app/cloud/sessions/connection.ts`, never with its own fetch (`tests/app/cloud/sessions/connection.test.ts`).+- An open Cloud document is live in its relay room, and only the elected saver (`electCloudSaver` in `src/app/cloud/rooms/live.ts`) uploads its revisions; guests from a link never save (`tests/integration/collab/cloud-relay.test.ts`).- The Cloud portal is its own entry (`cloud.html`, `src/cloud/`, `src/views/cloud/`) served by the Cloud server, not the editor; it must not import editor sessions, CanvasKit, or `src/app/shell/**`, so `bun run build:cloud-portal` stays small (`open-pencil/no-editor-imports-in-cloud-portal`, `check:arch`).- Which portal pages a visitor may open, by sign-in and account standing, is decided in `portalDestination` alone (`tests/app/cloud-portal/navigation.test.ts`).- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).diff --git a/src/App.vue b/src/App.vueindex 0c2e934f8..3560eff52 100644--- a/src/App.vue+++ b/src/App.vue@@ -3,10 +3,13 @@ import { useHead } from '@unhead/vue'import { useEventListener } from '@vueuse/core'import { MotionConfig } from 'motion-v'import { TooltipProvider } from 'reka-ui'-import { computed, onMounted } from 'vue'+import { computed, onMounted, onUnmounted } from 'vue'+import { useRouter } from 'vue-router'import { provideEditor, useI18n } from '@open-pencil/vue'+import { watchCloudRooms } from '@/app/cloud/rooms/live'+import { startCloudSessions } from '@/app/cloud/sessions/startup'import { useDocumentCloseProtection } from '@/app/document/close/use'import { useFollowingEditorStore } from '@/app/editor/active-store'import { animationsEnabled } from '@/app/shell/motion'@@ -16,6 +19,11 @@ import { useRestartApprovals } from '@/app/shell/updater/approvals'import { scheduleStartupUpdateCheck } from '@/app/shell/updater/check'import { kickSyncEngine } from '@/app/storage/sync'import { prepareForReload } from '@/app/tabs'+import CloudConnectHost from '@/components/cloud/connect/CloudConnectHost.vue'+import CloudInvitationHost from '@/components/cloud/invitation/CloudInvitationHost.vue'+import CloudSaveHost from '@/components/cloud/save/CloudSaveHost.vue'+import CloudNewWorkspaceHost from '@/components/cloud/workspace/CloudNewWorkspaceHost.vue'+import CloudWorkspaceMembersHost from '@/components/cloud/workspace/CloudWorkspaceMembersHost.vue'import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'@@ -28,6 +36,7 @@ import Toaster from '@/components/shell/Toaster.vue'import VoiceCallAudio from '@/components/voice-call/VoiceCallAudio.vue'const { updates, locale } = useI18n()+const router = useRouter()useHead({titleTemplate: (title) => (title ? `${title} — OpenPencil` : 'OpenPencil'),@@ -49,6 +58,10 @@ onMounted(() => {toast.setupGlobalErrorHandler()scheduleStartupUpdateCheck(updates)void kickSyncEngine()+ onUnmounted(watchCloudRooms())+ void startCloudSessions({+ leaveLinkAddress: () => router.isReady().then(() => router.replace('/'))+ })})</script>@@ -60,6 +73,11 @@ onMounted(() => {</AppShell><SettingsDialog /><AISetupDialog />+ <CloudConnectHost />+ <CloudSaveHost />+ <CloudInvitationHost />+ <CloudNewWorkspaceHost />+ <CloudWorkspaceMembersHost /><RecoveryDialog /><UnsavedChangesDialog /><PublishLibraryDialog />diff --git a/src/app/cloud-portal/auth.ts b/src/app/cloud-portal/auth.tsindex 8ca14e25f..d9fb7a193 100644--- a/src/app/cloud-portal/auth.ts+++ b/src/app/cloud-portal/auth.ts@@ -1,6 +1,9 @@import {cloudAuthFailure,createCloudAuthClient,+ resendCloudVerification,+ signInToCloudWithEmail,+ signUpToCloudWithEmail,type CloudAuthResult,type CloudSocialProvider} from '@open-pencil/cloud/client'@@ -10,7 +13,8 @@ const done = <T>(value: T): CloudAuthResult<T> => ({ ok: true, value })/** Sign-in steps against the Cloud server the portal is served from. */export function createPortalAuth(discovery: CloudDiscovery, options: { captcha?: string } = {}) {- const auth = createCloudAuthClient(discovery, { captchaResponse: options.captcha })+ const captcha = { captchaResponse: options.captcha }+ const auth = createCloudAuthClient(discovery, captcha)return {/** Leaves for the provider; the browser comes back to `returnURL`. */@@ -30,31 +34,15 @@ export function createPortalAuth(discovery: CloudDiscovery, options: { captcha?:email: stringpassword: string}): Promise<CloudAuthResult<'signed-in' | 'two-step'>> {- const result = await auth.signIn.email({ ...input, rememberMe: true })- if (result.error) return cloudAuthFailure(result.error)- const twoStep = 'twoFactorRedirect' in result.data && result.data.twoFactorRedirect === true- return done(twoStep ? 'two-step' : 'signed-in')+ const result = await signInToCloudWithEmail(discovery, input, captcha)+ return result.ok ? done(result.value.status) : result},- async signUp(input: {- name: string- email: string- password: string- verifiedURL: string- }): Promise<CloudAuthResult> {- const result = await auth.signUp.email({- name: input.name,- email: input.email,- password: input.password,- callbackURL: input.verifiedURL- })- return result.error ? cloudAuthFailure(result.error) : done(undefined)- },+ signUp: (input: { name: string; email: string; password: string; verifiedURL: string }) =>+ signUpToCloudWithEmail(discovery, input, captcha),- async resendVerification(email: string, verifiedURL: string): Promise<CloudAuthResult> {- const result = await auth.sendVerificationEmail({ email, callbackURL: verifiedURL })- return result.error ? cloudAuthFailure(result.error) : done(undefined)- },+ resendVerification: (email: string, verifiedURL: string) =>+ resendCloudVerification(discovery, { email, verifiedURL }, captcha),async requestPasswordReset(email: string, resetURL: string): Promise<CloudAuthResult> {const result = await auth.requestPasswordReset({ email, redirectTo: resetURL })diff --git a/src/app/cloud-portal/failure.ts b/src/app/cloud-portal/failure.tsindex 891784659..fb67163c8 100644--- a/src/app/cloud-portal/failure.ts+++ b/src/app/cloud-portal/failure.ts@@ -1,27 +1,12 @@import { CloudPortalAPIError, type CloudAuthFailure } from '@open-pencil/cloud/client'import { useCloudPortalMessages } from '@open-pencil/vue'+import { cloudAuthFailureMessage } from '@/app/cloud/sessions/account-form'+/** Words for a failed sign-in step, and for errors the provider sends back in the URL. */export function usePortalFailureMessages() {const messages = useCloudPortalMessages()- function failure(kind: CloudAuthFailure): string {- const value = messages.value- const words: Record<CloudAuthFailure, string> = {- 'invalid-credentials': value.failureInvalidCredentials,- 'email-not-verified': value.failureEmailNotVerified,- 'password-too-short': value.failurePasswordTooShort,- 'password-too-long': value.failurePasswordTooLong,- 'invalid-link': value.failureInvalidLink,- 'invalid-code': value.failureInvalidCode,- 'passkey-cancelled': value.failurePasskeyCancelled,- 'passkey-exists': value.failurePasskeyExists,- 'passkey-unavailable': value.failurePasskeyUnavailable,- 'session-not-fresh': value.errorSessionNotFresh,- 'rate-limited': value.failureRateLimited,- unavailable: value.failureUnavailable- }- return words[kind]- }+ const failure = (kind: CloudAuthFailure) => cloudAuthFailureMessage(kind, messages.value)/** The provider's `error` query values after a social sign-in comes back, or null. */function callback(query: Record<string, unknown>): string | null {const values = ['error', 'error_description', 'error_code']diff --git a/src/app/cloud/availability.ts b/src/app/cloud/availability.tsnew file mode 100644index 000000000..3502e57ff--- /dev/null+++ b/src/app/cloud/availability.ts@@ -0,0 +1,55 @@+import { useLocalStorage } from '@vueuse/core'+import { computed, ref } from 'vue'++import { APP_VERSION } from '@/app/runtime/version'+import { IS_BROWSER, OFFICIAL_CLOUD_URL } from '@/constants'++import { discoverCloudServer } from './sessions/connection'++/** `?cloud=preview` shows Cloud on this device before it is listed; `?cloud=off` stops that. */+const PREVIEW_PARAM = 'cloud'++/**+ * The editor version from which the official server lists itself, as it last said. Kept, so an+ * offline start shows what the last online one did.+ */+const listedFrom = IS_BROWSER+ ? useLocalStorage<string | null>('open-pencil:cloud-listed-from', null)+ : ref<string | null>(null)+const preview = IS_BROWSER ? useLocalStorage('open-pencil:cloud-preview', false) : ref(false)++function versionParts(version: string): number[] | null {+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version)+ return match ? match.slice(1).map(Number) : null+}++/** Whether `version` is `minimum` or later, comparing `major.minor.patch` numerically. */+export function isVersionAtLeast(version: string, minimum: string): boolean {+ const have = versionParts(version)+ const need = versionParts(minimum)+ if (!have || !need) return false+ for (let index = 0; index < need.length; index++) {+ const difference = (have[index] ?? 0) - (need[index] ?? 0)+ if (difference !== 0) return difference > 0+ }+ return true+}++/**+ * Whether the official server is open to this editor, or being previewed here; until then+ * Settings offers its waitlist.+ */+export const cloudOfficialListed = computed(+ () =>+ preview.value || (listedFrom.value !== null && isVersionAtLeast(APP_VERSION, listedFrom.value))+)++/** Reads the preview switch from the address and asks the official server whether it is listed. */+export async function checkCloudAvailability(address: string): Promise<void> {+ const choice = new URL(address).searchParams.get(PREVIEW_PARAM)+ if (choice === 'preview') preview.value = true+ else if (choice === 'off') preview.value = false+ // Unreachable, or not public yet: the last answer stands.+ const discovery = await discoverCloudServer(OFFICIAL_CLOUD_URL).catch(() => null)+ if (discovery) listedFrom.value = discovery.listing?.minimumEditorVersion ?? null+}diff --git a/src/app/cloud/connect/flow.ts b/src/app/cloud/connect/flow.tsnew file mode 100644index 000000000..6253fa5aa--- /dev/null+++ b/src/app/cloud/connect/flow.ts@@ -0,0 +1,306 @@+import { computed, ref, shallowRef } from 'vue'++import {+ CloudClientError,+ resendCloudVerification,+ signInToCloudWithEmail,+ signUpToCloudWithEmail,+ type CloudAuthFailure,+ type CloudDiscoveryFailure+} from '@open-pencil/cloud/client'+import type { CloudDiscovery } from '@open-pencil/cloud/contract'++import { IS_TAURI, OFFICIAL_CLOUD_URL } from '@/constants'++import { normalizeCloudServerURL } from '../servers/address'+import { addCloudServer, findCloudServer, type CloudServer } from '../servers/store'+import type { CloudAccountCredentials } from '../sessions/account-form'+import { cloudFetch, discoverCloudServer, refreshCloudConnection } from '../sessions/connection'+import { createCloudDeviceSignIn } from '../sessions/device'+import {+ cloudSignInRoute,+ redirectToCloudSignIn,+ type CloudSignInMethod+} from '../sessions/sign-in'+import { saveCloudSessionToken } from '../sessions/token'++export type CloudConnectStep = 'server' | 'checking' | 'sign-in' | 'sign-up' | 'verify' | 'device'+export type CloudConnectError = CloudDiscoveryFailure | 'denied' | 'expired' | 'sign-in-failed'++type CheckedServer = { url: string; kind: CloudServer['kind']; discovery: CloudDiscovery }++export const cloudConnectOpen = ref(false)+export const cloudConnectStep = ref<CloudConnectStep>('server')+export const cloudConnectKind = ref<CloudServer['kind']>('official')+/** Whether the dialog asks which server to use; Settings already asked when it names one. */+export const cloudConnectChoosing = ref(true)+export const cloudConnectAddress = ref('')+export const cloudConnectError = ref<CloudConnectError | null>(null)+/** Why the email form's last attempt failed. */+export const cloudConnectFailure = ref<CloudAuthFailure | null>(null)+export const cloudConnectBusy = ref(false)+/** The address a verification link went to, while the dialog waits for it to be opened. */+export const cloudConnectEmail = ref('')+export const cloudConnectResent = ref(false)+const checked = shallowRef<CheckedServer | null>(null)+/** Kept only while waiting for the email to be verified, to finish signing in afterwards. */+let awaitingVerification: CloudAccountCredentials | null = null+const device = createCloudDeviceSignIn()+export const cloudDeviceSignIn = device.state+/** The last sign-in that finished, for whoever opened the dialog to react to. */+export const cloudSignedIn = shallowRef<{ serverId: string } | null>(null)+let generation = 0++/**+ * The checked server's host and how to sign in to it. Email and password happen in the dialog+ * wherever the server accepts this app's requests: the desktop app and the server's own editor.+ */+export const cloudConnectServer = computed(() => {+ const server = checked.value+ if (!server) return null+ const authentication = server.discovery.authentication+ const route = cloudSignInRoute(server.discovery)+ const emailPassword = authentication.emailPassword?.signIn ? authentication.emailPassword : null+ const inline = emailPassword && (IS_TAURI || route === 'redirect') ? emailPassword : null+ const methods: CloudSignInMethod[] = [...authentication.socialProviders]+ if (emailPassword && !inline) methods.push('email')+ return {+ host: new URL(server.url).host,+ methods,+ route,+ emailPassword: inline+ ? { signUp: inline.signUp, minimumPasswordLength: inline.minimumPasswordLength }+ : null,+ approvalRequired: authentication.enrollmentMode === 'approval'+ }+})++/** Whether Back has somewhere to go from the current step. */+export const cloudConnectCanGoBack = computed(() => {+ const step = cloudConnectStep.value+ if (step === 'sign-up' || step === 'verify') return true+ if (step === 'sign-in') return cloudConnectChoosing.value || cloudConnectKind.value !== 'official'+ return false+})++function resetAttempt(): void {+ cloudConnectError.value = null+ cloudConnectFailure.value = null+ cloudConnectBusy.value = false+ cloudConnectResent.value = false+ awaitingVerification = null+}++async function check(url: string, kind: CloudServer['kind']): Promise<void> {+ const attempt = ++generation+ cloudConnectStep.value = 'checking'+ cloudConnectError.value = null+ try {+ const discovery = await discoverCloudServer(url)+ if (attempt !== generation) return+ checked.value = { url, kind, discovery }+ cloudConnectStep.value = 'sign-in'+ } catch (error) {+ if (attempt !== generation) return+ cloudConnectError.value = error instanceof CloudClientError ? error.reason : 'unreachable'+ cloudConnectStep.value = 'server'+ }+}++/**+ * Opens the connect dialog: on the server choice, on one kind of server Settings already chose,+ * or on signing in to a server this app knows, such as one whose sign-in expired.+ */+export function openCloudConnect(options: { kind?: CloudServer['kind']; serverId?: string } = {}) {+ device.cancel()+ checked.value = null+ resetAttempt()+ cloudConnectOpen.value = true+ const known = options.serverId ? findCloudServer(options.serverId) : null+ if (known) {+ cloudConnectChoosing.value = false+ cloudConnectKind.value = known.kind+ cloudConnectAddress.value = known.kind === 'self-hosted' ? known.url : ''+ void check(known.url, known.kind)+ return+ }+ cloudConnectChoosing.value = !options.kind+ cloudConnectKind.value = options.kind ?? 'official'+ cloudConnectAddress.value = ''+ if (options.kind === 'official') {+ void check(OFFICIAL_CLOUD_URL, 'official')+ return+ }+ cloudConnectStep.value = 'server'+}++/** Checks the chosen server answers as OpenPencil Cloud before asking anyone to sign in. */+export function continueCloudConnect(): void {+ const url =+ cloudConnectKind.value === 'official'+ ? OFFICIAL_CLOUD_URL+ : normalizeCloudServerURL(cloudConnectAddress.value)+ if (!url) {+ cloudConnectError.value = 'invalid-address'+ return+ }+ void check(url, cloudConnectKind.value)+}++export function backCloudConnect(): void {+ const step = cloudConnectStep.value+ cloudConnectFailure.value = null+ if (step === 'sign-up' || step === 'verify') {+ awaitingVerification = null+ cloudConnectStep.value = 'sign-in'+ return+ }+ generation+++ device.cancel()+ checked.value = null+ resetAttempt()+ cloudConnectStep.value = 'server'+}++export function showCloudSignUp(): void {+ cloudConnectFailure.value = null+ cloudConnectStep.value = 'sign-up'+}++export function cancelCloudConnect(): void {+ generation+++ device.cancel()+ resetAttempt()+ cloudConnectOpen.value = false+}++async function finishSignIn(server: CloudServer): Promise<void> {+ awaitingVerification = null+ await refreshCloudConnection(server)+ cloudSignedIn.value = { serverId: server.id }+ cloudConnectOpen.value = false+}++/**+ * Signs in to the checked server in the browser, remembering it first: a browser on the server's+ * own editor leaves for the server's pages and comes back; everything else approves a code.+ */+export async function signInToCloudServer(method: CloudSignInMethod): Promise<void> {+ const target = checked.value+ if (!target) return+ // Changing the server or cancelling starts a new generation; this attempt then stops.+ const attempt = generation+ cloudConnectError.value = null+ const server = await addCloudServer({ kind: target.kind, url: target.url })+ if (attempt !== generation) return+ if (cloudSignInRoute(target.discovery) === 'redirect') {+ redirectToCloudSignIn(server.id, target.discovery, method)+ return+ }+ cloudConnectStep.value = 'device'+ const signedIn = await device.start(server.id, target.discovery, cloudFetch)+ if (attempt !== generation) return+ if (signedIn) {+ await finishSignIn(server)+ return+ }+ const outcome = device.state.value.status+ if (outcome === 'idle') return+ cloudConnectError.value =+ outcome === 'denied' || outcome === 'expired' ? outcome : 'sign-in-failed'+ cloudConnectStep.value = 'sign-in'+}++/**+ * Signs in with an email and password in the dialog and keeps the session's token. An account+ * with two-step sign-in finishes in the browser, where the server asks for the second step.+ */+export async function signInWithCloudEmail(credentials: CloudAccountCredentials): Promise<void> {+ const target = checked.value+ if (!target || cloudConnectBusy.value) return+ const attempt = generation+ cloudConnectBusy.value = true+ cloudConnectFailure.value = null+ const result = await signInToCloudWithEmail(target.discovery, credentials, { fetch: cloudFetch })+ if (attempt !== generation) return+ cloudConnectBusy.value = false+ if (!result.ok) {+ if (result.failure === 'email-not-verified') {+ awaitingVerification = credentials+ cloudConnectEmail.value = credentials.email+ // Coming back without having opened the link says so on the same step.+ if (cloudConnectStep.value === 'verify') cloudConnectFailure.value = result.failure+ cloudConnectStep.value = 'verify'+ return+ }+ cloudConnectFailure.value = result.failure+ return+ }+ if (result.value.status === 'two-step') {+ await signInToCloudServer('email')+ return+ }+ const server = await addCloudServer({ kind: target.kind, url: target.url })+ if (attempt !== generation) return+ await saveCloudSessionToken(server.id, result.value.token)+ await finishSignIn(server)+}++/** The page the verification link opens: the server's own, saying to come back here. */+function verifiedURL(target: CheckedServer): string {+ return new URL('/auth/verified', target.url).href+}++export async function signUpWithCloudEmail(credentials: CloudAccountCredentials): Promise<void> {+ const target = checked.value+ if (!target || cloudConnectBusy.value) return+ const attempt = generation+ cloudConnectBusy.value = true+ cloudConnectFailure.value = null+ const result = await signUpToCloudWithEmail(+ target.discovery,+ { ...credentials, verifiedURL: verifiedURL(target) },+ { fetch: cloudFetch }+ )+ if (attempt !== generation) return+ cloudConnectBusy.value = false+ if (!result.ok) {+ cloudConnectFailure.value = result.failure+ return+ }+ awaitingVerification = credentials+ cloudConnectEmail.value = credentials.email+ cloudConnectResent.value = false+ cloudConnectStep.value = 'verify'+}++/** Tries the sign-in again once the person says, or shows by coming back, that they verified. */+export function continueAfterCloudVerification(): Promise<void> {+ if (cloudConnectStep.value !== 'verify' || !awaitingVerification) return Promise.resolve()+ return signInWithCloudEmail(awaitingVerification)+}++export async function resendCloudVerificationEmail(): Promise<void> {+ const target = checked.value+ if (!target || !cloudConnectEmail.value || cloudConnectBusy.value) return+ cloudConnectBusy.value = true+ cloudConnectFailure.value = null+ const result = await resendCloudVerification(+ target.discovery,+ { email: cloudConnectEmail.value, verifiedURL: verifiedURL(target) },+ { fetch: cloudFetch }+ )+ cloudConnectBusy.value = false+ if (result.ok) cloudConnectResent.value = true+ else cloudConnectFailure.value = result.failure+}++/** The server's own page for choosing a new password, opened in a browser. */+export function cloudForgotPasswordURL(): string | null {+ const target = checked.value+ return target ? new URL('/auth/forgot-password', target.url).href : null+}++export function reopenCloudSignInPage(): Promise<void> {+ return device.reopen()+}diff --git a/src/app/cloud/documents/conflict.ts b/src/app/cloud/documents/conflict.tsnew file mode 100644index 000000000..c2720da98--- /dev/null+++ b/src/app/cloud/documents/conflict.ts@@ -0,0 +1,37 @@+import type { EditorStore } from '@/app/editor/session'+import { rememberRecentStorageDocument } from '@/app/recent-files'+import {+ keepBothVersions,+ kickSyncEngine,+ replaceStoredVersion,+ takeStoredVersion+} from '@/app/storage/sync'+import { reloadStorageDocumentInTab } from '@/app/tabs'++export type CloudConflictChoice = 'keep-both' | 'use-cloud' | 'use-mine'++/**+ * Resolves the open document's conflict. Keeping both moves the tab to the copy, which already+ * shows this device's edits; taking the server's version reloads the tab with it; replacing it+ * uploads this device's version over the newer one.+ */+export async function resolveCloudConflict(+ store: EditorStore,+ choice: CloudConflictChoice,+ copyName: string+): Promise<void> {+ const binding = store.getStorageBinding()+ if (!binding) return+ if (choice === 'keep-both') {+ const copyId = await keepBothVersions(binding.documentId, copyName)+ const copy = { ...binding, documentId: copyId }+ store.setStorageDocumentSource(copy, copyName)+ rememberRecentStorageDocument(copy, copyName)+ } else if (choice === 'use-cloud') {+ await takeStoredVersion(binding.documentId)+ await reloadStorageDocumentInTab(store)+ } else {+ await replaceStoredVersion(binding.documentId)+ }+ await kickSyncEngine()+}diff --git a/src/app/cloud/documents/save.ts b/src/app/cloud/documents/save.tsnew file mode 100644index 000000000..ae81a4cb5--- /dev/null+++ b/src/app/cloud/documents/save.ts@@ -0,0 +1,254 @@+import { useLocalStorage } from '@vueuse/core'+import { computed, ref, shallowRef, watch } from 'vue'++import type { EditorStore } from '@/app/editor/session'+import {+ activeStorageProviderID,+ isStorageConfigured,+ readStoragePreferences+} from '@/app/integrations/storage'+import { rememberRecentStorageDocument } from '@/app/recent-files'+import { openSettingsDialog } from '@/app/settings/dialog'+import { getLocalCanvasStore } from '@/app/storage/local-store'+import { getOutbox, syncUIState, uploadProgressByCanvas } from '@/app/storage/sync'+import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'+import { IS_BROWSER } from '@/constants'++import { openCloudConnect } from '../connect/flow'+import { cloudServerHost } from '../servers/address'+import { cloudServers, findCloudServer } from '../servers/store'+import { cloudAPIClient, cloudConnection, refreshCloudConnection } from '../sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++export type CloudSaveState =+ | { kind: 'ready' }+ | { kind: 'saving'; sentBytes: number; totalBytes: number }+ | { kind: 'error'; reason: 'too-large'; limitBytes: number }+ | { kind: 'error'; reason: 'offline' | 'quota' | 'unavailable' }++/** Where Save to can put a document: a signed-in server's workspaces, or the storage bucket. */+export type SaveDestinationGroup =+ | {+ kind: 'cloud'+ serverId: string+ host: string+ workspaces: { id: string; name: string; role: 'viewer' | 'editor' | 'admin' }[]+ }+ | { kind: 'storage'; providerId: string; label: string }++export const cloudSaveOpen = ref(false)+export const cloudSaveName = ref('')+/** `cloud/serverId/workspaceId` or `storage/providerId`: the chosen destination. */+export const cloudSaveDestination = ref('')+export const cloudSaveState = shallowRef<CloudSaveState>({ kind: 'ready' })+export const cloudSaveDestinations = shallowRef<SaveDestinationGroup[]>([])+/** The destination saved to last, chosen first next time. */+const lastDestination = IS_BROWSER ? useLocalStorage('open-pencil:save-destination', '') : ref('')+let target: EditorStore | null = null++/** Workspaces of every signed-in server, grouped by server. */+const cloudDestinations = computed(() =>+ cloudServers.value.flatMap((server): SaveDestinationGroup[] => {+ const connection = cloudConnection(server.id)+ if (connection.state !== 'signed-in' || !connection.workspaces.length) return []+ return [+ {+ kind: 'cloud',+ serverId: server.id,+ host: cloudServerHost(server.url),+ workspaces: connection.workspaces.map(({ id, name, role }) => ({ id, name, role }))+ }+ ]+ })+)++async function storageDestination(): Promise<SaveDestinationGroup[]> {+ const providerId = activeStorageProviderID.value+ if (!(await isStorageConfigured(providerId))) return []+ const bucket = readStoragePreferences(providerId).bucket.trim()+ return [{ kind: 'storage', providerId, label: bucket || providerId }]+}++/** Every destination the document can go to, as `kind/...` keys a writer can save to. */+function writableKeys(groups: SaveDestinationGroup[]): string[] {+ return groups.flatMap((group) =>+ group.kind === 'storage'+ ? [`storage/${group.providerId}`]+ : group.workspaces+ .filter((workspace) => workspace.role !== 'viewer')+ .map((workspace) => `cloud/${group.serverId}/${workspace.id}`)+ )+}++/** Servers still being checked are waited for, so a fresh start does not look signed out. */+async function settledCloudDestinations(): Promise<SaveDestinationGroup[]> {+ const checking = cloudServers.value.filter(+ (server) => cloudConnection(server.id).state === 'checking'+ )+ await Promise.all(checking.map((server) => refreshCloudConnection(server)))+ return cloudDestinations.value+}++/**+ * Save to: straight to the only place the document can go, or a choice when there are several.+ * With nowhere to save yet, it signs in to the server this app knows, or opens Cloud settings.+ */+export async function openSaveTo(store: EditorStore): Promise<void> {+ const groups = [...(await settledCloudDestinations()), ...(await storageDestination())]+ const keys = writableKeys(groups)+ target = store+ cloudSaveName.value = store.state.documentName || 'Untitled'+ cloudSaveState.value = { kind: 'ready' }+ cloudSaveDestinations.value = groups+ if (keys.length === 0) {+ const signedOut = cloudServers.value.find((server) => {+ const state = cloudConnection(server.id).state+ return state === 'expired' || state === 'signed-out'+ })+ if (signedOut) openCloudConnect({ serverId: signedOut.id })+ else openSettingsDialog('cloud')+ return+ }+ if (keys.length === 1) {+ cloudSaveDestination.value = keys[0] ?? ''+ // The dialog only appears when the save fails, to say why.+ if (!(await saveToDestination())) cloudSaveOpen.value = true+ return+ }+ cloudSaveDestination.value = keys.includes(lastDestination.value)+ ? lastDestination.value+ : (keys[0] ?? '')+ cloudSaveOpen.value = true+}++/**+ * Follows a new document's first upload: true once it is on the server, or when the person+ * closes the dialog and leaves it to finish in the background; false when the upload failed.+ */+function waitForFirstUpload(documentId: string, totalBytes: number): Promise<boolean> {+ return new Promise((resolve) => {+ const stops: (() => void)[] = []+ const finish = (uploaded: boolean) => {+ for (const stop of stops) stop()+ resolve(uploaded)+ }+ async function check() {+ const meta = await getLocalCanvasStore().getMeta(documentId)+ if (meta?.syncStatus === 'synced') return finish(true)+ // The engine parks a job it cannot finish until the person acts, rather than dropping it.+ const jobs = await getOutbox().list()+ const parked = jobs.some(+ (job) => job.canvasId === documentId && job.nextAttemptAt === Number.MAX_SAFE_INTEGER+ )+ if (meta?.syncStatus === 'error' || parked) finish(false)+ }+ stops.push(+ watch(uploadProgressByCanvas, (progress) => {+ const sent = progress.get(documentId)+ if (sent !== undefined) {+ cloudSaveState.value = { kind: 'saving', sentBytes: sent * totalBytes, totalBytes }+ }+ }),+ watch(cloudSaveOpen, (open) => {+ if (!open) finish(true)+ }),+ // Failures move the engine's state without a document event.+ watch(syncUIState, () => void check()),+ onStorageWorkspaceEvent((event) => {+ if (event.documentId === documentId) void check()+ })+ )+ // A small file can finish uploading before these watchers exist.+ void check()+ })+}++/**+ * Why the first upload failed, from the workspace's limits: the server refuses a file over its+ * size limit or one that does not fit the remaining storage without saying which.+ */+async function uploadFailure(+ serverId: string,+ workspaceId: string,+ size: number+): Promise<CloudSaveState> {+ const server = findCloudServer(serverId)+ const discovery = server ? cloudConnection(server.id).discovery : null+ if (!server || !discovery) return { kind: 'error', reason: 'unavailable' }+ const entitlements = await cloudAPIClient(server, discovery)+ .getWorkspaceEntitlements(workspaceId)+ .catch(() => null)+ if (!entitlements) return { kind: 'error', reason: 'unavailable' }+ const { limits, usage } = entitlements+ if (size > limits.maximumFileBytes) {+ return { kind: 'error', reason: 'too-large', limitBytes: limits.maximumFileBytes }+ }+ const stored = usage.committedStorageBytes + usage.reservedStorageBytes+ if (limits.maximumStorageBytes !== null && stored + size > limits.maximumStorageBytes) {+ return { kind: 'error', reason: 'quota' }+ }+ return { kind: 'error', reason: 'unavailable' }+}++async function saveToStorageBucket(store: EditorStore, providerId: string): Promise<boolean> {+ if (!(await store.saveFigFileToStorage({ providerId }))) return false+ const binding = store.getStorageBinding()+ if (binding) rememberRecentStorageDocument(binding, store.state.documentName)+ return true+}++/**+ * Saves the document to the chosen destination. A Cloud copy is kept on this device and the tab+ * moves to it at once, then the save follows the first upload. The file it came from is left as+ * it was.+ */+export async function saveToDestination(): Promise<boolean> {+ const store = target+ const destination = cloudSaveDestination.value+ const [kind, first, second] = destination.split('/')+ const name = cloudSaveName.value.trim()+ if (!store || !name || !first) return false+ if (!navigator.onLine) {+ cloudSaveState.value = { kind: 'error', reason: 'offline' }+ return false+ }+ const previousName = store.state.documentName+ store.state.documentName = name+ cloudSaveState.value = { kind: 'saving', sentBytes: 0, totalBytes: 0 }+ if (kind === 'storage') {+ if (!(await saveToStorageBucket(store, first))) {+ store.state.documentName = previousName+ cloudSaveState.value = { kind: 'error', reason: 'unavailable' }+ return false+ }+ lastDestination.value = destination+ cloudSaveOpen.value = false+ return true+ }+ const serverId = first+ const workspaceId = second+ if (!workspaceId) return false+ const location = {+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: serverId,+ containerId: workspaceId+ }+ if (!(await store.saveFigFileToStorage(location))) {+ // Nothing was saved, so the tab keeps the name it had.+ store.state.documentName = previousName+ cloudSaveState.value = { kind: 'error', reason: 'unavailable' }+ return false+ }+ lastDestination.value = destination+ const binding = store.getStorageBinding()+ if (!binding) return false+ rememberRecentStorageDocument(binding, name)+ const meta = await getLocalCanvasStore().getMeta(binding.documentId)+ const size = meta?.figSize ?? 0+ if (!(await waitForFirstUpload(binding.documentId, size))) {+ cloudSaveState.value = await uploadFailure(serverId, workspaceId, size)+ return false+ }+ cloudSaveOpen.value = false+ return true+}diff --git a/src/app/cloud/documents/status.ts b/src/app/cloud/documents/status.tsnew file mode 100644index 000000000..dd948bcbc--- /dev/null+++ b/src/app/cloud/documents/status.ts@@ -0,0 +1,93 @@+import { tryOnScopeDispose, useOnline } from '@vueuse/core'+import { computed, shallowRef, watch } from 'vue'++import type { StorageDocumentBinding } from '@/app/integrations/storage/types'+import { getLocalCanvasStore, type LocalCanvasMeta } from '@/app/storage/local-store'+import { pendingSyncCount, syncUIState, uploadProgressByCanvas } from '@/app/storage/sync'+import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'++import { cloudServerHost } from '../servers/address'+import { findCloudServer } from '../servers/store'+import { cloudConnection } from '../sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++/** Where a Cloud document stands between this device and the server. */+export type CloudSyncState = 'synced' | 'uploading' | 'pending' | 'offline' | 'conflict' | 'error'++/**+ * The state from what this device recorded about the document: a choice to make or a failure+ * first, then an upload in flight, then changes waiting — offline or not — and otherwise saved.+ */+export function cloudSyncState(+ meta: Pick<LocalCanvasMeta, 'syncStatus'> | null,+ uploading: boolean,+ online: boolean+): CloudSyncState {+ if (meta?.syncStatus === 'conflict') return 'conflict'+ if (meta?.syncStatus === 'error') return 'error'+ if (uploading) return 'uploading'+ if (meta?.syncStatus === 'pending') return online ? 'pending' : 'offline'+ return 'synced'+}++export function isCloudBinding(binding: StorageDocumentBinding | null): boolean {+ return binding?.providerId === CLOUD_STORAGE_PROVIDER_ID+}++/** Documents on this device with changes that have not reached this server yet. */+export async function unsentCloudDocumentCount(serverId: string): Promise<number> {+ const metas = await getLocalCanvasStore().listMetas()+ return metas.filter(+ (meta) =>+ meta.providerId === CLOUD_STORAGE_PROVIDER_ID &&+ meta.profileId === serverId &&+ meta.syncStatus !== 'synced'+ ).length+}++/** The open document's Cloud status, kept current while the component using it lives. */+export function useCloudDocumentStatus(binding: () => StorageDocumentBinding | null) {+ const meta = shallowRef<LocalCanvasMeta | null>(null)+ const online = useOnline()+ let reading = 0++ async function refresh(): Promise<void> {+ const current = binding()+ const read = ++reading+ const next =+ isCloudBinding(current) && current+ ? await getLocalCanvasStore().getMeta(current.documentId)+ : null+ if (read === reading) meta.value = next+ }++ watch([binding, syncUIState, pendingSyncCount], () => void refresh(), { immediate: true })+ tryOnScopeDispose(+ onStorageWorkspaceEvent((event) => {+ if (event.documentId && event.documentId === binding()?.documentId) void refresh()+ })+ )++ const location = computed(() => {+ const current = binding()+ if (!current || !isCloudBinding(current) || !current.profileId) return null+ const server = findCloudServer(current.profileId)+ if (!server) return null+ const workspace = cloudConnection(server.id).workspaces.find(+ (candidate) => candidate.id === current.containerId+ )+ return { serverId: server.id, host: cloudServerHost(server.url), workspace: workspace?.name }+ })++ const state = computed(() => {+ const current = binding()+ if (!location.value || !current) return null+ return cloudSyncState(+ meta.value,+ uploadProgressByCanvas.value.has(current.documentId),+ online.value+ )+ })++ return { state, location, meta }+}diff --git a/src/app/cloud/invitations/flow.ts b/src/app/cloud/invitations/flow.tsnew file mode 100644index 000000000..51f57dcc5--- /dev/null+++ b/src/app/cloud/invitations/flow.ts@@ -0,0 +1,182 @@+import { useSessionStorage } from '@vueuse/core'+import * as v from 'valibot'+import { computed, ref, shallowRef } from 'vue'++import { CloudAPIError, createCloudAPIClient } from '@open-pencil/cloud/client'+import type { AcceptedInvitation, InvitationPreview } from '@open-pencil/cloud/contract'++import { openHomeLocation } from '@/app/shell/menu/navigation'+import { openStorageDocumentInNewTab } from '@/app/tabs'+import { IS_BROWSER, OFFICIAL_CLOUD_URL } from '@/constants'++import { openCloudConnect } from '../connect/flow'+import { cloudServerHost, normalizeCloudServerURL } from '../servers/address'+import { addCloudServer, cloudServers, showCloudServerOnHome } from '../servers/store'+import {+ cloudAPIClient,+ cloudConnection,+ cloudFetch,+ discoverCloudServer,+ refreshCloudConnection+} from '../sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++export type CloudInvitationState =+ | 'loading'+ | 'ready'+ | 'accepting'+ | 'sign-in'+ | 'wrong-account'+ | 'unavailable'++const pendingSchema = v.object({ id: v.string(), server: v.string(), token: v.string() })+type PendingInvitation = v.InferOutput<typeof pendingSchema>++/**+ * The invitation this tab is opening, kept for the tab so it survives leaving for the server's+ * sign-in pages, and cleared once accepted or dismissed.+ */+const stored = IS_BROWSER+ ? useSessionStorage<string | null>('open-pencil:cloud-invitation', null)+ : ref<string | null>(null)+const pending = computed<PendingInvitation | null>(() => {+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), pendingSchema), stored.value ?? '')+ return parsed.success ? parsed.output : null+})++export const cloudInvitationOpen = ref(false)+export const cloudInvitationState = ref<CloudInvitationState>('loading')+export const cloudInvitationPreview = shallowRef<InvitationPreview | null>(null)++const knownServer = () => {+ const url = pending.value ? normalizeCloudServerURL(pending.value.server) : null+ return url ? (cloudServers.value.find((server) => server.url === url) ?? null) : null+}++/** What the dialog shows: the document, who invited, and where. */+export const cloudInvitation = computed(() => {+ const preview = cloudInvitationPreview.value+ const invitation = pending.value+ if (!preview || !invitation) return null+ const url = normalizeCloudServerURL(invitation.server) ?? invitation.server+ return {+ ...preview,+ host: cloudServerHost(url),+ unknownServer: !knownServer() && url !== OFFICIAL_CLOUD_URL+ }+})++export const cloudInvitationAccount = computed(() => {+ const server = knownServer()+ return server ? cloudConnection(server.id).account : null+})++function signedInServer() {+ const server = knownServer()+ return server && cloudConnection(server.id).state === 'signed-in' ? server : null+}++/** Re-reads the invitation and where this app stands with its server. */+export async function checkCloudInvitation(): Promise<void> {+ const invitation = pending.value+ if (!invitation) return+ const url = normalizeCloudServerURL(invitation.server)+ if (!url) {+ cloudInvitationState.value = 'unavailable'+ return+ }+ cloudInvitationState.value = 'loading'+ try {+ const discovery = await discoverCloudServer(url)+ const client = createCloudAPIClient(discovery.apiURL, { fetch: cloudFetch })+ cloudInvitationPreview.value = await client.previewInvitation(invitation.id, {+ token: invitation.token+ })+ } catch {+ cloudInvitationState.value = 'unavailable'+ return+ }+ const server = knownServer()+ if (server) await refreshCloudConnection(server)+ cloudInvitationState.value = signedInServer() ? 'ready' : 'sign-in'+}++/** Opens an invitation link: `/cloud/invitations/:id?server=…#token`. */+export function beginCloudInvitation(id: string, server: string, token: string): void {+ stored.value = JSON.stringify({ id, server, token } satisfies PendingInvitation)+ cloudInvitationOpen.value = true+ void checkCloudInvitation()+}++/** Picks an invitation back up after the tab came back from signing in. */+export function resumeCloudInvitation(): void {+ if (!pending.value) return+ cloudInvitationOpen.value = true+ void checkCloudInvitation()+}++export function dismissCloudInvitation(): void {+ stored.value = null+ cloudInvitationOpen.value = false+}++/** Signs in to the invitation's server, remembering it first. */+export async function signInForCloudInvitation(): Promise<void> {+ const url = pending.value ? normalizeCloudServerURL(pending.value.server) : null+ if (!url) return+ const server = await addCloudServer({+ kind: url === OFFICIAL_CLOUD_URL ? 'official' : 'self-hosted',+ url+ })+ openCloudConnect({ serverId: server.id })+}++/**+ * Accepts the invitation and opens what it gives: the document, or the workspace on Home. The+ * server refuses another account's invitation the same way as a used one; right after a valid+ * preview, that means the account.+ */+export async function acceptCloudInvitation(): Promise<void> {+ const invitation = pending.value+ const server = signedInServer()+ const discovery = server ? cloudConnection(server.id).discovery : null+ if (!invitation || !server || !discovery) return+ cloudInvitationState.value = 'accepting'+ const client = cloudAPIClient(server, discovery)+ let accepted: AcceptedInvitation+ try {+ accepted = await client.acceptInvitation(invitation.id, { token: invitation.token })+ } catch (error) {+ cloudInvitationState.value =+ error instanceof CloudAPIError && error.status === 404 ? 'wrong-account' : 'unavailable'+ return+ }+ dismissCloudInvitation()+ if (accepted.kind === 'workspace') {+ await refreshCloudConnection(server)+ showCloudServerOnHome(server.id)+ const router = (await import('@/router')).default+ openHomeLocation(router, { kind: 'workspace', id: accepted.workspaceId })+ return+ }+ const { document } = await client.getDocument(accepted.grant.documentId)+ 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+ }+ )+}++/** Signs in with another account for the invitation. */+export function switchCloudInvitationAccount(): void {+ const server = knownServer()+ if (server) openCloudConnect({ serverId: server.id })+}diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.tsnew file mode 100644index 000000000..5741ccfa3--- /dev/null+++ b/src/app/cloud/rooms/live.ts@@ -0,0 +1,223 @@+import { shallowRef, watch } from 'vue'++import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'++import { 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 { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'+import { allTabs, getTabForStore, getTabsSnapshot } from '@/app/tabs'++import { isCloudBinding } from '../documents/status'+import { cloudConnections } from '../sessions/connection'+import { cloudShareTarget } from '../sharing/document'++/** Each Cloud tab's permission in its room, for the status beside the name. */+export const cloudRoomPermissions = shallowRef<ReadonlyMap<EditorStore, 'edit' | 'view'>>(new Map())+const starting = new WeakSet<EditorStore>()++function setPermission(store: EditorStore, permission: 'edit' | 'view' | null) {+ const next = new Map(cloudRoomPermissions.value)+ if (permission) next.set(store, permission)+ else next.delete(store)+ cloudRoomPermissions.value = next+}++/**+ * The editor that saves the room's document: the one with the lowest presence client among+ * signed-in editors, as the relay stamps them. Guests from a link may edit but cannot save.+ * Everyone else sees edits through the room, so nobody's revision conflicts with anyone else's.+ */+export function electCloudSaver(+ presence: ReadonlyMap<number, Record<string, unknown>>,+ self: { clientId: number; canSave: boolean }+): number | null {+ const editors = [...presence]+ .filter(([clientId, state]) => {+ if (clientId === self.clientId) return self.canSave+ const cloud = state.cloud+ if (typeof cloud !== 'object' || cloud === null) return false+ return Reflect.get(cloud, 'permission') === 'edit' && Reflect.get(cloud, 'kind') === 'user'+ })+ .map(([clientId]) => clientId)+ return editors.length ? Math.min(...editors) : null+}++/** Building on the server's latest revision: the room already holds every edit in it. */+async function catchUpWithServer(store: EditorStore): Promise<void> {+ const binding = store.getStorageBinding()+ if (!binding) return+ const documents = await createStorageAdapter(binding).listDocuments()+ const current = documents.find((document) => document.id === binding.documentId)+ if (current?.revision) {+ await getLocalCanvasStore().updateMeta(binding.documentId, { remoteRevision: current.revision })+ }+}++/**+ * 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.+ */+function followSaver(store: EditorStore, session: RoomSession, canSave: boolean): () => void {+ let saving: boolean | null = null+ const documentId = () => store.getStorageBinding()?.documentId ?? null++ async function decide() {+ const saver = electCloudSaver(session.presence(), { clientId: session.clientId, canSave })+ const next = saver === session.clientId+ if (next === saving) return+ saving = next+ store.state.autosaveEnabled = next+ const id = documentId()+ if (!id) return+ if (!next) {+ await dropCanvasUploads(id)+ return+ }+ await 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()+ }++ async function settleConflict(id: string) {+ if (!saving) return+ const meta = await getLocalCanvasStore().getMeta(id)+ if (meta?.syncStatus !== 'conflict') return+ await replaceStoredVersion(id)+ await kickSyncEngine()+ }++ const stopPeers = watch(session.peers, () => void decide(), { immediate: true })+ // Edits in a tab that does not save are kept by the room and uploaded by the saver, so the+ // tab neither calls them unsaved nor asks about them on closing.+ const stopDirty = watch(+ () => store.hasUnsavedChanges(),+ (dirty) => {+ if (dirty && saving === false) store.markDocumentSaved()+ }+ )+ const stopEvents = onStorageWorkspaceEvent((event) => {+ const id = documentId()+ if (id && event.documentId === id) void settleConflict(id)+ })+ return () => {+ stopPeers()+ stopDirty()+ stopEvents()+ }+}++/**+ * Puts a stored document's tab into its room: an empty room takes this tab's document once the+ * relay has answered, one editor saves for everyone, and a viewer never saves.+ */+export function openCloudDocumentRoom(+ store: EditorStore,+ options: {+ roomId: string+ transport: JoinCollabRoom+ permission: 'edit' | 'view'+ /** A guest from a link edits but has no account to save with. */+ guest?: boolean+ }+) {+ const canEdit = options.permission === 'edit'+ const canSave = canEdit && !options.guest+ const session = openDocumentRoom(store, options.roomId, options.transport)+ setPermission(store, options.permission)+ if (!canSave) store.state.autosaveEnabled = false+ const stopSynced = session.onSynced((peerId) => {+ if (peerId !== RELAY_SERVER_PEER) return+ stopSynced()+ if (canEdit && !session.roomHasDocument()) session.shareDocument()+ })+ const stopSaver = followSaver(store, session, canSave)+ return {+ session,+ stop() {+ stopSynced()+ stopSaver()+ setPermission(store, null)+ }+ }+}++/**+ * The relay connection for a room, presenting the ticket just issued first and a fresh one from+ * `next` before each expires.+ */+export function cloudRelayTransport(+ url: string,+ first: CollaborationTicket,+ next: () => Promise<CollaborationTicket>+): JoinCollabRoom {+ let unused: CollaborationTicket | null = first+ return createCloudRelayJoin({+ url,+ async ticket() {+ const ticket = unused ?? (await next())+ unused = null+ return { token: ticket.token, expiresAt: ticket.expiresAt }+ }+ })+}++/** Leaves the room's saving and status behind once its tab closes. */+export function stopWithTab(store: EditorStore, room: { stop(): void }): void {+ const stopLeaving = watch(allTabs, () => {+ if (roomForStore(store)) return+ room.stop()+ stopLeaving()+ })+}++/**+ * Joins a Cloud document's room on its server's relay, when the server runs one. Edits reach+ * everyone in the room as they happen; an empty room takes this tab's document once the relay+ * has answered; viewers' edits never leave the tab.+ */+export async function startCloudRoom(store: EditorStore): Promise<void> {+ const binding = store.getStorageBinding()+ if (!binding || !isCloudBinding(binding) || roomForStore(store) || starting.has(store)) return+ const target = cloudShareTarget(binding)+ if (!target?.discovery.capabilities.collaboration) return+ starting.add(store)+ try {+ const first = await target.client.getCollaborationTicket(binding.documentId)+ // 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 room = openCloudDocumentRoom(store, {+ roomId: first.roomId,+ transport: cloudRelayTransport(first.serverURL, first, () =>+ target.client.getCollaborationTicket(binding.documentId)+ ),+ permission: first.permission+ })+ stopWithTab(store, room)+ } finally {+ starting.delete(store)+ }+}++/** Starts the room of every open Cloud document, as tabs open and documents move to Cloud. */+export function watchCloudRooms(): () => void {+ return watch(+ () => {+ // Tabs, their bindings, and sign-ins are reactive; the snapshot carries the stores.+ void allTabs.value+ void cloudConnections.value+ return getTabsSnapshot().map((tab) => [tab.store, tab.store.getStorageBinding()] as const)+ },+ (entries) => {+ for (const [store] of entries) void startCloudRoom(store).catch(() => undefined)+ },+ { immediate: true }+ )+}diff --git a/src/app/cloud/servers/address.ts b/src/app/cloud/servers/address.tsnew file mode 100644index 000000000..0b96a6d51--- /dev/null+++ b/src/app/cloud/servers/address.ts@@ -0,0 +1,30 @@+/**+ * The canonical address of a Cloud server from what a person typed: HTTPS unless they wrote a+ * scheme, no query, fragment, or trailing slash. Null when it cannot be a server address.+ */+export function normalizeCloudServerURL(input: string): string | null {+ const trimmed = input.trim()+ if (!trimmed) return null+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`+ let url: URL+ try {+ url = new URL(withScheme)+ } catch {+ return null+ }+ if (!url.hostname) return null+ // The app sends its session token to the server, so plain HTTP is only for this computer, as+ // with MCP servers.+ const loopback =+ url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]'+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return null+ if (url.username || url.password) return null+ url.search = ''+ url.hash = ''+ return url.href.replace(/\/+$/, '')+}++/** The host a person recognizes a server by, such as `cloud.example.com`. */+export function cloudServerHost(url: string): string {+ return new URL(url).host+}diff --git a/src/app/cloud/servers/store.ts b/src/app/cloud/servers/store.tsnew file mode 100644index 000000000..ede9eb04f--- /dev/null+++ b/src/app/cloud/servers/store.ts@@ -0,0 +1,125 @@+import { StorageSerializers, useLocalStorage } from '@vueuse/core'+import * as v from 'valibot'+import { computed, ref } from 'vue'++import { IS_BROWSER } from '@open-pencil/core/constants'++import { OFFICIAL_CLOUD_URL } from '@/constants'++import { normalizeCloudServerURL } from './address'++const CLOUD_SERVERS_KEY = 'open-pencil:cloud-servers'++const cloudAccountSchema = v.object({+ id: v.string(),+ name: v.string(),+ email: v.string()+})++const cloudServerSchema = v.object({+ /** Lowercase hex from the address, so it can name credentials and storage profiles. */+ id: v.pipe(v.string(), v.regex(/^[0-9a-f]{32}$/)),+ url: v.pipe(v.string(), v.url()),+ kind: v.picklist(['official', 'self-hosted']),+ /** The last account signed in here, kept after sign-in expires to sign back in to it. */+ account: v.nullable(cloudAccountSchema),+ addedAt: v.string()+})++const cloudServersSchema = v.object({+ servers: v.array(cloudServerSchema),+ home: v.nullable(v.string())+})++export type CloudAccount = v.InferOutput<typeof cloudAccountSchema>+export type CloudServer = v.InferOutput<typeof cloudServerSchema>+type CloudServers = v.InferOutput<typeof cloudServersSchema>++const EMPTY: CloudServers = { servers: [], home: null }++const stored = !IS_BROWSER+ ? ref<unknown>(null)+ : useLocalStorage<unknown>(CLOUD_SERVERS_KEY, null, {+ serializer: StorageSerializers.object,+ writeDefaults: false+ })++const state = computed<CloudServers>(() => {+ const parsed = v.safeParse(cloudServersSchema, stored.value)+ return parsed.success ? parsed.output : EMPTY+})++function write(next: CloudServers): void {+ stored.value = next+}++/** Servers this app has connected to, in the order they were added. */+export const cloudServers = computed(() => state.value.servers)++/** The server whose workspaces Home shows, if any. */+export const homeCloudServer = computed(+ () => state.value.servers.find((server) => server.id === state.value.home) ?? null+)++export function findCloudServer(id: string): CloudServer | null {+ return state.value.servers.find((server) => server.id === id) ?? null+}++/** The same address always gets the same id, on every device. */+export async function cloudServerId(url: string): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(url))+ return Array.from(new Uint8Array(digest, 0, 16), (byte) =>+ byte.toString(16).padStart(2, '0')+ ).join('')+}++/**+ * Remembers a server, or returns it when already added. The first server goes on Home. Throws+ * when the address cannot be a server's.+ */+export async function addCloudServer(input: {+ kind: CloudServer['kind']+ url?: string+}): Promise<CloudServer> {+ const url = normalizeCloudServerURL(+ input.kind === 'official' ? OFFICIAL_CLOUD_URL : (input.url ?? '')+ )+ if (!url) throw new TypeError('Cloud server address is invalid')+ const existing = state.value.servers.find((server) => server.url === url)+ if (existing) return existing+ const id = await cloudServerId(url)+ // A second call for the same address may have added it while the id was computed.+ const added = state.value.servers.find((server) => server.url === url)+ if (added) return added+ const server: CloudServer = {+ id,+ url,+ kind: input.kind,+ account: null,+ addedAt: new Date().toISOString()+ }+ const current = state.value+ write({ servers: [...current.servers, server], home: current.home ?? server.id })+ return server+}++/** Forgets a server; Home moves to the next one. */+export function removeCloudServer(id: string): void {+ const current = state.value+ const servers = current.servers.filter((server) => server.id !== id)+ const home = current.home === id ? (servers[0]?.id ?? null) : current.home+ write({ servers, home })+}++export function showCloudServerOnHome(id: string): void {+ if (!findCloudServer(id)) return+ write({ ...state.value, home: id })+}++export function rememberCloudAccount(id: string, account: CloudAccount | null): void {+ const current = state.value+ write({+ ...current,+ servers: current.servers.map((server) => (server.id === id ? { ...server, account } : server))+ })+}diff --git a/src/app/cloud/sessions/account-form.ts b/src/app/cloud/sessions/account-form.tsnew file mode 100644index 000000000..3333c0ecf--- /dev/null+++ b/src/app/cloud/sessions/account-form.ts@@ -0,0 +1,103 @@+import * as v from 'valibot'+import { useForm } from 'vee-validate'+import { computed, type Ref } from 'vue'++import type { CloudAuthFailure } from '@open-pencil/cloud/client'+import type { useCloudPortalMessages } from '@open-pencil/vue'++import { validateAfterFirstError } from '@/app/settings/validation/use'++export type CloudAccountFormMode = 'sign-in' | 'sign-up'+export type CloudAccountCredentials = { name: string; email: string; password: string }++type Messages = ReturnType<typeof useCloudPortalMessages>['value']++/**+ * Signing in to or joining a Cloud server with an email and password: what the server would turn+ * down is caught here first, and sign-up asks for the password twice.+ */+export function useCloudAccountForm(+ mode: Readonly<Ref<CloudAccountFormMode>>,+ minimumPasswordLength: Readonly<Ref<number>>,+ messages: Readonly<Ref<Messages>>+) {+ const schema = computed(() => {+ const words = messages.value+ const email = v.pipe(+ v.string(),+ v.trim(),+ v.nonEmpty(words.errorEmailRequired),+ v.email(words.errorEmailInvalid)+ )+ if (mode.value === 'sign-in') {+ // Name and repeat stay in the shape, unchecked, so both modes share the form's fields.+ return v.object({+ name: v.string(),+ email,+ password: v.pipe(v.string(), v.nonEmpty(words.errorPasswordRequired)),+ repeat: v.string()+ })+ }+ return v.pipe(+ v.object({+ name: v.pipe(v.string(), v.trim(), v.nonEmpty(words.errorNameRequired)),+ email,+ password: v.pipe(+ v.string(),+ v.minLength(+ minimumPasswordLength.value,+ words.errorPasswordTooShort({ count: minimumPasswordLength.value })+ )+ ),+ repeat: v.string()+ }),+ v.forward(+ v.partialCheck(+ [['password'], ['repeat']],+ (input) => input.password === input.repeat,+ words.errorPasswordsDiffer+ ),+ ['repeat']+ )+ )+ })+ const form = useForm({+ initialValues: { name: '', email: '', password: '', repeat: '' },+ validationSchema: schema+ })+ const [name] = form.defineField('name', validateAfterFirstError)+ const [email] = form.defineField('email', validateAfterFirstError)+ const [password] = form.defineField('password', validateAfterFirstError)+ const [repeat] = form.defineField('repeat', validateAfterFirstError)++ return {+ fields: { name, email, password, repeat },+ errors: form.errors,+ blur: (field: 'name' | 'email' | 'password' | 'repeat') => form.validateField(field),+ submit: (send: (credentials: CloudAccountCredentials) => void) =>+ form.handleSubmit((values) =>+ send({ name: values.name.trim(), email: values.email.trim(), password: values.password })+ ),+ /** Clears what was typed and every message, keeping the email for the other mode. */+ switchMode: () => form.resetForm({ values: { ...form.values, password: '', repeat: '' } })+ }+}++/** Words for a failed sign-in step, the same in the editor and on the server's pages. */+export function cloudAuthFailureMessage(failure: CloudAuthFailure, words: Messages): string {+ const messages: Record<CloudAuthFailure, string> = {+ 'invalid-credentials': words.failureInvalidCredentials,+ 'email-not-verified': words.failureEmailNotVerified,+ 'password-too-short': words.failurePasswordTooShort,+ 'password-too-long': words.failurePasswordTooLong,+ 'invalid-link': words.failureInvalidLink,+ 'invalid-code': words.failureInvalidCode,+ 'passkey-cancelled': words.failurePasskeyCancelled,+ 'passkey-exists': words.failurePasskeyExists,+ 'passkey-unavailable': words.failurePasskeyUnavailable,+ 'session-not-fresh': words.errorSessionNotFresh,+ 'rate-limited': words.failureRateLimited,+ unavailable: words.failureUnavailable+ }+ return messages[failure]+}diff --git a/src/app/cloud/sessions/connection.ts b/src/app/cloud/sessions/connection.tsnew file mode 100644index 000000000..3cf639356--- /dev/null+++ b/src/app/cloud/sessions/connection.ts@@ -0,0 +1,154 @@+import { shallowRef } from 'vue'++import {+ CloudClientError,+ createCloudAPIClient,+ createCloudPortalClient,+ CloudPortalAPIError,+ discoverCloud,+ type CloudAPIClient,+ type CloudDiscoveryFailure,+ type CloudFetch+} from '@open-pencil/cloud/client'+import type { CloudDiscovery, WorkspaceSummary } from '@open-pencil/cloud/contract'++import { tauriFetch } from '@/app/tauri/http'+import { IS_TAURI } from '@/constants'++import { rememberCloudAccount, type CloudAccount, type CloudServer } from '../servers/store'+import { clearCloudSessionToken, readCloudSessionToken } from './token'++/**+ * Where this app stands with a server: signed in, waiting for an administrator, refused, signed+ * out after having been signed in, never signed in, or out of reach.+ */+export type CloudSessionState =+ | 'checking'+ | 'signed-in'+ | 'pending'+ | 'closed'+ | 'expired'+ | 'signed-out'+ | 'unreachable'++export type CloudConnection = {+ state: CloudSessionState+ discovery: CloudDiscovery | null+ account: CloudAccount | null+ workspaces: WorkspaceSummary[]+ /** Why the server could not be used, while `unreachable`. */+ failure: CloudDiscoveryFailure | null+}++const INITIAL: CloudConnection = {+ state: 'checking',+ discovery: null,+ account: null,+ workspaces: [],+ failure: null+}++/** Each server's connection, replaced whole on every change. */+export const cloudConnections = shallowRef<Readonly<Record<string, CloudConnection>>>({})+const discoveries = new Map<string, Promise<CloudDiscovery>>()+const generations = new Map<string, number>()++export function cloudConnection(serverId: string): CloudConnection {+ return cloudConnections.value[serverId] ?? INITIAL+}++function publish(serverId: string, connection: CloudConnection): void {+ cloudConnections.value = { ...cloudConnections.value, [serverId]: connection }+}++/** Desktop requests skip the webview's CORS, since a server lists only its web editors. */+export const cloudFetch: CloudFetch = (input, init) =>+ IS_TAURI ? tauriFetch(input, init) : globalThis.fetch(input, init)++/** Requests to one server, carrying its device-code token when this app has one. */+export function cloudServerFetch(serverId: string): CloudFetch {+ return async (input, init) => {+ const token = await readCloudSessionToken(serverId)+ if (!token) return cloudFetch(input, init)+ const headers = new Headers(init?.headers)+ headers.set('Authorization', `Bearer ${token}`)+ return cloudFetch(input, { ...init, headers })+ }+}++/** The server's discovery, fetched once per address while the app runs. */+export function discoverCloudServer(url: string): Promise<CloudDiscovery> {+ const cached = discoveries.get(url)+ if (cached) return cached+ const request = discoverCloud(url, { fetch: cloudFetch })+ discoveries.set(url, request)+ request.catch(() => discoveries.delete(url))+ return request+}++export function cloudAPIClient(server: CloudServer, discovery: CloudDiscovery): CloudAPIClient {+ return createCloudAPIClient(discovery.apiURL, { fetch: cloudServerFetch(server.id) })+}++async function signedInConnection(+ server: CloudServer,+ discovery: CloudDiscovery+): Promise<CloudConnection> {+ const portal = createCloudPortalClient({+ baseURL: new URL(discovery.apiURL).origin,+ fetch: cloudServerFetch(server.id)+ })+ let status: Awaited<ReturnType<typeof portal.accountStatus>>+ try {+ status = await portal.accountStatus()+ } catch (error) {+ if (!(error instanceof CloudPortalAPIError) || error.kind !== 'authentication-required') {+ throw error+ }+ // A token the server no longer accepts cannot be used again; keep the account to sign back in.+ if (await readCloudSessionToken(server.id)) await clearCloudSessionToken(server.id)+ return {+ ...INITIAL,+ state: server.account ? 'expired' : 'signed-out',+ discovery,+ account: server.account+ }+ }+ const account = { id: status.user.userId, name: status.user.name, email: status.user.email }+ rememberCloudAccount(server.id, account)+ if (status.state !== 'active') {+ const state = status.state === 'pending' ? 'pending' : 'closed'+ return { ...INITIAL, state, discovery, account }+ }+ const { workspaces } = await cloudAPIClient(server, discovery).listWorkspaces()+ return { state: 'signed-in', discovery, account, workspaces, failure: null }+}++/** Asks the server where this app stands and publishes the answer. */+export async function refreshCloudConnection(server: CloudServer): Promise<CloudConnection> {+ const generation = (generations.get(server.id) ?? 0) + 1+ generations.set(server.id, generation)+ const previous = cloudConnection(server.id)+ publish(server.id, { ...previous, state: 'checking', failure: null })+ let next: CloudConnection+ try {+ const discovery = await discoverCloudServer(server.url)+ next = await signedInConnection(server, discovery)+ } catch (error) {+ next = {+ ...previous,+ state: 'unreachable',+ account: previous.account ?? server.account,+ failure: error instanceof CloudClientError ? error.reason : 'unreachable'+ }+ }+ if (generations.get(server.id) === generation) publish(server.id, next)+ return next+}++/** Drops what the app knows about a server's session, after signing out or removing it. */+export function forgetCloudConnection(serverId: string): void {+ generations.set(serverId, (generations.get(serverId) ?? 0) + 1)+ const { [serverId]: _removed, ...rest } = cloudConnections.value+ cloudConnections.value = rest+}diff --git a/src/app/cloud/sessions/device.ts b/src/app/cloud/sessions/device.tsnew file mode 100644index 000000000..eae194d10--- /dev/null+++ b/src/app/cloud/sessions/device.ts@@ -0,0 +1,101 @@+import { shallowRef } from 'vue'++import {+ CloudDeviceAuthorizationError,+ pollCloudDeviceToken,+ requestCloudDeviceAuthorization,+ type CloudFetch+} from '@open-pencil/cloud/client'+import type { CloudDiscovery } from '@open-pencil/cloud/contract'++import { openExternalLink } from '@/app/shell/ui'++import { clearCloudSessionToken, saveCloudSessionToken } from './token'++/** A device-code sign-in: waiting for approval in the browser, or how it ended. */+export type CloudDeviceSignIn =+ | { status: 'idle' }+ | { status: 'waiting'; code: string; verificationURL: string; expiresAt: number }+ | { status: 'signed-in' }+ | { status: 'denied' | 'expired' | 'failed' }++export type CloudDeviceSignInDependencies = {+ request: typeof requestCloudDeviceAuthorization+ poll: typeof pollCloudDeviceToken+ open(url: string): Promise<void>+ save(serverId: string, token: string): Promise<void>+ clear(serverId: string): Promise<void>+}++const defaults: CloudDeviceSignInDependencies = {+ request: requestCloudDeviceAuthorization,+ poll: pollCloudDeviceToken,+ open: openExternalLink,+ save: saveCloudSessionToken,+ clear: clearCloudSessionToken+}++/**+ * Signing in by approving a code on the server's page. The app opens the page, waits for the+ * approval, and keeps the token it gets. Starting again or cancelling drops the attempt, and a+ * token that arrives after that is cleared rather than kept.+ */+export function createCloudDeviceSignIn(dependencies: CloudDeviceSignInDependencies = defaults) {+ const state = shallowRef<CloudDeviceSignIn>({ status: 'idle' })+ let controller: AbortController | null = null++ function cancel(): void {+ controller?.abort(new DOMException('Sign-in cancelled', 'AbortError'))+ controller = null+ state.value = { status: 'idle' }+ }++ async function start(+ serverId: string,+ discovery: CloudDiscovery,+ fetch?: CloudFetch+ ): Promise<boolean> {+ cancel()+ const attempt = new AbortController()+ controller = attempt+ const { signal } = attempt+ try {+ const authorization = await dependencies.request(discovery, serverId, { fetch })+ signal.throwIfAborted()+ state.value = {+ status: 'waiting',+ code: authorization.user_code,+ verificationURL: authorization.verification_uri_complete,+ expiresAt: Date.now() + authorization.expires_in * 1000+ }+ await dependencies.open(authorization.verification_uri_complete)+ const token = await dependencies.poll(discovery, serverId, authorization, { signal, fetch })+ signal.throwIfAborted()+ await dependencies.save(serverId, token.access_token)+ if (signal.aborted) {+ await dependencies.clear(serverId)+ return false+ }+ state.value = { status: 'signed-in' }+ return true+ } catch (error) {+ if (signal.aborted) return false+ state.value = {+ status:+ error instanceof CloudDeviceAuthorizationError && error.code !== 'unavailable'+ ? error.code+ : 'failed'+ }+ return false+ } finally {+ if (controller === attempt) controller = null+ }+ }++ /** Opens the approval page again, for when the person closed it. */+ async function reopen(): Promise<void> {+ if (state.value.status === 'waiting') await dependencies.open(state.value.verificationURL)+ }++ return { state, start, cancel, reopen }+}diff --git a/src/app/cloud/sessions/sign-in.ts b/src/app/cloud/sessions/sign-in.tsnew file mode 100644index 000000000..41e8fa3f2--- /dev/null+++ b/src/app/cloud/sessions/sign-in.ts@@ -0,0 +1,51 @@+import { useSessionStorage } from '@vueuse/core'+import { ref } from 'vue'++import { cloudSignInURL, type CloudSocialProvider } from '@open-pencil/cloud/client'+import type { CloudDiscovery } from '@open-pencil/cloud/contract'++import { IS_BROWSER, IS_TAURI } from '@/constants'++/** The server this tab left to sign in to; per tab, so another tab's return is not taken. */+const pendingSignIn = IS_BROWSER+ ? useSessionStorage<string | null>('open-pencil:cloud-sign-in', null)+ : ref<string | null>(null)++/**+ * How this app signs in to a server. A server sends people back only to its own editor, so a+ * browser on that address leaves for the server's pages and comes back to this tab; anything+ * else — the desktop app, another editor address — approves a code instead.+ */+export function cloudSignInRoute(discovery: CloudDiscovery): 'redirect' | 'device' {+ if (IS_TAURI || !discovery.appURL) return 'device'+ return new URL(discovery.appURL).origin === globalThis.location.origin ? 'redirect' : 'device'+}++export type CloudSignInMethod = CloudSocialProvider | 'email'++function returnURL(): string {+ const url = new URL(globalThis.location.href)+ url.hash = ''+ return url.href+}++/**+ * Leaves for the server's sign-in pages, which handle two-step sign-in and approval too;+ * `takePendingCloudSignIn` picks the server up after the return.+ */+export function redirectToCloudSignIn(+ serverId: string,+ discovery: CloudDiscovery,+ method: CloudSignInMethod+): void {+ pendingSignIn.value = serverId+ const provider = method === 'email' ? undefined : method+ globalThis.location.assign(cloudSignInURL(discovery, returnURL(), provider))+}++/** The server this tab left to sign in to, once, after coming back. */+export function takePendingCloudSignIn(): string | null {+ const serverId = pendingSignIn.value+ pendingSignIn.value = null+ return serverId+}diff --git a/src/app/cloud/sessions/sign-out.ts b/src/app/cloud/sessions/sign-out.tsnew file mode 100644index 000000000..576d897fc--- /dev/null+++ b/src/app/cloud/sessions/sign-out.ts@@ -0,0 +1,31 @@+import { signOutFromCloud } from '@open-pencil/cloud/client'+import type { CloudDiscovery } from '@open-pencil/cloud/contract'++import { rememberCloudAccount } from '../servers/store'+import { cloudServerFetch, forgetCloudConnection } from './connection'+import { clearCloudSessionToken } from './token'++export type CloudSignOutDependencies = {+ revoke: typeof signOutFromCloud+ clear(serverId: string): Promise<void>+}++const defaults: CloudSignOutDependencies = {+ revoke: signOutFromCloud,+ clear: clearCloudSessionToken+}++/**+ * Ends the session on the server first, so a failed sign-out keeps the token to try again+ * rather than leaving a live session behind, then forgets it here.+ */+export async function signOutOfCloud(+ serverId: string,+ discovery: CloudDiscovery,+ dependencies: CloudSignOutDependencies = defaults+): Promise<void> {+ await dependencies.revoke(discovery, { fetch: cloudServerFetch(serverId) })+ await dependencies.clear(serverId)+ rememberCloudAccount(serverId, null)+ forgetCloudConnection(serverId)+}diff --git a/src/app/cloud/sessions/startup.ts b/src/app/cloud/sessions/startup.tsnew file mode 100644index 000000000..8fde03fcd--- /dev/null+++ b/src/app/cloud/sessions/startup.ts@@ -0,0 +1,51 @@+import { cloudMessages } from '@open-pencil/vue'++import { toast } from '@/app/shell/ui'++import { checkCloudAvailability } from '../availability'+import { cloudSignedIn } from '../connect/flow'+import { beginCloudInvitation, resumeCloudInvitation } from '../invitations/flow'+import { cloudServers, findCloudServer } from '../servers/store'+import { openCloudShareLink } from '../sharing/link'+import { refreshCloudConnection } from './connection'+import { takePendingCloudSignIn } from './sign-in'++const CLOUD_LINK_PATH = /^\/cloud\/(invitations|share)\/([^/]+)$/++/**+ * A Cloud link this tab was opened with: an invitation, `/cloud/invitations/:id?server=…#token`,+ * or a document shared by link, `/cloud/share/:id?server=…#secret`.+ */+function readCloudLink() {+ const url = new URL(globalThis.location.href)+ const [, kind, id] = url.pathname.match(CLOUD_LINK_PATH) ?? []+ const server = url.searchParams.get('server')+ const secret = url.hash.slice(1)+ if (!kind || !id || !server || !secret) return null+ return { kind, id: decodeURIComponent(id), server, secret }+}++/**+ * 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. The+ * 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()+ if (link) await options.leaveLinkAddress()+ const pending = takePendingCloudSignIn()+ await Promise.all(cloudServers.value.map((server) => refreshCloudConnection(server)))+ const server = pending ? findCloudServer(pending) : null+ if (server) cloudSignedIn.value = { serverId: server.id }+ if (link?.kind === 'invitations') beginCloudInvitation(link.id, link.server, link.secret)+ else resumeCloudInvitation()+ if (link?.kind === 'share') {+ await openCloudShareLink({ shareId: link.id, server: link.server, secret: link.secret }).catch(+ () => toast.error(cloudMessages.get().shareLinkFailed)+ )+ }+}diff --git a/src/app/cloud/sessions/token.ts b/src/app/cloud/sessions/token.tsnew file mode 100644index 000000000..572496eee--- /dev/null+++ b/src/app/cloud/sessions/token.ts@@ -0,0 +1,25 @@+import { appCredentialServices } from '@/app/settings/credentials/app'+import { credentialRef } from '@/app/settings/credentials/reference'++/** Cloud servers are storage profiles of this provider; their sessions are its credential. */+export const CLOUD_STORAGE_PROVIDER_ID = 'openpencil-cloud'+export const CLOUD_SESSION_FIELD = 'session'++const sessionRef = (serverId: string) =>+ credentialRef(CLOUD_STORAGE_PROVIDER_ID, CLOUD_SESSION_FIELD, serverId)++/**+ * The bearer token from signing in with a device code. Browsers signed in through the server's+ * own pages have none and use its session cookie instead.+ */+export function readCloudSessionToken(serverId: string): Promise<string | null> {+ return appCredentialServices.resolver.resolve(sessionRef(serverId))+}++export function saveCloudSessionToken(serverId: string, token: string): Promise<void> {+ return appCredentialServices.manager.set(sessionRef(serverId), token)+}++export function clearCloudSessionToken(serverId: string): Promise<void> {+ return appCredentialServices.manager.clear(sessionRef(serverId))+}diff --git a/src/app/cloud/sharing/dialog.ts b/src/app/cloud/sharing/dialog.tsnew file mode 100644index 000000000..06838b0bb--- /dev/null+++ b/src/app/cloud/sharing/dialog.ts@@ -0,0 +1,4 @@+import { ref } from 'vue'++/** The open document's Cloud share dialog, opened from the Share button or its status. */+export const cloudShareOpen = ref(false)diff --git a/src/app/cloud/sharing/document.ts b/src/app/cloud/sharing/document.tsnew file mode 100644index 000000000..1446aac04--- /dev/null+++ b/src/app/cloud/sharing/document.ts@@ -0,0 +1,177 @@+import { cloudShareURL, type CloudAPIClient } from '@open-pencil/cloud/client'+import type { CloudDiscovery, DocumentPermission, DocumentShare } from '@open-pencil/cloud/contract'++import type { StorageDocumentBinding } from '@/app/integrations/storage/types'++import { findCloudServer, type CloudServer } from '../servers/store'+import { cloudAPIClient, cloudConnection } from '../sessions/connection'+import { clearShareSecret, readShareSecret, saveShareSecret } from './secrets'++/** Someone with access: a person granted it, or an invitation not accepted yet. */+export type CloudShareMember = {+ id: string+ name: string+ email: string+ permission: DocumentPermission+ /** When a pending invitation expires. */+ pendingUntil?: string+ you?: boolean+}++export type CloudShareLink =+ | { access: 'restricted' }+ | { access: 'link'; permission: DocumentPermission; copyable: boolean }++export type CloudSharing = {+ canManage: boolean+ members: CloudShareMember[]+ link: CloudShareLink+ /** What the workspace's plan allows for links. */+ links: { allowed: boolean; edit: boolean }+}++type Target = {+ server: CloudServer+ discovery: CloudDiscovery+ client: CloudAPIClient+ documentId: string+ workspaceId: string | null+ accountId: string | null+}++const GRANT = 'grant:'+const INVITATION = 'invitation:'++/** The server, client, and document for a Cloud binding, while signed in to its server. */+export function cloudShareTarget(binding: StorageDocumentBinding): Target | null {+ const server = binding.profileId ? findCloudServer(binding.profileId) : null+ if (!server) return null+ const connection = cloudConnection(server.id)+ if (connection.state !== 'signed-in' || !connection.discovery) return null+ return {+ server,+ discovery: connection.discovery,+ client: cloudAPIClient(server, connection.discovery),+ documentId: binding.documentId,+ workspaceId: binding.containerId ?? null,+ accountId: connection.account?.id ?? null+ }+}++const activeShare = (shares: DocumentShare[]) => shares.find((share) => !share.revokedAt) ?? null++/** Who can open the document and whether its link is on, as this account may see it. */+export async function readCloudSharing(target: Target): Promise<CloudSharing> {+ const { client, documentId } = target+ const access = await client.getDocumentAccess(documentId)+ const closed = { allowed: false, edit: false }+ if (!access.canManageSharing) {+ return { canManage: false, members: [], link: { access: 'restricted' }, links: closed }+ }+ const [grants, invitations, shares, entitlements] = await Promise.all([+ client.listDocumentGrants(documentId),+ client.listDocumentInvitations(documentId),+ client.listDocumentShares(documentId),+ target.workspaceId+ ? client.getWorkspaceEntitlements(target.workspaceId).catch(() => null)+ : Promise.resolve(null)+ ])+ const features = entitlements?.features+ // Links open the document without an account, so they need anonymous access as well.+ const links = features+ ? { allowed: features.capabilityLinks && features.anonymousView, edit: features.anonymousEdit }+ : closed+ const people = await Promise.all(+ grants.map(async (grant) => {+ const profile = await client.getUserProfile(documentId, grant.userId).catch(() => null)+ return {+ id: `${GRANT}${grant.userId}`,+ name: profile?.name ?? grant.userId,+ email: profile?.email ?? '',+ permission: grant.permission,+ you: grant.userId === target.accountId+ }+ })+ )+ const pending = invitations+ .filter((invitation) => !invitation.acceptedAt)+ .map((invitation) => ({+ id: `${INVITATION}${invitation.id}`,+ name: invitation.email,+ email: invitation.email,+ permission: invitation.permission,+ pendingUntil: invitation.expiresAt+ }))+ const share = activeShare(shares)+ const link: CloudShareLink = share+ ? {+ access: 'link',+ permission: share.permission,+ copyable: Boolean(await readShareSecret(target.server.id, share.id))+ }+ : { access: 'restricted' }+ return { canManage: true, members: [...people, ...pending], link, links }+}++export async function inviteToCloudDocument(+ target: Target,+ email: string,+ permission: DocumentPermission+): Promise<void> {+ await target.client.createDocumentInvitation(target.documentId, { email, permission })+}++/** Changes or removes a person's access, or withdraws an invitation. */+export async function changeCloudMember(+ target: Target,+ memberId: string,+ change: DocumentPermission | 'remove'+): Promise<void> {+ const { client, documentId } = target+ if (memberId.startsWith(INVITATION)) {+ const invitationId = memberId.slice(INVITATION.length)+ if (change === 'remove') await client.revokeDocumentInvitation(documentId, invitationId)+ return+ }+ const userId = memberId.slice(GRANT.length)+ if (change === 'remove') await client.revokeDocumentGrant(documentId, userId)+ else await client.putDocumentGrant(documentId, userId, { permission: change })+}++/**+ * Turns the link off, on with a permission, or changes its permission. A new link's secret is+ * kept on this device so the link can be copied here.+ */+export async function changeCloudLink(target: Target, link: CloudShareLink): Promise<void> {+ const { client, documentId, server } = target+ const share = activeShare(await client.listDocumentShares(documentId))+ if (link.access === 'restricted') {+ if (!share) return+ await client.revokeDocumentShare(documentId, share.id)+ await clearShareSecret(server.id, share.id)+ return+ }+ if (share) {+ await client.updateDocumentShare(documentId, share.id, { permission: link.permission })+ return+ }+ const created = await client.createDocumentShare(documentId, { permission: link.permission })+ await saveShareSecret(server.id, created.share.id, created.secret)+}++/** Replaces the link's secret, so old copies stop working and this device can copy it. */+export async function resetCloudLink(target: Target): Promise<void> {+ const { client, documentId, server } = target+ const share = activeShare(await client.listDocumentShares(documentId))+ if (!share) return+ const rotated = await client.rotateDocumentShare(documentId, share.id)+ await saveShareSecret(server.id, rotated.share.id, rotated.secret)+}++/** The link to copy, when this device has its secret. */+export async function cloudLinkURL(target: Target): Promise<string | null> {+ const share = activeShare(await target.client.listDocumentShares(target.documentId))+ if (!share) return null+ const secret = await readShareSecret(target.server.id, share.id)+ return secret ? cloudShareURL(target.discovery, target.server.url, share.id, secret) : null+}diff --git a/src/app/cloud/sharing/link.ts b/src/app/cloud/sharing/link.tsnew file mode 100644index 000000000..d21d26e3e--- /dev/null+++ b/src/app/cloud/sharing/link.ts@@ -0,0 +1,58 @@+import { useLocalStorage } from '@vueuse/core'+import { ref } from 'vue'++import { createCloudAPIClient } from '@open-pencil/cloud/client'+import { randomHex } from '@open-pencil/scene-graph/random'++import { useCollabIdentity } from '@/app/collab/identity'+import { downloadCloudRevision } from '@/app/integrations/storage/cloud/download'+import { storageFetch } from '@/app/integrations/storage/s3/fetch'+import { getTabForStore, openFileInNewTab } from '@/app/tabs'+import { IS_BROWSER } from '@/constants'++import { cloudRelayTransport, openCloudDocumentRoom, stopWithTab } from '../rooms/live'+import { normalizeCloudServerURL } from '../servers/address'+import { cloudFetch, discoverCloudServer } from '../sessions/connection'++/** Who this browser is to rooms it joins from links, kept so a guest stays the same person. */+const guestId = IS_BROWSER+ ? useLocalStorage('open-pencil:cloud-guest-id', randomHex(16))+ : ref(randomHex(16))++export type CloudShareLink = { shareId: string; server: string; secret: string }++/**+ * Opens a document someone shared by link: its latest revision in a tab of its own, then its+ * room as a guest with the link's permission. A guest has no account on the server, so the tab+ * is a copy that never saves there; edits reach the document through the room.+ */+export async function openCloudShareLink(link: CloudShareLink): Promise<void> {+ const url = normalizeCloudServerURL(link.server)+ if (!url) throw new TypeError('The link names no server')+ const discovery = await discoverCloudServer(url)+ const client = createCloudAPIClient(discovery.apiURL, { fetch: cloudFetch })+ const input = {+ secret: link.secret,+ guestName: useCollabIdentity().name.value,+ guestId: guestId.value+ }+ const { document } = await client.getSharedDocument(link.shareId, input)+ const bytes = await downloadCloudRevision(document, (input, init) => storageFetch(input, init))+ const name = document.document.name+ const store = await openFileInNewTab(+ new File([Uint8Array.from(bytes)], `${name}.fig`, { type: 'application/octet-stream' })+ )+ if (!discovery.capabilities.collaboration) return+ const first = await client.getSharedCollaborationTicket(link.shareId, input)+ // The tab may have closed while the ticket was on its way.+ if (first.provider !== 'relay' || !first.serverURL || !getTabForStore(store)) return+ const room = openCloudDocumentRoom(store, {+ roomId: first.roomId,+ transport: cloudRelayTransport(first.serverURL, first, () =>+ client.getSharedCollaborationTicket(link.shareId, input)+ ),+ permission: first.permission,+ guest: true+ })+ stopWithTab(store, room)+}diff --git a/src/app/cloud/sharing/secrets.ts b/src/app/cloud/sharing/secrets.tsnew file mode 100644index 000000000..0e856f391--- /dev/null+++ b/src/app/cloud/sharing/secrets.ts@@ -0,0 +1,23 @@+import { appCredentialServices } from '@/app/settings/credentials/app'+import { credentialRef } from '@/app/settings/credentials/reference'++import { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'++/**+ * A share link's secret, kept only on the device that made it: the server stores a hash, so+ * another device has to reset the link before it can copy one.+ */+const secretRef = (serverId: string, shareId: string) =>+ credentialRef(CLOUD_STORAGE_PROVIDER_ID, `share.${shareId}`, serverId)++export function readShareSecret(serverId: string, shareId: string): Promise<string | null> {+ return appCredentialServices.resolver.resolve(secretRef(serverId, shareId))+}++export function saveShareSecret(serverId: string, shareId: string, secret: string) {+ return appCredentialServices.manager.set(secretRef(serverId, shareId), secret)+}++export function clearShareSecret(serverId: string, shareId: string) {+ return appCredentialServices.manager.clear(secretRef(serverId, shareId))+}diff --git a/src/app/cloud/workspaces/manage.ts b/src/app/cloud/workspaces/manage.tsnew file mode 100644index 000000000..7c6c19d7b--- /dev/null+++ b/src/app/cloud/workspaces/manage.ts@@ -0,0 +1,214 @@+import { computed, ref, shallowRef } from 'vue'++import { CloudAPIError } from '@open-pencil/cloud/client'+import type { WorkspaceMembers, WorkspaceRole } from '@open-pencil/cloud/contract'++import { homeLocation } from '@/app/home/location'++import { findCloudServer, showCloudServerOnHome } from '../servers/store'+import { cloudAPIClient, cloudConnection, refreshCloudConnection } from '../sessions/connection'++/** Why a workspace change did not go through, in terms the dialogs explain. */+export type WorkspaceFailure =+ | 'not-empty'+ | 'cleanup-pending'+ | 'already-member'+ | 'last-admin'+ | 'forbidden'+ | 'not-found'+ | 'unavailable'++function failureOf(error: unknown): WorkspaceFailure {+ if (!(error instanceof CloudAPIError)) return 'unavailable'+ if (error.code === 'not_empty') return 'not-empty'+ if (error.code === 'cleanup_pending') return 'cleanup-pending'+ if (error.code === 'already_member') return 'already-member'+ if (error.code === 'last_admin') return 'last-admin'+ if (error.status === 403) return 'forbidden'+ if (error.status === 404) return 'not-found'+ return 'unavailable'+}++function serverClient(serverId: string) {+ const server = findCloudServer(serverId)+ const discovery = server ? cloudConnection(server.id).discovery : null+ if (!server || !discovery) return null+ return { server, client: cloudAPIClient(server, discovery) }+}++// New workspace++export const newWorkspaceOpen = ref(false)+export const newWorkspaceServerId = ref<string | null>(null)+export const newWorkspaceBusy = ref(false)+export const newWorkspaceFailure = ref<WorkspaceFailure | null>(null)++export function openNewWorkspace(serverId: string): void {+ newWorkspaceServerId.value = serverId+ newWorkspaceFailure.value = null+ newWorkspaceBusy.value = false+ newWorkspaceOpen.value = true+}++/** Creates a workspace the person administers, and shows it on Home. */+export async function createWorkspace(name: string): Promise<void> {+ const target = newWorkspaceServerId.value ? serverClient(newWorkspaceServerId.value) : null+ if (!target || newWorkspaceBusy.value) return+ newWorkspaceBusy.value = true+ newWorkspaceFailure.value = null+ try {+ const workspace = await target.client.createWorkspace(name)+ await refreshCloudConnection(target.server)+ showCloudServerOnHome(target.server.id)+ homeLocation.value = { kind: 'workspace', id: workspace.id }+ newWorkspaceOpen.value = false+ } catch (error) {+ newWorkspaceFailure.value = failureOf(error)+ } finally {+ newWorkspaceBusy.value = false+ }+}++// Members++type MembersTarget = { serverId: string; workspaceId: string }++export const membersOpen = ref(false)+const membersTarget = shallowRef<MembersTarget | null>(null)+export const workspaceMembers = shallowRef<WorkspaceMembers | null>(null)+export const membersLoading = ref(false)+export const membersBusy = ref(false)+export const membersFailure = ref<WorkspaceFailure | null>(null)+/** The link of the invitation just sent, to pass on when the server sends no email. */+export const lastInvitationLink = ref<string | null>(null)++/** The workspace the dialog manages, as the server last listed it to this person. */+export const membersWorkspace = computed(() => {+ const target = membersTarget.value+ if (!target) return null+ const workspace = cloudConnection(target.serverId).workspaces.find(+ (entry) => entry.id === target.workspaceId+ )+ return workspace ?? null+})++export const membersSelf = computed(() => {+ const target = membersTarget.value+ return target ? (cloudConnection(target.serverId).account?.id ?? null) : null+})++async function reload(): Promise<void> {+ const target = membersTarget.value+ const context = target ? serverClient(target.serverId) : null+ if (!target || !context) return+ try {+ workspaceMembers.value = await context.client.listWorkspaceMembers(target.workspaceId)+ } catch (error) {+ membersFailure.value = failureOf(error)+ }+}++export async function openWorkspaceMembers(serverId: string, workspaceId: string): Promise<void> {+ membersTarget.value = { serverId, workspaceId }+ workspaceMembers.value = null+ membersFailure.value = null+ lastInvitationLink.value = null+ membersOpen.value = true+ membersLoading.value = true+ await reload()+ membersLoading.value = false+}++/** Runs one change to the workspace, then lists it again; false when it was refused. */+async function change(+ action: (context: {+ client: ReturnType<typeof cloudAPIClient>+ workspaceId: string+ }) => Promise<void>+): Promise<boolean> {+ const target = membersTarget.value+ const context = target ? serverClient(target.serverId) : null+ if (!target || !context || membersBusy.value) return false+ membersBusy.value = true+ membersFailure.value = null+ try {+ await action({ client: context.client, workspaceId: target.workspaceId })+ await reload()+ return true+ } catch (error) {+ membersFailure.value = failureOf(error)+ return false+ } finally {+ membersBusy.value = false+ }+}++export function inviteToWorkspace(email: string, role: WorkspaceRole): Promise<boolean> {+ return change(async ({ client, workspaceId }) => {+ const created = await client.inviteToWorkspace(workspaceId, { email, role })+ lastInvitationLink.value = created.acceptanceURL+ })+}++export function revokeWorkspaceInvitation(invitationId: string): Promise<boolean> {+ return change(({ client, workspaceId }) =>+ client.revokeWorkspaceInvitation(workspaceId, invitationId)+ )+}++export function changeWorkspaceRole(userId: string, role: WorkspaceRole): Promise<boolean> {+ return change(({ client, workspaceId }) =>+ client.updateWorkspaceMember(workspaceId, userId, role)+ )+}++export function removeWorkspaceMember(userId: string): Promise<boolean> {+ return change(({ client, workspaceId }) => client.removeWorkspaceMember(workspaceId, userId))+}++export async function renameWorkspace(name: string): Promise<boolean> {+ const target = membersTarget.value+ const renamed = await change(async ({ client, workspaceId }) => {+ await client.renameWorkspace(workspaceId, name)+ })+ const context = target ? serverClient(target.serverId) : null+ if (renamed && context) await refreshCloudConnection(context.server)+ return renamed+}++/** Deletes an empty workspace; Home goes back to Recent once it is gone. */+export async function deleteWorkspace(): Promise<void> {+ const target = membersTarget.value+ const context = target ? serverClient(target.serverId) : null+ if (!target || !context || membersBusy.value) return+ membersBusy.value = true+ membersFailure.value = null+ try {+ await context.client.deleteWorkspace(target.workspaceId)+ membersOpen.value = false+ await refreshCloudConnection(context.server)+ } catch (error) {+ membersFailure.value = failureOf(error)+ } finally {+ membersBusy.value = false+ }+}++/** Leaves the workspace; Home goes back to Recent once it is gone. */+export async function leaveWorkspace(): Promise<void> {+ const target = membersTarget.value+ const self = membersSelf.value+ const context = target ? serverClient(target.serverId) : null+ if (!target || !self || !context || membersBusy.value) return+ membersBusy.value = true+ membersFailure.value = null+ try {+ await context.client.removeWorkspaceMember(target.workspaceId, self)+ membersOpen.value = false+ await refreshCloudConnection(context.server)+ } catch (error) {+ membersFailure.value = failureOf(error)+ } finally {+ membersBusy.value = false+ }+}diff --git a/src/app/collab/room/connection.ts b/src/app/collab/room/connection.tsindex 3fe3bebed..ce97c1bf6 100644--- a/src/app/collab/room/connection.ts+++ b/src/app/collab/room/connection.ts@@ -33,6 +33,8 @@ export type CollabRoomConnection = {onPeerLeave: (handler: (peerId: string) => void) => () => void/** The peer whose awareness carries a presence client, so media reaches the right person. */peerForClient: (clientId: number) => string | undefined+ /** Follow peers answering this tab's state with theirs; returns the unsubscribe. */+ onSynced: (handler: (peerId: string) => void) => () => void}type AwarenessEntry = { clientId: number; removed: boolean }@@ -93,6 +95,7 @@ export function connectCollabRoom({const agentPreview = room.makeAction(COLLAB_ACTIONS.agentPreview)// A transport keeps one leave handler, so the connection shares it with its users.const leaveHandlers = new Set<(peerId: string) => void>()+ const syncedHandlers = new Set<(peerId: string) => void>()const awarenessClientsByPeer = new Map<string, Set<number>>()@@ -116,7 +119,8 @@ export function connectCollabRoom({})getSyncReply((data, peerId) => {- applyRemote(ydoc, data, { limit: maxMessageBytes, peerId, compressed: true })+ if (!applyRemote(ydoc, data, { limit: maxMessageBytes, peerId, compressed: true })) return+ for (const handler of syncedHandlers) handler(peerId)})ydoc.on('updateV2', (update: Uint8Array, origin: unknown) => {@@ -160,6 +164,10 @@ export function connectCollabRoom({leaveHandlers.add(handler)return () => leaveHandlers.delete(handler)},+ onSynced(handler) {+ syncedHandlers.add(handler)+ return () => syncedHandlers.delete(handler)+ },peerForClient(clientId) {for (const [peerId, clients] of awarenessClientsByPeer) {if (clients.has(clientId)) return peerIddiff --git a/src/app/collab/rooms.ts b/src/app/collab/rooms.tsindex 749f5162b..ed2cfb828 100644--- a/src/app/collab/rooms.ts+++ b/src/app/collab/rooms.ts@@ -55,6 +55,28 @@ export function shareDocument(store: EditorStore, roomId = generateRoomId()): Roreturn session}+/**+ * Puts a tab's stored document into its server's room. The tab stays that document; what the room+ * already holds arrives through the connection, and an empty room is seeded by whoever asks.+ */+export function openDocumentRoom(+ store: EditorStore,+ roomId: string,+ transport: JoinCollabRoom+): RoomSession {+ const existing = roomForStore(store)+ if (existing) return existing+ const session = openRoomSession({+ roomId,+ store,+ origin: 'shared',+ joinRoom: transport,+ holdsDocument: true+ })+ addSession(session)+ return session+}+export interface JoinRoomOptions {/** What the new tab is called until the room's document brings its own name. */tabName: stringdiff --git a/src/app/collab/route.ts b/src/app/collab/route.tsindex 6b7d638a3..3ff501ef4 100644--- a/src/app/collab/route.ts+++ b/src/app/collab/route.ts@@ -1,6 +1,7 @@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/'@@ -9,15 +10,19 @@ 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. */-function roomPathFor(roomId: string | null, currentPath: string): string {- if (roomId) return shareRoutePath(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 room tab is active, and- * back to `/` when the active tab is not in a room, so a reload or a copied URL opens what is+ * 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 {diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 4962afd68..0ac7daa4e 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -47,6 +47,14 @@ export interface RoomSession {updateSelection(ids: string[]): void/** Writes the tab's whole document into the room and makes its root the room's. */shareDocument(): void+ /** Whether the room holds a document yet, from any peer. */+ roomHasDocument(): boolean+ /** Follow peers answering this tab's state with theirs; returns the unsubscribe. */+ onSynced(handler: (peerId: string) => void): () => void+ /** The awareness states of everyone in the room, this tab included. */+ presence(): ReadonlyMap<number, Record<string, unknown>>+ /** This tab's awareness client. */+ readonly clientId: number/** Leaves the room and releases its connection, presence, and saved-copy handle. */dispose(): void}@@ -69,6 +77,11 @@ export interface RoomSessionOptions {unreachableMs?: number/** How often the tab rechecks its connection while it waits for the file. */tickMs?: number+ /**+ * The tab already shows the room's document, as a stored document opened before its room was:+ * it counts as having the document until the room says it holds another.+ */+ holdsDocument?: boolean}function openIndexedDBCopy(roomId: string, ydoc: Y.Doc): RoomSavedCopy {@@ -85,7 +98,8 @@ export function openRoomSession({identity = useCollabIdentity(),openSavedCopy = openIndexedDBCopy,unreachableMs = ROOM_UNREACHABLE_MS,- tickMs = ROOM_STATUS_TICK_MS+ tickMs = ROOM_STATUS_TICK_MS,+ holdsDocument = false}: RoomSessionOptions): RoomSession {const ydoc = new Y.Doc()const awareness = new awarenessProtocol.Awareness(ydoc)@@ -133,7 +147,7 @@ export function openRoomSession({function refreshDocument() {if (disposed) returnconst rootId = readRoot(meta)- hasDocument.value = rootId !== undefined && store.graph.rootId === rootId+ hasDocument.value = rootId === undefined ? holdsDocument : store.graph.rootId === rootId// Newcomers wait for someone who has the file, so peers say whether they do.if (awareness.getLocalState()?.hasFile !== hasDocument.value) {awareness.setLocalStateField('hasFile', hasDocument.value)@@ -235,6 +249,10 @@ export function openRoomSession({writeRoomName(meta, store.state.documentName)refreshDocument()},+ roomHasDocument: () => readRoot(meta) !== undefined,+ onSynced: (handler) => connection.onSynced(handler),+ presence: () => awareness.getStates() as Map<number, Record<string, unknown>>,+ clientId: awareness.clientID,dispose() {if (disposed) return// Unbinding writes an edit still waiting to be sent, so it runs while the room is open.diff --git a/src/app/document/io/source-state.ts b/src/app/document/io/source-state.tsindex de34d9c37..332da5c99 100644--- a/src/app/document/io/source-state.ts+++ b/src/app/document/io/source-state.ts@@ -1,23 +1,27 @@+import { shallowRef } from 'vue'+import type { DocumentSourceIdentity } from '@/app/document/io/types'import type { StorageDocumentBinding } from '@/app/integrations/storage/types'export function createDocumentSourceState() {- let fileHandle: FileSystemFileHandle | null = null- let filePath: string | null = null+ // Reactive, so the File menu follows a document saved to a file mid-session.+ const fileHandle = shallowRef<FileSystemFileHandle | null>(null)+ const filePath = shallowRef<string | null>(null)let downloadName: string | null = nulllet sourceIdentity: DocumentSourceIdentity = { handle: null, path: null }- let storageBinding: StorageDocumentBinding | null = null+ // Reactive too, so the status beside the name follows a document saved to storage.+ const storageBinding = shallowRef<StorageDocumentBinding | null>(null)let savedVersion = 0let lastWriteTime = 0return {- getFileHandle: () => fileHandle,+ getFileHandle: () => fileHandle.value,setFileHandle: (handle: FileSystemFileHandle | null) => {- fileHandle = handle+ fileHandle.value = handle},- getFilePath: () => filePath,+ getFilePath: () => filePath.value,setFilePath: (path: string | null) => {- filePath = path+ filePath.value = path},getDownloadName: () => downloadName,setDownloadName: (name: string | null) => {@@ -27,9 +31,9 @@ export function createDocumentSourceState() {setSourceIdentity: (identity: DocumentSourceIdentity) => {sourceIdentity = identity},- getStorageBinding: () => storageBinding,+ getStorageBinding: () => storageBinding.value,setStorageBinding: (binding: StorageDocumentBinding | null) => {- storageBinding = binding+ storageBinding.value = binding},getSavedVersion: () => savedVersion,setSavedVersion: (version: number) => {diff --git a/src/app/document/io/source.ts b/src/app/document/io/source.tsindex 3ae095294..3a8f3da48 100644--- a/src/app/document/io/source.ts+++ b/src/app/document/io/source.ts@@ -13,7 +13,8 @@ import { createDocumentSourceState } from '@/app/document/io/source-state'import type { DocumentSourceAccess } from '@/app/document/io/types'import { createDocumentRecovery } from '@/app/document/recovery'import { recoveryEnabled } from '@/app/document/recovery/preferences'-import type { StorageDocumentBinding, StorageProviderID } from '@/app/integrations/storage/types'+import { storageLocationOf } from '@/app/integrations/storage/location'+import type { StorageDocumentBinding, StorageLocation } from '@/app/integrations/storage/types'import { createCanvasId } from '@/app/storage/id'import { trackDocumentFormat } from '@/app/telemetry'@@ -212,13 +213,13 @@ export function createDocumentSourceActions({}/** Upload the document to storage as a new stored document and keep editing it there. */- async function saveFigFileToStorage(providerId: StorageProviderID): Promise<boolean> {+ async function saveFigFileToStorage(location: StorageLocation): Promise<boolean> {const saved = await saveToNewTarget(() => {stopWatchingFile()setFileHandle(null)setFilePath(null)setDownloadName(`${state.documentName}.fig`)- setStorageBinding({ providerId, documentId: createCanvasId() })+ setStorageBinding({ ...storageLocationOf(location), documentId: createCanvasId() })})if (saved) {setSourceIdentity({ handle: null, path: null })diff --git a/src/app/document/io/write.ts b/src/app/document/io/write.tsindex 346141a6e..7b4194f05 100644--- a/src/app/document/io/write.ts+++ b/src/app/document/io/write.ts@@ -1,4 +1,5 @@import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'+import { storageLocationOf } from '@/app/integrations/storage/location'import type { StorageDocumentBinding } from '@/app/integrations/storage/types'import { persistStorageCanvasLocally } from '@/app/storage/sync/persist'import { isTauri } from '@/app/tauri/env'@@ -40,7 +41,7 @@ export function createDocumentWriter({const storage = getStorageBinding()if (storage) {await persistStorageCanvasLocally({- providerId: storage.providerId,+ ...storageLocationOf(storage),canvasId: storage.documentId,name: state.documentName || 'Untitled',figBytes: datadiff --git a/src/app/home/location.ts b/src/app/home/location.tsnew file mode 100644index 000000000..82b045cf7--- /dev/null+++ b/src/app/home/location.ts@@ -0,0 +1,35 @@+import { StorageSerializers, useLocalStorage } from '@vueuse/core'+import * as v from 'valibot'+import { computed, ref } from 'vue'++import { IS_BROWSER } from '@open-pencil/core/constants'++const homeLocationSchema = v.variant('kind', [+ v.object({ kind: v.literal('recent') }),+ v.object({ kind: v.literal('storage') }),+ v.object({ kind: v.literal('shared') }),+ /** A workspace of the server Home shows. */+ v.object({ kind: v.literal('workspace'), id: v.string() })+])++export type HomeLocation = v.InferOutput<typeof homeLocationSchema>++const RECENT: HomeLocation = { kind: 'recent' }++const stored = !IS_BROWSER+ ? ref<unknown>(null)+ : useLocalStorage<unknown>('open-pencil:home-location', null, {+ serializer: StorageSerializers.object,+ writeDefaults: false+ })++/** Where Home lists documents from; Recent until the person picks another place. */+export const homeLocation = computed<HomeLocation>({+ get() {+ const parsed = v.safeParse(homeLocationSchema, stored.value)+ return parsed.success ? parsed.output : RECENT+ },+ set(location) {+ stored.value = location+ }+})diff --git a/src/app/home/locations.ts b/src/app/home/locations.tsnew file mode 100644index 000000000..5896c46ba--- /dev/null+++ b/src/app/home/locations.ts@@ -0,0 +1,92 @@+import { computed } from 'vue'++import { openCloudConnect } from '@/app/cloud/connect/flow'+import { cloudServerHost } from '@/app/cloud/servers/address'+import { homeCloudServer } from '@/app/cloud/servers/store'+import { cloudConnection } from '@/app/cloud/sessions/connection'+import { signOutOfCloud } from '@/app/cloud/sessions/sign-out'+import { openNewWorkspace } from '@/app/cloud/workspaces/manage'+import { openSettingsDialog } from '@/app/settings/dialog'++import { homeLocation, type HomeLocation } from './location'++/** A Home location as the sidebar and the phone menu name it. */+export type HomeLocationView =+ | { kind: 'recent'; id: 'recent' }+ | { kind: 'workspace'; id: string }+ | { kind: 'shared'; id: 'shared' }+ | { kind: 'storage'; id: 'storage' }++const VIEWS = {+ recent: { kind: 'recent', id: 'recent' },+ shared: { kind: 'shared', id: 'shared' },+ storage: { kind: 'storage', id: 'storage' }+} as const satisfies Record<Exclude<HomeLocation['kind'], 'workspace'>, HomeLocationView>++function toView(location: HomeLocation): HomeLocationView {+ return location.kind === 'workspace' ? location : VIEWS[location.kind]+}++function fromView(location: HomeLocationView): HomeLocation {+ return location.kind === 'workspace' ? location : { kind: location.kind }+}++/**+ * Where Home can list documents from: Recent, the workspaces and shared documents of the server+ * Home shows when signed in to it, and storage. A Cloud location the account can no longer+ * reach falls back to Recent.+ */+export function useHomeLocations() {+ const connection = computed(() => {+ const server = homeCloudServer.value+ return server ? { server, ...cloudConnection(server.id) } : null+ })+ const signedIn = computed(() =>+ connection.value?.state === 'signed-in' ? connection.value : null+ )+ const account = computed(() => {+ const current = signedIn.value+ if (!current?.account) return null+ return { ...current.account, host: cloudServerHost(current.server.url) }+ })+ const workspaces = computed(() => signedIn.value?.workspaces ?? [])++ const location = computed<HomeLocation>(() => {+ const chosen = homeLocation.value+ if (chosen.kind === 'shared' && !signedIn.value) return { kind: 'recent' }+ if (chosen.kind === 'workspace' && !workspaces.value.some((entry) => entry.id === chosen.id)) {+ return { kind: 'recent' }+ }+ return chosen+ })+ const workspace = computed(() => {+ const current = location.value+ return current.kind === 'workspace'+ ? (workspaces.value.find((entry) => entry.id === current.id) ?? null)+ : null+ })++ return {+ account,+ workspaces,+ location,+ workspace,+ serverId: computed(() => signedIn.value?.server.id ?? null),+ active: computed(() => toView(location.value)),+ select(next: HomeLocationView) {+ homeLocation.value = fromView(next)+ },+ // Signing back in goes straight to the server Home shows; without one, choose a server.+ connect: () => openCloudConnect({ serverId: homeCloudServer.value?.id }),+ accountSettings: () => openSettingsDialog('cloud'),+ newWorkspace() {+ const server = signedIn.value?.server+ if (server) openNewWorkspace(server.id)+ },+ storageSettings: () => openSettingsDialog('storage'),+ async signOut() {+ const current = signedIn.value+ if (current?.discovery) await signOutOfCloud(current.server.id, current.discovery)+ }+ }+}diff --git a/src/app/integrations/mcp/settings/form.ts b/src/app/integrations/mcp/settings/form.tsindex a7df2a7ab..8d3864d00 100644--- a/src/app/integrations/mcp/settings/form.ts+++ b/src/app/integrations/mcp/settings/form.ts@@ -10,6 +10,7 @@ import {MCP_CONNECTION_NAME_MAX_LENGTH} from '@/app/integrations/mcp'import { requiredSetting, type SettingsValidationMessages } from '@/app/settings/validation/schema'+import { validateAfterFirstError } from '@/app/settings/validation/use'import type { MCPConnectionDraft } from '../types'@@ -71,11 +72,7 @@ export function useMCPConnectionForm(initialValues: { ...omit(createMCPConnectionDraft(), ['id']), credential: false },validationSchema: schema})- const config = (state: { errors: string[] }) => ({- validateOnModelUpdate: state.errors.length > 0,- validateOnChange: false,- validateOnInput: false- })+ const config = validateAfterFirstErrorconst [name] = form.defineField('name', config)const [url] = form.defineField('url', config)const [enabled] = form.defineField('enabled', config)diff --git a/src/app/integrations/storage/cloud/adapter.ts b/src/app/integrations/storage/cloud/adapter.tsnew file mode 100644index 000000000..258838093--- /dev/null+++ b/src/app/integrations/storage/cloud/adapter.ts@@ -0,0 +1,145 @@+import { CloudAPIError, type CloudAPIClient } from '@open-pencil/cloud/client'++import { cloudServerHost } from '@/app/cloud/servers/address'+import { findCloudServer } from '@/app/cloud/servers/store'+import {+ cloudAPIClient,+ cloudConnection,+ refreshCloudConnection+} from '@/app/cloud/sessions/connection'++import { StorageRevisionConflictError, StorageUnavailableError } from '../errors'+import { storageFetch } from '../s3/fetch'+import type { StorageAdapter, StorageProviderRuntime } from '../types'+import { cloudChecksum, downloadCloudRevision } from './download'+import { uploadCloudObject } from './upload'++function revisionConflict(error: unknown): boolean {+ return error instanceof CloudAPIError && error.code === 'revision_conflict'+}++export type CloudStorageDependencies = {+ /** The signed-in API client for a server, or a `StorageUnavailableError`. */+ client(serverId: string): Promise<CloudAPIClient>+ /** Object-store transfers carry no Cloud session, so desktop can send them natively. */+ objectFetch(input: string, init: RequestInit): Promise<Response>+}++/** The API client of a signed-in server, checking once more before giving up. */+async function signedInClient(serverId: string): Promise<CloudAPIClient> {+ const server = findCloudServer(serverId)+ if (!server) throw new StorageUnavailableError('This Cloud server was removed from the app')+ let connection = cloudConnection(server.id)+ if (connection.state !== 'signed-in') connection = await refreshCloudConnection(server)+ if (connection.state !== 'signed-in' || !connection.discovery) {+ throw new StorageUnavailableError(`Sign in to ${cloudServerHost(server.url)} to sync`)+ }+ return cloudAPIClient(server, connection.discovery)+}++const defaults: CloudStorageDependencies = {+ client: signedInClient,+ objectFetch: (input, init) => storageFetch(input, init)+}++/**+ * Documents in one workspace of a Cloud server: the storage profile is the server and the+ * container is the workspace. Every write names the revision it was edited from, and the server+ * refuses it when someone saved since.+ */+export function createCloudStorageAdapter(+ runtime: StorageProviderRuntime,+ dependencies: CloudStorageDependencies = defaults+): StorageAdapter {+ const serverId = runtime.profileId+ const client = () => dependencies.client(serverId)++ function workspaceId(): string {+ if (!runtime.containerId) throw new Error('A Cloud storage location names its workspace')+ return runtime.containerId+ }++ async function listed(id: string) {+ const documents = await (await client()).listDocuments(workspaceId())+ return documents.find((document) => document.id === id) ?? null+ }++ return {+ async testConnection() {+ try {+ const workspaces = await (await client()).listWorkspaces()+ const found = workspaces.workspaces.some((workspace) => workspace.id === workspaceId())+ return found+ ? { ok: true, message: 'Connected to OpenPencil Cloud.' }+ : { ok: false, message: 'This workspace is no longer available.' }+ } catch (error) {+ return { ok: false, message: error instanceof Error ? error.message : String(error) }+ }+ },++ async listDocuments() {+ const documents = await (await client()).listDocuments(workspaceId())+ return documents.map((document) => ({+ id: document.id,+ name: document.name,+ updatedAt: document.updatedAt,+ metadataAuthoritative: true,+ revision: document.currentRevisionId+ }))+ },++ async getDocument(id, onProgress, signal) {+ const download = await (await client()).getDocument(id)+ const bytes = await downloadCloudRevision(+ download,+ (input, init) => dependencies.objectFetch(input, init),+ { signal, onProgress }+ )+ return { bytes, revision: download.revisionId }+ },++ async putDocument(id, bytes, metadata, onProgress, options) {+ const cloud = await client()+ const baseRevision = options?.baseRevision ?? null+ // Without a revision this is the first save; the document may not exist on the server yet.+ if (!baseRevision && !(await listed(id))) {+ await cloud.createDocument(workspaceId(), { id, name: metadata.name })+ }+ const checksum = await cloudChecksum(bytes)+ try {+ const upload = await uploadCloudObject({+ cloud,+ documentId: id,+ bytes,+ checksum,+ baseRevision,+ objectFetch: (input, init) => dependencies.objectFetch(input, init),+ onProgress+ })+ const committed = await cloud.commitUpload(upload.uploadId, {+ checksum,+ multipart: upload.multipart+ })+ return { revision: committed.currentRevisionId }+ } catch (error) {+ if (revisionConflict(error)) {+ throw new StorageRevisionConflictError((await listed(id))?.currentRevisionId ?? null)+ }+ throw error+ }+ },++ async deleteDocument(id) {+ await (await client()).deleteDocument(id)+ },++ async getDocumentMetadata(id) {+ const document = await listed(id)+ return document ? { name: document.name, updatedAt: document.updatedAt } : null+ },++ async getUsage() {+ return (await client()).getUsage(workspaceId())+ }+ }+}diff --git a/src/app/integrations/storage/cloud/download.ts b/src/app/integrations/storage/cloud/download.tsnew file mode 100644index 000000000..b1791dbb4--- /dev/null+++ b/src/app/integrations/storage/cloud/download.ts@@ -0,0 +1,33 @@+import { fromUint8Array } from 'js-base64'++import type { DocumentDownload } from '@open-pencil/cloud/contract'++import type { StorageTransferProgress } from '../types'++export async function cloudChecksum(bytes: Uint8Array): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))+ return fromUint8Array(new Uint8Array(digest))+}++/** A revision's bytes from the object store, checked against what the server recorded. */+export async function downloadCloudRevision(+ download: DocumentDownload,+ objectFetch: (input: string, init: RequestInit) => Promise<Response>,+ options: { signal?: AbortSignal; onProgress?: (progress: StorageTransferProgress) => void } = {}+): Promise<Uint8Array> {+ const response = await objectFetch(download.download.url, {+ method: download.download.method,+ headers: download.download.headers,+ signal: options.signal+ })+ if (!response.ok) throw new Error(`Cloud document download failed with HTTP ${response.status}`)+ const bytes = new Uint8Array(await response.arrayBuffer())+ if (+ bytes.byteLength !== download.byteSize ||+ (await cloudChecksum(bytes)) !== download.checksum+ ) {+ throw new Error('The downloaded Cloud document does not match what the server stored')+ }+ options.onProgress?.({ transferredBytes: bytes.byteLength, totalBytes: download.byteSize })+ return bytes+}diff --git a/src/app/integrations/storage/cloud/upload.ts b/src/app/integrations/storage/cloud/upload.tsnew file mode 100644index 000000000..27c1fb4f0--- /dev/null+++ b/src/app/integrations/storage/cloud/upload.ts@@ -0,0 +1,150 @@+import { retry, Semaphore } from 'es-toolkit'++import type { CloudAPIClient, CloudUpload } from '@open-pencil/cloud/client'++import type { StorageTransferProgress } from '../types'++const MULTIPART_CONCURRENCY = 4+const PART_RETRIES = 2+const RETRY_DELAY_MS = 200++type ObjectFetch = (input: string, init: RequestInit) => Promise<Response>+type MultipartUpload = Extract<CloudUpload['upload'], { kind: 'multipart' }>++export type CloudObjectUpload = {+ cloud: Pick<CloudAPIClient, 'createUpload'>+ documentId: string+ bytes: Uint8Array+ checksum: string+ baseRevision: string | null+ objectFetch: ObjectFetch+ onProgress?: (progress: StorageTransferProgress) => void+ signal?: AbortSignal+}++export type CloudObjectUploadResult = {+ uploadId: string+ multipart?: { uploadId: string; parts: { partNumber: number; etag: string }[] }+}++/** An object-store request the presigned URL refused or the store failed. */+class ObjectUploadError extends Error {+ override readonly name = 'ObjectUploadError'+ constructor(readonly status: number) {+ super(`Cloud object upload failed with HTTP ${status}`)+ }+}++const retryable = (status: number) => status === 408 || status === 429 || status >= 500+// Presigned URLs expire; a fresh upload session gets new ones.+const expired = (error: unknown) =>+ error instanceof ObjectUploadError && (error.status === 401 || error.status === 403)++function body(bytes: Uint8Array): Uint8Array<ArrayBuffer> {+ return bytes.buffer instanceof ArrayBuffer+ ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)+ : Uint8Array.from(bytes)+}++function report(upload: CloudObjectUpload, transferredBytes: number): void {+ upload.onProgress?.({ transferredBytes, totalBytes: upload.bytes.byteLength })+}++async function putPart(+ upload: CloudObjectUpload,+ part: MultipartUpload['parts'][number],+ bytes: Uint8Array,+ signal: AbortSignal+): Promise<string> {+ return retry(+ async () => {+ const response = await upload.objectFetch(part.url, {+ method: part.method,+ headers: part.headers,+ body: body(bytes),+ signal+ })+ if (!response.ok) throw new ObjectUploadError(response.status)+ const etag = response.headers.get('etag')+ if (!etag) throw new Error('Cloud multipart upload response did not include an ETag')+ return etag+ },+ {+ retries: PART_RETRIES,+ delay: (attempt) => RETRY_DELAY_MS * 2 ** attempt,+ signal,+ shouldRetry: (error) => error instanceof ObjectUploadError && retryable(error.status)+ }+ )+}++async function putParts(upload: CloudObjectUpload, multipart: MultipartUpload) {+ const controller = new AbortController()+ const stop = () => controller.abort(upload.signal?.reason)+ upload.signal?.addEventListener('abort', stop, { once: true })+ const semaphore = new Semaphore(Math.min(MULTIPART_CONCURRENCY, multipart.parts.length))+ let transferred = 0+ try {+ return await Promise.all(+ multipart.parts.map(async (part) => {+ await semaphore.acquire()+ try {+ controller.signal.throwIfAborted()+ const start = (part.partNumber - 1) * multipart.partSize+ const bytes = upload.bytes.subarray(start, start + multipart.partSize)+ const etag = await putPart(upload, part, bytes, controller.signal)+ transferred += bytes.byteLength+ report(upload, transferred)+ return { partNumber: part.partNumber, etag }+ } catch (error) {+ // One failed part fails the upload; the others stop instead of finishing for nothing.+ controller.abort(error)+ throw error+ } finally {+ semaphore.release()+ }+ })+ )+ } finally {+ upload.signal?.removeEventListener('abort', stop)+ }+}++async function transfer(upload: CloudObjectUpload): Promise<CloudObjectUploadResult> {+ const pending = await upload.cloud.createUpload(upload.documentId, {+ baseRevisionId: upload.baseRevision,+ byteSize: upload.bytes.byteLength,+ checksum: upload.checksum,+ contentType: 'application/octet-stream'+ })+ report(upload, 0)+ if (pending.upload.kind === 'single') {+ const response = await upload.objectFetch(pending.upload.url, {+ method: pending.upload.method,+ headers: pending.upload.headers,+ body: body(upload.bytes),+ signal: upload.signal+ })+ if (!response.ok) throw new ObjectUploadError(response.status)+ report(upload, upload.bytes.byteLength)+ return { uploadId: pending.id }+ }+ const parts = await putParts(upload, pending.upload)+ return { uploadId: pending.id, multipart: { uploadId: pending.upload.uploadId, parts } }+}++/**+ * Sends a document's bytes straight to the server's object store through presigned URLs, in+ * parallel parts for large files, starting once more if the URLs expired on the way.+ */+export async function uploadCloudObject(+ upload: CloudObjectUpload+): Promise<CloudObjectUploadResult> {+ try {+ return await transfer(upload)+ } catch (error) {+ if (!expired(error)) throw error+ upload.signal?.throwIfAborted()+ return transfer(upload)+ }+}diff --git a/src/app/integrations/storage/errors.ts b/src/app/integrations/storage/errors.tsnew file mode 100644index 000000000..8708930c9--- /dev/null+++ b/src/app/integrations/storage/errors.ts@@ -0,0 +1,19 @@+/** A write based on a revision the provider has since replaced, as when someone else saved. */+export class StorageRevisionConflictError extends Error {+ override readonly name = 'StorageRevisionConflictError'++ constructor(+ /** The provider's current revision, when it reports one. */+ readonly currentRevision: string | null+ ) {+ super('The stored document changed since this copy was opened')+ }+}++/**+ * The provider cannot be reached with what this device has now, such as a signed-out Cloud+ * account. Work waits until the person fixes it rather than counting as failed attempts.+ */+export class StorageUnavailableError extends Error {+ override readonly name = 'StorageUnavailableError'+}diff --git a/src/app/integrations/storage/index.ts b/src/app/integrations/storage/index.tsindex 0e9ee64e4..820ddaa12 100644--- a/src/app/integrations/storage/index.ts+++ b/src/app/integrations/storage/index.ts@@ -10,8 +10,19 @@ export { defineStorageProvider, StorageProviderRegistry } from './registry'export { createS3StorageAdapter } from './s3/adapter'export type { S3StorageAdapter } from './s3/adapter'export type { S3CompatibleConfig, S3ConnectionResult } from './s3/types'+export { StorageRevisionConflictError, StorageUnavailableError } from './errors'+export {+ DEFAULT_STORAGE_PROFILE,+ sameStorageDocument,+ sameStorageLocation,+ storageLocationOf,+ storageProfileId+} from './location'export {createActiveStorageAdapter,+ createStorageAdapter,+ openStorageAdapter,+ resetStorageProviderRegistryForTests,isStorageConfigured,storageCredentialRefs,storageCredentialStatuses@@ -23,6 +34,10 @@ export type {StorageCredentialField,StorageDocument,StorageDocumentBinding,+ StorageDocumentContent,+ StorageLocation,+ StoragePutOptions,+ StoragePutResult,StorageDocumentMetadata,StorageFieldID,LibraryObjectStore,diff --git a/src/app/integrations/storage/location.ts b/src/app/integrations/storage/location.tsnew file mode 100644index 000000000..df76606d2--- /dev/null+++ b/src/app/integrations/storage/location.ts@@ -0,0 +1,30 @@+import type { StorageDocumentBinding, StorageLocation } from './types'++export const DEFAULT_STORAGE_PROFILE = 'default'++export function storageProfileId(location: StorageLocation): string {+ return location.profileId ?? DEFAULT_STORAGE_PROFILE+}++export function sameStorageLocation(first: StorageLocation, second: StorageLocation): boolean {+ return (+ first.providerId === second.providerId &&+ storageProfileId(first) === storageProfileId(second) &&+ first.containerId === second.containerId+ )+}++export function sameStorageDocument(+ first: StorageDocumentBinding,+ second: StorageDocumentBinding+): boolean {+ return sameStorageLocation(first, second) && first.documentId === second.documentId+}++/** The location part of a binding or stored row, without its document. */+export function storageLocationOf(source: StorageLocation): StorageLocation {+ const location: StorageLocation = { providerId: source.providerId }+ if (source.profileId !== undefined) location.profileId = source.profileId+ if (source.containerId !== undefined) location.containerId = source.containerId+ return location+}diff --git a/src/app/integrations/storage/providers.ts b/src/app/integrations/storage/providers.tsindex 7c2562624..a055eb8a1 100644--- a/src/app/integrations/storage/providers.ts+++ b/src/app/integrations/storage/providers.ts@@ -1,3 +1,6 @@+import { CLOUD_SESSION_FIELD, CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'++import { createCloudStorageAdapter } from './cloud/adapter'import { defineStorageProvider, StorageProviderRegistry } from './registry'import { createS3StorageAdapter } from './s3/adapter'@@ -17,4 +20,17 @@ export const S3_STORAGE_PROVIDER = defineStorageProvider({createAdapter: createS3StorageAdapter})-export const storageProviderRegistry = new StorageProviderRegistry([S3_STORAGE_PROVIDER])+/** Servers are profiles and workspaces containers; signing in replaces typed credentials. */+export const CLOUD_STORAGE_PROVIDER = defineStorageProvider({+ id: CLOUD_STORAGE_PROVIDER_ID,+ label: 'OpenPencil Cloud',+ description: 'Workspaces on OpenPencil Cloud or your team’s own server',+ preferenceFields: [],+ credentialFields: [{ id: CLOUD_SESSION_FIELD, label: 'Session' }],+ createAdapter: (runtime) => createCloudStorageAdapter(runtime)+})++export const storageProviderRegistry = new StorageProviderRegistry([+ S3_STORAGE_PROVIDER,+ CLOUD_STORAGE_PROVIDER+])diff --git a/src/app/integrations/storage/registry.ts b/src/app/integrations/storage/registry.tsindex 495d93711..e4fe2bca3 100644--- a/src/app/integrations/storage/registry.ts+++ b/src/app/integrations/storage/registry.ts@@ -40,7 +40,9 @@ export class StorageProviderRegistry {return Promise.reject(new Error(`Unknown credential field for ${id}: ${field}`))}return context.credentials.resolve(credentialRef(id, field, profileId))- }+ },+ profileId,+ containerId: context.containerId})}}diff --git a/src/app/integrations/storage/runtime.ts b/src/app/integrations/storage/runtime.tsindex 9a5fc2455..012497d41 100644--- a/src/app/integrations/storage/runtime.ts+++ b/src/app/integrations/storage/runtime.ts@@ -2,13 +2,16 @@ import { appCredentialServices } from '@/app/settings/credentials/app'import { credentialRef } from '@/app/settings/credentials/reference'import type { CredentialRef, CredentialStatus } from '@/app/settings/credentials/types'+import { StorageUnavailableError } from './errors'+import { storageProfileId } from './location'import {activeStorageProviderID,readStoragePreferences,storagePreferencesComplete} from './preferences'import { storageProviderRegistry } from './providers'-import type { StorageAdapter, StorageProviderID } from './types'+import type { StorageProviderRegistry } from './registry'+import type { StorageAdapter, StorageLocation, StorageProviderID } from './types'export function storageCredentialRefs(providerID: StorageProviderID,@@ -54,3 +57,46 @@ export function createActiveStorageAdapter(profileId: profileID})}++let registry: StorageProviderRegistry = storageProviderRegistry++/** Swaps the registered providers, so tests can supply an in-memory one. */+export function resetStorageProviderRegistryForTests(replacement?: StorageProviderRegistry) {+ registry = replacement ?? storageProviderRegistry+}++/** An adapter for one location: its provider, profile, and container. */+export function createStorageAdapter(location: StorageLocation): StorageAdapter {+ return registry.createAdapter(location.providerId, {+ preferences: readStoragePreferences(location.providerId),+ credentials: appCredentialServices.resolver,+ profileId: storageProfileId(location),+ containerId: location.containerId+ })+}++/**+ * An adapter for a location that is ready to use, for background work. Throws+ * `StorageUnavailableError` while the location still needs settings or credentials; providers+ * that sign in rather than store fields throw it from their own calls.+ */+export async function openStorageAdapter(location: StorageLocation): Promise<StorageAdapter> {+ const provider = registry.get(location.providerId)+ const required = provider.preferenceFields.filter((field) => field.required)+ const preferences = readStoragePreferences(location.providerId)+ if (required.some((field) => !preferences[field.id]?.trim())) {+ throw new StorageUnavailableError(`${provider.label} is not configured`)+ }+ const missing = await Promise.all(+ provider.credentialFields+ .filter((field) => field.required)+ .map(async (field) => {+ const ref = credentialRef(location.providerId, field.id, storageProfileId(location))+ return (await appCredentialServices.manager.status(ref)) !== 'configured'+ })+ )+ if (missing.includes(true)) {+ throw new StorageUnavailableError(`${provider.label} credentials are unavailable`)+ }+ return createStorageAdapter(location)+}diff --git a/src/app/integrations/storage/s3/adapter.ts b/src/app/integrations/storage/s3/adapter.tsindex c352c4ea4..f5f8d26c3 100644--- a/src/app/integrations/storage/s3/adapter.ts+++ b/src/app/integrations/storage/s3/adapter.ts@@ -202,7 +202,8 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Storasignal)if (!bytes) throw new Error(`Document not found: ${id}`)- return bytes+ // Buckets do not record which version a copy came from, so S3 documents are last-writer-wins.+ return { bytes, revision: null }},async putDocument(id, bytes, metadata, onProgress) {@@ -229,6 +230,7 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Stora}),'application/json')+ return { revision: null }},async getDocumentMetadata(id) {diff --git a/src/app/integrations/storage/types.ts b/src/app/integrations/storage/types.tsindex 9872952be..39dadb706 100644--- a/src/app/integrations/storage/types.ts+++ b/src/app/integrations/storage/types.ts@@ -3,8 +3,18 @@ import type { CredentialResolver } from '@/app/settings/credentials/types'export type StorageProviderID = stringexport type StorageFieldID = string-export type StorageDocumentBinding = {+/**+ * Where documents live: a provider, the account or server profile used with it, and, for+ * providers that hold several collections such as Cloud workspaces, which one.+ */+export type StorageLocation = {providerId: StorageProviderID+ /** Defaults to `default`, the one profile of single-account providers. */+ profileId?: string+ containerId?: string+}++export type StorageDocumentBinding = StorageLocation & {documentId: string}@@ -22,6 +32,30 @@ export type StorageDocument = StorageDocumentMetadata & {id: stringthumbnailURL?: string | nullmetadataAuthoritative?: boolean+ /**+ * The provider's opaque version of the stored bytes, for providers that track revisions. A+ * local copy based on the same revision is current.+ */+ revision?: string | null+}++/** Stored bytes and the revision they are, when the provider tracks revisions. */+export type StorageDocumentContent = {+ bytes: Uint8Array+ revision: string | null+}++export type StoragePutOptions = {+ /**+ * The revision the local bytes were edited from. A provider that tracks revisions refuses+ * the write with `StorageRevisionConflictError` when the stored revision has moved on.+ */+ baseRevision?: string | null+}++export type StoragePutResult = {+ /** The revision the write created, or null when the provider does not track revisions. */+ revision: string | null}export type StorageUsage = {@@ -70,13 +104,14 @@ export interface StorageAdapter {id: string,onProgress?: (progress: StorageTransferProgress) => void,signal?: AbortSignal- ): Promise<Uint8Array>+ ): Promise<StorageDocumentContent>putDocument(id: string,bytes: Uint8Array,metadata: StorageDocumentMetadata,- onProgress?: (progress: StorageTransferProgress) => void- ): Promise<void>+ onProgress?: (progress: StorageTransferProgress) => void,+ options?: StoragePutOptions+ ): Promise<StoragePutResult>deleteDocument(id: string): Promise<void>getDocumentMetadata?(id: string): Promise<StorageDocumentMetadata | null>getUsage(): Promise<StorageUsage>@@ -103,6 +138,8 @@ export type StorageCredentialField = {export type StorageProviderRuntime = {preferences: Readonly<Record<StorageFieldID, string>>resolveCredential(field: StorageFieldID): Promise<string | null>+ profileId: string+ containerId?: string}export type StorageProviderRegistration = {@@ -118,4 +155,5 @@ export type StorageAdapterContext = {preferences: Readonly<Record<StorageFieldID, string>>credentials: CredentialResolverprofileId?: string+ containerId?: string}diff --git a/src/app/recent-files/store.ts b/src/app/recent-files/store.tsindex 23a599f37..1de5b29bd 100644--- a/src/app/recent-files/store.ts+++ b/src/app/recent-files/store.ts@@ -1,7 +1,13 @@import { useLocalStorage } from '@vueuse/core'import { computed } from 'vue'-import type { StorageProviderID } from '@/app/integrations/storage'+import {+ DEFAULT_STORAGE_PROFILE,+ storageLocationOf,+ storageProfileId,+ type StorageDocumentBinding,+ type StorageProviderID+} from '@/app/integrations/storage'import { clearRecentFileThumbnails } from './thumbnails'@@ -20,6 +26,8 @@ export interface RecentStorageDocument {id: stringkind: 'storage'providerId: StorageProviderID+ profileId?: string+ containerId?: stringdocumentId: stringname: stringupdatedAt: string@@ -37,8 +45,12 @@ function localDocumentId(path: string): string {return `local:${path}`}-function storageDocumentId(providerId: StorageProviderID, documentId: string): string {- return `storage:${providerId}:${documentId}`+function storageDocumentId(binding: StorageDocumentBinding): string {+ const profileId = storageProfileId(binding)+ // Documents of single-account providers keep the IDs they had before profiles existed.+ return profileId === DEFAULT_STORAGE_PROFILE+ ? `storage:${binding.providerId}:${binding.documentId}`+ : `storage:${binding.providerId}:${profileId}:${binding.documentId}`}function normalizedRecentDocuments(): RecentDocument[] {@@ -70,16 +82,12 @@ export function rememberRecentFile(path: string): void {})}-export function rememberRecentStorageDocument(- providerId: StorageProviderID,- documentId: string,- name: string-): void {+export function rememberRecentStorageDocument(binding: StorageDocumentBinding, name: string): void {remember({- id: storageDocumentId(providerId, documentId),+ id: storageDocumentId(binding),kind: 'storage',- providerId,- documentId,+ ...storageLocationOf(binding),+ documentId: binding.documentId,name,updatedAt: new Date().toISOString()})diff --git a/src/app/settings/dialog.ts b/src/app/settings/dialog.tsindex 7c2586d62..77459910d 100644--- a/src/app/settings/dialog.ts+++ b/src/app/settings/dialog.ts@@ -11,6 +11,7 @@ export type SettingsSection =| 'tools'| 'media'| 'storage'+ | 'cloud'export const settingsDialogOpen = ref(false)export const settingsDialogSection = ref<SettingsSection>('general')diff --git a/src/app/settings/validation/use.ts b/src/app/settings/validation/use.tsindex 883b0dd03..75d934f1a 100644--- a/src/app/settings/validation/use.ts+++ b/src/app/settings/validation/use.ts@@ -2,6 +2,13 @@ import type { GenericSchema } from 'valibot'import { useForm } from 'vee-validate'import { watch, type Ref } from 'vue'+/** A field is checked when the person leaves it, then on every change until it is right. */+export const validateAfterFirstError = (state: { errors: string[] }) => ({+ validateOnModelUpdate: state.errors.length > 0,+ validateOnChange: false,+ validateOnInput: false+})+/** Validate a non-secret projection without moving persistence into the form layer. */export function useSettingsValidation(values: Readonly<Ref<Record<string, string | boolean>>>,@@ -16,11 +23,7 @@ export function useSettingsValidation(for (const field of Object.keys(values.value)) {if (registered.has(field)) continueregistered.add(field)- form.defineField(field, (state) => ({- validateOnModelUpdate: state.errors.length > 0,- validateOnChange: false,- validateOnInput: false- }))+ form.defineField(field, validateAfterFirstError)}}registerFields()diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex e9ab53432..b14963f5f 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -32,10 +32,13 @@ import {import { appPreferences } from '@/app/settings/preferences/store'import { createSharedEditorMenuActions } from '@/app/shell/menu/actions/editor'import { createSelectionMenuActions } from '@/app/shell/menu/actions/selection'-import { openStorageWorkspace } from '@/app/shell/menu/navigation'+import { menuFeatureAvailable } from '@/app/shell/menu/features'+import { browseFiles } from '@/app/shell/menu/navigation'+import { createSaveMenuActions } from '@/app/shell/menu/save-actions'import type {AppMenuActionItem,AppMenuEntry,+ AppMenuFeature,AppMenuGroupSchema,AppMenuIcon} from '@/app/shell/menu/schema'@@ -43,7 +46,6 @@ import { APP_MENU_SCHEMA } from '@/app/shell/menu/schema'import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'import { openFileDialog } from '@/app/shell/menu/use'import { useAppTheme } from '@/app/shell/theme'-import { saveDocumentToStorage } from '@/app/storage/workspace/save'import { closeTab, activeTab } from '@/app/tabs'export interface AppMenuGroup {@@ -80,8 +82,8 @@ function shortcutKeys(shortcut: string | undefined): string[] | undefined {})}-function isVisible(entry: { target?: string }): boolean {- return entry.target !== 'native'+function isVisible(entry: { target?: string; feature?: AppMenuFeature }): boolean {+ return entry.target !== 'native' && menuFeatureAvailable(entry.feature)}function isSeparator(entry: AppMenuEntry): entry is Extract<AppMenuEntry, { type: 'separator' }> {@@ -103,11 +105,11 @@ export function useAppMenu() {const translatedMenuItemLabels: Partial<Record<string, keyof typeof menu.value>> = {new: 'new',open: 'open',- 'open-storage-workspace': 'openStorageWorkspace',+ 'browse-files': 'browseFiles','open-tour': 'openTour',save: 'save','save-as': 'saveAs',- 'save-to-storage': 'saveToStorage',+ 'save-to': 'saveTo','export-selection': 'exportSelection',autosave: 'autosave',close: 'closeTab',@@ -171,13 +173,11 @@ export function useAppMenu() {void import('@/app/tabs').then((m) => m.createTab())},open: () => void openFileDialog(),- 'open-storage-workspace': () => openStorageWorkspace(router),+ 'browse-files': () => browseFiles(router),'open-tour': () => {openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))},- save: () => void store.saveFigFile(),- 'save-as': () => void store.saveFigFileAs(),- 'save-to-storage': () => void saveDocumentToStorage(store),+ ...createSaveMenuActions(store),'export-selection': () => exportSelection('png'),...createSelectionMenuActions(store),close: () => {diff --git a/src/app/shell/menu/editor.ts b/src/app/shell/menu/editor.tsindex 12d81a71e..ccd1fb4c1 100644--- a/src/app/shell/menu/editor.ts+++ b/src/app/shell/menu/editor.ts@@ -6,13 +6,14 @@ import { clearRecentFiles, forgetRecentFile, recentLocalFileAt } from '@/app/recimport { runFocusedCommand } from '@/app/shell/commands/focused'import { createSharedEditorMenuActions } from '@/app/shell/menu/actions/editor'import { createSelectionMenuActions } from '@/app/shell/menu/actions/selection'+import { watchNativeMenuFeatures } from '@/app/shell/menu/features'import { openFileDialog, openFileFromPath } from '@/app/shell/menu/files'import { useNativeMenuEvents } from '@/app/shell/menu/native-events'import { OPEN_RECENT_EVENT_PREFIX, watchRecentFilesMenu } from '@/app/shell/menu/recent-files'+import { createSaveMenuActions } from '@/app/shell/menu/save-actions'import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'import { SHELL_MENU_IDS } from '@/app/shell/menu/shell'import { useAppTheme } from '@/app/shell/theme'-import { saveDocumentToStorage } from '@/app/storage/workspace/save'import { createTab, closeTab, activeTab } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'@@ -32,6 +33,7 @@ export function useEditorMenu() {if (!isTauri()) returnwatchRecentFilesMenu()+ watchNativeMenuFeatures()const { setTheme } = useAppTheme()const { runCommand } = useEditorCommands()@@ -42,9 +44,7 @@ export function useEditorMenu() {close: () => {if (activeTab.value) void closeTab(activeTab.value.id)},- save: () => void store.saveFigFile(),- 'save-as': () => void store.saveFigFileAs(),- 'save-to-storage': () => void saveDocumentToStorage(store),+ ...createSaveMenuActions(store),'export-selection': () => {if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png')},diff --git a/src/app/shell/menu/features.ts b/src/app/shell/menu/features.tsnew file mode 100644index 000000000..dc2c4220a--- /dev/null+++ b/src/app/shell/menu/features.ts@@ -0,0 +1,38 @@+import { computed, watch } from 'vue'++import { useEditorStore } from '@/app/editor/active-store'+import { isTauri } from '@/app/tauri/env'++import type { AppMenuFeature } from './schema'++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()+}++/** Whether a menu item that waits for a feature shows; items without one always do. */+export function menuFeatureAvailable(feature: AppMenuFeature | undefined): boolean {+ return feature === undefined || available[feature]()+}++const availableFeatures = computed(() =>+ (Object.keys(available) as AppMenuFeature[]).filter((feature) => available[feature]())+)++/** Keeps the desktop menu's feature items in step: it builds them only once told they're on. */+export function watchNativeMenuFeatures(): () => void {+ return watch(+ availableFeatures,+ (features) => {+ if (!isTauri()) return+ void import('@tauri-apps/api/core')+ .then(({ invoke }) => invoke('set_native_menu_features', { features }))+ .catch((error: unknown) => {+ console.warn('[Menu] Failed to update the native menu', error)+ })+ },+ { immediate: true }+ )+}diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex 0266272c1..ace3757d5 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -46,9 +46,9 @@ fileDialog.onChange((files) => {* Opens a picked or dropped document in a new tab, rejecting formats OpenPencil cannot read.* A file system handle, when the browser provides one, lets the tab save back to the file.*/-export function openDesignFile(file: File, handle?: FileSystemFileHandle): Promise<void> {+export async function openDesignFile(file: File, handle?: FileSystemFileHandle): Promise<void> {assertSupportedDesignFile(file.name)- return openFileInNewTab(file, handle)+ await openFileInNewTab(file, handle)}if (IS_BROWSER && 'window' in globalThis) {diff --git a/src/app/shell/menu/navigation.ts b/src/app/shell/menu/navigation.tsindex 9523b427b..98f0fa86c 100644--- a/src/app/shell/menu/navigation.ts+++ b/src/app/shell/menu/navigation.ts@@ -1,8 +1,17 @@import type { Router } from 'vue-router'-export function openStorageWorkspace(router: Router): void {+import { homeLocation, type HomeLocation } from '@/app/home/location'++/** Shows Home at one of its places, in a new tab when a document is open. */+export function openHomeLocation(router: Router, location: HomeLocation): void {+ homeLocation.value = locationvoid router.push('/').then(() => import('@/app/tabs')).then(({ showNewTab }) => showNewTab())}++/** Home at the place the person browsed last: a Cloud workspace, the bucket, or Recent. */+export function browseFiles(router: Router): void {+ openHomeLocation(router, homeLocation.value)+}diff --git a/src/app/shell/menu/save-actions.ts b/src/app/shell/menu/save-actions.tsnew file mode 100644index 000000000..edd894b6a--- /dev/null+++ b/src/app/shell/menu/save-actions.ts@@ -0,0 +1,10 @@+import { openSaveTo } from '@/app/cloud/documents/save'+import type { EditorStore } from '@/app/editor/active-store'++export function createSaveMenuActions(store: EditorStore) {+ return {+ save: () => void store.saveFigFile(),+ 'save-as': () => void store.saveFigFileAs(),+ 'save-to': () => void openSaveTo(store)+ }+}diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex 3ebf06fda..4a196524c 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -33,6 +33,10 @@ export interface AppMenuPaletteMetadata {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 interface AppMenuActionItem {type?: 'item'id: string@@ -43,6 +47,7 @@ export interface AppMenuActionItem {checkbox?: booleantarget?: AppMenuTargethandler?: AppMenuHandler+ feature?: AppMenuFeaturepalette?: AppMenuPaletteMetadatasub?: AppMenuEntry[]}@@ -77,12 +82,12 @@ export const APP_MENU_SCHEMA = [{ id: 'new', label: 'New', shortcut: 'MOD+N' },{ id: 'open', label: 'Open…', shortcut: 'MOD+O' },{ id: 'open-recent', label: 'Open Recent', target: 'native' },- { id: 'open-storage-workspace', label: 'Open Storage Workspace…', handler: 'shell' },+ { id: 'browse-files', label: 'Browse Files…', handler: 'shell' },{ id: 'open-tour', label: 'Open the Tour', handler: 'shell' },{ type: 'separator' },{ id: 'save', label: 'Save', shortcut: 'MOD+S' },{ id: 'save-as', label: 'Save As…', shortcut: 'MOD+SHIFT+S' },- { id: 'save-to-storage', label: 'Save to Storage…' },+ { id: 'save-to', label: 'Save To…' },{ type: 'separator' },{id: 'export-selection',@@ -113,7 +118,7 @@ export const APP_MENU_SCHEMA = []},{ type: 'separator' },- { id: 'autosave', label: 'Autosave', checkbox: true },+ { id: 'autosave', label: 'Autosave', checkbox: true, feature: 'local-file' },{ id: 'close', label: 'Close Tab', shortcut: 'MOD+W' },// Windows, Linux, and the browser menu; macOS shows it in the application menu instead.{ type: 'separator' },diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.tsindex 05a1375f0..443bae164 100644--- a/src/app/shell/menu/shell.ts+++ b/src/app/shell/menu/shell.ts@@ -11,7 +11,7 @@ import {} from '@/app/settings/preferences/native-menu'import { appPreferences } from '@/app/settings/preferences/store'import { useNativeMenuEvents } from '@/app/shell/menu/native-events'-import { openStorageWorkspace } from '@/app/shell/menu/navigation'+import { browseFiles } from '@/app/shell/menu/navigation'import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'import { useAppTheme } from '@/app/shell/theme'import { checkForAppUpdate } from '@/app/shell/updater/check'@@ -53,8 +53,8 @@ export function useShellMenu() {const { setTheme } = useAppTheme()const { updates } = useI18n()const actions: Partial<Record<string, () => void>> = {- 'open-storage-workspace': () => {- void import('@/router').then(({ default: router }) => openStorageWorkspace(router))+ 'browse-files': () => {+ void import('@/router').then(({ default: router }) => browseFiles(router))},'open-tour': () => {openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))diff --git a/src/app/storage/local-store/meta.ts b/src/app/storage/local-store/meta.tsindex 458ec4ef0..8cbc6b78b 100644--- a/src/app/storage/local-store/meta.ts+++ b/src/app/storage/local-store/meta.ts@@ -13,6 +13,39 @@ export function sortAndFilterMetas(return filtered.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))}+/**+ * Local edits keep the revision they build on and any unresolved conflict; bytes written straight+ * from the provider replace the base revision and leave nothing to resolve.+ */+function writtenRevisions(+ input: LocalCanvasWriteInput,+ existing: LocalCanvasMeta | null+): Pick<LocalCanvasMeta, 'remoteRevision' | 'conflictRevision'> {+ if (input.remoteRevision !== undefined) {+ return { remoteRevision: input.remoteRevision, conflictRevision: null }+ }+ return {+ remoteRevision: existing?.remoteRevision ?? null,+ conflictRevision: existing?.conflictRevision ?? null+ }+}++type CanvasIdentity = Pick<+ LocalCanvasMeta,+ 'id' | 'providerId' | 'profileId' | 'containerId' | 'name'+>++/** A write may omit where the canvas lives; it stays where it was. */+function canvasIdentity(input: CanvasIdentity, existing: LocalCanvasMeta | null): CanvasIdentity {+ return {+ id: input.id,+ providerId: input.providerId,+ profileId: input.profileId ?? existing?.profileId,+ containerId: input.containerId ?? existing?.containerId,+ name: input.name+ }+}+/** Meta row for a full canvas write (fig bytes present). */export function buildWriteMeta(input: LocalCanvasWriteInput,@@ -20,9 +53,7 @@ export function buildWriteMeta(hasThumb: boolean): LocalCanvasMeta {return {- id: input.id,- providerId: input.providerId,- name: input.name,+ ...canvasIdentity(input, existing),updatedAt: input.updatedAt ?? new Date().toISOString(),revision: input.revision ?? (existing ? existing.revision + 1 : 1),syncStatus: input.syncStatus ?? 'pending',@@ -33,7 +64,8 @@ export function buildWriteMeta(hasFig: true,hasThumb,figSize: input.figBytes.byteLength,- lastOpenedAt: existing?.lastOpenedAt+ lastOpenedAt: existing?.lastOpenedAt,+ ...writtenRevisions(input, existing)}}@@ -43,9 +75,7 @@ export function buildIndexMeta(existing: LocalCanvasMeta | null): LocalCanvasMeta {return {- id: input.id,- providerId: input.providerId,- name: input.name,+ ...canvasIdentity(input, existing),updatedAt: input.updatedAt,revision: input.revision ?? existing?.revision ?? 1,syncStatus: input.syncStatus,@@ -53,6 +83,8 @@ export function buildIndexMeta(lastSyncError: input.lastSyncError,tombstoned: false,hasFig: input.hasFig ?? existing?.hasFig ?? false,- hasThumb: input.hasThumb ?? existing?.hasThumb ?? false+ hasThumb: input.hasThumb ?? existing?.hasThumb ?? false,+ remoteRevision: input.remoteRevision ?? existing?.remoteRevision ?? null,+ conflictRevision: existing?.conflictRevision ?? null}}diff --git a/src/app/storage/local-store/types.ts b/src/app/storage/local-store/types.tsindex aa1736df3..f0a0df5ca 100644--- a/src/app/storage/local-store/types.ts+++ b/src/app/storage/local-store/types.ts@@ -1,9 +1,15 @@import type { StorageProviderID } from '@/app/integrations/storage/types'+/** Where a stored canvas lives besides its provider; see `StorageLocation`. */+type LocalCanvasLocation = {+ profileId?: string+ containerId?: string+}+export type LocalSyncStatus = 'synced' | 'pending' | 'error' | 'conflict'/** Metadata for a stored canvas cached on device (document bytes stored separately). */-export type LocalCanvasMeta = {+export type LocalCanvasMeta = LocalCanvasLocation & {id: stringproviderId: StorageProviderIDname: string@@ -21,6 +27,10 @@ export type LocalCanvasMeta = {figSize?: number/** Last time this canvas was opened on this device (LRU eviction key). */lastOpenedAt?: string+ /** The provider revision the local bytes were edited from, when the provider tracks them. */+ remoteRevision?: string | null+ /** The newer provider revision found when an upload conflicted, kept until resolved. */+ conflictRevision?: string | null}/** Index-only row for remote canvases not yet downloaded (no fig body). */@@ -33,7 +43,7 @@ export type LocalCanvasIndexInput = Omit<hasThumb?: boolean}-export type LocalCanvasWriteInput = {+export type LocalCanvasWriteInput = LocalCanvasLocation & {id: stringproviderId: StorageProviderIDname: string@@ -43,4 +53,6 @@ export type LocalCanvasWriteInput = {/** If set, keep this revision; otherwise increment from existing. */revision?: numbersyncStatus?: LocalSyncStatus+ /** Replaces the base revision, as when the bytes come straight from the provider. */+ remoteRevision?: string | null}diff --git a/src/app/storage/reconcile.ts b/src/app/storage/reconcile.tsindex 7bd57bbe5..162f3e04f 100644--- a/src/app/storage/reconcile.ts+++ b/src/app/storage/reconcile.ts@@ -30,7 +30,8 @@ export function reconcileStorageDocuments(id: metadata.id,name: metadata.name,updatedAt: metadata.updatedAt,- metadataAuthoritative: true+ metadataAuthoritative: true,+ revision: metadata.remoteRevision ?? null})}diff --git a/src/app/storage/sync/conflicts.ts b/src/app/storage/sync/conflicts.tsnew file mode 100644index 000000000..0a9871e9d--- /dev/null+++ b/src/app/storage/sync/conflicts.ts@@ -0,0 +1,102 @@+import { createStorageAdapter, storageLocationOf } from '@/app/integrations/storage'+import { createCanvasId } from '@/app/storage/id'+import { getLocalCanvasStore } from '@/app/storage/local-store'+import { kickSyncEngine } from '@/app/storage/sync/engine'+import { getOutbox } from '@/app/storage/sync/outbox'+import {+ persistStorageCanvasLocally,+ seedStorageCanvasFromRemote+} from '@/app/storage/sync/persist'+import { emitStorageWorkspaceEvent } from '@/app/storage/workspace/events'++/**+ * Ways out of a conflict, where this device holds edits made from a revision the provider has+ * since replaced. Until one runs, both versions are kept: the local bytes here and the newer+ * revision on the provider.+ */++async function conflictedCanvas(canvasId: string) {+ const store = getLocalCanvasStore()+ const meta = await store.getMeta(canvasId)+ if (meta?.syncStatus !== 'conflict') {+ throw new Error('This document has no conflict to resolve')+ }+ return { store, meta }+}++/** Drops a document's queued uploads, for edits that are kept elsewhere. */+export async function dropCanvasUploads(canvasId: string): Promise<void> {+ const outbox = getOutbox()+ const jobs = await outbox.list()+ await Promise.all(+ jobs+ .filter((job) => job.canvasId === canvasId && job.type !== 'deleteCanvas')+ .map((job) => outbox.remove(job.id))+ )+}++/** 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)+ const location = storageLocationOf(meta)+ const content = await createStorageAdapter(location).getDocument(canvasId)+ await dropCanvasUploads(canvasId)+ await seedStorageCanvasFromRemote({+ ...location,+ canvasId,+ name: meta.name,+ updatedAt: new Date().toISOString(),+ figBytes: content.bytes,+ remoteRevision: content.revision+ })+ emitStorageWorkspaceEvent({ ...location, documentId: canvasId, kind: 'changed' })+}++/**+ * Saves this device's edits as a new document beside the original, then takes the provider's+ * revision for the original. Returns the copy's ID.+ */+export async function keepBothVersions(canvasId: string, copyName: string): Promise<string> {+ const { store, meta } = await conflictedCanvas(canvasId)+ const local = await store.readFig(canvasId)+ if (!local?.byteLength) throw new Error('This device no longer has its version of the document')+ const copyId = createCanvasId()+ await persistStorageCanvasLocally({+ ...storageLocationOf(meta),+ canvasId: copyId,+ name: copyName,+ figBytes: local+ })+ await takeStoredVersion(canvasId)+ return copyId+}++/** Uploads this device's edits over the provider's newer revision. */+export async function replaceStoredVersion(canvasId: string): Promise<void> {+ const { store, meta } = await conflictedCanvas(canvasId)+ // Replacing builds on the provider's newest revision; a conflict that couldn't name it is+ // looked up first, or the upload would build on the old base and conflict again.+ const newest =+ meta.conflictRevision ??+ (await createStorageAdapter(storageLocationOf(meta)).listDocuments()).find(+ (document) => document.id === canvasId+ )?.revision+ await store.updateMeta(canvasId, {+ syncStatus: 'pending',+ remoteRevision: newest ?? meta.remoteRevision ?? null,+ conflictRevision: null,+ lastSyncError: null+ })+ const outbox = getOutbox()+ const jobs = (await outbox.list()).filter(+ (job) => job.canvasId === canvasId && job.type === 'putCanvas'+ )+ if (jobs.length === 0) {+ await outbox.enqueue({ canvasId, type: 'putCanvas', revision: meta.revision })+ } else {+ const now = Date.now()+ await Promise.all(jobs.map((job) => outbox.update({ ...job, nextAttemptAt: now })))+ }+ emitStorageWorkspaceEvent({ ...storageLocationOf(meta), documentId: canvasId, kind: 'changed' })+ void kickSyncEngine()+}diff --git a/src/app/storage/sync/engine.ts b/src/app/storage/sync/engine.tsindex 2e8000d91..fffb32a11 100644--- a/src/app/storage/sync/engine.ts+++ b/src/app/storage/sync/engine.ts@@ -7,10 +7,10 @@ import {} from '@/app/diagnostics'import {activeStorageProviderID,- createActiveStorageAdapter,- storageCredentialStatuses,- storagePreferencesComplete,- storageProviderRegistry+ openStorageAdapter,+ storageLocationOf,+ StorageRevisionConflictError,+ StorageUnavailableError} from '@/app/integrations/storage'import { evictLocalFigCache } from '@/app/storage/cache-eviction'import { getLocalCanvasStore } from '@/app/storage/local-store'@@ -24,20 +24,15 @@ const MAX_ATTEMPTS = 8const BASE_BACKOFF_MS = 1500const MAX_BACKOFF_MS = 60_000-class StorageSyncBlockedError extends Error {- constructor(message: string) {- super(message)- this.name = 'StorageSyncBlockedError'- }-}-let pumping = falselet wakeTimer: ReturnType<typeof setTimeout> | null = nulllet onlineBound = falsefunction isOnline(): boolean {+ // Runtimes without a network indicator, such as workers and tests, count as online.if (typeof navigator === 'undefined') return true- return navigator.onLine+ const online: unknown = Reflect.get(navigator, 'onLine')+ return online !== false}function backoffMs(attempts: number): number {@@ -59,27 +54,15 @@ function isPermanentError(error: unknown): boolean {msg.includes('403') ||msg.includes('401') ||msg.includes('access denied') ||- msg.includes('invalid access key') ||- msg.includes('not configured')+ msg.includes('invalid access key'))}async function runJob(job: OutboxJob): Promise<void> {const store = getLocalCanvasStore()const meta = await store.getMeta(job.canvasId)- const providerID = meta?.providerId ?? activeStorageProviderID.value- if (!storagePreferencesComplete(providerID)) {- throw new StorageSyncBlockedError('Storage is not configured')- }- const provider = storageProviderRegistry.get(providerID)- const statuses = await storageCredentialStatuses(providerID)- const missingCredential = provider.credentialFields.some(- (field) => field.required && statuses[field.id] !== 'configured'- )- if (missingCredential) {- throw new StorageSyncBlockedError('Storage credentials are unavailable')- }- const adapter = createActiveStorageAdapter(providerID)+ const location = meta ? storageLocationOf(meta) : { providerId: activeStorageProviderID.value }+ const adapter = await openStorageAdapter(location)if (job.type === 'deleteCanvas') {await adapter.deleteDocument(job.canvasId)@@ -102,8 +85,9 @@ async function runJob(job: OutboxJob): Promise<void> {const fig = await store.readFig(job.canvasId)if (!fig || fig.byteLength === 0) throw new Error('Local document missing for sync')setUploadProgress(job.canvasId, 0)+ let written: { revision: string | null }try {- await adapter.putDocument(+ written = await adapter.putDocument(job.canvasId,fig,{@@ -112,11 +96,16 @@ async function runJob(job: OutboxJob): Promise<void> {},({ transferredBytes, totalBytes }) => {if (totalBytes) setUploadProgress(job.canvasId, transferredBytes / totalBytes)- }+ },+ { baseRevision: meta.remoteRevision ?? null })} finally {setUploadProgress(job.canvasId, null)}+ // Later local edits build on what was just stored, even when they arrived mid-upload.+ if (written.revision !== null) {+ await store.updateMeta(job.canvasId, { remoteRevision: written.revision })+ }// Only mark synced if still on this revision and no other pending work for newer revconst latest = await store.getMeta(job.canvasId)if (latest && latest.revision === job.revision && !latest.tombstoned) {@@ -125,13 +114,14 @@ async function runJob(job: OutboxJob): Promise<void> {{syncStatus: 'synced',lastSyncedAt: new Date().toISOString(),- lastSyncError: null+ lastSyncError: null,+ conflictRevision: null},{ expectedRevision: job.revision })await evictLocalFigCache(new Set([job.canvasId]))emitStorageWorkspaceEvent({- providerId: providerID,+ ...location,documentId: job.canvasId,kind: 'synced'})@@ -188,7 +178,27 @@ async function pumpOnce(): Promise<void> {retryable})const message = error instanceof Error ? error.message : String(error)- if (error instanceof StorageSyncBlockedError) {+ if (error instanceof StorageRevisionConflictError) {+ // Both versions stay: the local bytes on this device, the newer one on the provider.+ // The job waits for the person to choose, and other work carries on.+ await getLocalCanvasStore().updateMeta(job.canvasId, {+ syncStatus: 'conflict',+ conflictRevision: error.currentRevision,+ lastSyncError: null+ })+ await outbox.update({ ...job, nextAttemptAt: Number.MAX_SAFE_INTEGER })+ const conflicted = await getLocalCanvasStore().getMeta(job.canvasId)+ if (conflicted) {+ emitStorageWorkspaceEvent({+ ...storageLocationOf(conflicted),+ documentId: job.canvasId,+ kind: 'changed'+ })+ }+ scheduleWake(50)+ return+ }+ if (error instanceof StorageUnavailableError) {await outbox.update({...job,nextAttemptAt: Number.MAX_SAFE_INTEGERdiff --git a/src/app/storage/sync/index.ts b/src/app/storage/sync/index.tsindex 5c04d19cf..fd6d40d5a 100644--- a/src/app/storage/sync/index.ts+++ b/src/app/storage/sync/index.ts@@ -6,6 +6,12 @@ export {kickSyncEngine,resumeStorageSync} from './engine'+export {+ dropCanvasUploads,+ keepBothVersions,+ replaceStoredVersion,+ takeStoredVersion+} from './conflicts'export { createMemoryOutbox, getOutbox, resetOutboxForTests } from './outbox'export {persistStorageCanvasLocally,diff --git a/src/app/storage/sync/persist.ts b/src/app/storage/sync/persist.tsindex 3bbb4c1e3..1a98ab3d1 100644--- a/src/app/storage/sync/persist.ts+++ b/src/app/storage/sync/persist.ts@@ -1,6 +1,7 @@import { extractFigThumbnailFromReader } from '@open-pencil/fig'-import type { StorageProviderID } from '@/app/integrations/storage/types'+import { storageLocationOf } from '@/app/integrations/storage/location'+import type { StorageLocation } from '@/app/integrations/storage/types'import { evictLocalFigCache } from '@/app/storage/cache-eviction'import { getLocalCanvasStore } from '@/app/storage/local-store'import type { LocalCanvasStore } from '@/app/storage/local-store/store'@@ -12,8 +13,7 @@ export type StoragePersistenceDependencies = {enqueueCanvas(canvasId: string, revision: number): Promise<void>}-export type PersistStorageCanvasOptions = {- providerId: StorageProviderID+export type PersistStorageCanvasOptions = StorageLocation & {canvasId: stringname: stringfigBytes: Uint8Array@@ -37,6 +37,8 @@ export async function persistStorageCanvasLocally(const metadata = await runtime.store.writeCanvas({id: options.canvasId,providerId: options.providerId,+ profileId: options.profileId,+ containerId: options.containerId,name: options.name,figBytes: options.figBytes,thumbBytes: thumbnailBytes,@@ -44,21 +46,22 @@ export async function persistStorageCanvasLocally(})await runtime.enqueueCanvas(options.canvasId, metadata.revision)emitStorageWorkspaceEvent({- providerId: options.providerId,+ ...storageLocationOf(options),documentId: options.canvasId,kind: 'changed'})return { revision: metadata.revision }}-export type SeedStorageCanvasOptions = {- providerId: StorageProviderID+export type SeedStorageCanvasOptions = StorageLocation & {canvasId: stringname: stringupdatedAt: stringfigBytes: Uint8ArraythumbnailBytes?: Uint8Array | nullmarkSynced?: boolean+ /** The provider revision the bytes are, so later uploads build on it. */+ remoteRevision?: string | null}export async function seedStorageCanvasFromRemote(@@ -67,8 +70,11 @@ export async function seedStorageCanvasFromRemote(await getLocalCanvasStore().writeCanvas({id: options.canvasId,providerId: options.providerId,+ profileId: options.profileId,+ containerId: options.containerId,name: options.name,updatedAt: options.updatedAt,+ remoteRevision: options.remoteRevision ?? null,figBytes: options.figBytes,thumbBytes: options.thumbnailBytes,syncStatus: options.markSynced === false ? 'pending' : 'synced'diff --git a/src/app/storage/workspace/create.ts b/src/app/storage/workspace/create.tsnew file mode 100644index 000000000..2d3d89589--- /dev/null+++ b/src/app/storage/workspace/create.ts@@ -0,0 +1,11 @@+import type { StorageLocation } from '@/app/integrations/storage'+import { rememberRecentStorageDocument } from '@/app/recent-files'+import { createDocumentInCurrentTab } from '@/app/tabs'++/** Starts a design that lives in a Cloud workspace or the storage bucket from its first edit. */+export async function createStoredDocument(location: StorageLocation): Promise<void> {+ const { store } = createDocumentInCurrentTab()+ if (!(await store.saveFigFileToStorage(location))) return+ const binding = store.getStorageBinding()+ if (binding) rememberRecentStorageDocument(binding, store.state.documentName)+}diff --git a/src/app/storage/workspace/events.ts b/src/app/storage/workspace/events.tsindex 57e7b1e83..85d633556 100644--- a/src/app/storage/workspace/events.ts+++ b/src/app/storage/workspace/events.ts@@ -1,7 +1,6 @@-import type { StorageProviderID } from '@/app/integrations/storage/types'+import type { StorageLocation } from '@/app/integrations/storage/types'-export type StorageWorkspaceEvent = {- providerId: StorageProviderID+export type StorageWorkspaceEvent = StorageLocation & {documentId?: stringkind: 'changed' | 'synced'}diff --git a/src/app/storage/workspace/save.ts b/src/app/storage/workspace/save.tsdeleted file mode 100644index e799ab451..000000000--- a/src/app/storage/workspace/save.ts+++ /dev/null@@ -1,25 +0,0 @@-import { activeStorageProviderID, isStorageConfigured } from '@/app/integrations/storage'-import type { StorageDocumentBinding, StorageProviderID } from '@/app/integrations/storage/types'-import { rememberRecentStorageDocument } from '@/app/recent-files'-import { openSettingsDialog } from '@/app/settings/dialog'--type StorageSaveTarget = {- state: { documentName: string }- saveFigFileToStorage: (providerId: StorageProviderID) => Promise<boolean>- getStorageBinding: () => StorageDocumentBinding | null-}--/** Save the open document as a new stored document, or ask for storage settings first. */-export async function saveDocumentToStorage(store: StorageSaveTarget): Promise<boolean> {- const providerId = activeStorageProviderID.value- if (!(await isStorageConfigured(providerId))) {- openSettingsDialog('storage')- return false- }- const saved = await store.saveFigFileToStorage(providerId)- const binding = store.getStorageBinding()- if (saved && binding) {- rememberRecentStorageDocument(providerId, binding.documentId, store.state.documentName)- }- return saved-}diff --git a/src/app/storage/workspace/source.ts b/src/app/storage/workspace/source.tsindex b1c79db54..ba9a974c6 100644--- a/src/app/storage/workspace/source.ts+++ b/src/app/storage/workspace/source.ts@@ -1,8 +1,10 @@-import type { StorageDocument } from '@/app/integrations/storage'+import type { StorageDocument, StorageLocation } from '@/app/integrations/storage'import {activeStorageProviderID,- createActiveStorageAdapter,- isStorageConfigured+ createStorageAdapter,+ isStorageConfigured,+ sameStorageLocation,+ storageLocationOf} from '@/app/integrations/storage'import { getLocalCanvasStore } from '@/app/storage/local-store'import { reconcileStorageDocuments } from '@/app/storage/reconcile'@@ -13,66 +15,89 @@ export type StorageWorkspaceSnapshot = {configured: boolean}+/** The configured storage bucket, the location home lists when no other is chosen. */+export function activeStorageLocation(): StorageLocation {+ return { providerId: activeStorageProviderID.value }+}++/**+ * Lists one storage location for home: the provider's documents merged with this device's+ * copies, so unsent work shows while the provider is unreachable or not configured.+ */export function createStorageWorkspaceSource(- onSnapshot: (snapshot: StorageWorkspaceSnapshot) => void+ onSnapshot: (snapshot: StorageWorkspaceSnapshot) => void,+ location: () => StorageLocation = activeStorageLocation) {+ const isCurrent = (requested: StorageLocation) => sameStorageLocation(requested, location())+ const isHere = (metadata: StorageLocation, requested: StorageLocation) =>+ sameStorageLocation(storageLocationOf(metadata), requested)+return {subscribe(listener: () => void): () => void {return onStorageWorkspaceEvent((event) => {- if (event.providerId === activeStorageProviderID.value) listener()+ if (isCurrent(event)) listener()})},async refresh(): Promise<StorageDocument[] | null> {- const providerID = activeStorageProviderID.value- const configured = await isStorageConfigured(providerID)+ const requested = location()+ const configured = await isStorageConfigured(requested.providerId)const localStore = getLocalCanvasStore()- const local = (await localStore.listMetas(true)).filter(- (metadata) => metadata.providerId === providerID+ const local = (await localStore.listMetas(true)).filter((metadata) =>+ isHere(metadata, requested))+ const localDocuments = local+ .filter((metadata) => !metadata.tombstoned)+ .map((metadata) => ({+ id: metadata.id,+ name: metadata.name,+ updatedAt: metadata.updatedAt,+ metadataAuthoritative: true,+ revision: metadata.remoteRevision ?? null+ }))if (!configured) {- const documents = local- .filter((metadata) => !metadata.tombstoned)- .map((metadata) => ({- id: metadata.id,- name: metadata.name,- updatedAt: metadata.updatedAt,- metadataAuthoritative: true- }))- if (activeStorageProviderID.value !== providerID) return null- onSnapshot({ documents, configured })- return documents+ if (!isCurrent(requested)) return null+ onSnapshot({ documents: localDocuments, configured })+ return localDocuments}- const remote = await createActiveStorageAdapter(providerID).listDocuments()+ let remote: StorageDocument[]+ try {+ remote = await createStorageAdapter(requested).listDocuments()+ } catch (error) {+ // Out of reach or signed out: this device's copies still show, beside the error.+ if (isCurrent(requested)) onSnapshot({ documents: localDocuments, configured })+ throw error+ }const reconciliation = reconcileStorageDocuments(local, remote)for (const id of reconciliation.localIdsToPurge) await localStore.remove(id)for (const document of reconciliation.remoteDocumentsToSeed) {await localStore.upsertIndexMeta({id: document.id,- providerId: providerID,+ ...storageLocationOf(requested),name: document.name,updatedAt: document.updatedAt,syncStatus: 'synced',lastSyncedAt: document.updatedAt,- lastSyncError: null+ lastSyncError: null,+ remoteRevision: document.revision ?? null})}- if (activeStorageProviderID.value !== providerID) return null+ if (!isCurrent(requested)) return nullonSnapshot({ documents: reconciliation.documents, configured })return reconciliation.documents},async loadPreview(id: string): Promise<Uint8Array | null> {- const providerID = activeStorageProviderID.value+ const requested = location()const localStore = getLocalCanvasStore()const local = await localStore.readThumb(id)if (local?.byteLength) return local- const adapter = createActiveStorageAdapter(providerID)+ const adapter = createStorageAdapter(requested)if (!adapter.getThumbnail) return nullconst remote = await adapter.getThumbnail(id)if (!remote?.byteLength) return null- if (activeStorageProviderID.value === providerID) await localStore.writeThumb(id, remote)+ if (isCurrent(requested)) await localStore.writeThumb(id, remote)return remote}}diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 5ddf3a20b..5683c6bba 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -23,8 +23,11 @@ import type { EditorStore } from '@/app/editor/session'import { notificationMessages } from '@/app/i18n/notifications'import {activeStorageProviderID,- createActiveStorageAdapter,- type StorageDocument+ sameStorageDocument,+ storageLocationOf,+ type StorageDocument,+ type StorageDocumentBinding,+ type StorageLocation} from '@/app/integrations/storage'import {cacheRecentFileThumbnail,@@ -33,10 +36,9 @@ import {} from '@/app/recent-files'import { createDeferred } from '@/app/runtime/deferred'import { toast } from '@/app/shell/ui'-import { getLocalCanvasStore } from '@/app/storage/local-store'-import { seedStorageCanvasFromRemote } from '@/app/storage/sync/persist'import { createFileOpenCoordinator } from '@/app/tabs/open/coordinator'import { findTabByFileIdentity } from '@/app/tabs/open/identity'+import { readStorageDocument } from '@/app/tabs/open/storage'export type TabKind = 'home' | 'document'@@ -290,10 +292,10 @@ function watchOpenedFigCover(path: string, store: EditorStore): void {)}-function findStorageTab(providerId: string, documentId: string): Tab | undefined {+function findStorageTab(target: StorageDocumentBinding): Tab | undefined {return tabsRef.value.find((tab) => {const binding = tab.store.getStorageBinding()- return binding?.providerId === providerId && binding.documentId === documentId+ return binding !== null && sameStorageDocument(binding, target)})}@@ -310,12 +312,60 @@ function failPreparation(})}-export async function openStorageDocumentInNewTab(document: StorageDocument): Promise<void> {- const providerId = activeStorageProviderID.value- const existing = findStorageTab(providerId, document.id)+async function showStorageDocument(+ store: EditorStore,+ binding: StorageDocumentBinding,+ document: StorageDocument,+ load: DocumentLoadSession+): 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'+ })+ load.update({ phase: 'decoding', detail: document.name })+ const imported = await readFigForTab(file, load.signal)+ await showImportedGraph(+ store,+ imported,+ () => store.setStorageDocumentSource(binding, document.name),+ load+ )+}++/** Shows what this device now holds for a tab's stored document, as after a conflict. */+export async function reloadStorageDocumentInTab(store: EditorStore): Promise<void> {+ const binding = store.getStorageBinding()+ if (!binding) return+ const name = store.state.documentName+ const load = store.preparationController.begin({ kind: 'storage-open', subject: name })+ try {+ await showStorageDocument(+ store,+ binding,+ { id: binding.documentId, name, updatedAt: new Date().toISOString() },+ load+ )+ load.complete()+ } catch (error) {+ failPreparation(load, 'read-failed', error)+ throw error+ }+}++export async function openStorageDocumentInNewTab(+ document: StorageDocument,+ location: StorageLocation = { providerId: activeStorageProviderID.value }+): Promise<void> {+ const binding: StorageDocumentBinding = {+ ...storageLocationOf(location),+ documentId: document.id+ }+ const existing = findStorageTab(binding)if (existing) {switchTab(existing.id)- rememberRecentStorageDocument(providerId, document.id, document.name)+ rememberRecentStorageDocument(binding, document.name)return}@@ -327,55 +377,8 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): Pr})let succeeded = falsetry {- load.update({ phase: 'reading', detail: document.name })- const local = getLocalCanvasStore()- const localMetadata = await local.getMeta(document.id)- load.signal.throwIfAborted()- const localBytes = localMetadata?.hasFig ? await local.readFig(document.id) : null- load.signal.throwIfAborted()- const localIsAuthoritative =- localMetadata?.syncStatus !== 'synced' ||- !document.metadataAuthoritative ||- localMetadata.updatedAt >= document.updatedAt- let bytes = localBytes && localIsAuthoritative ? localBytes : null-- if (!bytes) {- bytes = await createActiveStorageAdapter(providerId).getDocument(- document.id,- (progress) =>- load.update({- phase: 'reading',- detail: document.name,- completed: progress.transferredBytes,- total: progress.totalBytes,- unit: 'bytes'- }),- load.signal- )- await seedStorageCanvasFromRemote({- providerId,- canvasId: document.id,- name: document.name,- updatedAt: document.updatedAt,- figBytes: bytes- })- load.signal.throwIfAborted()- }-- const fileBytes = new Uint8Array(bytes.byteLength)- fileBytes.set(bytes)- const file = new File([fileBytes.buffer], `${document.name}.fig`, {- type: 'application/octet-stream'- })- load.update({ phase: 'decoding', detail: document.name })- const imported = await readFigForTab(file, load.signal)- await showImportedGraph(- store,- imported,- () => store.setStorageDocumentSource({ providerId, documentId: document.id }, document.name),- load- )- rememberRecentStorageDocument(providerId, document.id, document.name)+ await showStorageDocument(store, binding, document, load)+ rememberRecentStorageDocument(binding, document.name)succeeded = true} catch (error) {if (!load.signal.aborted) {@@ -407,7 +410,7 @@ export async function openFileInNewTab(file: File,handle?: FileSystemFileHandle,path?: string-): Promise<void> {+): Promise<EditorStore> {const identity: DocumentSourceIdentity = {handle: handle ?? null,path: path ?? null@@ -417,7 +420,7 @@ export async function openFileInNewTab(if (pending) {const tab = getTabForStore(pending.store)if (tab) switchTab(tab.id)- return { kind: 'pending' as const, completion: pending.completion }+ return { kind: 'pending' as const, completion: pending.completion, store: pending.store }}const existing = await findTabByFileIdentity(tabsRef.value, identity)@@ -429,7 +432,7 @@ export async function openFileInNewTab(console.warn('[Recent files] Failed to cache the Cover thumbnail', error)})}- return { kind: 'existing' as const }+ return { kind: 'existing' as const, store: existing.store }}const { store, created } = reusableTabStore()@@ -446,10 +449,10 @@ export async function openFileInNewTab(return { kind: 'owner' as const, completion, pendingOpen, store, created, load }})- if (decision.kind === 'existing') return+ if (decision.kind === 'existing') return decision.storeif (decision.kind === 'pending') {await decision.completion- return+ return decision.store}const { completion, pendingOpen, store, created, load } = decision@@ -459,7 +462,7 @@ export async function openFileInNewTab(await store.openDOMFile(file, { handle, path, preparation: load })completion.resolve(undefined)succeeded = true- return+ return store}await yieldToUI()@@ -497,6 +500,7 @@ export async function openFileInNewTab(}completion.resolve(undefined)succeeded = true+ return store} catch (error) {failPreparation(load, 'decode-failed', error)completion.reject(error)diff --git a/src/app/tabs/open/storage.ts b/src/app/tabs/open/storage.tsnew file mode 100644index 000000000..aa9ad3a4c--- /dev/null+++ b/src/app/tabs/open/storage.ts@@ -0,0 +1,58 @@+import type { EditorPreparationHandle } from '@/app/editor/preparation/types'+import {+ createStorageAdapter,+ storageLocationOf,+ type StorageDocument,+ type StorageDocumentBinding+} from '@/app/integrations/storage'+import { getLocalCanvasStore, type LocalCanvasMeta } from '@/app/storage/local-store'+import { seedStorageCanvasFromRemote } from '@/app/storage/sync/persist'++/**+ * Whether this device's copy can open in place of downloading: it has unsent changes or a+ * conflict to resolve, or it is based on the revision the provider lists. Providers without+ * revisions fall back to comparing modification times.+ */+export function localCopyIsCurrent(local: LocalCanvasMeta, document: StorageDocument): boolean {+ if (local.syncStatus !== 'synced') return true+ if (document.revision != null) return local.remoteRevision === document.revision+ return !document.metadataAuthoritative || local.updatedAt >= document.updatedAt+}++/** A stored document's bytes: this device's copy when current, otherwise downloaded and kept. */+export async function readStorageDocument(+ binding: StorageDocumentBinding,+ document: StorageDocument,+ load: EditorPreparationHandle+): Promise<Uint8Array> {+ load.update({ phase: 'reading', detail: document.name })+ const local = getLocalCanvasStore()+ const localMetadata = await local.getMeta(document.id)+ load.signal.throwIfAborted()+ const localBytes = localMetadata?.hasFig ? await local.readFig(document.id) : null+ load.signal.throwIfAborted()+ if (localBytes && localMetadata && localCopyIsCurrent(localMetadata, document)) return localBytes++ const content = await createStorageAdapter(binding).getDocument(+ document.id,+ (progress) =>+ load.update({+ phase: 'reading',+ detail: document.name,+ completed: progress.transferredBytes,+ total: progress.totalBytes,+ unit: 'bytes'+ }),+ load.signal+ )+ await seedStorageCanvasFromRemote({+ ...storageLocationOf(binding),+ canvasId: document.id,+ name: document.name,+ updatedAt: document.updatedAt,+ figBytes: content.bytes,+ remoteRevision: content.revision+ })+ load.signal.throwIfAborted()+ return content.bytes+}diff --git a/src/cloud/router.ts b/src/cloud/router.tsindex be28d4f9d..665310940 100644--- a/src/cloud/router.ts+++ b/src/cloud/router.ts@@ -26,6 +26,11 @@ export function createCloudPortalRouter(context: PortalContext) {name: 'check-email',component: () => import('@/views/cloud/CheckEmailView.vue')},+ {+ path: '/auth/verified',+ name: 'verified',+ component: () => import('@/views/cloud/VerifiedView.vue')+ },{path: '/auth/two-factor',name: 'two-factor',diff --git a/src/components/cloud-portal/account/PortalPasswordDialog.vue b/src/components/cloud-portal/account/PortalPasswordDialog.vueindex b426bd031..ca60e3d0e 100644--- a/src/components/cloud-portal/account/PortalPasswordDialog.vue+++ b/src/components/cloud-portal/account/PortalPasswordDialog.vue@@ -1,5 +1,6 @@<script setup lang="ts">-import { ref, watch } from 'vue'+import * as v from 'valibot'+import { computed, ref, watch } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue'@@ -9,7 +10,7 @@ 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 AppPasswordInput from '@/components/ui/input/AppPasswordInput.vue'import { portalForm } from '@/theme/cloud-portal/form'/**@@ -18,7 +19,7 @@ import { portalForm } from '@/theme/cloud-portal/form'*/const {purpose,- minimumPasswordLength = 15,+ minimumPasswordLength = 8,error = null,saving = false} = defineProps<{@@ -34,12 +35,61 @@ const ui = portalForm()const messages = useCloudPortalMessages()const current = ref('')const next = ref('')+const repeat = ref('')+const errors = ref<{ current?: string; next?: string; repeat?: string }>({})watch(open, (value) => {if (!value) {current.value = ''next.value = ''+ repeat.value = ''+ errors.value = {}}})++/** What the server would turn down, caught before it is asked. */+const schema = computed(() => {+ const words = messages.value+ const fields = v.object({+ current: v.pipe(v.string(), v.nonEmpty(words.errorPasswordRequired)),+ next: v.pipe(+ v.string(),+ v.minLength(+ minimumPasswordLength,+ words.errorPasswordTooShort({ count: minimumPasswordLength })+ )+ ),+ repeat: v.string()+ })+ if (purpose === 'confirm') {+ return v.object({ current: fields.entries.current, next: v.string(), repeat: v.string() })+ }+ return v.pipe(+ fields,+ v.forward(+ v.partialCheck(+ [['next'], ['repeat']],+ (input) => input.next === input.repeat,+ words.errorPasswordsDiffer+ ),+ ['repeat']+ )+ )+})++function submit() {+ const result = v.safeParse(schema.value, {+ current: current.value,+ next: next.value,+ repeat: repeat.value+ })+ if (!result.success) {+ const flat = v.flatten<typeof schema.value>(result.issues).nested ?? {}+ errors.value = { current: flat.current?.[0], next: flat.next?.[0], repeat: flat.repeat?.[0] }+ return+ }+ errors.value = {}+ emit('submit', { current: current.value, next: next.value })+}</script><template>@@ -48,35 +98,49 @@ watch(open, (value) => {:heading="purpose === 'change' ? messages.changePasswordTitle : messages.confirmPasswordTitle":close-label="messages.cancel"/>- <form novalidate @submit.prevent="emit('submit', { current, next })">+ <form novalidate @submit.prevent="submit"><AppDialogBody :ui="{ body: 'flex flex-col gap-3' }"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><div :class="ui.field()"><label for="portal-current-password" :class="ui.label()">{{ messages.currentPassword }}</label>- <AppInput+ <AppPasswordInputid="portal-current-password"v-model="current"- type="password"autocomplete="current-password"+ :state="errors.current ? 'invalid' : 'idle'"/>+ <p v-if="errors.current" :class="ui.error()">{{ errors.current }}</p></div><div v-if="purpose === 'change'" :class="ui.field()"><label for="portal-next-password" :class="ui.label()">{{ messages.newPassword }}</label>- <AppInput+ <AppPasswordInputid="portal-next-password"v-model="next"- type="password"autocomplete="new-password"+ :state="errors.next ? 'invalid' : 'idle'"+ />+ <p v-if="errors.next" :class="ui.error()">{{ errors.next }}</p>+ <p v-else :class="ui.hint()">+ {{ messages.passwordHint({ count: minimumPasswordLength }) }}+ </p>+ </div>+ <div v-if="purpose === 'change'" :class="ui.field()">+ <label for="portal-repeat-password" :class="ui.label()">+ {{ messages.repeatPassword }}+ </label>+ <AppPasswordInput+ id="portal-repeat-password"+ v-model="repeat"+ autocomplete="new-password"+ :state="errors.repeat ? 'invalid' : 'idle'"/>- <p :class="ui.hint()">{{ messages.passwordHint({ count: minimumPasswordLength }) }}</p>+ <p v-if="errors.repeat" :class="ui.error()">{{ errors.repeat }}</p></div></AppDialogBody>- <AppDialogFooter>- <AppButton type="button" variant="ghost" @click="open = false">{{- messages.cancel- }}</AppButton>+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppButton type="button" @click="open = false">{{ messages.cancel }}</AppButton><AppButton type="submit" color="primary" variant="solid" :loading="saving">{{ purpose === 'change' ? messages.savePassword : messages.continue }}</AppButton>diff --git a/src/components/cloud-portal/auth/CloudPortalPublic.stories.ts b/src/components/cloud-portal/auth/CloudPortalPublic.stories.tsindex de7c948c6..0312c727f 100644--- a/src/components/cloud-portal/auth/CloudPortalPublic.stories.ts+++ b/src/components/cloud-portal/auth/CloudPortalPublic.stories.ts@@ -41,16 +41,16 @@ const story = (template: string): Story => ({})export const SignIn = story(- `<PortalSignIn :host="host" mode="sign-in" :providers="['google', 'apple']" :email-password="{ signUp: true, minimumPasswordLength: 15 }" />`+ `<PortalSignIn :host="host" mode="sign-in" :providers="['google', 'apple']" :email-password="{ signUp: true, minimumPasswordLength: 8 }" />`)export const SignInForTheDesktopApp = story(- `<PortalSignIn :host="host" mode="sign-in" :providers="['google']" :email-password="{ signUp: true, minimumPasswordLength: 15 }" returns-to="desktop" />`+ `<PortalSignIn :host="host" mode="sign-in" :providers="['google']" :email-password="{ signUp: true, minimumPasswordLength: 8 }" returns-to="desktop" />`)export const SignInWithAnError = story(- `<PortalSignIn :host="host" mode="sign-in" :providers="[]" :email-password="{ signUp: false, minimumPasswordLength: 15 }" error="The email or password is wrong." />`+ `<PortalSignIn :host="host" mode="sign-in" :providers="[]" :email-password="{ signUp: false, minimumPasswordLength: 8 }" error="The email or password is wrong." />`)export const SignUpWithApproval = story(- `<PortalSignIn :host="host" mode="sign-up" :providers="['google']" :email-password="{ signUp: true, minimumPasswordLength: 15 }" approval-required />`+ `<PortalSignIn :host="host" mode="sign-up" :providers="['google']" :email-password="{ signUp: true, minimumPasswordLength: 8 }" approval-required />`)export const CheckYourEmail = story(`<PortalNotice :host="host" heading="Check your email" description="We sent a link to [email protected]. Open it on this device to finish creating your account.">diff --git a/src/components/cloud-portal/auth/PortalDeviceApproval.vue b/src/components/cloud-portal/auth/PortalDeviceApproval.vueindex 26dd91884..173906456 100644--- a/src/components/cloud-portal/auth/PortalDeviceApproval.vue+++ b/src/components/cloud-portal/auth/PortalDeviceApproval.vue@@ -3,6 +3,7 @@ import { useCloudPortalMessages } from '@open-pencil/vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import { portalForm } from '@/theme/cloud-portal/form'import PortalPublicLayout from '../layout/PortalPublicLayout.vue'@@ -27,6 +28,7 @@ const {}>()const emit = defineEmits<{ approve: []; deny: [] }>()const messages = useCloudPortalMessages()+const ui = portalForm({ size: 'lg' })</script><template>@@ -35,8 +37,8 @@ const messages = useCloudPortalMessages():heading="messages.deviceTitle":description="messages.deviceDescription({ email })">- <div class="flex flex-col items-center gap-2 rounded-lg bg-input px-4 py-4">- <span class="text-[11px] text-muted">{{ messages.deviceCheckCode }}</span>+ <div class="flex flex-col items-center gap-2 rounded-lg border border-border px-4 py-4">+ <span class="text-xs text-muted">{{ messages.deviceCheckCode }}</span><span class="font-mono text-xl tracking-[0.3em] text-surface">{{ code }}</span></div><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />@@ -45,13 +47,26 @@ const messages = useCloudPortalMessages():heading="messages.deviceWarningTitle":description="messages.deviceWarningDescription"/>- <div class="flex items-center justify-end gap-2">- <AppButton variant="ghost" :disabled="deciding" @click="emit('deny')">- {{ messages.deny }}- </AppButton>- <AppButton color="primary" variant="solid" :loading="deciding" @click="emit('approve')">+ <div :class="ui.methods()">+ <AppButton+ size="lg"+ color="primary"+ variant="solid"+ :class="ui.submit()"+ :loading="deciding"+ @click="emit('approve')"+ >{{ messages.approve }}</AppButton>+ <AppButton+ size="lg"+ variant="outline"+ :class="ui.submit()"+ :disabled="deciding"+ @click="emit('deny')"+ >+ {{ messages.deny }}+ </AppButton></div></PortalPublicLayout></template>diff --git a/src/components/cloud-portal/auth/PortalNotice.vue b/src/components/cloud-portal/auth/PortalNotice.vueindex 1eab90b37..0b6694e23 100644--- a/src/components/cloud-portal/auth/PortalNotice.vue+++ b/src/components/cloud-portal/auth/PortalNotice.vue@@ -1,7 +1,12 @@<script setup lang="ts">+import { portalPublic } from '@/theme/cloud-portal/public'+import PortalPublicLayout from '../layout/PortalPublicLayout.vue'-/** A Cloud page that tells the person where they stand and what to do next. */+/**+ * A Cloud page that tells the person where they stand and what to do next: an icon, one+ * sentence, and at most a primary and a secondary button stacked below.+ */const {host,heading,@@ -13,21 +18,20 @@ const {description: stringtone?: 'neutral' | 'success' | 'waiting'}>()++const ui = portalPublic()</script><template><PortalPublicLayout :host="host" :heading="heading" :description="description"><template #icon>- <span- class="flex size-10 items-center justify-center rounded-full bg-panel-field text-muted data-[tone=success]:bg-success/10 data-[tone=success]:text-success"- :data-tone="tone"- >- <slot name="icon" />- </span>+ <span :class="ui.tile({ tone })" aria-hidden="true"><slot name="icon" /></span>+ </template>+ <template v-if="$slots.default || $slots.actions" #default>+ <slot />+ <div v-if="$slots.actions" :class="ui.actions()">+ <slot name="actions" />+ </div></template>- <slot />- <div v-if="$slots.actions" class="flex flex-wrap items-center gap-2">- <slot name="actions" />- </div></PortalPublicLayout></template>diff --git a/src/components/cloud-portal/auth/PortalResetPassword.vue b/src/components/cloud-portal/auth/PortalResetPassword.vueindex 26fc74cb1..fab743fba 100644--- a/src/components/cloud-portal/auth/PortalResetPassword.vue+++ b/src/components/cloud-portal/auth/PortalResetPassword.vue@@ -6,6 +6,7 @@ import { useCloudPortalMessages } from '@open-pencil/vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppInput from '@/components/ui/input/AppInput.vue'+import AppPasswordInput from '@/components/ui/input/AppPasswordInput.vue'import { portalForm } from '@/theme/cloud-portal/form'import PortalPublicLayout from '../layout/PortalPublicLayout.vue'@@ -14,7 +15,7 @@ import PortalPublicLayout from '../layout/PortalPublicLayout.vue'const {host,step,- minimumPasswordLength = 15,+ minimumPasswordLength = 8,submitting = false,error = null} = defineProps<{@@ -26,7 +27,7 @@ const {}>()const emit = defineEmits<{ request: [email: string]; choose: [password: string]; back: [] }>()-const ui = portalForm()+const ui = portalForm({ size: 'lg' })const messages = useCloudPortalMessages()const value = ref('')</script>@@ -48,11 +49,20 @@ const value = ref(''){{ step === 'request' ? messages.email : messages.newPassword }}</label><AppInput+ v-if="step === 'request'"id="portal-reset"v-model="value"- :type="step === 'request' ? 'text' : 'password'"- :inputmode="step === 'request' ? 'email' : undefined"- :autocomplete="step === 'request' ? 'email' : 'new-password'"+ size="lg"+ type="email"+ inputmode="email"+ autocomplete="email"+ />+ <AppPasswordInput+ v-else+ id="portal-reset"+ v-model="value"+ size="lg"+ autocomplete="new-password"/><p v-if="step === 'choose'" :class="ui.hint()">{{ messages.passwordHint({ count: minimumPasswordLength }) }}@@ -60,19 +70,25 @@ const value = ref('')</div><AppButtontype="submit"+ size="lg"color="primary"variant="solid"- size="lg"+ :class="ui.submit()":loading="submitting"- :ui="{ base: ui.submit() }">{{ step === 'request' ? messages.sendLink : messages.savePassword }}</AppButton></form>- <template #footer>- <AppButton size="xs" variant="link" @click="emit('back')">{{- messages.backToSignIn- }}</AppButton>+ <template #aside>+ <AppButton+ size="lg"+ color="primary"+ variant="link"+ :class="ui.inlineLink()"+ @click="emit('back')"+ >+ {{ messages.backToSignIn }}+ </AppButton></template></PortalPublicLayout></template>diff --git a/src/components/cloud-portal/auth/PortalSignIn.vue b/src/components/cloud-portal/auth/PortalSignIn.vueindex ac7cb2050..94cd30c03 100644--- a/src/components/cloud-portal/auth/PortalSignIn.vue+++ b/src/components/cloud-portal/auth/PortalSignIn.vue@@ -1,12 +1,11 @@<script setup lang="ts">-import { computed, ref } from 'vue'+import { computed } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue'+import CloudAccountForm from '@/components/cloud/account/CloudAccountForm.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'-import AppInput from '@/components/ui/input/AppInput.vue'-import AppActionRow from '@/components/ui/list/AppActionRow.vue'import { portalForm } from '@/theme/cloud-portal/form'import PortalPublicLayout from '../layout/PortalPublicLayout.vue'@@ -45,24 +44,19 @@ const emit = defineEmits<{switchMode: []}>()-const ui = portalForm()+const ui = portalForm({ size: 'lg' })const messages = useCloudPortalMessages()-const name = ref('')-const email = ref('')-const password = ref('')const signUp = computed(() => mode === 'sign-up')const labels = computed<Record<PortalSignInMethod, string>>(() => ({google: messages.value.continueWithGoogle,apple: messages.value.continueWithApple}))const description = computed(() => {- if (returnsTo) {- return messages.value.returnsTo({- destination:- returnsTo === 'desktop' ? messages.value.returnsToDesktop : messages.value.returnsToEditor- })- }- return signUp.value ? messages.value.signUpDescription : messages.value.signInWelcome+ if (!returnsTo) return undefined+ return messages.value.returnsTo({+ destination:+ returnsTo === 'desktop' ? messages.value.returnsToDesktop : messages.value.returnsToEditor+ })})const showForm = computed(() => !!emailPassword && (!signUp.value || emailPassword.signUp))</script>@@ -87,84 +81,60 @@ const showForm = computed(() => !!emailPassword && (!signUp.value || emailPasswo:description="messages.noSignInMethods"/>+ <template v-if="showForm && emailPassword">+ <CloudAccountForm+ id="portal-account"+ size="lg"+ :mode="mode"+ :minimum-password-length="emailPassword.minimumPasswordLength"+ :disabled="submitting"+ @submit="(credentials) => emit('submit', credentials)"+ @forgot-password="emit('forgotPassword')"+ />+ <AppButton+ type="submit"+ form="portal-account"+ size="lg"+ color="primary"+ variant="solid"+ :class="ui.submit()"+ :loading="submitting"+ >+ {{ signUp ? messages.createAccount : messages.signIn }}+ </AppButton>+ </template>++ <div v-if="providers.length && showForm" :class="ui.divider()">+ <span :class="ui.dividerLine()" />{{ messages.or }}<span :class="ui.dividerLine()" />+ </div>+<div v-if="providers.length" :class="ui.methods()">- <AppActionRow+ <AppButtonv-for="method in providers":key="method"+ size="lg"+ variant="outline"+ :class="ui.submit()":disabled="submitting"@click="emit('provider', method)"><template #leading>- <icon-ai-google v-if="method === 'google'" class="size-4 text-surface" />- <icon-ai-apple v-else class="size-4 text-surface" />+ <icon-ai-google v-if="method === 'google'" class="size-4" />+ <icon-ai-apple v-else class="size-4" /></template>{{ labels[method] }}- <template #trailing><icon-lucide-chevron-right class="size-3.5" /></template>- </AppActionRow>- </div>-- <div v-if="providers.length && showForm" :class="ui.divider()">- <span :class="ui.dividerLine()" />{{ messages.or }}<span :class="ui.dividerLine()" />+ </AppButton></div>- <form- v-if="showForm && emailPassword"- :class="ui.form()"- novalidate- @submit.prevent="emit('submit', { name, email, password })"- >- <div v-if="signUp" :class="ui.field()">- <label for="portal-name" :class="ui.label()">{{ messages.name }}</label>- <AppInput id="portal-name" v-model="name" autocomplete="name" />- </div>- <div :class="ui.field()">- <label for="portal-email" :class="ui.label()">{{ messages.email }}</label>- <AppInput- id="portal-email"- v-model="email"- inputmode="email"- autocomplete="email"- :placeholder="messages.emailPlaceholder"- />- </div>- <div :class="ui.field()">- <div :class="ui.labelRow()">- <label for="portal-password" :class="ui.label()">{{ messages.password }}</label>- <AppButton- v-if="!signUp"- size="xs"- variant="link"- type="button"- @click="emit('forgotPassword')"- >- {{ messages.forgotPassword }}- </AppButton>- </div>- <AppInput- id="portal-password"- v-model="password"- type="password"- :autocomplete="signUp ? 'new-password' : 'current-password'"- />- <p v-if="signUp" :class="ui.hint()">- {{ messages.passwordHint({ count: emailPassword.minimumPasswordLength }) }}- </p>- </div>+ <template v-if="emailPassword?.signUp || signUp" #aside>+ {{ signUp ? messages.haveAccount : messages.newHere }}<AppButton- type="submit"- color="primary"- variant="solid"size="lg"- :loading="submitting"- :ui="{ base: ui.submit() }"+ color="primary"+ variant="link"+ :class="ui.inlineLink()"+ @click="emit('switchMode')">- {{ signUp ? messages.createAccount : messages.signIn }}- </AppButton>- </form>-- <template v-if="emailPassword?.signUp || signUp" #footer>- {{ signUp ? messages.haveAccount : messages.newHere }}- <AppButton size="xs" variant="link" @click="emit('switchMode')">{{ signUp ? messages.signIn : messages.createAnAccount }}</AppButton></template>diff --git a/src/components/cloud-portal/auth/PortalTwoFactor.vue b/src/components/cloud-portal/auth/PortalTwoFactor.vueindex 5f8425d7d..d0f1400f2 100644--- a/src/components/cloud-portal/auth/PortalTwoFactor.vue+++ b/src/components/cloud-portal/auth/PortalTwoFactor.vue@@ -30,7 +30,7 @@ const emit = defineEmits<{passkey: []}>()-const ui = portalForm()+const ui = portalForm({ size: 'lg' })const messages = useCloudPortalMessages()const code = ref('')</script>@@ -47,6 +47,7 @@ const code = ref('')<form :class="ui.form()" novalidate @submit.prevent="emit('verify', code)"><AppInputv-model="code"+ size="lg":inputmode="method === 'authenticator' ? 'numeric' : 'text'"autocomplete="one-time-code":aria-label="@@ -57,28 +58,38 @@ const code = ref('')/><AppButtontype="submit"+ size="lg"color="primary"variant="solid"- size="lg"+ :class="ui.submit()":loading="verifying"- :ui="{ base: ui.submit() }">{{ messages.continue }}</AppButton></form>- <div class="flex flex-wrap items-center justify-between gap-2">- <AppButton size="xs" variant="link" @click="emit('switchMethod')">- {{ method === 'authenticator' ? messages.useRecoveryCode : messages.useAuthenticator }}- </AppButton>+ <template #aside><AppButton- v-if="passkeys"- size="xs"+ size="lg"+ color="primary"variant="link"- :disabled="verifying"- @click="emit('passkey')"+ :class="ui.inlineLink()"+ @click="emit('switchMethod')">- {{ messages.usePasskey }}+ {{ method === 'authenticator' ? messages.useRecoveryCode : messages.useAuthenticator }}</AppButton>- </div>+ <template v-if="passkeys">+ <span aria-hidden="true">·</span>+ <AppButton+ size="lg"+ color="primary"+ variant="link"+ :class="ui.inlineLink()"+ :disabled="verifying"+ @click="emit('passkey')"+ >+ {{ messages.usePasskey }}+ </AppButton>+ </template>+ </template></PortalPublicLayout></template>diff --git a/src/components/cloud-portal/layout/PortalPublicLayout.vue b/src/components/cloud-portal/layout/PortalPublicLayout.vueindex 767558e4c..d2cd6e084 100644--- a/src/components/cloud-portal/layout/PortalPublicLayout.vue+++ b/src/components/cloud-portal/layout/PortalPublicLayout.vue@@ -2,38 +2,50 @@import { useCloudPortalMessages } from '@open-pencil/vue'import BrandMark from '@/components/brand/BrandMark.vue'-import { portalLayout } from '@/theme/cloud-portal/layout'+import { CLOUD_DOCS_URL } from '@/constants'+import { portalPublic } from '@/theme/cloud-portal/public'-/** A Cloud page for people who are signing in or answering a request, around one card. */+/**+ * A Cloud page for people who are signing in or answering a request, laid out as the app's+ * startup notice: the app icon, or the page's own icon, then a title and one narrow column whose+ * buttons sit right under what they act on.+ */const { host, heading, description } = defineProps<{host: stringheading: stringdescription?: string}>()-const ui = portalLayout()+const ui = portalPublic()const messages = useCloudPortalMessages()</script><template><div :class="ui.page()">- <header :class="ui.bar()">- <BrandMark variant="micro" decorative />- <span :class="ui.barTitle()">{{ messages.productName }}</span>- <span :class="ui.barHost()">{{ host }}</span>- </header>- <main :class="ui.center()">- <section :class="ui.card()" :aria-label="heading">- <slot name="icon" />- <div :class="ui.cardHeader()">- <h1 :class="ui.cardTitle()">{{ heading }}</h1>- <p v-if="description" :class="ui.cardDescription()">{{ description }}</p>+ <main :class="ui.main()">+ <section :class="ui.column()" aria-labelledby="portal-heading">+ <header :class="ui.header()">+ <slot name="icon">+ <BrandMark variant="app-icon" decorative :class="ui.icon()" />+ </slot>+ <div :class="ui.headingGroup()">+ <h1 id="portal-heading" :class="ui.title()">{{ heading }}</h1>+ <p v-if="description" :class="ui.description()">{{ description }}</p>+ </div>+ </header>+ <div v-if="$slots.default" :class="ui.body()">+ <slot /></div>- <slot />- <footer v-if="$slots.footer" :class="ui.cardFooter()">- <slot name="footer" />- </footer>+ <p v-if="$slots.aside" :class="ui.aside()">+ <slot name="aside" />+ </p></section></main>+ <footer :class="ui.footer()">+ <span>{{ host }}</span>+ <a :href="CLOUD_DOCS_URL" target="_blank" rel="noreferrer" :class="ui.footerLink()">+ {{ messages.help }}+ </a>+ </footer></div></template>diff --git a/src/components/cloud-portal/sections/SecuritySection.vue b/src/components/cloud-portal/sections/SecuritySection.vueindex df4a2f8cd..17b5cdf07 100644--- a/src/components/cloud-portal/sections/SecuritySection.vue+++ b/src/components/cloud-portal/sections/SecuritySection.vue@@ -35,7 +35,12 @@ const mfa = computed(() => security.data.value?.mfa ?? null)const passkeys = computed(() => security.data.value?.passkeys ?? [])const notice = ref<string | null>(null)-type PasswordStep = 'change' | 'enable-authenticator' | 'disable-authenticator' | 'recovery-codes'+type PasswordStep =+ | 'change'+ | 'enable-authenticator'+ | 'disable-authenticator'+ | 'recovery-codes'+ | 'add-passkey'const passwordStep = ref<PasswordStep | null>(null)const setupURI = ref<string | null>(null)const recoveryCodes = ref<string[] | null>(null)@@ -59,7 +64,7 @@ const linkable = computed<PortalSignInMethod[]>(() =>))const minimum = computed(- () => portal.discovery.authentication.emailPassword?.minimumPasswordLength ?? 15+ () => portal.discovery.authentication.emailPassword?.minimumPasswordLength ?? 8)/** One change from the page, then what the page shows read again. */@@ -77,9 +82,32 @@ const verifyAction = usePortalAction(async (code: string) => {await security.reload()})+/**+ * Adding a passkey needs a recent sign-in, so a stale session signs in again with the password+ * first; an account that also asks for a second step has to sign in again in full.+ */+async function addPasskeyAfterSignIn(password: string): Promise<string | null> {+ const email = portal.account.value?.user.email ?? ''+ const signedIn = await portal.auth.withEmail({ email, password })+ if (!signedIn.ok) return failures.failure(signedIn.failure)+ if (signedIn.value === 'two-step') return failures.failure('session-not-fresh')+ const added = await portal.auth.addPasskey()+ return added.ok ? null : failures.failure(added.failure)+}+/** A step behind the password dialog; its failure shows in the dialog while it is open. */const passwordAction = usePortalAction(async (step: PasswordStep, password: string | undefined, next: string) => {+ if (step === 'add-passkey') {+ const failure = await addPasskeyAfterSignIn(password ?? '')+ if (failure) {+ passwordAction.fail(failure)+ return+ }+ passwordStep.value = null+ await security.reload()+ return+ }let setup: { totpURI: string; backupCodes: string[] } | null = nulllet codes: string[] | null = nullif (step === 'change') await portal.api.changePassword(password ?? '', next)@@ -161,7 +189,9 @@ function closeAuthenticatorSetup() {function addPasskey() {void change.run(async () => {const result = await portal.auth.addPasskey()- if (!result.ok) change.fail(failures.failure(result.failure))+ if (result.ok) return+ if (result.failure === 'session-not-fresh' && hasPassword.value) openPasswordStep('add-passkey')+ else change.fail(failures.failure(result.failure))})}</script>diff --git a/src/components/cloud/account/CloudAccountForm.vue b/src/components/cloud/account/CloudAccountForm.vuenew file mode 100644index 000000000..c60d0bff8--- /dev/null+++ b/src/components/cloud/account/CloudAccountForm.vue@@ -0,0 +1,142 @@+<script setup lang="ts">+import { computed, toRef, watch } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue'++import {+ useCloudAccountForm,+ type CloudAccountCredentials,+ type CloudAccountFormMode+} from '@/app/cloud/sessions/account-form'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import AppPasswordInput from '@/components/ui/input/AppPasswordInput.vue'+import { portalForm } from '@/theme/cloud-portal/form'++/**+ * The email and password form for a Cloud server, in the editor's connect dialog and, larger, on+ * the server's own pages. The submit button lives with the host's actions and names this form by+ * `id`.+ */+const {+ id,+ mode,+ minimumPasswordLength,+ disabled = false,+ size = 'md'+} = defineProps<{+ id: string+ mode: CloudAccountFormMode+ minimumPasswordLength: number+ disabled?: boolean+ size?: 'md' | 'lg'+}>()++const emit = defineEmits<{ submit: [credentials: CloudAccountCredentials]; forgotPassword: [] }>()++const ui = computed(() => portalForm({ size }))+const messages = useCloudPortalMessages()+const form = useCloudAccountForm(+ toRef(() => mode),+ toRef(() => minimumPasswordLength),+ messages+)+const { name, email, password, repeat } = form.fields+const { errors } = form+const submit = form.submit((credentials) => emit('submit', credentials))+watch(() => mode, form.switchMode)++function describedBy(field: 'name' | 'email' | 'password' | 'repeat', hint = false) {+ if (errors.value[field]) return `${id}-${field}-error`+ return hint ? `${id}-${field}-hint` : undefined+}+</script>++<template>+ <form :id="id" :class="ui.form()" novalidate @submit.prevent="submit">+ <fieldset :disabled="disabled" class="contents">+ <div v-if="mode === 'sign-up'" :class="ui.field()">+ <label :for="`${id}-name`" :class="ui.label()">{{ messages.name }}</label>+ <AppInput+ :size="size"+ :id="`${id}-name`"+ v-model="name"+ autocomplete="name"+ :state="errors.name ? 'invalid' : 'idle'"+ :aria-invalid="errors.name ? true : undefined"+ :aria-describedby="describedBy('name')"+ @blur="form.blur('name')"+ />+ <p v-if="errors.name" :id="`${id}-name-error`" :class="ui.error()">+ {{ errors.name }}+ </p>+ </div>+ <div :class="ui.field()">+ <label :for="`${id}-email`" :class="ui.label()">{{ messages.email }}</label>+ <AppInput+ :size="size"+ :id="`${id}-email`"+ v-model="email"+ type="email"+ inputmode="email"+ autocomplete="email"+ :placeholder="messages.emailPlaceholder"+ :state="errors.email ? 'invalid' : 'idle'"+ :aria-invalid="errors.email ? true : undefined"+ :aria-describedby="describedBy('email')"+ @blur="form.blur('email')"+ />+ <p v-if="errors.email" :id="`${id}-email-error`" :class="ui.error()">+ {{ errors.email }}+ </p>+ </div>+ <div :class="ui.field()">+ <div :class="ui.labelRow()">+ <label :for="`${id}-password`" :class="ui.label()">{{ messages.password }}</label>+ <AppButton+ v-if="mode === 'sign-in'"+ :size="size === 'lg' ? 'lg' : 'xs'"+ :class="ui.inlineLink()"+ variant="link"+ type="button"+ @click="emit('forgotPassword')"+ >+ {{ messages.forgotPassword }}+ </AppButton>+ </div>+ <AppPasswordInput+ :size="size"+ :id="`${id}-password`"+ v-model="password"+ :autocomplete="mode === 'sign-up' ? 'new-password' : 'current-password'"+ :state="errors.password ? 'invalid' : 'idle'"+ :aria-invalid="errors.password ? true : undefined"+ :aria-describedby="describedBy('password', mode === 'sign-up')"+ @blur="form.blur('password')"+ />+ <p v-if="errors.password" :id="`${id}-password-error`" :class="ui.error()">+ {{ errors.password }}+ </p>+ <p v-else-if="mode === 'sign-up'" :id="`${id}-password-hint`" :class="ui.hint()">+ {{ messages.passwordHint({ count: minimumPasswordLength }) }}+ </p>+ </div>+ <div v-if="mode === 'sign-up'" :class="ui.field()">+ <label :for="`${id}-repeat`" :class="ui.label()">{{ messages.repeatPassword }}</label>+ <AppPasswordInput+ :size="size"+ :id="`${id}-repeat`"+ v-model="repeat"+ autocomplete="new-password"+ :state="errors.repeat ? 'invalid' : 'idle'"+ :aria-invalid="errors.repeat ? true : undefined"+ :aria-describedby="describedBy('repeat')"+ @blur="form.blur('repeat')"+ />+ <p v-if="errors.repeat" :id="`${id}-repeat-error`" :class="ui.error()">+ {{ errors.repeat }}+ </p>+ </div>+ </fieldset>+ </form>+</template>diff --git a/src/components/cloud/conflict/CloudConflictDialog.stories.ts b/src/components/cloud/conflict/CloudConflictDialog.stories.tsnew file mode 100644index 000000000..9ea2b9449--- /dev/null+++ b/src/components/cloud/conflict/CloudConflictDialog.stories.ts@@ -0,0 +1,39 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'+import { ref } from 'vue'++import { previewDocuments } from '@/components/home/cloud/preview-data'++import CloudConflictDialog from './CloudConflictDialog.vue'+import type { ConflictChoice } from './types'++type Args = { choice: ConflictChoice; onConfirm: (choice: ConflictChoice) => void }++const meta = {+ title: 'App/Cloud/Conflict Dialog',+ tags: ['autodocs'],+ args: { choice: 'keep-both', onConfirm: fn() },+ render: (args) => ({+ components: { CloudConflictDialog },+ setup: () => ({+ args,+ choice: ref(args.choice),+ mine: {+ previewURL: previewDocuments[2]?.previewURL,+ by: 'You, on this device',+ savedAgo: '12 min ago'+ },+ cloud: { previewURL: previewDocuments[0]?.previewURL, by: 'Ben', savedAgo: '5 min ago' }+ }),+ template: `+ <div class="h-[700px]">+ <CloudConflictDialog :open="true" v-model:choice="choice" document-name="Pricing page" :mine="mine" :cloud="cloud" @confirm="args.onConfirm" />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const KeepBoth: Story = {}+export const ReplaceCloudVersion: Story = { args: { choice: 'use-mine' } }diff --git a/src/components/cloud/conflict/CloudConflictDialog.vue b/src/components/cloud/conflict/CloudConflictDialog.vuenew file mode 100644index 000000000..cbbee7513--- /dev/null+++ b/src/components/cloud/conflict/CloudConflictDialog.vue@@ -0,0 +1,121 @@+<script setup lang="ts">+import { RadioGroupItem, RadioGroupRoot } from 'reka-ui'+import { computed } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++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 { cloudConflict } from '@/theme/cloud/conflict'++import type { ConflictChoice, ConflictVersion } from './types'++/**+ * A Cloud document saved elsewhere while this device held unsent changes. Both versions are kept+ * until the person chooses; the safe choice keeps both, the others say whose work they discard.+ */+const { documentName, mine, cloud } = defineProps<{+ documentName: string+ mine: ConflictVersion+ cloud: ConflictVersion+}>()++const open = defineModel<boolean>('open', { default: false })+const choice = defineModel<ConflictChoice>('choice', { default: 'keep-both' })+const emit = defineEmits<{ confirm: [choice: ConflictChoice]; later: [] }>()++const ui = cloudConflict()+const t = useCloudMessages()+const common = useCommonMessages()+const options = computed(() => [+ {+ value: 'keep-both' as const,+ label: t.value.conflictKeepBoth,+ description: t.value.conflictKeepBothDescription({+ name: documentName,+ copyName: t.value.conflictYourCopyName({ name: documentName })+ })+ },+ {+ value: 'use-cloud' as const,+ label: t.value.conflictUseCloud,+ description: t.value.conflictUseCloudDescription+ },+ {+ value: 'use-mine' as const,+ label: t.value.conflictUseMine,+ description: cloud.by+ ? t.value.conflictUseMineDescriptionBy({ name: cloud.by })+ : t.value.conflictUseMineDescription+ }+])+const confirmLabel = computed(+ () =>+ ({+ 'keep-both': t.value.conflictKeepBoth,+ 'use-cloud': t.value.conflictConfirmUseCloud,+ 'use-mine': t.value.conflictConfirmUseMine+ })[choice.value]+)+</script>++<template>+ <AppDialogRoot v-model:open="open" size="md">+ <AppDialogHeader+ :heading="t.changedInTwoPlaces({ name: documentName })"+ :description="t.conflictDescription"+ :close-label="common.close"+ />+ <AppDialogBody>+ <div :class="ui.versions()">+ <figure+ v-for="version in [+ { ...mine, label: t.conflictYourVersion },+ { ...cloud, label: t.conflictCloudVersion }+ ]"+ :key="version.label"+ :class="ui.version()"+ >+ <span :class="ui.preview()">+ <img v-if="version.previewURL" :src="version.previewURL" alt="" :class="ui.image()" />+ <icon-lucide-file-image v-else class="size-6 text-muted/40" />+ </span>+ <figcaption :class="ui.caption()">+ <span :class="ui.versionLabel()">{{ version.label }}</span>+ <span :class="ui.versionMeta()">+ {{ version.by ? `${version.by} · ${version.savedAgo}` : version.savedAgo }}+ </span>+ </figcaption>+ </figure>+ </div>+ <RadioGroupRoot v-model="choice" :aria-label="t.conflictWhichVersion" :class="ui.options()">+ <RadioGroupItem+ v-for="option in options"+ :key="option.value"+ :value="option.value"+ :class="ui.option()"+ :data-tone="option.value === 'use-mine' ? 'danger' : undefined"+ >+ <span :class="ui.optionMark()" aria-hidden="true" />+ <span class="min-w-0">+ <span :class="ui.optionLabel()">{{ option.label }}</span>+ <span :class="ui.optionDescription()">{{ option.description }}</span>+ </span>+ </RadioGroupItem>+ </RadioGroupRoot>+ </AppDialogBody>+ <AppDialogFooter>+ <AppButton variant="ghost" @click="emit('later')">{{ t.conflictDecideLater }}</AppButton>+ <AppButton+ :color="choice === 'use-mine' ? 'error' : 'primary'"+ variant="solid"+ @click="emit('confirm', choice)"+ >+ {{ confirmLabel }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/conflict/types.ts b/src/components/cloud/conflict/types.tsnew file mode 100644index 000000000..39481768e--- /dev/null+++ b/src/components/cloud/conflict/types.ts@@ -0,0 +1,4 @@+export type ConflictChoice = 'keep-both' | 'use-cloud' | 'use-mine'++/** One side of a conflict; `by` is unknown for the server's side, which records no author. */+export type ConflictVersion = { previewURL?: string | null; savedAgo: string; by?: string }diff --git a/src/components/cloud/connect/CloudConnectDialog.stories.ts b/src/components/cloud/connect/CloudConnectDialog.stories.tsnew file mode 100644index 000000000..29ca3f096--- /dev/null+++ b/src/components/cloud/connect/CloudConnectDialog.stories.ts@@ -0,0 +1,161 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'+import { ref } from 'vue'++import CloudConnectDialog from './CloudConnectDialog.vue'+import type {+ CloudAuthFailure,+ CloudConnectError,+ CloudConnectServer,+ CloudConnectStep,+ CloudServerKind,+ CloudSignInMethod+} from './types'++type Args = {+ step: CloudConnectStep+ kind: CloudServerKind+ choosing: boolean+ address: string+ server: CloudConnectServer | null+ error: CloudConnectError | null+ failure: CloudAuthFailure | null+ email: string+ device: { code: string; expiresIn: string } | null+ desktop: boolean+ canGoBack: boolean+ onContinue: () => void+ onSignIn: (method: CloudSignInMethod) => void+}++const EMAIL_PASSWORD = { signUp: true, minimumPasswordLength: 8 }+const TEAM: CloudConnectServer = {+ host: 'cloud.studio.example',+ methods: [],+ emailPassword: EMAIL_PASSWORD,+ approvalRequired: false+}++const meta = {+ title: 'App/Cloud/Connect Dialog',+ tags: ['autodocs'],+ args: {+ step: 'server',+ kind: 'official',+ choosing: true,+ address: '',+ server: null,+ error: null,+ failure: null,+ email: '',+ device: null,+ desktop: false,+ canGoBack: false,+ onContinue: fn(),+ onSignIn: fn()+ },+ render: (args) => ({+ components: { CloudConnectDialog },+ setup: () => ({ args, kind: ref(args.kind), address: ref(args.address) }),+ template: `+ <div class="h-[640px]">+ <CloudConnectDialog+ :open="true"+ v-model:kind="kind"+ v-model:address="address"+ official="cloud.openpencil.dev"+ :step="args.step"+ :choosing="args.choosing"+ :server="args.server"+ :error="args.error"+ :failure="args.failure"+ :email="args.email"+ :device="args.device"+ :desktop="args.desktop"+ :can-go-back="args.canGoBack"+ @continue="args.onContinue"+ @sign-in="args.onSignIn"+ />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const ChooseServer: Story = {}++export const TeamServerAddress: Story = {+ args: { kind: 'self-hosted', choosing: false, address: 'https://cloud.studio.example' }+}++export const Checking: Story = {+ args: { kind: 'self-hosted', address: 'https://cloud.studio.example', step: 'checking' }+}++export const NotACloudServer: Story = {+ args: { kind: 'self-hosted', address: 'https://studio.example', error: 'not-cloud' }+}++export const SignIn: Story = {+ args: {+ step: 'sign-in',+ choosing: false,+ server: {+ host: 'cloud.openpencil.dev',+ methods: ['google', 'apple'],+ emailPassword: EMAIL_PASSWORD,+ approvalRequired: false+ }+ }+}++export const SignInToTeamServer: Story = {+ args: { step: 'sign-in', kind: 'self-hosted', choosing: false, canGoBack: true, server: TEAM }+}++export const WrongPassword: Story = {+ args: { ...SignInToTeamServer.args, failure: 'invalid-credentials' }+}++export const SignUp: Story = {+ args: {+ step: 'sign-up',+ kind: 'self-hosted',+ canGoBack: true,+ server: { ...TEAM, approvalRequired: true }+ }+}++export const CheckEmail: Story = {+ args: {+ step: 'verify',+ kind: 'self-hosted',+ canGoBack: true,+ server: TEAM,+ email: '[email protected]'+ }+}++export const NotConfirmedYet: Story = {+ args: { ...CheckEmail.args, failure: 'email-not-verified' }+}++/** Editors on another address than the server's own can only approve a code in the browser. */+export const SignInElsewhere: Story = {+ args: {+ step: 'sign-in',+ choosing: false,+ desktop: true,+ server: { ...TEAM, methods: ['google', 'email'], emailPassword: null }+ }+}++export const ConfirmCodeOnDesktop: Story = {+ args: {+ step: 'device',+ desktop: true,+ server: { ...TEAM, methods: ['google'] },+ device: { code: 'WDJB-MJHT', expiresIn: '9:41' }+ }+}diff --git a/src/components/cloud/connect/CloudConnectDialog.vue b/src/components/cloud/connect/CloudConnectDialog.vuenew file mode 100644index 000000000..1e2aba6c1--- /dev/null+++ b/src/components/cloud/connect/CloudConnectDialog.vue@@ -0,0 +1,372 @@+<script setup lang="ts">+import { RadioGroupItem, RadioGroupRoot } from 'reka-ui'+import { computed } from 'vue'++import { useCloudMessages, useCloudPortalMessages, useCommonMessages } from '@open-pencil/vue'++import {+ cloudAuthFailureMessage,+ type CloudAccountCredentials+} from '@/app/cloud/sessions/account-form'+import CloudAccountForm from '@/components/cloud/account/CloudAccountForm.vue'+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 AppCopyField from '@/components/ui/input/AppCopyField.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import AppActionRow from '@/components/ui/list/AppActionRow.vue'+import { cloudConnect } from '@/theme/cloud/connect'++import type {+ CloudAuthFailure,+ CloudConnectError,+ CloudConnectServer,+ CloudConnectStep,+ CloudServerKind,+ CloudSignInMethod+} from './types'++/**+ * Connecting the editor to an OpenPencil Cloud server and signing in: the server's address when+ * none was chosen yet, then email and password right here, or a provider in the browser. The+ * desktop app and other editors approve a one-time code in the browser for providers.+ */+const {+ step,+ official,+ choosing = true,+ server = null,+ error = null,+ failure = null,+ busy = false,+ email = '',+ resent = false,+ device = null,+ desktop = false,+ canGoBack = false+} = defineProps<{+ step: CloudConnectStep+ /** The hosted service's address, offered as the first choice. */+ official: string+ /** Whether to ask which server; false when the person already chose one. */+ choosing?: boolean+ /** The server that answered, once checked. */+ server?: CloudConnectServer | null+ error?: CloudConnectError | null+ /** Why the last email sign-in, sign-up, or resend failed. */+ failure?: CloudAuthFailure | null+ busy?: boolean+ /** Where the verification link went. */+ email?: string+ resent?: boolean+ /** The code the desktop app asks the person to confirm in the browser. */+ device?: { code: string; expiresIn: string } | null+ desktop?: boolean+ canGoBack?: boolean+}>()++const open = defineModel<boolean>('open', { default: false })+const kind = defineModel<CloudServerKind>('kind', { default: 'official' })+const address = defineModel<string>('address', { default: '' })+const emit = defineEmits<{+ continue: []+ back: []+ signIn: [method: CloudSignInMethod]+ signInWithEmail: [credentials: CloudAccountCredentials]+ signUp: [credentials: CloudAccountCredentials]+ showSignUp: []+ verified: []+ resend: []+ forgotPassword: []+ reopenBrowser: []+ cancel: []+}>()++const FORM_ID = 'cloud-connect-account'+const ui = cloudConnect()+const t = useCloudMessages()+const portal = useCloudPortalMessages()+const common = useCommonMessages()+const errors = computed<Record<CloudConnectError, { heading: string; description: string }>>(+ () => ({+ 'invalid-address': {+ heading: t.value.errorInvalidAddressHeading,+ description: t.value.errorInvalidAddressDescription+ },+ unreachable: {+ heading: t.value.errorUnreachableHeading,+ description: t.value.errorUnreachableDescription+ },+ 'not-cloud': {+ heading: t.value.errorNotCloudHeading,+ description: t.value.errorNotCloudDescription+ },+ outdated: {+ heading: t.value.errorOutdatedHeading,+ description: t.value.errorOutdatedDescription+ },+ denied: { heading: t.value.errorDeniedHeading, description: t.value.errorDeniedDescription },+ expired: { heading: t.value.errorExpiredHeading, description: t.value.errorExpiredDescription },+ 'sign-in-failed': {+ heading: t.value.errorSignInFailedHeading,+ description: t.value.errorSignInFailedDescription+ }+ })+)+const methodLabels = computed<Record<CloudSignInMethod, string>>(() => ({+ google: t.value.continueWithGoogle,+ apple: t.value.continueWithApple,+ email: t.value.continueWithEmail+}))+const heading = computed(() => {+ switch (step) {+ case 'device':+ return t.value.deviceHeading+ case 'sign-in':+ return kind.value === 'official'+ ? t.value.signInHeading({ name: t.value.productName })+ : t.value.signIn+ case 'sign-up':+ return portal.value.signUpTitle+ case 'verify':+ return portal.value.checkEmailTitle+ default:+ return choosing ? t.value.connectHeading : t.value.connectServerHeading+ }+})+const description = computed(() => {+ const host = server?.host+ switch (step) {+ case 'device':+ return host ? t.value.deviceDescription({ host }) : t.value.deviceDescriptionNoHost+ case 'sign-in':+ return kind.value === 'official' || !host+ ? t.value.connectDescription+ : t.value.onHost({ host })+ case 'sign-up':+ return host ? t.value.onHost({ host }) : undefined+ case 'verify':+ return t.value.verifyDescription({ email })+ default:+ return choosing ? t.value.connectDescription : t.value.connectServerDescription+ }+})+const failureMessage = computed(() =>+ failure ? cloudAuthFailureMessage(failure, portal.value) : null+)+const mode = computed(() => (step === 'sign-up' ? 'sign-up' : 'sign-in'))++function submitAccount(credentials: CloudAccountCredentials) {+ if (step === 'sign-up') emit('signUp', credentials)+ else emit('signInWithEmail', credentials)+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader :heading="heading" :description="description" :close-label="common.close" />++ <AppDialogBody v-if="step === 'server' || step === 'checking'">+ <RadioGroupRoot v-if="choosing" v-model="kind" :aria-label="t.server" :class="ui.choices()">+ <RadioGroupItem value="official" :class="ui.choice()">+ <span :class="ui.choiceIcon()"><icon-lucide-cloud class="size-4" /></span>+ <span :class="ui.choiceBody()">+ <span :class="ui.choiceLabel()">{{ t.productName }}</span>+ <span :class="ui.choiceDescription()">{{+ t.officialDescription({ host: official })+ }}</span>+ </span>+ <span :class="ui.choiceMark()" aria-hidden="true" />+ </RadioGroupItem>+ <RadioGroupItem value="self-hosted" :class="ui.choice()">+ <span :class="ui.choiceIcon()"><icon-lucide-server class="size-4" /></span>+ <span :class="ui.choiceBody()">+ <span :class="ui.choiceLabel()">{{ t.selfHostedLabel }}</span>+ <span :class="ui.choiceDescription()">{{ t.selfHostedDescription }}</span>+ </span>+ <span :class="ui.choiceMark()" aria-hidden="true" />+ </RadioGroupItem>+ </RadioGroupRoot>+ <form+ v-if="kind === 'self-hosted'"+ :class="choosing ? ui.address() : ui.addressAlone()"+ novalidate+ @submit.prevent="emit('continue')"+ >+ <label for="cloud-server-address" :class="ui.addressLabel()">{{ t.serverAddress }}</label>+ <AppInput+ id="cloud-server-address"+ v-model="address"+ type="url"+ inputmode="url"+ autocomplete="url"+ placeholder="https://cloud.example.com"+ :autofocus="!choosing"+ :disabled="step === 'checking'"+ :aria-invalid="error ? true : undefined"+ >+ <template #leading><icon-lucide-globe class="size-3.5" /></template>+ </AppInput>+ </form>+ <p v-else-if="!choosing && step === 'checking'" :class="ui.deviceStatus()" role="status">+ <icon-lucide-loader-circle :class="ui.spinner()" aria-hidden="true" />+ {{ t.checkingServer }}+ </p>+ <AppAlert+ v-if="error"+ tone="error"+ :heading="errors[error].heading"+ :description="errors[error].description"+ :ui="{ root: 'mt-3' }"+ />+ </AppDialogBody>++ <AppDialogBody v-else-if="(step === 'sign-in' || step === 'sign-up') && server">+ <div :class="ui.stack()">+ <AppAlert+ v-if="error"+ tone="error"+ :heading="errors[error].heading"+ :description="errors[error].description"+ />+ <AppAlert+ v-if="step === 'sign-up' && server.approvalRequired"+ tone="info"+ :heading="portal.approvalTitle"+ :description="portal.approvalDescription"+ />+ <AppAlert v-if="failureMessage" tone="error" :heading="failureMessage" />+ <div v-if="step === 'sign-in' && server.methods.length" :class="ui.methods()">+ <AppActionRow+ v-for="method in server.methods"+ :key="method"+ :disabled="busy"+ @click="emit('signIn', method)"+ >+ <template #leading>+ <icon-ai-google v-if="method === 'google'" class="size-4 text-surface" />+ <icon-ai-apple v-else-if="method === 'apple'" class="size-4 text-surface" />+ <icon-lucide-mail v-else class="size-4 text-surface" />+ </template>+ {{ methodLabels[method] }}+ <template #trailing>+ <icon-lucide-arrow-up-right v-if="desktop" class="size-3.5" />+ <icon-lucide-chevron-right v-else class="size-3.5" />+ </template>+ </AppActionRow>+ </div>+ <div+ v-if="step === 'sign-in' && server.methods.length && server.emailPassword"+ :class="ui.divider()"+ >+ <span :class="ui.dividerLine()" />{{ portal.or }}<span :class="ui.dividerLine()" />+ </div>+ <CloudAccountForm+ v-if="server.emailPassword"+ :id="FORM_ID"+ :mode="mode"+ :minimum-password-length="server.emailPassword.minimumPasswordLength"+ :disabled="busy"+ @submit="submitAccount"+ @forgot-password="emit('forgotPassword')"+ />+ <p v-if="server.emailPassword?.signUp" :class="ui.switch()">+ {{ step === 'sign-up' ? portal.haveAccount : portal.newHere }}+ <AppButton+ size="xs"+ variant="link"+ :disabled="busy"+ @click="step === 'sign-up' ? emit('back') : emit('showSignUp')"+ >+ {{ step === 'sign-up' ? portal.signIn : portal.createAnAccount }}+ </AppButton>+ </p>+ <p v-else-if="!server.emailPassword" :class="ui.note()">+ {{ desktop ? t.signInNoteDesktop : t.signInNoteBrowser }}+ </p>+ </div>+ </AppDialogBody>++ <AppDialogBody v-else-if="step === 'verify'">+ <div :class="ui.stack()">+ <div :class="ui.verify()">+ <span :class="ui.verifyIcon()"><icon-lucide-mail-check class="size-5" /></span>+ <p :class="ui.verifyText()">{{ t.verifyNote }}</p>+ </div>+ <AppAlert+ v-if="failure === 'email-not-verified'"+ tone="warning"+ :heading="t.verifyNotYet"+ />+ <AppAlert v-else-if="failureMessage" tone="error" :heading="failureMessage" />+ <p :class="ui.switch()">+ {{ t.verifyNoEmail }}+ <AppButton size="xs" variant="link" :disabled="busy || resent" @click="emit('resend')">+ {{ resent ? portal.sent : portal.sendAgain }}+ </AppButton>+ </p>+ </div>+ </AppDialogBody>++ <AppDialogBody v-else-if="step === 'device' && device">+ <div :class="ui.device()">+ <p :class="ui.deviceLabel()">{{ t.yourCode }}</p>+ <AppCopyField+ :value="device.code"+ :copy-label="t.copyCode"+ :copied-label="common.copied"+ look="command"+ :ui="{ root: 'w-full py-3 pl-4', value: 'flex-1 text-center text-lg tracking-[0.3em]' }"+ />+ <p :class="ui.deviceStatus()" role="status">+ <icon-lucide-loader-circle :class="ui.spinner()" aria-hidden="true" />+ {{ t.deviceWaiting({ duration: device.expiresIn }) }}+ </p>+ </div>+ </AppDialogBody>++ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppButton v-if="canGoBack" :disabled="busy" @click="emit('back')">+ {{ common.back }}+ </AppButton>+ <AppButton v-else @click="emit('cancel')">{{ common.cancel }}</AppButton>++ <AppButton v-if="step === 'device'" variant="outline" @click="emit('reopenBrowser')">+ <template #leading><icon-lucide-external-link class="size-3.5" /></template>+ {{ t.openBrowserAgain }}+ </AppButton>+ <AppButton+ v-else-if="(step === 'sign-in' || step === 'sign-up') && server?.emailPassword"+ type="submit"+ :form="FORM_ID"+ color="primary"+ variant="solid"+ :loading="busy"+ >+ {{ step === 'sign-up' ? portal.createAccount : t.signIn }}+ </AppButton>+ <AppButton+ v-else-if="step === 'verify'"+ color="primary"+ variant="solid"+ :loading="busy"+ @click="emit('verified')"+ >+ {{ t.continue }}+ </AppButton>+ <AppButton+ v-else-if="step === 'server' || step === 'checking'"+ color="primary"+ variant="solid"+ :loading="step === 'checking'"+ :disabled="kind === 'self-hosted' && !address.trim()"+ @click="emit('continue')"+ >+ {{ t.continue }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/connect/CloudConnectHost.vue b/src/components/cloud/connect/CloudConnectHost.vuenew file mode 100644index 000000000..3817b0388--- /dev/null+++ b/src/components/cloud/connect/CloudConnectHost.vue@@ -0,0 +1,121 @@+<script setup lang="ts">+import { useDocumentVisibility, useNow } from '@vueuse/core'+import { computed, watch } from 'vue'++import { useCloudMessages, useI18n } from '@open-pencil/vue'++import {+ backCloudConnect,+ cancelCloudConnect,+ cloudConnectAddress,+ cloudConnectBusy,+ cloudConnectCanGoBack,+ cloudConnectChoosing,+ cloudConnectEmail,+ cloudConnectError,+ cloudConnectFailure,+ cloudConnectKind,+ cloudConnectOpen,+ cloudConnectResent,+ cloudConnectServer,+ cloudConnectStep,+ cloudDeviceSignIn,+ cloudForgotPasswordURL,+ cloudSignedIn,+ continueAfterCloudVerification,+ continueCloudConnect,+ reopenCloudSignInPage,+ resendCloudVerificationEmail,+ showCloudSignUp,+ signInToCloudServer,+ signInWithCloudEmail,+ signUpWithCloudEmail+} from '@/app/cloud/connect/flow'+import { cloudServerHost } from '@/app/cloud/servers/address'+import { findCloudServer } from '@/app/cloud/servers/store'+import { cloudConnection } from '@/app/cloud/sessions/connection'+import { openExternalLink, toast } from '@/app/shell/ui'+import { OFFICIAL_CLOUD_URL } from '@/constants'++import CloudConnectDialog from './CloudConnectDialog.vue'++/** The one connect dialog, driven by the app's connect flow wherever it was opened from. */+const { locale } = useI18n()+const t = useCloudMessages()+const now = useNow({ interval: 1000 })+const official = new URL(OFFICIAL_CLOUD_URL).host++const device = computed(() => {+ const state = cloudDeviceSignIn.value+ if (state.status !== 'waiting') return null+ const minutes = Math.max(1, Math.ceil((state.expiresAt - now.value.getTime()) / 60_000))+ const expiresIn = new Intl.NumberFormat(locale.value, {+ style: 'unit',+ unit: 'minute',+ unitDisplay: 'long'+ }).format(minutes)+ return { code: state.code, expiresIn }+})++// Coming back from the server's pages leaves no dialog open, so say where the person stands.+watch(cloudSignedIn, (signedIn) => {+ const server = signedIn ? findCloudServer(signedIn.serverId) : null+ if (!server) return+ const connection = cloudConnection(server.id)+ const host = cloudServerHost(server.url)+ if (connection.state === 'pending') {+ toast.info(t.value.accountPending({ host }))+ } else if (connection.state === 'signed-in' && connection.account) {+ toast.info(t.value.signedInAs({ host, email: connection.account.email }))+ }+})++function onOpenChange(open: boolean) {+ if (!open) cancelCloudConnect()+}++// Coming back from the email's link is the signal to finish signing in.+const visibility = useDocumentVisibility()+watch(visibility, (state) => {+ if (state === 'visible' && cloudConnectStep.value === 'verify') {+ void continueAfterCloudVerification()+ }+})++function forgotPassword() {+ const url = cloudForgotPasswordURL()+ if (url) void openExternalLink(url)+}+</script>++<template>+ <CloudConnectDialog+ :open="cloudConnectOpen"+ v-model:kind="cloudConnectKind"+ v-model:address="cloudConnectAddress"+ :step="cloudConnectStep"+ :official="official"+ :choosing="cloudConnectChoosing"+ :server="cloudConnectServer"+ :error="cloudConnectError"+ :failure="cloudConnectFailure"+ :busy="cloudConnectBusy"+ :email="cloudConnectEmail"+ :resent="cloudConnectResent"+ :device="device"+ :desktop="cloudConnectServer?.route === 'device'"+ :can-go-back="cloudConnectCanGoBack"+ @update:open="onOpenChange"+ @continue="continueCloudConnect"+ @back="backCloudConnect"+ @sign-in="signInToCloudServer"+ @sign-in-with-email="signInWithCloudEmail"+ @sign-up="signUpWithCloudEmail"+ @show-sign-up="showCloudSignUp"+ @verified="continueAfterCloudVerification"+ @resend="resendCloudVerificationEmail"+ @forgot-password="forgotPassword"+ @reopen-browser="reopenCloudSignInPage"+ @cancel="cancelCloudConnect"+ />+</template>diff --git a/src/components/cloud/connect/types.ts b/src/components/cloud/connect/types.tsnew file mode 100644index 000000000..e0b3a70f2--- /dev/null+++ b/src/components/cloud/connect/types.ts@@ -0,0 +1,27 @@+import type { CloudAuthFailure } from '@open-pencil/cloud/client'++export type CloudServerKind = 'official' | 'self-hosted'++export type CloudSignInMethod = 'google' | 'apple' | 'email'++export type CloudConnectStep = 'server' | 'checking' | 'sign-in' | 'sign-up' | 'verify' | 'device'++export type CloudConnectError =+ | 'unreachable'+ | 'not-cloud'+ | 'outdated'+ | 'invalid-address'+ | 'denied'+ | 'expired'+ | 'sign-in-failed'++export type CloudConnectServer = {+ host: string+ /** Ways that leave the app: providers, and email where the form cannot be used here. */+ methods: CloudSignInMethod[]+ /** Email and password in the dialog, when this app can sign in with them directly. */+ emailPassword: { signUp: boolean; minimumPasswordLength: number } | null+ approvalRequired: boolean+}++export type { CloudAuthFailure }diff --git a/src/components/cloud/invitation/CloudInvitationDialog.stories.ts b/src/components/cloud/invitation/CloudInvitationDialog.stories.tsnew file mode 100644index 000000000..b4058616d--- /dev/null+++ b/src/components/cloud/invitation/CloudInvitationDialog.stories.ts@@ -0,0 +1,77 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'++import CloudInvitationDialog from './CloudInvitationDialog.vue'+import type { CloudInvitationState, CloudInvitationSummary } from './types'++type Args = {+ state: CloudInvitationState+ invitation: CloudInvitationSummary | null+ account: { email: string } | null+ onAccept: () => void+ onSignIn: () => void+}++const invitation: CloudInvitationSummary = {+ kind: 'document',+ documentName: 'Pricing page',+ inviterName: 'Ana Duarte',+ permission: 'edit',+ expiresIn: '6 days',+ recipientHint: 'b•••@studio.example',+ host: 'cloud.openpencil.dev'+}++const meta = {+ title: 'App/Cloud/Invitation Dialog',+ tags: ['autodocs'],+ args: {+ state: 'ready',+ invitation,+ account: { email: '[email protected]' },+ onAccept: fn(),+ onSignIn: fn()+ },+ render: (args) => ({+ components: { CloudInvitationDialog },+ setup: () => ({ args }),+ template: `+ <div class="h-[600px]">+ <CloudInvitationDialog :open="true" :state="args.state" :invitation="args.invitation" :account="args.account" @accept="args.onAccept" @sign-in="args.onSignIn" />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Ready: Story = {}+export const Loading: Story = { args: { state: 'loading', invitation: null } }+export const SignInFirst: Story = { args: { state: 'sign-in', account: null } }+export const UnknownServer: Story = {+ args: {+ state: 'sign-in',+ account: null,+ invitation: { ...invitation, host: 'design.acme.internal', unknownServer: true }+ }+}+export const WrongAccount: Story = {+ args: { state: 'wrong-account', account: { email: '[email protected]' } }+}+export const ViewOnly: Story = {+ args: { invitation: { ...invitation, kind: 'document', permission: 'view' } }+}+export const JoinWorkspace: Story = {+ args: {+ invitation: {+ kind: 'workspace',+ workspaceName: 'Studio',+ role: 'editor',+ inviterName: 'Ana Duarte',+ expiresIn: '6 days',+ recipientHint: 'b•••@studio.example',+ host: 'cloud.openpencil.dev'+ }+ }+}+export const Unavailable: Story = { args: { state: 'unavailable' } }diff --git a/src/components/cloud/invitation/CloudInvitationDialog.vue b/src/components/cloud/invitation/CloudInvitationDialog.vuenew file mode 100644index 000000000..36ce2b622--- /dev/null+++ b/src/components/cloud/invitation/CloudInvitationDialog.vue@@ -0,0 +1,175 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++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 { cloudInvitation } from '@/theme/cloud/invitation'++import type { CloudInvitationState, CloudInvitationSummary } from './types'++/**+ * Opening an invitation link: who invited you to which document or workspace and on which+ * server, then the+ * one step left — accept it, sign in to that server first, or switch to the invited account.+ * A self-hosted server the editor has never used gets a warning before anyone signs in to it.+ */+const {+ state,+ invitation = null,+ account = null+} = defineProps<{+ state: CloudInvitationState+ invitation?: CloudInvitationSummary | null+ /** The account signed in to the invitation's server, if any. */+ account?: { email: string } | null+}>()++const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{ accept: []; signIn: []; switchAccount: []; cancel: [] }>()++const ui = cloudInvitation()+const t = useCloudMessages()+const common = useCommonMessages()+const heading = computed(() => {+ if (state === 'unavailable') return t.value.invitationUnavailableHeading+ if (!invitation) return t.value.invitationOpening+ return t.value.invitedYou({ name: invitation.inviterName })+})+const description = computed(() => {+ if (!invitation || state === 'unavailable') return undefined+ if (invitation.kind === 'workspace') {+ return t.value.invitationWorkspaceDescription({ host: invitation.host })+ }+ return invitation.permission === 'edit'+ ? t.value.invitationEditDescription({ host: invitation.host })+ : t.value.invitationViewDescription({ host: invitation.host })+})+const roles = computed(() => ({+ admin: t.value.roleAdmin,+ editor: t.value.roleEditor,+ viewer: t.value.roleViewer+}))+/** The invited thing's name and the access it brings. */+const target = computed(() => {+ if (!invitation) return null+ return invitation.kind === 'workspace'+ ? { name: invitation.workspaceName, access: roles.value[invitation.role] }+ : {+ name: invitation.documentName,+ access: invitation.permission === 'edit' ? t.value.canEdit : t.value.canView+ }+})+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader :heading="heading" :description="description" :close-label="common.close" />++ <AppDialogBody v-if="state === 'loading'">+ <p :class="ui.loading()" role="status">+ <icon-lucide-loader-circle :class="ui.spinner()" aria-hidden="true" />+ {{ t.invitationChecking }}+ </p>+ </AppDialogBody>++ <AppDialogBody v-else-if="state === 'unavailable'">+ <div :class="ui.unavailable()">+ <span :class="ui.unavailableIcon()"><icon-lucide-mail-x class="size-4" /></span>+ <p :class="ui.unavailableDescription()">+ {{+ invitation+ ? t.invitationUnavailableDescription({ name: invitation.inviterName })+ : t.invitationUnavailableDescriptionNoName+ }}+ </p>+ </div>+ </AppDialogBody>++ <AppDialogBody v-else-if="invitation">+ <div :class="ui.stack()">+ <div :class="ui.document()">+ <span :class="ui.documentIcon()">+ <icon-lucide-layers v-if="invitation.kind === 'workspace'" class="size-4" />+ <icon-lucide-file v-else class="size-4" />+ </span>+ <span :class="ui.documentBody()">+ <span :class="ui.documentName()">{{ target?.name }}</span>+ <span :class="ui.documentMeta()">{{+ t.invitationSentTo({ recipient: invitation.recipientHint })+ }}</span>+ <span :class="ui.documentMeta()">{{+ t.invitationExpiresIn({ duration: invitation.expiresIn })+ }}</span>+ </span>+ <span :class="ui.permission()">{{ target?.access }}</span>+ </div>++ <AppAlert+ v-if="state === 'sign-in' && invitation.unknownServer"+ tone="warning"+ :heading="t.unknownServerHeading({ host: invitation.host })"+ :description="+ invitation.kind === 'workspace'+ ? t.unknownServerWorkspaceDescription+ : t.unknownServerDescription+ "+ />+ <AppAlert+ v-else-if="state === 'sign-in'"+ tone="info"+ :heading="t.invitationSignInHeading({ host: invitation.host })"+ :description="t.invitationSignInDescription"+ />+ <AppAlert+ v-else-if="state === 'wrong-account' && account"+ tone="warning"+ :heading="t.wrongAccountHeading"+ :description="+ t.wrongAccountDescription({ email: account.email, recipient: invitation.recipientHint })+ "+ />+ </div>+ </AppDialogBody>++ <AppDialogFooter>+ <template v-if="state === 'unavailable'">+ <AppButton variant="outline" @click="emit('cancel')">{{ common.close }}</AppButton>+ </template>+ <template v-else>+ <AppButton variant="ghost" @click="emit('cancel')">{{ t.notNow }}</AppButton>+ <AppButton+ v-if="state === 'sign-in'"+ color="primary"+ variant="solid"+ @click="emit('signIn')"+ >+ {{ t.signInToOpen }}+ </AppButton>+ <AppButton+ v-else-if="state === 'wrong-account'"+ color="primary"+ variant="solid"+ @click="emit('switchAccount')"+ >+ {{ t.useAnotherAccount }}+ </AppButton>+ <AppButton+ v-else+ color="primary"+ variant="solid"+ :disabled="state === 'loading'"+ :loading="state === 'accepting'"+ @click="emit('accept')"+ >+ {{ invitation?.kind === 'workspace' ? t.joinWorkspace : t.openDocument }}+ </AppButton>+ </template>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/invitation/CloudInvitationHost.vue b/src/components/cloud/invitation/CloudInvitationHost.vuenew file mode 100644index 000000000..a7ec0e6b7--- /dev/null+++ b/src/components/cloud/invitation/CloudInvitationHost.vue@@ -0,0 +1,58 @@+<script setup lang="ts">+import { useNow } from '@vueuse/core'+import { computed, watch } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { cloudSignedIn } from '@/app/cloud/connect/flow'+import {+ acceptCloudInvitation,+ checkCloudInvitation,+ cloudInvitation,+ cloudInvitationAccount,+ cloudInvitationOpen,+ cloudInvitationState,+ dismissCloudInvitation,+ signInForCloudInvitation,+ switchCloudInvitationAccount+} from '@/app/cloud/invitations/flow'++import CloudInvitationDialog from './CloudInvitationDialog.vue'++/** The invitation an opened link names, until it is accepted or dismissed. */+const { locale } = useI18n()+const now = useNow({ interval: 60_000 })+const HOUR = 3_600_000++const summary = computed(() => {+ const invitation = cloudInvitation.value+ if (!invitation) return null+ const left = Date.parse(invitation.expiresAt) - now.value.getTime()+ const days = left >= 24 * HOUR+ const expiresIn = new Intl.NumberFormat(locale.value, {+ style: 'unit',+ unit: days ? 'day' : 'hour',+ unitDisplay: 'long'+ }).format(Math.max(1, Math.ceil(left / (days ? 24 * HOUR : HOUR))))+ return { ...invitation, expiresIn }+})++// Signing in for the invitation comes back here; check it again with the new account.+watch(cloudSignedIn, () => {+ if (cloudInvitationOpen.value) void checkCloudInvitation()+})+</script>++<template>+ <CloudInvitationDialog+ :open="cloudInvitationOpen"+ :state="cloudInvitationState"+ :invitation="summary"+ :account="cloudInvitationAccount"+ @update:open="(open) => !open && dismissCloudInvitation()"+ @accept="acceptCloudInvitation"+ @sign-in="signInForCloudInvitation"+ @switch-account="switchCloudInvitationAccount"+ @cancel="dismissCloudInvitation"+ />+</template>diff --git a/src/components/cloud/invitation/types.ts b/src/components/cloud/invitation/types.tsnew file mode 100644index 000000000..fa724daa4--- /dev/null+++ b/src/components/cloud/invitation/types.ts@@ -0,0 +1,23 @@+/** What an invitation link can lead to once the editor has asked the server about it. */+export type CloudInvitationState =+ | 'loading'+ | 'ready'+ | 'accepting'+ | 'sign-in'+ | 'wrong-account'+ | 'unavailable'++/** What the invitation opens: one document, or a whole workspace. */+export type CloudInvitationSummary = (+ | { kind: 'document'; documentName: string; permission: 'edit' | 'view' }+ | { kind: 'workspace'; workspaceName: string; role: 'admin' | 'editor' | 'viewer' }+) & {+ inviterName: string+ /** How long until it expires, already worded, such as `6 days`. */+ expiresIn: string+ /** The invited address with most of it hidden, such as `g•••@studio.example`. */+ recipientHint: string+ host: string+ /** A self-hosted server this editor has never connected to. */+ unknownServer?: boolean+}diff --git a/src/components/cloud/save/CloudSaveDialog.stories.ts b/src/components/cloud/save/CloudSaveDialog.stories.tsnew file mode 100644index 000000000..3f4d5d931--- /dev/null+++ b/src/components/cloud/save/CloudSaveDialog.stories.ts@@ -0,0 +1,64 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'+import { ref } from 'vue'++import CloudSaveDialog from './CloudSaveDialog.vue'+import type { CloudSaveDestination, CloudSaveState } from './types'++type Args = {+ destinations: CloudSaveDestination[]+ state: CloudSaveState+ destination: string+ onSave: () => void+}++const official: CloudSaveDestination = {+ kind: 'cloud',+ serverId: 'official',+ host: 'cloud.openpencil.dev',+ workspaces: [+ { id: 'design', name: 'Design team', role: 'editor' },+ { id: 'personal', name: 'Personal', role: 'admin' },+ { id: 'brand', name: 'Brand archive', role: 'viewer' }+ ]+}+const team: CloudSaveDestination = {+ kind: 'cloud',+ serverId: 'acme',+ host: 'design.acme.internal',+ workspaces: [{ id: 'product', name: 'Product', role: 'editor' }]+}+const bucket: CloudSaveDestination = { kind: 'storage', providerId: 's3', label: 'studio-designs' }++const meta = {+ title: 'App/Cloud/Save Dialog',+ tags: ['autodocs'],+ args: {+ destinations: [official],+ state: { kind: 'ready' },+ destination: 'cloud/official/design',+ onSave: fn()+ },+ render: (args) => ({+ components: { CloudSaveDialog },+ setup: () => ({ args, name: ref('Onboarding flow'), destination: ref(args.destination) }),+ template: `+ <div class="h-[680px]">+ <CloudSaveDialog :open="true" v-model:name="name" v-model:destination="destination" :destinations="args.destinations" :state="args.state" @save="args.onSave" />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const ChooseWorkspace: Story = {}+export const TwoServers: Story = { args: { destinations: [official, team] } }+export const WorkspaceOrBucket: Story = { args: { destinations: [official, bucket] } }+export const Uploading: Story = {+ args: { state: { kind: 'saving', sentBytes: 14.2 * 1024 ** 2, totalBytes: 38.5 * 1024 ** 2 } }+}+export const TooLarge: Story = {+ args: { state: { kind: 'error', reason: 'too-large', limitBytes: 256 * 1024 ** 2 } }+}+export const Offline: Story = { args: { state: { kind: 'error', reason: 'offline' } } }diff --git a/src/components/cloud/save/CloudSaveDialog.vue b/src/components/cloud/save/CloudSaveDialog.vuenew file mode 100644index 000000000..0692694bc--- /dev/null+++ b/src/components/cloud/save/CloudSaveDialog.vue@@ -0,0 +1,152 @@+<script setup lang="ts">+import { RadioGroupItem, RadioGroupRoot } from 'reka-ui'+import { computed } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import { formatStorageBytes } from '@/app/storage/format-bytes'+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 { cloudSave } from '@/theme/cloud/save'++import type { CloudSaveDestination, CloudSaveState } from './types'++/**+ * Saving a document from this device to a Cloud workspace or the storage bucket, when there is+ * more than one place to choose from. The saved copy opens in the same tab and syncs from then+ * on; the file on this device is left as it was.+ */+const { destinations, state } = defineProps<{+ destinations: CloudSaveDestination[]+ state: CloudSaveState+}>()++const open = defineModel<boolean>('open', { default: false })+const name = defineModel<string>('name', { default: '' })+/** `cloud/serverId/workspaceId` or `storage/providerId`: the chosen destination. */+const destination = defineModel<string>('destination', { default: '' })+const emit = defineEmits<{ save: []; cancel: [] }>()++const ui = cloudSave()+const t = useCloudMessages()+const common = useCommonMessages()+const saving = computed(() => state.kind === 'saving')+const progress = computed(() =>+ state.kind === 'saving' && state.totalBytes > 0+ ? Math.round((state.sentBytes / state.totalBytes) * 100)+ : 0+)+const roles = computed(() => ({+ viewer: t.value.viewOnly,+ editor: t.value.roleEditor,+ admin: t.value.roleAdmin+}))+const errors = computed(() => ({+ quota: { heading: t.value.saveQuotaHeading, description: t.value.saveQuotaDescription },+ offline: { heading: t.value.saveOfflineHeading, description: t.value.saveOfflineDescription },+ unavailable: { heading: t.value.saveFailedHeading, description: t.value.saveFailedDescription }+}))+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader+ :heading="t.saveHeading"+ :description="t.saveDescription"+ :close-label="common.close"+ />++ <AppDialogBody>+ <fieldset :class="ui.stack()" :disabled="saving">+ <div :class="ui.field()">+ <label for="cloud-save-name" :class="ui.label()">{{ t.saveName }}</label>+ <AppInput id="cloud-save-name" v-model="name" />+ </div>++ <div :class="ui.field()">+ <span id="cloud-save-destination" :class="ui.label()">{{ t.saveWhere }}</span>+ <RadioGroupRoot+ v-model="destination"+ aria-labelledby="cloud-save-destination"+ :class="ui.choices()"+ >+ <template+ v-for="group in destinations"+ :key="group.kind === 'cloud' ? group.serverId : group.providerId"+ >+ <span v-if="destinations.length > 1" :class="ui.server()">{{+ group.kind === 'cloud' ? group.host : t.saveStorageGroup+ }}</span>+ <template v-if="group.kind === 'cloud'">+ <RadioGroupItem+ v-for="workspace in group.workspaces"+ :key="workspace.id"+ :value="`cloud/${group.serverId}/${workspace.id}`"+ :disabled="workspace.role === 'viewer'"+ :class="ui.choice()"+ >+ <icon-lucide-layers :class="ui.choiceIcon()" />+ <span :class="ui.choiceLabel()">{{ workspace.name }}</span>+ <span :class="ui.choiceRole()">{{ roles[workspace.role] }}</span>+ <span :class="ui.choiceMark()" aria-hidden="true" />+ </RadioGroupItem>+ </template>+ <RadioGroupItem v-else :value="`storage/${group.providerId}`" :class="ui.choice()">+ <icon-lucide-database :class="ui.choiceIcon()" />+ <span :class="ui.choiceLabel()">{{ group.label }}</span>+ <span :class="ui.choiceMark()" aria-hidden="true" />+ </RadioGroupItem>+ </template>+ </RadioGroupRoot>+ </div>++ <div v-if="state.kind === 'saving'" :class="ui.progress()" role="status">+ <div :class="ui.progressTrack()">+ <div :class="ui.progressBar()" :style="{ width: `${progress}%` }" />+ </div>+ <span :class="ui.progressText()">+ {{+ t.saveUploading({+ sent: formatStorageBytes(state.sentBytes),+ total: formatStorageBytes(state.totalBytes)+ })+ }}+ </span>+ </div>+ <AppAlert+ v-else-if="state.kind === 'error' && state.reason === 'too-large'"+ tone="error"+ :heading="t.saveTooLargeHeading"+ :description="t.saveTooLargeDescription({ limit: formatStorageBytes(state.limitBytes) })"+ />+ <AppAlert+ v-else-if="state.kind === 'error'"+ tone="error"+ :heading="errors[state.reason].heading"+ :description="errors[state.reason].description"+ />+ <p v-else :class="ui.note()">+ {{ t.saveNote }}+ </p>+ </fieldset>+ </AppDialogBody>++ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppButton @click="emit('cancel')">{{ common.cancel }}</AppButton>+ <AppButton+ color="primary"+ variant="solid"+ :loading="saving"+ :disabled="!name.trim() || !destination"+ @click="emit('save')"+ >+ {{ t.saveAction }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/save/CloudSaveHost.vue b/src/components/cloud/save/CloudSaveHost.vuenew file mode 100644index 000000000..0cb860ff4--- /dev/null+++ b/src/components/cloud/save/CloudSaveHost.vue@@ -0,0 +1,26 @@+<script setup lang="ts">+import {+ cloudSaveDestination,+ cloudSaveDestinations,+ cloudSaveName,+ cloudSaveOpen,+ cloudSaveState,+ saveToDestination+} from '@/app/cloud/documents/save'++import CloudSaveDialog from './CloudSaveDialog.vue'++/** The Save to dialog, driven by the app's save flow for whichever tab opened it. */+</script>++<template>+ <CloudSaveDialog+ v-model:open="cloudSaveOpen"+ v-model:name="cloudSaveName"+ v-model:destination="cloudSaveDestination"+ :destinations="cloudSaveDestinations"+ :state="cloudSaveState"+ @save="saveToDestination"+ @cancel="cloudSaveOpen = false"+ />+</template>diff --git a/src/components/cloud/save/types.ts b/src/components/cloud/save/types.tsnew file mode 100644index 000000000..34c38ba00--- /dev/null+++ b/src/components/cloud/save/types.ts@@ -0,0 +1,15 @@+/** Where a document can be saved: a server's workspaces, or the storage bucket. */+export type CloudSaveDestination =+ | {+ kind: 'cloud'+ serverId: string+ host: string+ workspaces: { id: string; name: string; role: 'viewer' | 'editor' | 'admin' }[]+ }+ | { kind: 'storage'; providerId: string; label: string }++export type CloudSaveState =+ | { kind: 'ready' }+ | { kind: 'saving'; sentBytes: number; totalBytes: number }+ | { kind: 'error'; reason: 'too-large'; limitBytes: number }+ | { kind: 'error'; reason: 'quota' | 'offline' | 'unavailable' }diff --git a/src/components/cloud/share/CloudShareButton.vue b/src/components/cloud/share/CloudShareButton.vuenew file mode 100644index 000000000..ea92a82c5--- /dev/null+++ b/src/components/cloud/share/CloudShareButton.vue@@ -0,0 +1,147 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import { computed, ref, shallowRef, watch } from 'vue'++import type { DocumentPermission } from '@open-pencil/cloud/contract'+import { useCloudMessages, useI18n } from '@open-pencil/vue'++import { cloudConnection } from '@/app/cloud/sessions/connection'+import { cloudShareOpen } from '@/app/cloud/sharing/dialog'+import {+ changeCloudLink,+ changeCloudMember,+ cloudLinkURL,+ cloudShareTarget,+ inviteToCloudDocument,+ readCloudSharing,+ resetCloudLink,+ type CloudShareLink,+ type CloudSharing+} from '@/app/cloud/sharing/document'+import { useEditorStore } from '@/app/editor/active-store'+import { toast } from '@/app/shell/ui'+import { shareButton } from '@/theme/collaboration/share-button'++import CloudShareDialog from './CloudShareDialog.vue'++/** Share for a Cloud document: who can open it and its link, managed on the server. */+const store = useEditorStore()+const { collaboration, locale } = useI18n()+const t = useCloudMessages()+const sharing = shallowRef<CloudSharing | null>(null)+const inviting = ref(false)+const { copy, copied } = useClipboard({ legacy: true })++const target = computed(() => {+ const binding = store.getStorageBinding()+ return binding ? cloudShareTarget(binding) : null+})+const workspace = computed(() => {+ const binding = store.getStorageBinding()+ if (!binding?.profileId) return null+ const found = cloudConnection(binding.profileId).workspaces.find(+ (candidate) => candidate.id === binding.containerId+ )+ return found ? { name: found.name, permission: 'edit' as const } : null+})+const expires = (iso: string) =>+ new Intl.DateTimeFormat(locale.value, { day: 'numeric', month: 'short' }).format(new Date(iso))+const members = computed(() =>+ (sharing.value?.members ?? []).map((member) => ({+ ...member,+ pendingUntil: member.pendingUntil ? expires(member.pendingUntil) : undefined+ }))+)++// Each read is numbered so a slower earlier one never replaces a newer one.+let latestRead = 0++async function refresh() {+ const current = target.value+ if (!current) return+ const read = ++latestRead+ try {+ const next = await readCloudSharing(current)+ if (read === latestRead && target.value?.documentId === current.documentId) sharing.value = next+ } catch {+ if (read === latestRead) toast.error(t.value.shareLoadFailed)+ }+}++/** Runs a change on the server and shows what it left. */+async function change(run: () => Promise<void>) {+ try {+ await run()+ } catch {+ toast.error(t.value.shareChangeFailed)+ }+ await refresh()+}++async function invite(email: string, permission: DocumentPermission) {+ const current = target.value+ if (!current) return+ inviting.value = true+ await change(() => inviteToCloudDocument(current, email, permission))+ inviting.value = false+}++function changeMember(id: string, permission: DocumentPermission | 'remove') {+ const current = target.value+ if (current) void change(() => changeCloudMember(current, id, permission))+}++function changeLink(link: CloudShareLink) {+ const current = target.value+ if (current) void change(() => changeCloudLink(current, link))+}++function resetLink() {+ const current = target.value+ if (current) void change(() => resetCloudLink(current))+}++async function copyLink() {+ const current = target.value+ const url = current ? await cloudLinkURL(current) : null+ if (url) await copy(url)+}++// Another document's members and link never show, or take changes, while this one's load.+watch(+ () => [cloudShareOpen.value, target.value?.documentId] as const,+ ([open], previous) => {+ if (target.value?.documentId !== previous?.[1]) sharing.value = null+ if (open) void refresh()+ }+)+</script>++<template>+ <button+ data-test-id="cloud-share-button"+ :class="shareButton({ connection: 'idle' })"+ :disabled="!target"+ @click="cloudShareOpen = true"+ >+ <icon-lucide-share-2 class="size-3.5" />+ {{ collaboration.share }}+ </button>+ <CloudShareDialog+ v-if="target"+ v-model:open="cloudShareOpen"+ :document-name="store.state.documentName"+ :workspace="workspace"+ :members="members"+ :link="sharing?.link ?? { access: 'restricted' }"+ :can-manage="sharing?.canManage ?? false"+ :links="sharing?.links"+ :inviting="inviting"+ :copied="copied"+ @invite="invite"+ @change-member="changeMember"+ @change-link="changeLink"+ @copy-link="copyLink"+ @reset-link="resetLink"+ />+</template>diff --git a/src/components/cloud/share/CloudShareDialog.stories.ts b/src/components/cloud/share/CloudShareDialog.stories.tsnew file mode 100644index 000000000..156d2451d--- /dev/null+++ b/src/components/cloud/share/CloudShareDialog.stories.ts@@ -0,0 +1,86 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'++import CloudShareDialog from './CloudShareDialog.vue'+import type { ShareLinkState, ShareMember } from './types'++type Args = {+ members: ShareMember[]+ link: ShareLinkState+ canManage: boolean+ copied: boolean+ onInvite: (email: string, permission: string) => void+}++const members: ShareMember[] = [+ {+ id: 'user-ana',+ name: 'Ana Duarte',+ email: '[email protected]',+ permission: 'owner',+ you: true+ },+ { id: 'user-ben', name: 'Ben Ortiz', email: '[email protected]', permission: 'edit' },+ { id: 'user-mia', name: 'Mia Chen', email: '[email protected]', permission: 'view' },+ {+ id: 'invite-chloe',+ name: '[email protected]',+ email: '[email protected]',+ permission: 'edit',+ pendingUntil: 'in 6 days'+ }+]++const meta = {+ title: 'App/Cloud/Share Dialog',+ tags: ['autodocs'],+ args: {+ members,+ link: { access: 'restricted' },+ canManage: true,+ copied: false,+ onInvite: fn()+ },+ render: (args) => ({+ components: { CloudShareDialog },+ setup: () => ({ args }),+ template: `+ <div class="h-[640px]">+ <CloudShareDialog+ :open="true"+ document-name="Homepage redesign"+ :workspace="{ name: 'Design team', memberCount: 4, permission: 'edit' }"+ :members="args.members"+ :link="args.link"+ :can-manage="args.canManage"+ :copied="args.copied"+ @invite="args.onInvite"+ />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const OnlyPeopleWithAccess: Story = {}++export const AnyoneWithTheLink: Story = {+ args: { link: { access: 'link', permission: 'view', copyable: true } }+}++export const LinkCopied: Story = {+ args: { link: { access: 'link', permission: 'view', copyable: true }, copied: true }+}++export const LinkMadeOnAnotherDevice: Story = {+ args: { link: { access: 'link', permission: 'edit', copyable: false } }+}++export const ViewerCannotManage: Story = {+ args: {+ canManage: false,+ members: members.map((member) => ({ ...member, you: member.id === 'user-mia' })),+ link: { access: 'link', permission: 'view', copyable: true }+ }+}diff --git a/src/components/cloud/share/CloudShareDialog.vue b/src/components/cloud/share/CloudShareDialog.vuenew file mode 100644index 000000000..b68079272--- /dev/null+++ b/src/components/cloud/share/CloudShareDialog.vue@@ -0,0 +1,258 @@+<script setup lang="ts">+import { computed, ref } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+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 AppBadge from '@/components/ui/feedback/AppBadge.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import Tip from '@/components/ui/overlay/Tip.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import { cloudShare } from '@/theme/cloud/share'++import type { SharePermission, ShareMember, ShareLinkState } from './types'++/**+ * Who can open a Cloud document and how: people invited by email, the workspace it lives in, and+ * whether anyone with the link may open it. Links are kept only as a hash on the server, so a+ * link made on another device has to be reset before it can be copied here.+ */+const {+ documentName,+ workspace = null,+ members,+ link,+ canManage = true,+ inviting = false,+ copied = false,+ links = { allowed: true, edit: true }+} = defineProps<{+ documentName: string+ /** The workspace the document lives in, when this account belongs to it. */+ workspace?: { name: string; memberCount?: number; permission: SharePermission } | null+ members: ShareMember[]+ link: ShareLinkState+ canManage?: boolean+ inviting?: boolean+ copied?: boolean+ /** What the workspace's plan allows for links: any link at all, and links that can edit. */+ links?: { allowed: boolean; edit: boolean }+}>()++const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{+ invite: [email: string, permission: SharePermission]+ changeMember: [id: string, permission: SharePermission | 'remove']+ changeLink: [state: ShareLinkState]+ copyLink: []+ resetLink: []+}>()++const ui = cloudShare()+const t = useCloudMessages()+const common = useCommonMessages()+const email = ref('')+const invitePermission = ref<SharePermission>('edit')+const permissionOptions = computed(() => [+ { value: 'edit' as const, label: t.value.canEdit },+ { value: 'view' as const, label: t.value.canView }+])+const memberOptions = computed(() => [+ ...permissionOptions.value,+ { value: 'remove' as const, label: t.value.shareRemoveAccess }+])+const accessOptions = computed(() => [+ { value: 'restricted', label: t.value.shareRestricted },+ { value: 'link', label: t.value.shareAnyoneWithLink }+])+const accessValue = computed(() => link.access)+const linkPermission = computed<SharePermission>(() =>+ link.access === 'link' ? link.permission : 'view'+)+const permissionLabel = (permission: SharePermission | 'owner') =>+ ({ owner: t.value.shareOwner, edit: t.value.canEdit, view: t.value.canView })[permission]++function submitInvite() {+ const value = email.value.trim()+ if (!value) return+ emit('invite', value, invitePermission.value)+ email.value = ''+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="md">+ <AppDialogHeader+ :heading="t.shareHeading({ name: documentName })"+ :description="+ workspace+ ? t.shareDescriptionInWorkspace({ workspace: workspace.name })+ : t.shareDescription+ "+ :close-label="common.close"+ />+ <AppDialogBody :ui="{ body: 'flex flex-col gap-5' }">+ <form v-if="canManage" :class="ui.invite()" @submit.prevent="submitInvite">+ <AppInput+ v-model="email"+ type="text"+ inputmode="email"+ autocomplete="email"+ :placeholder="t.shareAddPeople"+ :aria-label="t.shareEmailAddress"+ density="compact"+ class="min-w-0 flex-1"+ >+ <template #leading><icon-lucide-user-plus class="size-3.5" /></template>+ </AppInput>+ <AppSelect+ v-model="invitePermission"+ :label="t.shareNewPeoplePermission"+ :options="permissionOptions"+ :ui="{ trigger: 'h-8 w-28' }"+ />+ <AppButton+ type="submit"+ color="primary"+ variant="solid"+ :loading="inviting"+ :ui="{ base: 'h-8 px-3' }"+ >+ {{ t.shareInvite }}+ </AppButton>+ </form>++ <section aria-labelledby="share-people-heading">+ <h3 id="share-people-heading" :class="ui.heading()">{{ t.sharePeopleWithAccess }}</h3>+ <ul :class="ui.list()">+ <li v-for="member in members" :key="member.id" :class="ui.row()">+ <span v-if="member.pendingUntil" :class="ui.pendingAvatar()">+ <icon-lucide-mail class="size-3" />+ </span>+ <AccountAvatar v-else :id="member.id" :name="member.name" size="md" />+ <span :class="ui.rowBody()">+ <span :class="ui.rowName()">+ {{ member.pendingUntil ? member.email : member.name }}+ <span v-if="member.you" class="text-muted">{{ t.shareYou }}</span>+ <AppBadge v-if="member.pendingUntil">{{ t.shareInvited }}</AppBadge>+ </span>+ <span :class="ui.rowDetail()">+ {{+ member.pendingUntil+ ? t.shareInvitationExpires({ date: member.pendingUntil })+ : member.email+ }}+ </span>+ </span>+ <span v-if="member.permission === 'owner' || !canManage" :class="ui.rowRole()">+ {{ permissionLabel(member.permission) }}+ </span>+ <AppSelect+ v-else+ :model-value="member.permission"+ :label="t.shareAccessFor({ name: member.name })"+ :options="memberOptions"+ :ui="{ trigger: 'w-28' }"+ @update:model-value="emit('changeMember', member.id, $event)"+ />+ </li>+ <li v-if="workspace" :class="ui.row()">+ <span :class="ui.groupAvatar()"><icon-lucide-layers class="size-3.5" /></span>+ <span :class="ui.rowBody()">+ <span :class="ui.rowName()">{{+ t.shareEveryoneIn({ workspace: workspace.name })+ }}</span>+ <span v-if="workspace.memberCount" :class="ui.rowDetail()">+ {{ t.shareMemberCount(workspace.memberCount) }}+ </span>+ </span>+ <Tip :label="t.shareWorkspacePermissionTip">+ <span :class="ui.rowRole()">{{ permissionLabel(workspace.permission) }}</span>+ </Tip>+ </li>+ </ul>+ </section>++ <section aria-labelledby="share-link-heading">+ <h3 id="share-link-heading" :class="ui.heading()">{{ t.shareGeneralAccess }}</h3>+ <div :class="ui.access()">+ <span :class="ui.accessIcon()" :data-access="link.access">+ <icon-lucide-globe v-if="link.access === 'link'" class="size-4" />+ <icon-lucide-lock v-else class="size-4" />+ </span>+ <div :class="ui.accessBody()">+ <AppSelect+ v-if="canManage && (links.allowed || link.access === 'link')"+ :model-value="accessValue"+ :label="t.shareGeneralAccess"+ :options="accessOptions"+ :ui="{+ trigger: 'h-6 w-auto border-transparent bg-transparent px-1 -ml-1 font-medium'+ }"+ @update:model-value="+ emit(+ 'changeLink',+ $event === 'link'+ ? { access: 'link', permission: linkPermission, copyable: true }+ : { access: 'restricted' }+ )+ "+ />+ <p v-else :class="ui.accessLabel()">+ {{ link.access === 'link' ? t.shareAnyoneWithLink : t.shareRestricted }}+ </p>+ <p :class="ui.accessDetail()">+ {{+ link.access === 'link'+ ? t.shareLinkDetail+ : links.allowed+ ? t.shareRestrictedDetail+ : t.shareRestrictedNoLinksDetail+ }}+ </p>+ </div>+ <AppSelect+ v-if="link.access === 'link' && canManage"+ :model-value="link.permission"+ :label="t.shareLinkPermission"+ :options="+ links.edit+ ? permissionOptions+ : permissionOptions.filter((option) => option.value === 'view')+ "+ :ui="{ trigger: 'w-28' }"+ @update:model-value="emit('changeLink', { ...link, permission: $event })"+ />+ </div>+ </section>+ </AppDialogBody>++ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <p v-if="!canManage" :class="ui.footnote()">+ {{ t.shareCannotManage }}+ </p>+ <template v-else-if="link.access === 'link' && !link.copyable">+ <Tip :label="t.shareResetLinkTip">+ <AppButton variant="outline" @click="emit('resetLink')">+ <template #leading><icon-lucide-refresh-cw class="size-3.5" /></template>+ {{ t.shareResetLink }}+ </AppButton>+ </Tip>+ </template>+ <AppButton v-else-if="link.access === 'link'" variant="outline" @click="emit('copyLink')">+ <template #leading>+ <icon-lucide-check v-if="copied" class="size-3.5" />+ <icon-lucide-link v-else class="size-3.5" />+ </template>+ {{ copied ? t.shareLinkCopied : t.shareCopyLink }}+ </AppButton>+ <span v-else />+ <AppButton color="primary" variant="solid" @click="open = false">{{ common.done }}</AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/share/types.ts b/src/components/cloud/share/types.tsnew file mode 100644index 000000000..3f3d01efb--- /dev/null+++ b/src/components/cloud/share/types.ts@@ -0,0 +1,15 @@+export type SharePermission = 'edit' | 'view'++export type ShareMember = {+ id: string+ name: string+ email: string+ permission: SharePermission | 'owner'+ /** An invitation not accepted yet, with when it expires. */+ pendingUntil?: string+ you?: boolean+}++export type ShareLinkState =+ | { access: 'restricted' }+ | { access: 'link'; permission: SharePermission; copyable: boolean }diff --git a/src/components/cloud/status/CloudDocumentStatus.stories.ts b/src/components/cloud/status/CloudDocumentStatus.stories.tsnew file mode 100644index 000000000..ab11f2f8e--- /dev/null+++ b/src/components/cloud/status/CloudDocumentStatus.stories.ts@@ -0,0 +1,44 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { userEvent, within } from 'storybook/test'+import IconSettings from '~icons/lucide/settings'++import type { CloudSyncState } from '@/components/home/cloud/types'+import IconButton from '@/components/ui/button/IconButton.vue'++import CloudDocumentStatus from './CloudDocumentStatus.vue'++type Args = { state: CloudSyncState; viewOnly: boolean; savedAgo: string | null }++const meta = {+ title: 'App/Cloud/Document Status',+ tags: ['autodocs'],+ args: { state: 'synced', viewOnly: false, savedAgo: 'just now' },+ render: (args) => ({+ components: { CloudDocumentStatus, IconButton, IconSettings },+ setup: () => ({ args }),+ template: `+ <div class="h-[320px]">+ <div class="flex w-64 items-center gap-1 border-b border-border bg-panel px-2 py-2">+ <span class="flex size-6 items-center justify-center rounded bg-accent text-[11px] font-bold text-on-accent">P</span>+ <span class="min-w-0 flex-1 truncate px-1 text-xs text-surface">Homepage redesign</span>+ <CloudDocumentStatus :state="args.state" :view-only="args.viewOnly" :saved-ago="args.savedAgo" workspace="Design team" host="cloud.openpencil.dev" />+ <IconButton label="Settings"><IconSettings class="size-3.5" /></IconButton>+ </div>+ </div>`+ }),+ play: async ({ canvasElement }) => {+ const trigger = canvasElement.querySelector<HTMLElement>('[data-state-sync]')+ if (trigger) await userEvent.click(trigger)+ await within(document.body).findByRole('dialog')+ }+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Saved: Story = {}+export const Saving: Story = { args: { state: 'uploading' } }+export const Offline: Story = { args: { state: 'offline' } }+export const NeedsAChoice: Story = { args: { state: 'conflict' } }+export const CouldNotSave: Story = { args: { state: 'error' } }+export const ViewOnly: Story = { args: { viewOnly: true } }diff --git a/src/components/cloud/status/CloudDocumentStatus.vue b/src/components/cloud/status/CloudDocumentStatus.vuenew file mode 100644index 000000000..df313981d--- /dev/null+++ b/src/components/cloud/status/CloudDocumentStatus.vue@@ -0,0 +1,145 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { computed, ref } from 'vue'++import { useCloudMessages } from '@open-pencil/vue'++import type { CloudSyncState } from '@/components/home/cloud/types'+import AppButton from '@/components/ui/button/AppButton.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'+import Tip from '@/components/ui/overlay/Tip.vue'+import { cloudStatus } from '@/theme/cloud/status'++/**+ * Where the open Cloud document stands, beside its name: saved, saving, waiting on this device,+ * or needing a choice. Opening it says where the file lives and offers what fits the state.+ */+const {+ state,+ workspace,+ host,+ savedAgo = null,+ viewOnly = false+} = defineProps<{+ state: CloudSyncState+ workspace: string+ host: string+ savedAgo?: string | null+ viewOnly?: boolean+}>()++const emit = defineEmits<{+ share: []+ openWorkspace: []+ resolve: []+ retry: []+}>()++const ui = cloudStatus()+const popoverOpen = ref(false)+/** Every action leads somewhere else, so the popover closes first. */+function act(action: 'share' | 'openWorkspace' | 'resolve' | 'retry') {+ popoverOpen.value = false+ if (action === 'share') emit('share')+ else if (action === 'openWorkspace') emit('openWorkspace')+ else if (action === 'resolve') emit('resolve')+ else emit('retry')+}+const popover = usePopoverUI({ content: 'w-72 p-3' })+const t = useCloudMessages()+const summary = computed(() => {+ const m = t.value+ if (viewOnly) return { label: m.viewOnly, detail: m.statusViewOnlyDetail }+ const summaries: Record<CloudSyncState, { label: string; detail: string }> = {+ synced: {+ label: m.statusSavedTo({ workspace }),+ detail: savedAgo ? m.statusSavedAgo({ time: savedAgo }) : m.statusUpToDate+ },+ uploading: { label: m.statusSaving, detail: m.statusUploadingTo({ workspace }) },+ pending: { label: m.statusSavedOnDevice, detail: m.statusUploadsSoon },+ offline: { label: m.statusSavedOnDevice, detail: m.statusOfflineDetail },+ conflict: { label: m.statusConflict, detail: m.statusConflictDetail },+ error: { label: m.saveFailedHeading, detail: m.statusErrorDetail }+ }+ return summaries[state]+})+</script>++<template>+ <PopoverRoot v-model:open="popoverOpen">+ <Tip :label="summary.label" as-child>+ <PopoverTrigger+ :class="ui.trigger()"+ :data-state-sync="viewOnly ? 'view' : state"+ :aria-label="summary.label"+ >+ <icon-lucide-eye v-if="viewOnly" class="size-3.5" />+ <icon-lucide-cloud-check v-else-if="state === 'synced'" class="size-3.5" />+ <icon-lucide-loader-circle+ v-else-if="state === 'uploading'"+ class="size-3.5 animate-spin motion-reduce:animate-none"+ />+ <icon-lucide-cloud-off v-else-if="state === 'offline'" class="size-3.5" />+ <icon-lucide-cloud-upload v-else-if="state === 'pending'" class="size-3.5" />+ <icon-lucide-git-compare-arrows v-else-if="state === 'conflict'" class="size-3.5" />+ <icon-lucide-circle-alert v-else class="size-3.5" />+ <span v-if="viewOnly || state === 'conflict'" :class="ui.triggerLabel()">+ {{ viewOnly ? t.viewOnly : t.statusResolve }}+ </span>+ </PopoverTrigger>+ </Tip>+ <PopoverPortal>+ <PopoverContent side="bottom" align="start" :side-offset="6" :class="popover.content">+ <div :class="ui.header()">+ <span :class="ui.headerIcon()" :data-state-sync="viewOnly ? 'view' : state">+ <icon-lucide-eye v-if="viewOnly" class="size-4" />+ <icon-lucide-git-compare-arrows v-else-if="state === 'conflict'" class="size-4" />+ <icon-lucide-circle-alert v-else-if="state === 'error'" class="size-4" />+ <icon-lucide-cloud-off v-else-if="state === 'offline'" class="size-4" />+ <icon-lucide-cloud class="size-4" v-else />+ </span>+ <div class="min-w-0">+ <p :class="ui.title()">{{ summary.label }}</p>+ <p :class="ui.detail()">{{ summary.detail }}</p>+ </div>+ </div>+ <dl :class="ui.facts()">+ <div :class="ui.fact()">+ <dt>{{ t.workspace }}</dt>+ <dd>{{ workspace }}</dd>+ </div>+ <div :class="ui.fact()">+ <dt>{{ t.server }}</dt>+ <dd>{{ host }}</dd>+ </div>+ </dl>+ <div :class="ui.actions()">+ <AppButton+ v-if="state === 'conflict' && !viewOnly"+ size="sm"+ color="primary"+ variant="solid"+ @click="act('resolve')"+ >+ {{ t.statusChooseVersion }}+ </AppButton>+ <AppButton+ v-else-if="state === 'error' && !viewOnly"+ size="sm"+ variant="outline"+ @click="act('retry')"+ >+ {{ t.tryAgain }}+ </AppButton>+ <AppButton size="sm" variant="outline" @click="act('share')">+ <template #leading><icon-lucide-user-plus class="size-3.5" /></template>+ {{ t.share }}+ </AppButton>+ <AppButton size="sm" variant="ghost" @click="act('openWorkspace')">{{+ t.statusOpenWorkspace+ }}</AppButton>+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/cloud/status/CloudDocumentStatusHost.vue b/src/components/cloud/status/CloudDocumentStatusHost.vuenew file mode 100644index 000000000..2c1385c1e--- /dev/null+++ b/src/components/cloud/status/CloudDocumentStatusHost.vue@@ -0,0 +1,128 @@+<script setup lang="ts">+import { useObjectUrl } from '@vueuse/core'+import { computed, ref, shallowRef } from 'vue'+import { useRouter } from 'vue-router'++import { useCloudMessages, useI18n } from '@open-pencil/vue'++import { openCloudConnect } from '@/app/cloud/connect/flow'+import { resolveCloudConflict, type CloudConflictChoice } from '@/app/cloud/documents/conflict'+import { useCloudDocumentStatus } from '@/app/cloud/documents/status'+import { cloudRoomPermissions } from '@/app/cloud/rooms/live'+import { showCloudServerOnHome } from '@/app/cloud/servers/store'+import { cloudConnection } from '@/app/cloud/sessions/connection'+import { cloudShareOpen } from '@/app/cloud/sharing/dialog'+import { formatCommentTime, useCommentClock } from '@/app/comments/time'+import { useEditorStore } from '@/app/editor/active-store'+import { createStorageAdapter } from '@/app/integrations/storage'+import { openHomeLocation } from '@/app/shell/menu/navigation'+import { toast } from '@/app/shell/ui'+import { getLocalCanvasStore } from '@/app/storage/local-store'+import { resumeStorageSync } from '@/app/storage/sync'+import CloudConflictDialog from '@/components/cloud/conflict/CloudConflictDialog.vue'++import CloudDocumentStatus from './CloudDocumentStatus.vue'++/** The open document's Cloud status beside its name, and the choice when it conflicts. */+const store = useEditorStore()+const router = useRouter()+const { locale } = useI18n()+const t = useCloudMessages()+const now = useCommentClock()+const { state, location, meta } = useCloudDocumentStatus(() => store.getStorageBinding())++const ago = (iso: string | null | undefined) =>+ iso ? formatCommentTime(iso, now.value.getTime(), locale.value) : ''+const savedAgo = computed(() => ago(meta.value?.lastSyncedAt) || null)+const viewOnly = computed(() => cloudRoomPermissions.value.get(store) === 'view')+/**+ * Saving and saved need nothing from the person, and the tab's dot already shows unsaved edits,+ * so the status shows only for what does: being offline, a failed save, a conflict, view only.+ */+const needsAttention = computed(+ () =>+ viewOnly.value ||+ state.value === 'offline' ||+ state.value === 'error' ||+ state.value === 'conflict'+)++const resolving = ref(false)+const choice = ref<CloudConflictChoice>('keep-both')+const localPreview = shallowRef<Blob | null>(null)+const localPreviewURL = useObjectUrl(localPreview)+const cloudSavedAt = ref<string | null>(null)++async function openConflict() {+ const binding = store.getStorageBinding()+ if (!binding) return+ choice.value = 'keep-both'+ resolving.value = true+ const thumb = await getLocalCanvasStore().readThumb(binding.documentId)+ localPreview.value = thumb ? new Blob([Uint8Array.from(thumb)], { type: 'image/png' }) : null+ const stored = await createStorageAdapter(binding)+ .getDocumentMetadata?.(binding.documentId)+ .catch(() => null)+ cloudSavedAt.value = stored?.updatedAt ?? null+}++async function confirm(picked: CloudConflictChoice) {+ resolving.value = false+ try {+ await resolveCloudConflict(+ store,+ picked,+ t.value.conflictYourCopyName({ name: store.state.documentName })+ )+ } catch {+ toast.error(t.value.conflictResolveFailed)+ }+}++/** Home lists one server's workspaces at a time, so it switches to this document's server. */+function openWorkspace() {+ const binding = store.getStorageBinding()+ if (!binding?.profileId || !binding.containerId) return+ showCloudServerOnHome(binding.profileId)+ openHomeLocation(router, { kind: 'workspace', id: binding.containerId })+}++function retry() {+ const serverId = location.value?.serverId+ if (serverId && cloudConnection(serverId).state !== 'signed-in') {+ openCloudConnect({ serverId })+ return+ }+ void resumeStorageSync()+}+</script>++<template>+ <template v-if="state && location">+ <CloudDocumentStatus+ v-if="needsAttention"+ :state="state"+ :workspace="location.workspace ?? location.host"+ :host="location.host"+ :saved-ago="savedAgo"+ :view-only="viewOnly"+ @resolve="openConflict"+ @share="cloudShareOpen = true"+ @retry="retry"+ @open-workspace="openWorkspace"+ />+ <CloudConflictDialog+ v-model:open="resolving"+ v-model:choice="choice"+ :document-name="store.state.documentName"+ :mine="{+ previewURL: localPreviewURL,+ by: t.conflictYouOnThisDevice,+ savedAgo: ago(meta?.updatedAt)+ }"+ :cloud="{ previewURL: null, savedAgo: ago(cloudSavedAt) }"+ @confirm="confirm"+ @later="resolving = false"+ />+ </template>+</template>diff --git a/src/components/cloud/workspace/CloudNewWorkspaceDialog.vue b/src/components/cloud/workspace/CloudNewWorkspaceDialog.vuenew file mode 100644index 000000000..e07284eea--- /dev/null+++ b/src/components/cloud/workspace/CloudNewWorkspaceDialog.vue@@ -0,0 +1,70 @@+<script setup lang="ts">+import { computed, ref, watch } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++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 { cloudWorkspace } from '@/theme/cloud/workspace'++/** Naming a new workspace on a Cloud server; the person who creates it administers it. */+const { busy = false, failed = false } = defineProps<{ busy?: boolean; failed?: boolean }>()+const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{ create: [name: string]; cancel: [] }>()++const ui = cloudWorkspace()+const t = useCloudMessages()+const common = useCommonMessages()+const name = ref('')+const trimmed = computed(() => name.value.trim())+watch(open, (isOpen) => {+ if (isOpen) name.value = ''+})+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader+ :heading="t.newWorkspaceHeading"+ :description="t.newWorkspaceDescription"+ :close-label="common.close"+ />+ <AppDialogBody>+ <form+ id="cloud-new-workspace"+ :class="ui.form()"+ novalidate+ @submit.prevent="trimmed && emit('create', trimmed)"+ >+ <label for="cloud-new-workspace-name" :class="ui.label()">{{ t.workspaceName }}</label>+ <AppInput+ id="cloud-new-workspace-name"+ v-model="name"+ autofocus+ maxlength="100"+ :disabled="busy"+ :placeholder="t.workspaceNamePlaceholder"+ />+ <AppAlert v-if="failed" tone="error" :heading="t.workspaceFailed" />+ </form>+ </AppDialogBody>+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppButton @click="emit('cancel')">{{ common.cancel }}</AppButton>+ <AppButton+ type="submit"+ form="cloud-new-workspace"+ color="primary"+ variant="solid"+ :loading="busy"+ :disabled="!trimmed"+ >+ {{ t.createWorkspace }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud/workspace/CloudNewWorkspaceHost.vue b/src/components/cloud/workspace/CloudNewWorkspaceHost.vuenew file mode 100644index 000000000..3ad451330--- /dev/null+++ b/src/components/cloud/workspace/CloudNewWorkspaceHost.vue@@ -0,0 +1,22 @@+<script setup lang="ts">+import {+ createWorkspace,+ newWorkspaceBusy,+ newWorkspaceFailure,+ newWorkspaceOpen+} from '@/app/cloud/workspaces/manage'++import CloudNewWorkspaceDialog from './CloudNewWorkspaceDialog.vue'++/** The one New workspace dialog, driven by the app's workspace actions. */+</script>++<template>+ <CloudNewWorkspaceDialog+ v-model:open="newWorkspaceOpen"+ :busy="newWorkspaceBusy"+ :failed="newWorkspaceFailure !== null"+ @create="createWorkspace"+ @cancel="newWorkspaceOpen = false"+ />+</template>diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vuenew file mode 100644index 000000000..78522038f--- /dev/null+++ b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue@@ -0,0 +1,330 @@+<script setup lang="ts">+import { useClipboard } from '@vueuse/core'+import { computed, ref, watch } from 'vue'++import type { WorkspaceMembers, WorkspaceRole } from '@open-pencil/cloud/contract'+import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.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 AppSelect from '@/components/ui/select/AppSelect.vue'+import { cloudWorkspace } from '@/theme/cloud/workspace'++/**+ * Who belongs to a Cloud workspace. Administrators rename it, invite people by email with a+ * role, change roles, and remove people; everyone sees the members and may leave. Leaving and+ * deleting sit apart in a danger zone, and deleting asks for the workspace's name.+ */+const {+ workspaceName,+ canManage = false,+ self = null,+ members = null,+ loading = false,+ busy = false,+ failure = null,+ invitationLink = null+} = defineProps<{+ workspaceName: string+ /** The person administers the workspace. */+ canManage?: boolean+ /** The person's own user id, so their row offers Leave rather than Remove. */+ self?: string | null+ members?: WorkspaceMembers | null+ loading?: boolean+ busy?: boolean+ /** Why the last change was refused, already worded. */+ failure?: string | null+ /** The link of the invitation just sent, for when the server sends no email. */+ invitationLink?: string | null+}>()++const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{+ rename: [name: string]+ invite: [email: string, role: WorkspaceRole]+ revoke: [invitationId: string]+ changeRole: [userId: string, role: WorkspaceRole]+ remove: [userId: string]+ leave: []+ delete: []+}>()++const ui = cloudWorkspace()+const { copy, copied } = useClipboard({ copiedDuring: 1500 })+const t = useCloudMessages()+const common = useCommonMessages()+const name = ref(workspaceName)+const email = ref('')+const role = ref<WorkspaceRole>('editor')+watch(+ () => workspaceName,+ (next) => {+ name.value = next+ }+)+watch(open, (isOpen) => {+ if (isOpen) email.value = ''+})+const roleOptions = computed(() => [+ { value: 'admin' as const, label: t.value.roleAdmin },+ { value: 'editor' as const, label: t.value.roleEditor },+ { value: 'viewer' as const, label: t.value.roleViewer }+])+/** As in the Share dialog, removing someone is the last choice of their role menu. */+const memberOptions = computed(() => [+ ...roleOptions.value,+ { value: 'remove' as const, label: t.value.shareRemoveAccess }+])+function changeMember(userId: string, name: string, next: WorkspaceRole | 'remove') {+ if (next === 'remove') confirming.value = { kind: 'remove', userId, name }+ else emit('changeRole', userId, next)+}+const roleLabels = computed<Record<WorkspaceRole, string>>(() => ({+ admin: t.value.roleAdmin,+ editor: t.value.roleEditor,+ viewer: t.value.roleViewer+}))+const renamed = computed(() => name.value.trim() && name.value.trim() !== workspaceName)++/** Leaving or removing someone takes away access, so it is asked once more. */+const confirming = ref<+ { kind: 'leave' } | { kind: 'delete' } | { kind: 'remove'; userId: string; name: string } | null+>(null)+const confirmation = computed(() => {+ const pending = confirming.value+ if (!pending) return null+ if (pending.kind === 'delete') {+ return {+ heading: t.value.deleteWorkspaceHeading({ workspace: workspaceName }),+ description: t.value.deleteWorkspaceDescription,+ confirm: t.value.deleteWorkspace+ }+ }+ return pending.kind === 'leave'+ ? {+ heading: t.value.leaveWorkspaceHeading({ workspace: workspaceName }),+ description: t.value.leaveWorkspaceDescription,+ confirm: t.value.leaveWorkspace+ }+ : {+ heading: t.value.removeMemberHeading({ name: pending.name, workspace: workspaceName }),+ description: t.value.removeMemberDescription,+ confirm: t.value.removeMemberConfirm+ }+})+/** Deleting can't be undone, so it waits for the workspace's name. */+const typedName = ref('')+watch(confirming, () => {+ typedName.value = ''+})+const confirmBlocked = computed(+ () => confirming.value?.kind === 'delete' && typedName.value.trim() !== workspaceName.trim()+)+function confirm() {+ const pending = confirming.value+ if (confirmBlocked.value) return+ confirming.value = null+ if (pending?.kind === 'leave') emit('leave')+ else if (pending?.kind === 'delete') emit('delete')+ else if (pending) emit('remove', pending.userId)+}++function invite() {+ const address = email.value.trim()+ if (!address) return+ emit('invite', address, role.value)+ email.value = ''+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="md">+ <AppDialogHeader+ :heading="workspaceName"+ :description="t.membersDescription"+ :close-label="common.close"+ />+ <AppDialogBody>+ <div :class="ui.stack()">+ <form+ v-if="canManage"+ :class="ui.section()"+ novalidate+ @submit.prevent="renamed && emit('rename', name.trim())"+ >+ <label for="cloud-workspace-name" :class="ui.sectionTitle()">{{ t.workspaceName }}</label>+ <div :class="ui.inline()">+ <AppInput+ id="cloud-workspace-name"+ v-model="name"+ maxlength="100"+ :disabled="busy"+ :ui="{ root: 'flex-1' }"+ />+ <AppButton v-if="renamed" type="submit" variant="outline" :disabled="busy">+ {{ t.renameWorkspace }}+ </AppButton>+ </div>+ </form>++ <section v-if="canManage" :class="ui.section()">+ <h3 :class="ui.sectionTitle()">{{ t.invitePeople }}</h3>+ <form :class="ui.inline()" novalidate @submit.prevent="invite">+ <label for="cloud-workspace-invite" class="sr-only">{{ t.inviteEmail }}</label>+ <AppInput+ id="cloud-workspace-invite"+ v-model="email"+ type="email"+ autocomplete="off"+ :placeholder="t.inviteEmailPlaceholder"+ :disabled="busy"+ :ui="{ root: 'flex-1' }"+ />+ <AppSelect+ v-model="role"+ :label="t.inviteRole"+ :options="roleOptions"+ :ui="{ trigger: ui.roleSelect() }"+ />+ <AppButton type="submit" variant="outline" :disabled="busy || !email.trim()">+ {{ t.invite }}+ </AppButton>+ </form>+ <div v-if="invitationLink" :class="ui.sent()">+ <p :class="ui.note()">{{ t.invitationSentNote }}</p>+ <AppButton class="self-start" size="sm" variant="outline" @click="copy(invitationLink)">+ <template #leading>+ <icon-lucide-check v-if="copied" class="size-3.5" />+ <icon-lucide-link v-else class="size-3.5" />+ </template>+ {{ copied ? common.copied : t.copyInvitationLink }}+ </AppButton>+ </div>+ </section>++ <AppAlert v-if="failure" tone="error" :heading="failure" />++ <section :class="ui.section()">+ <h3 :class="ui.sectionTitle()">+ {{ t.shareMemberCount(members?.members.length ?? 0) }}+ </h3>+ <p v-if="loading" :class="ui.note()" role="status">{{ t.membersLoading }}</p>+ <ul v-else :class="ui.list()">+ <li v-for="member in members?.members ?? []" :key="member.userId" :class="ui.row()">+ <AccountAvatar :id="member.userId" :name="member.name" />+ <span :class="ui.person()">+ <span :class="ui.personName()">+ {{ member.name }}+ <span v-if="member.userId === self" :class="ui.you()">{{ common.you }}</span>+ </span>+ <span :class="ui.personEmail()">{{ member.email }}</span>+ </span>+ <AppSelect+ v-if="canManage"+ :model-value="member.role"+ :label="t.memberRole({ name: member.name })"+ :options="member.userId === self ? roleOptions : memberOptions"+ :disabled="busy"+ :ui="{ trigger: ui.roleSelect() }"+ @update:model-value="(next) => changeMember(member.userId, member.name, next)"+ />+ <span v-else :class="ui.role()">{{ roleLabels[member.role] }}</span>+ </li>+ </ul>+ </section>++ <section v-if="canManage && members?.invitations.length" :class="ui.section()">+ <h3 :class="ui.sectionTitle()">{{ t.pendingInvitations }}</h3>+ <ul :class="ui.list()">+ <li v-for="invitation in members.invitations" :key="invitation.id" :class="ui.row()">+ <span :class="ui.pendingIcon()"><icon-lucide-mail class="size-3.5" /></span>+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ invitation.email }}</span>+ </span>+ <span :class="ui.role()">{{ roleLabels[invitation.role] }}</span>+ <AppButton+ size="xs"+ variant="link"+ :disabled="busy"+ @click="emit('revoke', invitation.id)"+ >+ {{ t.revokeInvitation }}+ </AppButton>+ </li>+ </ul>+ </section>++ <section :class="ui.section()" aria-labelledby="cloud-workspace-danger">+ <h3 id="cloud-workspace-danger" :class="ui.dangerTitle()">{{ t.dangerZone }}</h3>+ <ul :class="ui.dangerList()">+ <li :class="ui.dangerRow()">+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ t.leaveWorkspace }}</span>+ <span :class="ui.dangerDescription()">{{ t.leaveWorkspaceDescription }}</span>+ </span>+ <AppButton+ color="error"+ variant="outline"+ :disabled="busy"+ @click="confirming = { kind: 'leave' }"+ >+ {{ t.leaveWorkspaceShort }}+ </AppButton>+ </li>+ <li v-if="canManage" :class="ui.dangerRow()">+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ t.deleteWorkspace }}</span>+ <span :class="ui.dangerDescription()">{{ t.deleteWorkspaceDescription }}</span>+ </span>+ <AppButton+ color="error"+ variant="outline"+ :disabled="busy"+ @click="confirming = { kind: 'delete' }"+ >+ {{ t.deleteWorkspaceShort }}+ </AppButton>+ </li>+ </ul>+ </section>+ </div>+ </AppDialogBody>+ <AppDialogFooter>+ <AppButton color="primary" variant="solid" @click="open = false">+ {{ common.done }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+ <AppConfirmationDialog+ :open="confirmation !== null"+ tone="danger"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="common.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ :confirm-disabled="confirmBlocked"+ @update:open="(isOpen) => !isOpen && (confirming = null)"+ @confirm="confirm"+ >+ <div v-if="confirming?.kind === 'delete'" :class="ui.confirmName()">+ <label for="cloud-workspace-delete-name" :class="ui.label()">+ {{ t.deleteWorkspaceTypeName({ workspace: workspaceName }) }}+ </label>+ <AppInput+ id="cloud-workspace-delete-name"+ v-model="typedName"+ autocomplete="off"+ spellcheck="false"+ @enter="confirm"+ />+ </div>+ </AppConfirmationDialog>+</template>diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vuenew file mode 100644index 000000000..becc698ff--- /dev/null+++ b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue@@ -0,0 +1,65 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudMessages } from '@open-pencil/vue'++import {+ changeWorkspaceRole,+ deleteWorkspace,+ inviteToWorkspace,+ lastInvitationLink,+ leaveWorkspace,+ membersBusy,+ membersFailure,+ membersLoading,+ membersOpen,+ membersSelf,+ membersWorkspace,+ removeWorkspaceMember,+ renameWorkspace,+ revokeWorkspaceInvitation,+ workspaceMembers,+ type WorkspaceFailure+} from '@/app/cloud/workspaces/manage'++import CloudWorkspaceMembersDialog from './CloudWorkspaceMembersDialog.vue'++/** The one Members dialog, for whichever workspace Home opened it from. */+const t = useCloudMessages()+const failure = computed(() => {+ const kind = membersFailure.value+ if (!kind) return null+ const words: Record<WorkspaceFailure, string> = {+ 'not-empty': t.value.workspaceNotEmpty,+ 'cleanup-pending': t.value.workspaceCleanupPending,+ 'already-member': t.value.workspaceAlreadyMember,+ 'last-admin': t.value.workspaceLastAdmin,+ forbidden: t.value.workspaceForbidden,+ 'not-found': t.value.workspaceNotFound,+ unavailable: t.value.workspaceFailed+ }+ return words[kind]+})+</script>++<template>+ <CloudWorkspaceMembersDialog+ v-if="membersWorkspace"+ v-model:open="membersOpen"+ :workspace-name="membersWorkspace.name"+ :can-manage="membersWorkspace.role === 'admin'"+ :self="membersSelf"+ :members="workspaceMembers"+ :loading="membersLoading"+ :busy="membersBusy"+ :failure="failure"+ :invitation-link="lastInvitationLink"+ @rename="renameWorkspace"+ @invite="inviteToWorkspace"+ @revoke="revokeWorkspaceInvitation"+ @change-role="changeWorkspaceRole"+ @remove="removeWorkspaceMember"+ @leave="leaveWorkspace"+ @delete="deleteWorkspace"+ />+</template>diff --git a/src/components/collab-panel/CollabPanel.vue b/src/components/collab-panel/CollabPanel.vueindex 4235d4a98..52a41421b 100644--- a/src/components/collab-panel/CollabPanel.vue+++ b/src/components/collab-panel/CollabPanel.vue@@ -1,10 +1,18 @@<script setup lang="ts">+import { computed } from 'vue'++import { isCloudBinding } from '@/app/cloud/documents/status'+import { useEditorStore } from '@/app/editor/active-store'+import CloudShareButton from '@/components/cloud/share/CloudShareButton.vue'import CollabAvatarStack from '@/components/collab-panel/CollabAvatarStack.vue'import CollabSharePopover from '@/components/collab-panel/CollabSharePopover.vue'import { provideCollabPanel } from '@/components/collab-panel/context'import VoiceCallControl from '@/components/voice-call/VoiceCallControl.vue'const collab = provideCollabPanel()+const store = useEditorStore()+// Cloud documents share through their server; everything else through a peer-to-peer room.+const cloud = computed(() => isCloudBinding(store.getStorageBinding()))</script><template>@@ -12,6 +20,7 @@ const collab = provideCollabPanel()<CollabAvatarStack /><VoiceCallControl v-if="collab.state.inRoom" :people="collab.callRows" /><div class="flex-1" />- <CollabSharePopover />+ <CloudShareButton v-if="cloud" />+ <CollabSharePopover v-else /></div></template>diff --git a/src/components/home/HomeLayout.vue b/src/components/home/HomeLayout.vuenew file mode 100644index 000000000..5838e6ae0--- /dev/null+++ b/src/components/home/HomeLayout.vue@@ -0,0 +1,20 @@+<script setup lang="ts">+/**+ * The home tab: where documents come from on the side, what is there in the middle. Phones get+ * the locations as a menu above the documents instead of the sidebar.+ */+</script>++<template>+ <div class="flex min-h-0 flex-1 bg-canvas text-surface">+ <div class="hidden md:flex">+ <slot name="sidebar" />+ </div>+ <main class="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-auto">+ <div class="mx-auto flex w-full max-w-6xl flex-col px-4 py-4 sm:px-6 sm:py-5">+ <div v-if="$slots.locations" class="mb-3 md:hidden"><slot name="locations" /></div>+ <slot />+ </div>+ </main>+ </div>+</template>diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vueindex 82f435380..5f25d66a8 100644--- a/src/components/home/HomeWorkspace.vue+++ b/src/components/home/HomeWorkspace.vue@@ -4,12 +4,18 @@ import { computed, ref, watch } from 'vue'import { useDocumentWorkspace, useI18n, useViewportKind } from '@open-pencil/vue'+import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { useHomeLocations } from '@/app/home/locations'import {activeStorageProviderID,+ createStorageAdapter,readStoragePreferences,storagePreferencesComplete,+ sameStorageLocation,+ storageLocationOf,storageProviderRegistry,- type StorageDocument+ type StorageDocument,+ type StorageLocation} from '@/app/integrations/storage'import {clearRecentFiles,@@ -21,10 +27,16 @@ import {import { useCredentialSettings } from '@/app/settings/credentials/preferences/use'import { openSettingsDialog } from '@/app/settings/dialog'import { openFileFromPath } from '@/app/shell/menu/use'-import { createStorageWorkspaceSource } from '@/app/storage/workspace/source'+import { createStoredDocument } from '@/app/storage/workspace/create'+import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'import { openStorageDocumentInNewTab } from '@/app/tabs'+import CloudSharedSection from '@/components/home/cloud/CloudSharedSection.vue'+import CloudWorkspaceSection from '@/components/home/cloud/CloudWorkspaceSection.vue'import DocumentEntry from '@/components/home/document/DocumentEntry.vue'+import HomeLayout from '@/components/home/HomeLayout.vue'import HomeSearchActions from '@/components/home/search/HomeSearchActions.vue'+import HomeLocationMenu from '@/components/home/sidebar/HomeLocationMenu.vue'+import HomeSidebar from '@/components/home/sidebar/HomeSidebar.vue'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'@@ -36,6 +48,14 @@ const view = useLocalStorage<'grid' | 'list'>('open-pencil:home-files-view', 'grconst query = ref('')const openError = ref<string | null>(null)const storageConfigured = ref(storagePreferencesComplete(activeStorageProviderID.value))+const places = useHomeLocations()++/** A new design lands in the place Home shows: a Cloud workspace, the bucket, or a local file. */+function newDocument() {+ const target = newDesignTarget.value+ if (target) void createStoredDocument(target.location)+ else emit('new-document')+}const workspace = useDocumentWorkspace<RecentDocument>({source: {@@ -46,7 +66,10 @@ const workspace = useDocumentWorkspace<RecentDocument>({const document = recentFiles.value.find((candidate) => candidate.id === documentId)if (!document) return Promise.resolve(null)if (document.kind === 'local') return loadRecentFileThumbnail(document.path)- return createStorageWorkspaceSource(() => undefined).loadPreview(document.documentId)+ return createStorageWorkspaceSource(+ () => undefined,+ () => storageLocationOf(document)+ ).loadPreview(document.documentId)}},refreshOnFocus: false,@@ -97,6 +120,43 @@ const storageDescription = computed(() => {}return bucket ? `${label} · ${bucket}` : label})+/** The storage bucket as the sidebar lists it, or a prompt to set it up. */+const sidebarStorage = computed(() => {+ if (!storageConfigured.value)+ return { label: storage.value.workspace, detail: settings.value.notConfigured }+ const bucket = readStoragePreferences(activeStorageProviderID.value).bucket?.trim()+ return { label: bucket || storage.value.workspace, detail: storageDescription.value }+})+/** Where New design creates, named on the button; a local file when this is null. */+const newDesignTarget = computed<{ location: StorageLocation; label: string } | null>(() => {+ const workspace = places.workspace.value+ const serverId = places.serverId.value+ if (workspace && serverId && workspace.role !== 'viewer') {+ return {+ location: {+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: serverId,+ containerId: workspace.id+ },+ label: workspace.name+ }+ }+ // Shared documents belong to other people's workspaces, so a new one goes to the person's own.+ const own = places.workspaces.value.find((entry) => entry.role !== 'viewer')+ if (places.location.value.kind === 'shared' && own && serverId) {+ return {+ location: { providerId: CLOUD_STORAGE_PROVIDER_ID, profileId: serverId, containerId: own.id },+ label: own.name+ }+ }+ if (places.location.value.kind === 'storage' && storageConfigured.value) {+ return {+ location: { providerId: activeStorageProviderID.value },+ label: sidebarStorage.value.label+ }+ }+ return null+})const storagePreviewURL = storageWorkspace.previewURLconst vStoragePreview = storageWorkspace.previewDirectiveconst normalizedQuery = computed(() => query.value.trim().toLocaleLowerCase(locale.value))@@ -131,15 +191,18 @@ async function openRecent(document: RecentDocument): Promise<void> {await openFileFromPath(document.path)return}- const storageDocument = storageDocuments.value.find(- (candidate) => candidate.id === document.documentId- )+ const location = storageLocationOf(document)+ // The listing carries the revision that tells whether this device's copy is still current;+ // offline, the copy opens as it is.+ const listing = sameStorageLocation(location, activeStorageLocation())+ ? storageDocuments.value+ : await createStorageAdapter(location)+ .listDocuments()+ .catch(() => [])+ const listed = listing.find((candidate) => candidate.id === document.documentId)await openStorageDocumentInNewTab(- storageDocument ?? {- id: document.documentId,- name: document.name,- updatedAt: document.updatedAt- }+ listed ?? { id: document.documentId, name: document.name, updatedAt: document.updatedAt },+ location)} catch (error) {forgetRecentDocument(document.id)@@ -164,16 +227,52 @@ function formattedDate(updatedAt: string): string {</script><template>- <main- class="flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto bg-canvas text-surface"- data-test-id="recent-files-home"- >- <section- class="mx-auto flex w-full max-w-7xl flex-col pt-4 pr-[max(1rem,env(safe-area-inset-right))] pb-4 pl-[max(1rem,env(safe-area-inset-left))] sm:px-6 sm:py-5"- >- <HomeSearchActions v-model="query" @new-document="emit('new-document')" />+ <HomeLayout data-test-id="recent-files-home">+ <template #sidebar>+ <HomeSidebar+ :active="places.active.value"+ :account="places.account.value"+ :workspaces="places.workspaces.value"+ :storage="sidebarStorage"+ @select="places.select"+ @connect="places.connect"+ @account-settings="places.accountSettings"+ @storage-settings="places.storageSettings"+ @switch-server="places.connect"+ @new-workspace="places.newWorkspace"+ @sign-out="places.signOut"+ />+ </template>+ <template #locations>+ <HomeLocationMenu+ :active="places.active.value"+ :account="places.account.value"+ :workspaces="places.workspaces.value"+ :storage="sidebarStorage"+ @select="places.select"+ @connect="places.connect"+ @new-workspace="places.newWorkspace"+ />+ </template>+ <HomeSearchActions+ v-model="query"+ :destination="newDesignTarget?.label ?? null"+ @new-document="newDocument"+ />- <p v-if="openError" class="mb-4 text-xs text-error" role="alert">{{ openError }}</p>+ <p v-if="openError" class="mb-4 text-xs text-error" role="alert">{{ openError }}</p>+ <CloudWorkspaceSection+ v-if="places.workspace.value && places.serverId.value"+ :server-id="places.serverId.value"+ :workspace="places.workspace.value"+ :query="normalizedQuery"+ />+ <CloudSharedSection+ v-else-if="places.location.value.kind === 'shared' && places.serverId.value"+ :server-id="places.serverId.value"+ :query="normalizedQuery"+ />+ <template v-else><pv-if="noSearchMatches"class="rounded-lg border border-dashed border-border px-4 py-8 text-center text-xs text-muted"@@ -181,7 +280,7 @@ function formattedDate(updatedAt: string): string {{{ files.noMatchingFiles({ query: query.trim() }) }}</p>- <section v-if="!noSearchMatches">+ <section v-if="!noSearchMatches && places.location.value.kind === 'recent'"><div class="mb-3 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-2"><div class="col-span-2 min-w-0 sm:col-span-1"><h1 class="text-base font-semibold">{{ files.recentFiles }}</h1>@@ -253,7 +352,7 @@ function formattedDate(updatedAt: string): string {</div></section>- <section class="mt-7">+ <section v-if="places.location.value.kind === 'storage'"><div class="mb-3 flex items-start gap-3"><div class="min-w-0"><h2 class="text-base font-semibold">{{ storage.workspace }}</h2>@@ -366,6 +465,6 @@ function formattedDate(updatedAt: string): string {{{ storage.emptyStorageWorkspace }}</div></section>- </section>- </main>+ </template>+ </HomeLayout></template>diff --git a/src/components/home/cloud/CloudHome.stories.ts b/src/components/home/cloud/CloudHome.stories.tsnew file mode 100644index 000000000..e6b896df1--- /dev/null+++ b/src/components/home/cloud/CloudHome.stories.ts@@ -0,0 +1,193 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'+import { ref } from 'vue'+import IconFolderOpen from '~icons/lucide/folder-open'+import IconPlus from '~icons/lucide/plus'+import IconSearch from '~icons/lucide/search'+import IconUsers from '~icons/lucide/users'++import HomeLayout from '@/components/home/HomeLayout.vue'+import HomeSearchActions from '@/components/home/search/HomeSearchActions.vue'+import HomeLocationMenu from '@/components/home/sidebar/HomeLocationMenu.vue'+import HomeSidebar from '@/components/home/sidebar/HomeSidebar.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'++import CloudWorkspaceView from './CloudWorkspaceView.vue'+import { previewDocuments } from './preview-data'+import type { CloudDocumentRow, HomeCloudAccount, HomeLocation } from './types'++type Args = {+ account: HomeCloudAccount | null+ active: HomeLocation+ title: string+ subtitle?: string+ role?: string | null+ documents: CloudDocumentRow[]+ state: 'loading' | 'ready' | 'offline' | 'error'+ usage: { usedBytes: number; totalBytes: number | null } | null+ onOpen: (document: CloudDocumentRow) => void+ realActions?: boolean+}++const account: HomeCloudAccount = {+ id: 'user-ana',+ name: 'Ana Duarte',+ email: '[email protected]',+ host: 'cloud.openpencil.dev'+}+const workspaces = [+ { id: 'design', name: 'Design team', documentCount: 6, attention: true },+ { id: 'personal', name: 'Personal', documentCount: 12 }+]+const synced = previewDocuments.map((document) =>+ document.sync === 'conflict' ? { ...document, sync: 'synced' as const } : document+)++const meta = {+ title: 'App/Home/Cloud Home',+ tags: ['autodocs'],+ parameters: { layout: 'fullscreen' },+ args: {+ account,+ active: { kind: 'workspace', id: 'design' },+ title: 'Design team',+ subtitle: '6 files',+ role: 'Editor',+ documents: synced,+ state: 'ready',+ usage: { usedBytes: 2.1 * 1024 ** 3, totalBytes: 10 * 1024 ** 3 },+ onOpen: fn()+ },+ render: (args) => ({+ components: {+ HomeLayout,+ HomeSearchActions,+ HomeLocationMenu,+ HomeSidebar,+ CloudWorkspaceView,+ AppButton,+ AppInput,+ IconFolderOpen,+ IconPlus,+ IconSearch,+ IconUsers+ },+ setup: () => ({ args, workspaces, query: ref(''), view: ref<'grid' | 'list'>('grid') }),+ template: `+ <div :class="['flex h-dvh max-h-[760px] flex-col', args.realActions && '-m-8 max-h-none']">+ <HomeLayout>+ <template #sidebar>+ <HomeSidebar+ :active="args.active"+ :account="args.account"+ :workspaces="args.account ? workspaces : []"+ :shared-count="3"+ :storage="{ label: 'Studio bucket', detail: 'R2' }"+ />+ </template>+ <template #locations>+ <HomeLocationMenu+ :active="args.active"+ :account="args.account"+ :workspaces="args.account ? workspaces : []"+ :shared-count="3"+ :storage="{ label: 'Studio bucket', detail: 'R2' }"+ />+ </template>+ <HomeSearchActions v-if="args.realActions" v-model="query" />+ <div v-else class="mb-6 flex items-center gap-3">+ <AppInput v-model="query" type="search" density="compact" class="flex-1" placeholder="Search files…" aria-label="Search files">+ <template #leading><IconSearch class="size-4" /></template>+ </AppInput>+ <AppButton variant="outline"><template #leading><IconUsers class="size-3.5" /></template>Join room…</AppButton>+ <AppButton variant="outline"><template #leading><IconFolderOpen class="size-3.5" /></template>Open…</AppButton>+ <AppButton color="primary" variant="solid"><template #leading><IconPlus class="size-3.5" /></template>New design</AppButton>+ </div>+ <CloudWorkspaceView+ v-model:view="view"+ :heading="args.title"+ :can-create="Boolean(args.role)"+ :subtitle="args.subtitle"+ :role="args.role"+ :documents="args.documents"+ :state="args.state"+ :usage="args.usage"+ @open="args.onOpen"+ />+ </HomeLayout>+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Workspace: Story = {}++export const NeedsAttention: Story = {+ args: { documents: previewDocuments }+}++export const Offline: Story = {+ args: {+ state: 'offline',+ documents: synced+ .slice(0, 4)+ .map((document) =>+ document.id === '2' ? { ...document, sync: 'offline' as const } : document+ )+ }+}++export const Loading: Story = {+ args: { state: 'loading', documents: [] }+}++export const EmptyWorkspace: Story = {+ args: {+ active: { kind: 'workspace', id: 'personal' },+ title: 'Personal',+ subtitle: undefined,+ role: 'Owner',+ documents: [],+ usage: { usedBytes: 0, totalBytes: 10 * 1024 ** 3 }+ }+}++export const SharedWithYou: Story = {+ args: {+ active: { kind: 'shared', id: 'shared' },+ title: 'Shared with you',+ subtitle: 'Files people invited you to',+ role: null,+ usage: null,+ documents: synced.slice(2, 5).map((document) => ({+ ...document,+ editedBy: `Shared by ${document.editedBy === 'You' ? 'Chloe' : document.editedBy}`+ }))+ }+}++export const SignedOut: Story = {+ args: {+ account: null,+ active: { kind: 'storage', id: 'storage' },+ title: 'Studio bucket',+ subtitle: 'Cloudflare R2 · studio-designs',+ role: null,+ usage: null,+ documents: synced+ .slice(0, 4)+ .map((document) => ({ ...document, shared: false, editedBy: undefined }))+ }+}++export const Phone: Story = {+ args: { realActions: true },+ parameters: { viewport: { defaultViewport: 'mobile1' } }+}++export const PhoneSharedWithYou: Story = {+ args: { ...SharedWithYou.args, realActions: true }+}diff --git a/src/components/home/cloud/CloudSharedSection.vue b/src/components/home/cloud/CloudSharedSection.vuenew file mode 100644index 000000000..48c64d193--- /dev/null+++ b/src/components/home/cloud/CloudSharedSection.vue@@ -0,0 +1,106 @@+<script setup lang="ts">+import { useAsyncState, useLocalStorage } from '@vueuse/core'+import { computed, watch } from 'vue'++import type { SharedDocument } from '@open-pencil/cloud/contract'+import { useCloudMessages, useI18n } from '@open-pencil/vue'++import { findCloudServer } from '@/app/cloud/servers/store'+import { cloudAPIClient, cloudConnection } from '@/app/cloud/sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { formatCommentTime, useCommentClock } from '@/app/comments/time'+import { openStorageDocumentInNewTab } from '@/app/tabs'++import CloudWorkspaceView from './CloudWorkspaceView.vue'+import type { CloudDocumentRow } from './types'++/** Documents people on the server Home shows shared with this account directly. */+const { serverId, query = '' } = defineProps<{+ serverId: string+ /** Home's search, already lowercased in the app's locale. */+ query?: string+}>()++const { locale } = useI18n()+const t = useCloudMessages()+const now = useCommentClock()+const view = useLocalStorage<'grid' | 'list'>('open-pencil:home-files-view', 'grid')+const {+ state: documents,+ isLoading,+ error,+ execute: refresh+} = useAsyncState(+ async (): Promise<SharedDocument[]> => {+ const server = findCloudServer(serverId)+ const discovery = cloudConnection(serverId).discovery+ if (!server || !discovery) return []+ return cloudAPIClient(server, discovery).listSharedDocuments()+ },+ [],+ // Keep the last list on screen while it reloads.+ { resetOnExecute: false }+)+// Home's server can change under this list; another server's documents never stay listed.+watch(+ () => serverId,+ () => {+ documents.value = []+ void refresh()+ }+)+const state = computed(() => {+ if (isLoading.value) return 'loading'+ return error.value ? 'error' : 'ready'+})++const rows = computed<CloudDocumentRow[]>(() =>+ documents.value.map((document) => ({+ id: document.id,+ name: document.name,+ editedAt: formatCommentTime(document.updatedAt, now.value.getTime(), locale.value),+ editedBy: document.sharedBy+ ? t.value.homeSharedBy({ name: document.sharedBy.name })+ : undefined,+ sync: 'synced',+ permission: document.permission+ }))+)++const matching = computed(() =>+ query+ ? rows.value.filter((row) => row.name.toLocaleLowerCase(locale.value).includes(query))+ : rows.value+)++function open(row: CloudDocumentRow) {+ const document = documents.value.find((candidate) => candidate.id === row.id)+ if (!document) return+ // A shared document stays in its owner's workspace; the direct grant is what opens it.+ void openStorageDocumentInNewTab(+ {+ id: document.id,+ name: document.name,+ updatedAt: document.updatedAt,+ revision: document.currentRevisionId+ },+ {+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: serverId,+ containerId: document.workspaceId+ }+ )+}+</script>++<template>+ <CloudWorkspaceView+ v-model:view="view"+ :heading="t.homeSharedWithYou"+ :subtitle="t.homeSharedSubtitle"+ :documents="matching"+ :state="state"+ @open="open"+ @refresh="refresh"+ />+</template>diff --git a/src/components/home/cloud/CloudSyncIcon.vue b/src/components/home/cloud/CloudSyncIcon.vuenew file mode 100644index 000000000..99c28bfe4--- /dev/null+++ b/src/components/home/cloud/CloudSyncIcon.vue@@ -0,0 +1,43 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudMessages } from '@open-pencil/vue'++import Tip from '@/components/ui/overlay/Tip.vue'++import type { CloudSyncState } from './types'++/** A Cloud document's sync state as one small icon, explained on hover; nothing when synced. */+const { state } = defineProps<{ state: CloudSyncState }>()++const t = useCloudMessages()+const label = computed(+ () =>+ ({+ synced: t.value.syncSynced,+ uploading: t.value.syncUploading,+ pending: t.value.syncPending,+ offline: t.value.syncOffline,+ conflict: t.value.syncConflict,+ error: t.value.syncError+ })[state]+)+</script>++<template>+ <Tip v-if="state !== 'synced'" :label="label">+ <span role="img" :aria-label="label" class="inline-flex" :data-sync="state">+ <icon-lucide-loader-circle+ v-if="state === 'uploading'"+ class="size-3 animate-spin motion-reduce:animate-none"+ />+ <icon-lucide-cloud-upload v-else-if="state === 'pending'" class="size-3" />+ <icon-lucide-cloud-off v-else-if="state === 'offline'" class="size-3" />+ <icon-lucide-git-compare-arrows+ v-else-if="state === 'conflict'"+ class="size-3 text-warning"+ />+ <icon-lucide-circle-alert v-else class="size-3 text-error" />+ </span>+ </Tip>+</template>diff --git a/src/components/home/cloud/CloudWorkspaceSection.vue b/src/components/home/cloud/CloudWorkspaceSection.vuenew file mode 100644index 000000000..7b2fb7a8c--- /dev/null+++ b/src/components/home/cloud/CloudWorkspaceSection.vue@@ -0,0 +1,162 @@+<script setup lang="ts">+import { computedAsync, useLocalStorage, useOnline } from '@vueuse/core'+import { computed, shallowRef, watch } from 'vue'++import { useCloudMessages, useDocumentWorkspace, useI18n } from '@open-pencil/vue'++import { cloudSyncState } from '@/app/cloud/documents/status'+import { findCloudServer } from '@/app/cloud/servers/store'+import { cloudAPIClient, cloudConnection } from '@/app/cloud/sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { openWorkspaceMembers } from '@/app/cloud/workspaces/manage'+import { formatCommentTime, useCommentClock } from '@/app/comments/time'+import {+ sameStorageLocation,+ storageLocationOf,+ type StorageDocument,+ type StorageLocation+} from '@/app/integrations/storage'+import { getLocalCanvasStore, type LocalCanvasMeta } from '@/app/storage/local-store'+import { pendingSyncCount, syncUIState, uploadProgressByCanvas } from '@/app/storage/sync'+import { createStoredDocument } from '@/app/storage/workspace/create'+import { createStorageWorkspaceSource } from '@/app/storage/workspace/source'+import { openStorageDocumentInNewTab } from '@/app/tabs'++import CloudWorkspaceView from './CloudWorkspaceView.vue'+import type { CloudDocumentRow } from './types'++/** One workspace of the server Home shows, listed with this device's copies and their state. */+const {+ serverId,+ workspace,+ query = ''+} = defineProps<{+ serverId: string+ workspace: { id: string; name: string; role: 'viewer' | 'editor' | 'admin' }+ /** Home's search, already lowercased in the app's locale. */+ query?: string+}>()++const { locale } = useI18n()+const t = useCloudMessages()+const now = useCommentClock()+const online = useOnline()+const view = useLocalStorage<'grid' | 'list'>('open-pencil:home-files-view', 'grid')+const location = computed<StorageLocation>(() => ({+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: serverId,+ containerId: workspace.id+}))++// What this device holds, shown when the server cannot list the workspace.+const fallback = shallowRef<StorageDocument[]>([])+const files = useDocumentWorkspace<StorageDocument>({+ source: createStorageWorkspaceSource(+ (snapshot) => {+ fallback.value = snapshot.documents+ },+ () => location.value+ ),+ refreshInterval: 60_000,+ previewConcurrency: 6+})+// Both reads re-run when the workspace or its files change; a slower earlier read never+// overwrites a newer one.+const metas = computedAsync<ReadonlyMap<string, LocalCanvasMeta>>(async () => {+ const requested = location.value+ // Read before the await, so the sync engine's progress re-runs this too.+ void [files.documents.value, syncUIState.value, pendingSyncCount.value]+ const all = await getLocalCanvasStore().listMetas(true)+ const here = all.filter((meta) => sameStorageLocation(storageLocationOf(meta), requested))+ return new Map(here.map((meta) => [meta.id, meta]))+}, new Map())++const usage = computedAsync<{ usedBytes: number; totalBytes: number | null } | null>(async () => {+ void files.documents.value+ const workspaceId = workspace.id+ const server = findCloudServer(serverId)+ const discovery = cloudConnection(serverId).discovery+ if (!server || !discovery) return null+ try {+ const { limits, usage: used } = await cloudAPIClient(+ server,+ discovery+ ).getWorkspaceEntitlements(workspaceId)+ return { usedBytes: used.committedStorageBytes, totalBytes: limits.maximumStorageBytes }+ } catch {+ // Usage is a detail; the files still list without it.+ return null+ }+}, null)++watch(location, () => {+ fallback.value = []+ void files.refresh()+})+watch(+ files.documents,+ (documents) => {+ for (const document of documents) void files.loadPreview(document.id)+ },+ { immediate: true }+)++const listed = computed(() => (files.error.value ? fallback.value : files.documents.value))+const rows = computed<CloudDocumentRow[]>(() =>+ listed.value.map((document) => ({+ id: document.id,+ name: document.name,+ previewURL: files.previewURL(document.id),+ editedAt: formatCommentTime(document.updatedAt, now.value.getTime(), locale.value),+ sync: cloudSyncState(+ metas.value.get(document.id) ?? null,+ uploadProgressByCanvas.value.has(document.id),+ online.value+ ),+ permission: workspace.role === 'viewer' ? 'view' : 'edit'+ }))+)+const state = computed(() => {+ if (files.error.value) return online.value ? 'error' : 'offline'+ return files.loading.value && !files.documents.value.length ? 'loading' : 'ready'+})+const roles = computed(() => ({+ viewer: t.value.roleViewer,+ editor: t.value.roleEditor,+ admin: t.value.roleAdmin+}))++const matching = computed(() =>+ query+ ? rows.value.filter((row) => row.name.toLocaleLowerCase(locale.value).includes(query))+ : rows.value+)++/** Conflicts are resolved in the document, so Review opens the first one. */+function reviewConflicts() {+ const conflicted = rows.value.find((row) => row.sync === 'conflict')+ if (conflicted) open(conflicted)+}++function open(row: CloudDocumentRow) {+ const document = listed.value.find((candidate) => candidate.id === row.id)+ if (document) void openStorageDocumentInNewTab(document, location.value)+}+</script>++<template>+ <CloudWorkspaceView+ v-model:view="view"+ :heading="workspace.name"+ :role="roles[workspace.role]"+ :documents="matching"+ :state="state"+ :usage="usage"+ :can-create="workspace.role !== 'viewer'"+ @open="open"+ @members="openWorkspaceMembers(serverId, workspace.id)"+ @refresh="files.refresh"+ @new-design="createStoredDocument(location)"+ @review-conflicts="reviewConflicts"+ />+</template>diff --git a/src/components/home/cloud/CloudWorkspaceView.vue b/src/components/home/cloud/CloudWorkspaceView.vuenew file mode 100644index 000000000..4fcb44799--- /dev/null+++ b/src/components/home/cloud/CloudWorkspaceView.vue@@ -0,0 +1,208 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import { formatStorageBytes } from '@/app/storage/format-bytes'+import DocumentEntry from '@/components/home/document/DocumentEntry.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppBadge from '@/components/ui/feedback/AppBadge.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppProgress from '@/components/ui/feedback/AppProgress.vue'+import Tip from '@/components/ui/overlay/Tip.vue'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'++import CloudSyncIcon from './CloudSyncIcon.vue'+import type { CloudDocumentRow } from './types'++/**+ * One Cloud workspace on the home tab: its files with where each stands against the server, how+ * much of the workspace's storage they use, and what needs attention.+ */+const {+ heading,+ subtitle,+ role = null,+ documents,+ usage = null,+ state = 'ready',+ canCreate = false+} = defineProps<{+ heading: string+ subtitle?: string+ /** The person's role in the workspace, when it is a workspace rather than a shared list. */+ role?: string | null+ documents: CloudDocumentRow[]+ usage?: { usedBytes: number; totalBytes: number | null } | null+ state?: 'loading' | 'ready' | 'offline' | 'error'+ /** The person may create designs here. */+ canCreate?: boolean+}>()++const view = defineModel<'grid' | 'list'>('view', { default: 'grid' })+const emit = defineEmits<{+ open: [document: CloudDocumentRow]+ newDesign: []+ members: []+ refresh: []+ reviewConflicts: []+}>()++const t = useCloudMessages()+const common = useCommonMessages()+const conflicts = computed(() => documents.filter((document) => document.sync === 'conflict'))+const usageLabel = computed(() => {+ if (!usage) return null+ const used = formatStorageBytes(usage.usedBytes)+ return usage.totalBytes === null+ ? t.value.homeUsageUsed({ used })+ : t.value.homeUsageOf({ used, total: formatStorageBytes(usage.totalBytes) })+})+const metadata = (document: CloudDocumentRow) =>+ document.editedBy ? `${document.editedAt} · ${document.editedBy}` : document.editedAt+</script>++<template>+ <section class="flex min-w-0 flex-col gap-4">+ <header class="flex flex-wrap items-start gap-x-4 gap-y-2">+ <div class="min-w-0 flex-1">+ <div class="flex items-center gap-2">+ <h1 class="truncate text-base font-semibold">{{ heading }}</h1>+ <AppBadge v-if="role">{{ role }}</AppBadge>+ </div>+ <div+ v-if="subtitle || usageLabel"+ class="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs whitespace-nowrap text-muted"+ >+ <span v-if="subtitle">{{ subtitle }}</span>+ <span v-if="subtitle && usageLabel" aria-hidden="true">·</span>+ <template v-if="usage && usage.totalBytes !== null && usageLabel">+ <AppProgress+ :amount="{ value: usage.usedBytes, max: usage.totalBytes }"+ :aria-label="t.homeWorkspaceStorage({ usage: usageLabel })"+ :ui="{ root: 'w-16' }"+ />+ <span>{{ usageLabel }}</span>+ </template>+ <span v-else-if="usageLabel">{{ usageLabel }}</span>+ </div>+ </div>+ <div class="flex items-center gap-1">+ <AppButton v-if="role" size="sm" variant="ghost" @click="emit('members')">+ <template #leading><icon-lucide-users class="size-3.5" /></template>+ {{ t.homeMembers }}+ </AppButton>+ <IconButton :label="common.refresh" class="size-7" @click="emit('refresh')">+ <icon-lucide-refresh-cw class="size-3.5" />+ </IconButton>+ <SegmentedControl+ v-model="view"+ required+ :label="t.homeView"+ :options="[+ { value: 'grid', label: t.homeGrid },+ { value: 'list', label: t.homeList }+ ]"+ >+ <template #option="{ option }">+ <icon-lucide-layout-grid v-if="option.value === 'grid'" class="size-3.5" />+ <icon-lucide-list v-else class="size-3.5" />+ </template>+ </SegmentedControl>+ </div>+ </header>++ <AppAlert+ v-if="state === 'offline'"+ tone="info"+ :heading="t.homeOfflineHeading"+ :description="t.homeOfflineDescription"+ />+ <AppAlert+ v-else-if="state === 'error'"+ tone="error"+ :heading="t.homeLoadFailedHeading"+ :description="t.homeLoadFailedDescription"+ >+ <template #actions>+ <AppButton size="sm" variant="outline" @click="emit('refresh')">{{ t.tryAgain }}</AppButton>+ </template>+ </AppAlert>+ <AppAlert+ v-if="conflicts.length"+ tone="warning"+ :heading="+ conflicts.length === 1+ ? t.changedInTwoPlaces({ name: conflicts[0]?.name ?? '' })+ : t.homeConflicts(conflicts.length)+ "+ :description="t.conflictDescription"+ >+ <template #actions>+ <AppButton size="sm" variant="outline" @click="emit('reviewConflicts')">{{+ t.homeReview+ }}</AppButton>+ </template>+ </AppAlert>++ <div+ v-if="state === 'loading'"+ class="grid grid-cols-1 gap-x-5 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(200px,1fr))]"+ :aria-label="t.homeLoadingFiles"+ >+ <div v-for="index in 4" :key="index" class="min-w-0 animate-pulse motion-reduce:animate-none">+ <div class="aspect-video rounded-lg border border-border bg-panel-field" />+ <div class="mt-2 h-3 w-2/3 rounded bg-panel-field" />+ <div class="mt-1.5 h-2.5 w-1/3 rounded bg-panel-field" />+ </div>+ </div>++ <AppPlaceholder+ v-else-if="documents.length === 0"+ size="page"+ label-as="h2"+ :label="role ? t.homeEmptyWorkspace({ workspace: heading }) : t.homeNothingShared"+ :description="role ? t.homeEmptyWorkspaceDescription : t.homeNothingSharedDescription"+ :ui="{ root: 'rounded-lg border border-dashed border-border py-10' }"+ >+ <template #icon><icon-lucide-layers class="size-5" /></template>+ <template v-if="canCreate" #action>+ <AppButton color="primary" variant="solid" @click="emit('newDesign')">+ <template #leading><icon-lucide-plus class="size-3.5" /></template>+ {{ t.homeNewDesign }}+ </AppButton>+ </template>+ </AppPlaceholder>++ <div+ v-else+ :class="+ view === 'grid'+ ? 'grid grid-cols-1 gap-x-5 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(200px,1fr))]'+ : 'overflow-hidden rounded-lg border border-border'+ "+ >+ <DocumentEntry+ v-for="document in documents"+ :key="document.id"+ :view="view"+ :name="document.name"+ :metadata="metadata(document)"+ :previewURL="document.previewURL"+ @open="emit('open', document)"+ >+ <template #status>+ <Tip v-if="document.permission === 'view'" :label="t.homeViewOnlyTip">+ <icon-lucide-eye class="size-3" role="img" :aria-label="t.viewOnly" />+ </Tip>+ <Tip v-if="document.shared" :label="t.homeSharedTip">+ <icon-lucide-users class="size-3" role="img" :aria-label="t.homeShared" />+ </Tip>+ <CloudSyncIcon :state="document.sync" />+ </template>+ </DocumentEntry>+ </div>+ </section>+</template>diff --git a/src/components/home/cloud/preview-data.ts b/src/components/home/cloud/preview-data.tsnew file mode 100644index 000000000..6b3ef52fe--- /dev/null+++ b/src/components/home/cloud/preview-data.ts@@ -0,0 +1,76 @@+import type { CloudDocumentRow } from './types'++/** A stand-in canvas preview: a few frames on a page in one hue. */+function preview(hue: number): string {+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180" viewBox="0 0 320 180">+<rect width="320" height="180" fill="hsl(${hue} 18% 14%)"/>+<rect x="24" y="28" width="132" height="124" rx="6" fill="hsl(${hue} 30% 92%)"/>+<rect x="36" y="42" width="64" height="8" rx="2" fill="hsl(${hue} 60% 45%)"/>+<rect x="36" y="58" width="104" height="5" rx="2" fill="hsl(${hue} 10% 70%)"/>+<rect x="36" y="68" width="88" height="5" rx="2" fill="hsl(${hue} 10% 70%)"/>+<rect x="36" y="118" width="48" height="18" rx="4" fill="hsl(${hue} 60% 50%)"/>+<rect x="172" y="28" width="124" height="58" rx="6" fill="hsl(${hue} 55% 55%)"/>+<rect x="172" y="94" width="58" height="58" rx="6" fill="hsl(${(hue + 40) % 360} 45% 60%)"/>+<rect x="238" y="94" width="58" height="58" rx="6" fill="hsl(${hue} 25% 85%)"/>+</svg>`+ return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`+}++export const previewDocuments: CloudDocumentRow[] = [+ {+ id: '1',+ name: 'Homepage redesign',+ previewURL: preview(220),+ editedAt: 'Edited 4 min ago',+ editedBy: 'Ana',+ sync: 'synced',+ shared: true,+ permission: 'edit'+ },+ {+ id: '2',+ name: 'Mobile onboarding',+ previewURL: preview(150),+ editedAt: 'Edited 1 hour ago',+ editedBy: 'You',+ sync: 'uploading',+ permission: 'edit'+ },+ {+ id: '3',+ name: 'Pricing page',+ previewURL: preview(30),+ editedAt: 'Edited yesterday',+ editedBy: 'Ben',+ sync: 'conflict',+ permission: 'edit'+ },+ {+ id: '4',+ name: 'Design system — tokens',+ previewURL: preview(280),+ editedAt: 'Edited 3 days ago',+ editedBy: 'Ana',+ sync: 'synced',+ permission: 'view'+ },+ {+ id: '5',+ name: 'Checkout flow',+ previewURL: preview(340),+ editedAt: 'Edited last week',+ editedBy: 'You',+ sync: 'pending',+ permission: 'edit'+ },+ {+ id: '6',+ name: 'Brand moodboard',+ previewURL: preview(190),+ editedAt: 'Edited Sep 28',+ editedBy: 'Chloe',+ sync: 'synced',+ shared: true,+ permission: 'edit'+ }+]diff --git a/src/components/home/cloud/types.ts b/src/components/home/cloud/types.tsnew file mode 100644index 000000000..6b73b9792--- /dev/null+++ b/src/components/home/cloud/types.ts@@ -0,0 +1,29 @@+/** A place the home tab lists documents from. */+export type HomeLocation =+ | { kind: 'recent'; id: 'recent' }+ | { kind: 'workspace'; id: string }+ | { kind: 'shared'; id: 'shared' }+ | { kind: 'storage'; id: 'storage' }++export type HomeCloudAccount = {+ id: string+ name: string+ email: string+ /** The Cloud server's host, such as `cloud.openpencil.dev`. */+ host: string+}++/** Where a Cloud document stands between this device and the server. */+export type CloudSyncState = 'synced' | 'uploading' | 'pending' | 'offline' | 'conflict' | 'error'++export type CloudDocumentRow = {+ id: string+ name: string+ previewURL?: string | null+ editedAt: string+ editedBy?: string+ sync: CloudSyncState+ /** Shared beyond the workspace, with people or a link. */+ shared?: boolean+ permission: 'edit' | 'view'+}diff --git a/src/components/home/document/DocumentEntry.vue b/src/components/home/document/DocumentEntry.vueindex e02992cf3..3870d235b 100644--- a/src/components/home/document/DocumentEntry.vue+++ b/src/components/home/document/DocumentEntry.vue@@ -37,7 +37,12 @@ const styles = computed(() => documentEntry({ view }))</span><icon-lucide-file-image v-else :class="styles.icon()" /><span data-slot="body" :class="styles.body()">- <span data-slot="name" :class="styles.name()">{{ name }}</span>+ <span data-slot="title" :class="styles.title()">+ <span data-slot="name" :class="styles.name()">{{ name }}</span>+ <span v-if="$slots.status" data-slot="status" :class="styles.status()">+ <slot name="status" />+ </span>+ </span><span data-slot="metadata" :class="styles.metadata()">{{ metadata }}</span></span><span v-if="view === 'list'" :class="styles.trailingMetadata()">{{ metadata }}</span>diff --git a/src/components/home/search/HomeSearchActions.vue b/src/components/home/search/HomeSearchActions.vueindex 877e0ecd0..2d5ceeee3 100644--- a/src/components/home/search/HomeSearchActions.vue+++ b/src/components/home/search/HomeSearchActions.vue@@ -11,6 +11,8 @@ import AppInput from '@/components/ui/input/AppInput.vue'import HomeJoinRoom from './HomeJoinRoom.vue'+/** The place a new design is created in, when it is not a local file. */+const { destination = null } = defineProps<{ destination?: string | null }>()const emit = defineEmits<{ 'new-document': [] }>()const query = defineModel<string>({ required: true })const { menu, files } = useI18n()@@ -76,7 +78,9 @@ watch(@click="emit('new-document')"><template #leading><icon-lucide-plus class="size-3.5" /></template>- {{ files.newDesign }}+ <span class="max-w-56 truncate">{{+ destination ? files.newDesignIn({ place: destination }) : files.newDesign+ }}</span></AppButton></div></div>diff --git a/src/components/home/sidebar/HomeLocationMenu.vue b/src/components/home/sidebar/HomeLocationMenu.vuenew file mode 100644index 000000000..a9e53f884--- /dev/null+++ b/src/components/home/sidebar/HomeLocationMenu.vue@@ -0,0 +1,161 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed } from 'vue'++import { useCloudMessages } from '@open-pencil/vue'++import { menu } from '@/components/ui/menu/menu'+import { homeLocationMenu } from '@/theme/home/location-menu'++import type { HomeCloudAccount, HomeLocation } from '../cloud/types'++/**+ * The home tab's locations on a phone, where the sidebar does not fit: the current one as a+ * button, and the same places as the sidebar in a menu.+ */+const {+ active,+ account = null,+ workspaces = [],+ sharedCount = 0,+ storage = null+} = defineProps<{+ active: HomeLocation+ account?: HomeCloudAccount | null+ workspaces?: { id: string; name: string; documentCount?: number; attention?: boolean }[]+ sharedCount?: number+ storage?: { label: string; detail: string } | null+}>()++const emit = defineEmits<{+ select: [location: HomeLocation]+ connect: []+ newWorkspace: []+}>()++const ui = homeLocationMenu()+const menuUI = menu()+const t = useCloudMessages()+const current = computed(() => {+ if (active.kind === 'recent') return t.value.homeRecent+ if (active.kind === 'shared') return t.value.homeSharedWithYou+ if (active.kind === 'storage') return storage?.label ?? t.value.homeStorage+ return workspaces.find((workspace) => workspace.id === active.id)?.name ?? t.value.workspace+})+const isActive = (location: HomeLocation) =>+ active.kind === location.kind && active.id === location.id+</script>++<template>+ <DropdownMenuRoot>+ <DropdownMenuTrigger :class="ui.trigger()">+ <icon-lucide-clock v-if="active.kind === 'recent'" :class="ui.icon()" />+ <icon-lucide-users v-else-if="active.kind === 'shared'" :class="ui.icon()" />+ <icon-lucide-database v-else-if="active.kind === 'storage'" :class="ui.icon()" />+ <icon-lucide-layers v-else :class="ui.icon()" />+ <span :class="ui.label()">{{ current }}</span>+ <icon-lucide-chevrons-up-down :class="ui.chevron()" />+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent+ side="bottom"+ align="start"+ :side-offset="4"+ :class="[menuUI.content(), ui.content()]"+ >+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('select', { kind: 'recent', id: 'recent' })"+ >+ <icon-lucide-clock :class="menuUI.icon()" />+ <span :class="ui.itemLabel()">{{ t.homeRecent }}</span>+ <icon-lucide-check+ v-if="isActive({ kind: 'recent', id: 'recent' })"+ :class="ui.check()"+ />+ </DropdownMenuItem>++ <DropdownMenuSeparator :class="menuUI.separator()" />+ <DropdownMenuGroup>+ <DropdownMenuLabel :class="menuUI.label()">+ {{ account ? t.homeCloudOnHost({ host: account.host }) : t.productName }}+ </DropdownMenuLabel>+ <template v-if="account">+ <DropdownMenuItem+ v-for="workspace in workspaces"+ :key="workspace.id"+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('select', { kind: 'workspace', id: workspace.id })"+ >+ <icon-lucide-layers :class="menuUI.icon()" />+ <span :class="ui.itemLabel()">{{ workspace.name }}</span>+ <icon-lucide-check+ v-if="isActive({ kind: 'workspace', id: workspace.id })"+ :class="ui.check()"+ />+ <icon-lucide-git-compare-arrows+ v-else-if="workspace.attention"+ :class="ui.attention()"+ role="img"+ :aria-label="t.homeNeedsAttention"+ />+ <span v-else :class="ui.count()">{{ workspace.documentCount }}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('select', { kind: 'shared', id: 'shared' })"+ >+ <icon-lucide-users :class="menuUI.icon()" />+ <span :class="ui.itemLabel()">{{ t.homeSharedWithYou }}</span>+ <icon-lucide-check+ v-if="isActive({ kind: 'shared', id: 'shared' })"+ :class="ui.check()"+ />+ <span v-else-if="sharedCount" :class="ui.count()">{{ sharedCount }}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('newWorkspace')"+ >+ <icon-lucide-plus :class="menuUI.icon()" />+ <span :class="ui.itemLabel()">{{ t.homeNewWorkspace }}</span>+ </DropdownMenuItem>+ </template>+ <DropdownMenuItem+ v-else+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('connect')"+ >+ <icon-lucide-log-in :class="menuUI.icon()" />+ {{ t.homeSignIn }}+ </DropdownMenuItem>+ </DropdownMenuGroup>++ <template v-if="storage">+ <DropdownMenuSeparator :class="menuUI.separator()" />+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('select', { kind: 'storage', id: 'storage' })"+ >+ <icon-lucide-database :class="menuUI.icon()" />+ <span :class="ui.itemLabel()">{{ storage.label }}</span>+ <icon-lucide-check+ v-if="isActive({ kind: 'storage', id: 'storage' })"+ :class="ui.check()"+ />+ <span v-else :class="ui.count()">{{ storage.detail }}</span>+ </DropdownMenuItem>+ </template>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+</template>diff --git a/src/components/home/sidebar/HomeSidebar.vue b/src/components/home/sidebar/HomeSidebar.vuenew file mode 100644index 000000000..9079b3541--- /dev/null+++ b/src/components/home/sidebar/HomeSidebar.vue@@ -0,0 +1,190 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed } from 'vue'++import { useCloudMessages } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import { menu } from '@/components/ui/menu/menu'+import Tip from '@/components/ui/overlay/Tip.vue'+import { sideList } from '@/theme/list/side-list'++import type { HomeCloudAccount, HomeLocation } from '../cloud/types'++/**+ * Where the home tab can show documents from: recent files, each Cloud workspace of the signed-in+ * account, documents shared with that account, and the configured storage bucket.+ */+const {+ active,+ account = null,+ workspaces = [],+ sharedCount = 0,+ storage = null+} = defineProps<{+ active: HomeLocation+ account?: HomeCloudAccount | null+ workspaces?: { id: string; name: string; documentCount?: number; attention?: boolean }[]+ sharedCount?: number+ /** The configured storage bucket, or null when no storage is set up. */+ storage?: { label: string; detail: string } | null+}>()++const emit = defineEmits<{+ select: [location: HomeLocation]+ connect: []+ accountSettings: []+ storageSettings: []+ switchServer: []+ newWorkspace: []+ signOut: []+}>()++const ui = sideList()+const menuUI = menu()+const t = useCloudMessages()+const isActive = (location: HomeLocation) =>+ active.kind === location.kind && active.id === location.id+const workspaceLocations = computed(() =>+ workspaces.map((workspace) => ({+ ...workspace,+ location: { kind: 'workspace', id: workspace.id } satisfies HomeLocation+ }))+)+</script>++<template>+ <nav :class="ui.root()" :aria-label="t.homeLocations">+ <div :class="[ui.items(), 'pt-1']">+ <button+ type="button"+ :class="ui.item()"+ :data-active="isActive({ kind: 'recent', id: 'recent' })"+ @click="emit('select', { kind: 'recent', id: 'recent' })"+ >+ <icon-lucide-clock :class="ui.icon()" />+ <span :class="ui.label()">{{ t.homeRecent }}</span>+ </button>+ </div>++ <div :class="ui.group()">+ <div :class="ui.header()">+ <span :class="ui.title()">{{ t.productName }}</span>+ <div v-if="account" :class="ui.actions()">+ <IconButton :label="t.homeNewWorkspace" @click="emit('newWorkspace')">+ <icon-lucide-plus class="size-3.5" />+ </IconButton>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="t.homeAccount({ email: account.email })">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent+ side="bottom"+ align="end"+ :side-offset="4"+ :class="[menuUI.content(), 'w-56']"+ >+ <DropdownMenuLabel :class="menuUI.label()">+ {{ account.email }} · {{ account.host }}+ </DropdownMenuLabel>+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('accountSettings')"+ >+ <icon-lucide-settings-2 :class="menuUI.icon()" />+ {{ t.homeAccountSettings }}+ </DropdownMenuItem>+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('switchServer')"+ >+ <icon-lucide-server :class="menuUI.icon()" />+ {{ t.homeConnectAnotherServer }}+ </DropdownMenuItem>+ <DropdownMenuSeparator :class="menuUI.separator()" />+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('signOut')"+ >+ <icon-lucide-log-out :class="menuUI.icon()" />+ {{ t.signOut }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </div>+ </div>+ <div :class="ui.items()">+ <template v-if="account">+ <button+ v-for="workspace in workspaceLocations"+ :key="workspace.id"+ type="button"+ :class="ui.item()"+ :data-active="isActive(workspace.location)"+ @click="emit('select', workspace.location)"+ >+ <icon-lucide-layers :class="ui.icon()" />+ <span :class="ui.label()">{{ workspace.name }}</span>+ <span :class="ui.trailing()">+ <Tip v-if="workspace.attention" :label="t.homeAttentionTip">+ <icon-lucide-git-compare-arrows+ :class="ui.attention()"+ role="img"+ :aria-label="t.homeNeedsAttention"+ />+ </Tip>+ <template v-else>{{ workspace.documentCount }}</template>+ </span>+ </button>+ <button+ type="button"+ :class="ui.item()"+ :data-active="isActive({ kind: 'shared', id: 'shared' })"+ @click="emit('select', { kind: 'shared', id: 'shared' })"+ >+ <icon-lucide-users :class="ui.icon()" />+ <span :class="ui.label()">{{ t.homeSharedWithYou }}</span>+ <span v-if="sharedCount" :class="ui.trailing()">{{ sharedCount }}</span>+ </button>+ </template>+ <button v-else type="button" :class="ui.item()" @click="emit('connect')">+ <icon-lucide-log-in :class="ui.icon()" />+ <span :class="ui.label()">{{ t.homeSignIn }}</span>+ </button>+ </div>+ </div>++ <div v-if="storage" :class="ui.group()">+ <div :class="ui.header()">+ <span :class="ui.title()">{{ t.homeStorage }}</span>+ <IconButton :label="t.homeStorageSettings" @click="emit('storageSettings')">+ <icon-lucide-settings-2 class="size-3.5" />+ </IconButton>+ </div>+ <div :class="ui.items()">+ <button+ type="button"+ :class="ui.item()"+ :data-active="isActive({ kind: 'storage', id: 'storage' })"+ @click="emit('select', { kind: 'storage', id: 'storage' })"+ >+ <icon-lucide-database :class="ui.icon()" />+ <span :class="ui.label()">{{ storage.label }}</span>+ <span :class="ui.trailing()">{{ storage.detail }}</span>+ </button>+ </div>+ </div>+ </nav>+</template>diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex de8976741..53c79b39f 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -13,6 +13,7 @@ import {} from '@/app/settings/dialog'import { provideSettingsNavigation } from '@/app/settings/navigation/use'import ChatSettingsSection from '@/components/settings/chat/ChatSettingsSection.vue'+import CloudSettingsSection from '@/components/settings/cloud/CloudSettingsSection.vue'import DiagnosticsSettingsPanel from '@/components/settings/diagnostics/DiagnosticsSettingsPanel.vue'import GeneralSettingsPanel from '@/components/settings/general/GeneralSettingsPanel.vue'import SettingsPage from '@/components/settings/layout/SettingsPage.vue'@@ -54,7 +55,8 @@ const sections = computed({ value: 'mcp', label: settings.value.mcp },{ value: 'tools', label: settings.value.toolAccess },{ value: 'media', label: settings.value.media },- { value: 'storage', label: settings.value.storage }+ { value: 'storage', label: settings.value.storage },+ { value: 'cloud', label: settings.value.cloud }] satisfies { value: SettingsSection; label: string }[])function onSectionChange(section: string | number): void {@@ -140,9 +142,13 @@ function onOpenChange(open: boolean): void {{{ settings.media }}</AppTabsTrigger><AppTabsTrigger value="storage" data-test-id="settings-section-storage">- <template #leading><icon-lucide-cloud class="size-3.5" /></template>+ <template #leading><icon-lucide-database class="size-3.5" /></template>{{ settings.storage }}</AppTabsTrigger>+ <AppTabsTrigger value="cloud" data-test-id="settings-section-cloud">+ <template #leading><icon-lucide-cloud class="size-3.5" /></template>+ {{ settings.cloud }}+ </AppTabsTrigger></AppTabsList><AppTabsContent value="general" as-child>@@ -179,6 +185,9 @@ function onOpenChange(open: boolean): void {<AppTabsContent value="storage" as-child><StorageSettingsPanel /></AppTabsContent>+ <AppTabsContent value="cloud" as-child>+ <CloudSettingsSection />+ </AppTabsContent></AppTabsRoot><AppDialogFooter v-if="!editing">diff --git a/src/components/settings/cloud/CloudSettingsPanel.stories.ts b/src/components/settings/cloud/CloudSettingsPanel.stories.tsnew file mode 100644index 000000000..cc3c27e52--- /dev/null+++ b/src/components/settings/cloud/CloudSettingsPanel.stories.ts@@ -0,0 +1,74 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { fn } from 'storybook/test'++import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'++import CloudSettingsPanel from './CloudSettingsPanel.vue'+import type { CloudServerEntry } from './types'++type Args = {+ servers: CloudServerEntry[]+ listed: boolean+ confirmRemove: boolean+ onConnect: () => void+}++const official: CloudServerEntry = {+ id: 'official',+ host: 'cloud.openpencil.dev',+ kind: 'official',+ account: { id: 'user-ana', name: 'Ana Duarte', email: '[email protected]' },+ session: 'signed-in',+ onHome: true+}+const team: CloudServerEntry = {+ id: 'acme',+ host: 'design.acme.internal',+ kind: 'self-hosted',+ account: { id: 'user-ana-acme', name: 'Ana Duarte', email: '[email protected]' },+ session: 'signed-in',+ onHome: false+}++const meta = {+ title: 'App/Settings/Cloud',+ tags: ['autodocs'],+ parameters: { layout: 'fullscreen' },+ args: { servers: [official, team], listed: true, confirmRemove: false, onConnect: fn() },+ render: (args) => ({+ components: { CloudSettingsPanel, AppConfirmationDialog },+ setup: () => ({ args }),+ template: `+ <div class="flex h-[560px] bg-panel p-6">+ <div class="flex w-full max-w-2xl flex-col">+ <CloudSettingsPanel :servers="args.servers" :listed="args.listed" @connect="args.onConnect">+ <template #hosted>+ <div class="rounded border border-dashed border-border p-3 text-[11px] text-muted">+ The OpenPencil Cloud waitlist+ </div>+ </template>+ </CloudSettingsPanel>+ </div>+ <AppConfirmationDialog+ :open="args.confirmRemove"+ tone="danger"+ heading="Disconnect design.acme.internal?"+ description="You’re signed out and its workspaces leave Home on this device. 2 documents have changes that haven’t reached the server yet; disconnecting discards them."+ cancel-label="Cancel"+ confirm-label="Disconnect and discard changes"+ />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const TwoServers: Story = {}+export const SignInExpired: Story = {+ args: { servers: [official, { ...team, session: 'expired' }] }+}+export const NoServers: Story = { args: { servers: [] } }+/** Before the hosted service opens, its waitlist takes the place of connecting to it. */+export const BeforeLaunch: Story = { args: { servers: [], listed: false } }+export const RemoveWithUnsavedChanges: Story = { args: { confirmRemove: true } }diff --git a/src/components/settings/cloud/CloudSettingsPanel.vue b/src/components/settings/cloud/CloudSettingsPanel.vuenew file mode 100644index 000000000..3a6d1a72c--- /dev/null+++ b/src/components/settings/cloud/CloudSettingsPanel.vue@@ -0,0 +1,189 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'++import { useCloudMessages } from '@open-pencil/vue'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsPage from '@/components/settings/layout/SettingsPage.vue'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppActionRow from '@/components/ui/list/AppActionRow.vue'+import { menu } from '@/components/ui/menu/menu'+import { cloudServers } from '@/theme/cloud/servers'++import type { CloudServerEntry } from './types'++/**+ * The Cloud servers this app syncs with: who is signed in to each, which one Home shows, and+ * what can be done with it. Account settings live on the server's own pages, opened in a browser.+ */+const { servers, listed = true } = defineProps<{+ servers: CloudServerEntry[]+ /** Whether the hosted service takes sign-ins yet; until then the `hosted` slot stands in. */+ listed?: boolean+}>()+const emit = defineEmits<{+ connect: [kind?: 'official' | 'self-hosted']+ signIn: [id: string]+ manageAccount: [id: string]+ showOnHome: [id: string]+ signOut: [id: string]+ remove: [id: string]+}>()++const ui = cloudServers()+/** Signed in, even to an account still waiting for approval or declined. */+const hasSession = (server: CloudServerEntry) =>+ server.session === 'signed-in' || server.session === 'pending' || server.session === 'closed'+const menuUI = menu()+const t = useCloudMessages()+const title = (server: CloudServerEntry) =>+ server.kind === 'official' ? t.value.productName : server.host+</script>++<template>+ <SettingsPage>+ <SettingsSection>+ <template #title>{{ t.settingsTitle }}</template>+ <template #description>+ {{ servers.length ? t.settingsDescription : t.settingsEmptyDescription }}+ </template>+ <template v-if="servers.length" #actions>+ <AppButton+ size="sm"+ variant="outline"+ @click="emit('connect', listed ? undefined : 'self-hosted')"+ >+ <template #leading><icon-lucide-plus class="size-3.5" /></template>+ {{ t.settingsConnectServer }}+ </AppButton>+ </template>++ <div v-if="!servers.length" :class="ui.choices()">+ <slot v-if="!listed" name="hosted" />+ <AppActionRow v-else @click="emit('connect', 'official')">+ <template #leading>+ <span :class="ui.choiceIcon()"><icon-lucide-cloud class="size-4" /></span>+ </template>+ {{ t.productName }}+ <template #description>{{ t.settingsOfficialDescription }}</template>+ <template #trailing><icon-lucide-chevron-right class="size-3.5" /></template>+ </AppActionRow>+ <AppActionRow @click="emit('connect', 'self-hosted')">+ <template #leading>+ <span :class="ui.choiceIcon()"><icon-lucide-server class="size-4" /></span>+ </template>+ {{ t.selfHostedLabel }}+ <template #description>{{ t.settingsSelfHostedDescription }}</template>+ <template #trailing><icon-lucide-chevron-right class="size-3.5" /></template>+ </AppActionRow>+ </div>++ <SettingsGroup v-else>+ <div v-for="server in servers" :key="server.id" :class="ui.row()">+ <span :class="ui.icon()">+ <icon-lucide-cloud v-if="server.kind === 'official'" class="size-4" />+ <icon-lucide-server v-else class="size-4" />+ </span>+ <div :class="ui.body()">+ <div :class="ui.titleRow()">+ <span :class="ui.title()">{{ title(server) }}</span>+ <span v-if="server.kind === 'official'" :class="ui.host()">{{ server.host }}</span>+ <span v-if="server.onHome" :class="ui.badge()">{{ t.settingsOnHome }}</span>+ </div>+ <p v-if="server.session === 'expired'" :class="ui.expired()">+ <icon-lucide-circle-alert class="size-3 shrink-0" />+ {{+ server.account+ ? t.settingsSignInExpiredFor({ email: server.account.email })+ : t.settingsSignInExpired+ }}+ </p>+ <p v-else-if="server.session === 'pending'" :class="ui.expired()">+ <icon-lucide-clock class="size-3 shrink-0" />+ {{ t.settingsWaitingForApproval }}+ </p>+ <p v-else-if="server.session === 'closed'" :class="ui.expired()">+ <icon-lucide-circle-x class="size-3 shrink-0" />+ {{ t.settingsAccessClosed }}+ </p>+ <p v-else-if="server.account && server.session === 'signed-in'" :class="ui.account()">+ <AccountAvatar :id="server.account.id" :name="server.account.name" />+ <span :class="ui.accountText()">+ {{ server.account.name }} · {{ server.account.email }}+ </span>+ </p>+ <p v-else :class="ui.account()">{{ t.settingsSignedOut }}</p>+ </div>+ <div :class="ui.trailing()">+ <AppButton+ v-if="server.session === 'expired' || server.session === 'signed-out'"+ size="sm"+ variant="outline"+ @click="emit('signIn', server.id)"+ >+ {{ t.signIn }}+ </AppButton>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton :label="t.settingsOptionsFor({ host: server.host })">+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent+ side="bottom"+ align="end"+ :side-offset="4"+ :class="[menuUI.content(), 'w-56']"+ >+ <DropdownMenuItem+ v-if="server.session === 'signed-in'"+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('manageAccount', server.id)"+ >+ <icon-lucide-external-link :class="menuUI.icon()" />+ {{ t.settingsAccountAndSecurity }}+ </DropdownMenuItem>+ <DropdownMenuItem+ v-if="!server.onHome"+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('showOnHome', server.id)"+ >+ <icon-lucide-house :class="menuUI.icon()" />+ {{ t.settingsShowOnHome }}+ </DropdownMenuItem>+ <DropdownMenuItem+ v-if="hasSession(server)"+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('signOut', server.id)"+ >+ <icon-lucide-log-out :class="menuUI.icon()" />+ {{ t.signOut }}+ </DropdownMenuItem>+ <DropdownMenuSeparator :class="menuUI.separator()" />+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="emit('remove', server.id)"+ >+ <icon-lucide-unplug :class="menuUI.icon()" />+ {{ t.settingsDisconnectServer }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </div>+ </div>+ </SettingsGroup>+ </SettingsSection>+ </SettingsPage>+</template>diff --git a/src/components/settings/cloud/CloudSettingsSection.vue b/src/components/settings/cloud/CloudSettingsSection.vuenew file mode 100644index 000000000..533162a40--- /dev/null+++ b/src/components/settings/cloud/CloudSettingsSection.vue@@ -0,0 +1,121 @@+<script setup lang="ts">+import { computed, ref } from 'vue'++import { useCloudMessages, useCommonMessages } from '@open-pencil/vue'++import { cloudOfficialListed } from '@/app/cloud/availability'+import { openCloudConnect } from '@/app/cloud/connect/flow'+import { unsentCloudDocumentCount } from '@/app/cloud/documents/status'+import { cloudServerHost } from '@/app/cloud/servers/address'+import {+ cloudServers,+ findCloudServer,+ homeCloudServer,+ removeCloudServer,+ showCloudServerOnHome+} from '@/app/cloud/servers/store'+import { cloudConnection, forgetCloudConnection } from '@/app/cloud/sessions/connection'+import { signOutOfCloud } from '@/app/cloud/sessions/sign-out'+import { clearCloudSessionToken } from '@/app/cloud/sessions/token'+import { openExternalLink, toast } from '@/app/shell/ui'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'++import CloudSettingsPanel from './CloudSettingsPanel.vue'+import CloudWaitlist from './CloudWaitlist.vue'+import type { CloudServerEntry } from './types'++/** The Cloud section of Settings: the saved servers with their live sessions, and their actions. */+const t = useCloudMessages()+const common = useCommonMessages()+const entries = computed<CloudServerEntry[]>(() =>+ cloudServers.value.map((server) => {+ const connection = cloudConnection(server.id)+ const account = connection.account ?? server.account+ let session: CloudServerEntry['session'] = account ? 'signed-in' : 'signed-out'+ if (+ connection.state === 'pending' ||+ connection.state === 'closed' ||+ connection.state === 'expired' ||+ connection.state === 'signed-out'+ ) {+ session = connection.state+ }+ return {+ id: server.id,+ host: cloudServerHost(server.url),+ kind: server.kind,+ account,+ session,+ onHome: homeCloudServer.value?.id === server.id+ }+ })+)++/** The server being removed, and how many documents would lose changes the server hasn't got. */+const removing = ref<{ entry: CloudServerEntry; unsaved: number } | null>(null)++async function askToRemove(id: string) {+ const entry = entries.value.find((candidate) => candidate.id === id)+ if (!entry) return+ const unsaved = await unsentCloudDocumentCount(id).catch(() => 0)+ removing.value = { entry, unsaved }+}++function manageAccount(id: string) {+ const server = findCloudServer(id)+ if (server) void openExternalLink(new URL('/account', server.url).href)+}++async function signOut(id: string) {+ const discovery = cloudConnection(id).discovery+ if (!discovery) return+ try {+ await signOutOfCloud(id, discovery)+ } catch {+ toast.error(t.value.settingsSignOutFailed)+ }+}++async function remove() {+ const entry = removing.value?.entry+ removing.value = null+ if (!entry) return+ const discovery = cloudConnection(entry.id).discovery+ // End the session on the server when it answers; the app forgets the server either way.+ if (discovery && entry.session === 'signed-in') await signOut(entry.id)+ await clearCloudSessionToken(entry.id).catch(() => undefined)+ forgetCloudConnection(entry.id)+ removeCloudServer(entry.id)+}+</script>++<template>+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">+ <CloudSettingsPanel+ :servers="entries"+ :listed="cloudOfficialListed"+ @connect="(kind) => openCloudConnect({ kind })"+ @sign-in="(id) => openCloudConnect({ serverId: id })"+ @manage-account="manageAccount"+ @show-on-home="showCloudServerOnHome"+ @sign-out="signOut"+ @remove="askToRemove"+ >+ <template #hosted><CloudWaitlist /></template>+ </CloudSettingsPanel>+ <AppConfirmationDialog+ :open="removing !== null"+ tone="danger"+ :heading="t.settingsDisconnectHeading({ host: removing?.entry.host ?? '' })"+ :description="+ removing?.unsaved+ ? t.settingsDisconnectUnsavedDescription(removing.unsaved)+ : t.settingsDisconnectDescription+ "+ :cancel-label="common.cancel"+ :confirm-label="removing?.unsaved ? t.settingsDisconnectAndDiscard : t.settingsDisconnect"+ @update:open="(open) => !open && (removing = null)"+ @confirm="remove"+ />+ </div>+</template>diff --git a/src/components/settings/storage/CloudWaitlistSection.vue b/src/components/settings/cloud/CloudWaitlist.vuesimilarity index 78%rename from src/components/settings/storage/CloudWaitlistSection.vuerename to src/components/settings/cloud/CloudWaitlist.vueindex 9a7998313..883e48530 100644--- a/src/components/settings/storage/CloudWaitlistSection.vue+++ b/src/components/settings/cloud/CloudWaitlist.vue@@ -5,18 +5,20 @@ import { useStorageMessages } from '@open-pencil/vue'import { useWaitlistSignup } from '@/app/cloud/waitlist/signup'import { openExternalLink } from '@/app/shell/ui'-import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppInput from '@/components/ui/input/AppInput.vue'import { CLOUD_WAITLIST_URL, IS_TAURI } from '@/constants'+import { cloudServers } from '@/theme/cloud/servers'/**- * OpenPencil Cloud, offered where people set up storage by hand. The web app signs up here; the- * desktop app opens the website, since Turnstile runs only on the sites the service accepts.+ * The hosted OpenPencil Cloud before it opens: its waitlist, in place of connecting to it. The web+ * app signs up here; the desktop app opens the website, since Turnstile runs only on the sites+ * the service accepts.*/const storage = useStorageMessages()+const ui = cloudServers()const turnstile = useTemplateRef<HTMLElement>('turnstile')const { email, status, submitting, confirming, edit, submit } = useWaitlistSignup(turnstile)@@ -30,9 +32,18 @@ const failure = computed(() => {</script><template>- <SettingsSection data-test-id="settings-cloud-waitlist">- <template #title>{{ storage.cloudTitle }}</template>- <template #description>{{ storage.cloudDescription }}</template>+ <section+ :class="ui.waitlist()"+ data-test-id="settings-cloud-waitlist"+ :aria-label="storage.cloudTitle"+ >+ <div :class="ui.waitlistHeader()">+ <span :class="ui.icon()"><icon-lucide-cloud class="size-4" /></span>+ <div :class="ui.body()">+ <p :class="ui.title()">{{ storage.cloudTitle }}</p>+ <p :class="ui.waitlistDescription()">{{ storage.cloudDescription }}</p>+ </div>+ </div><AppButtonv-if="IS_TAURI"class="self-start"@@ -49,7 +60,7 @@ const failure = computed(() => {:description="storage.waitlistJoinedDetail"/><template v-else>- <!-- The Storage panel is a form of its own, so this is a group that submits on Enter. -->+ <!-- A group that submits on Enter, like the form it would be outside Settings. --><div class="flex flex-col gap-2" role="group" :aria-label="storage.cloudTitle"><ProviderSettingsFieldv-slot="{ control }"@@ -89,5 +100,5 @@ const failure = computed(() => {</template></AppAlert></template>- </SettingsSection>+ </section></template>diff --git a/src/components/settings/cloud/types.ts b/src/components/settings/cloud/types.tsnew file mode 100644index 000000000..a73c0c232--- /dev/null+++ b/src/components/settings/cloud/types.ts@@ -0,0 +1,11 @@+/** A Cloud server this app has connected to, and how its account stands on this device. */+export type CloudServerEntry = {+ id: string+ host: string+ kind: 'official' | 'self-hosted'+ account: { id: string; name: string; email: string } | null+ /** `expired` keeps the account so the person can sign back in to the same one. */+ session: 'signed-in' | 'pending' | 'closed' | 'expired' | 'signed-out'+ /** The server whose workspaces Home shows. */+ onHome: boolean+}diff --git a/src/components/settings/storage/StorageSettingsPanel.vue b/src/components/settings/storage/StorageSettingsPanel.vueindex 4797057e9..27eb10462 100644--- a/src/components/settings/storage/StorageSettingsPanel.vue+++ b/src/components/settings/storage/StorageSettingsPanel.vue@@ -9,6 +9,7 @@ import {useStorageMessages} from '@open-pencil/vue'+import { homeLocation } from '@/app/home/location'import { useNotificationMessages } from '@/app/i18n/notifications'import { useStorageSettingsFeedback } from '@/app/integrations/storage/settings/feedback'import { useStorageSettings } from '@/app/integrations/storage/settings/use'@@ -19,7 +20,6 @@ import SettingsPage from '@/components/settings/layout/SettingsPage.vue'import SettingsSaveFeedback from '@/components/settings/layout/SettingsSaveFeedback.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'-import CloudWaitlistSection from '@/components/settings/storage/CloudWaitlistSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppInput from '@/components/ui/input/AppInput.vue'@@ -83,6 +83,7 @@ async function save() {}async function openWorkspace() {settingsDialogOpen.value = false+ homeLocation.value = { kind: 'storage' }await router.push('/storage')}async function testConnection() {@@ -132,7 +133,6 @@ async function testConnection() {{{ settings.configureStorageHint }}</p></SettingsSection>- <CloudWaitlistSection /></div><SettingsSection v-else><template #title>{{ settings.storage }}</template>diff --git a/src/components/shell/AppMenu.vue b/src/components/shell/AppMenu.vueindex 5cce99b84..1201ffe96 100644--- a/src/components/shell/AppMenu.vue+++ b/src/components/shell/AppMenu.vue@@ -38,6 +38,7 @@ import {import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'import { resolvedAppTheme } from '@/app/shell/theme'import BrandMark from '@/components/brand/BrandMark.vue'+import CloudDocumentStatusHost from '@/components/cloud/status/CloudDocumentStatusHost.vue'import { useScrollOverflow } from '@/components/shell/useScrollOverflow'import IconButton from '@/components/ui/button/IconButton.vue'import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'@@ -91,6 +92,7 @@ const { overflowStart, overflowEnd, scrollTowardHidden } = useScrollOverflow(men@dblclick="startRename">{{ store.state.documentName }}</span>+ <CloudDocumentStatusHost /><IconButton:label="settings.title"data-test-id="app-settings-trigger"diff --git a/src/components/ui/dialog/AppConfirmationDialog.vue b/src/components/ui/dialog/AppConfirmationDialog.vueindex a431826d5..a1680e635 100644--- a/src/components/ui/dialog/AppConfirmationDialog.vue+++ b/src/components/ui/dialog/AppConfirmationDialog.vue@@ -1,10 +1,5 @@<script setup lang="ts">-import {- AlertDialogAction,- AlertDialogCancel,- AlertDialogDescription,- AlertDialogTitle-} from 'reka-ui'+import { AlertDialogCancel, AlertDialogDescription, AlertDialogTitle } from 'reka-ui'import { computed } from 'vue'import AppButton from '@/components/ui/button/AppButton.vue'@@ -33,6 +28,14 @@ const {const emit = defineEmits<{ confirm: []; cancel: [] }>()const open = defineModel<boolean>('open', { default: false })+/**+ * Confirms, then closes. Reka's action closes first, so a caller that forgets its pending action+ * when the dialog closes would lose it before the confirmation arrived.+ */+function confirm() {+ emit('confirm')+ open.value = false+}const confirmColor = computed(() => {if (tone === 'danger') return 'error'if (tone === 'neutral') return 'neutral'@@ -45,8 +48,12 @@ const confirmColor = computed(() => {<div class="border-b border-border px-4 py-3"><AlertDialogTitle class="text-sm font-semibold text-surface">{{ heading }}</AlertDialogTitle></div>- <AppDialogBody v-if="description">- <AlertDialogDescription class="text-xs text-muted">{{ description }}</AlertDialogDescription>+ <AppDialogBody v-if="description || $slots.default">+ <AlertDialogDescription v-if="description" class="text-xs text-muted">{{+ description+ }}</AlertDialogDescription>+ <!-- What the person must do before confirming, such as typing a name. -->+ <slot /></AppDialogBody><AppDialogFooter><AlertDialogCancel as-child>@@ -54,16 +61,14 @@ const confirmColor = computed(() => {cancelLabel}}</AppButton></AlertDialogCancel>- <AlertDialogAction as-child>- <AppButton- :color="confirmColor"- variant="solid"- :disabled="confirmDisabled"- :loading="confirmLoading"- @click="emit('confirm')"- >{{ confirmLabel }}</AppButton- >- </AlertDialogAction>+ <AppButton+ :color="confirmColor"+ variant="solid"+ :disabled="confirmDisabled"+ :loading="confirmLoading"+ @click="confirm"+ >{{ confirmLabel }}</AppButton+ ></AppDialogFooter></AppAlertDialogRoot></template>diff --git a/src/components/ui/input/AppPasswordInput.vue b/src/components/ui/input/AppPasswordInput.vuenew file mode 100644index 000000000..d253a2ea1--- /dev/null+++ b/src/components/ui/input/AppPasswordInput.vue@@ -0,0 +1,44 @@+<script setup lang="ts">+import { ref } from 'vue'++import { useCommonMessages } from '@open-pencil/vue'++import type { ControlSize } from '@/theme/control'++import AppInput from './AppInput.vue'++/** A password field whose contents the person can show while typing, to check what they typed. */+defineOptions({ inheritAttrs: false })++const { id, size = 'md' } = defineProps<{+ id?: string+ size?: ControlSize+}>()++const value = defineModel<string>({ required: true })+const shown = ref(false)+const common = useCommonMessages()+</script>++<template>+ <AppInput+ :id="id"+ v-model="value"+ v-bind="$attrs"+ :type="shown ? 'text' : 'password'"+ :size="size"+ >+ <template #trailing>+ <button+ type="button"+ class="flex size-6 cursor-pointer items-center justify-center rounded text-muted hover:bg-hover hover:text-surface"+ :aria-label="shown ? common.hidePassword : common.showPassword"+ :aria-pressed="shown"+ @click="shown = !shown"+ >+ <icon-lucide-eye-off v-if="shown" class="size-3.5" />+ <icon-lucide-eye v-else class="size-3.5" />+ </button>+ </template>+ </AppInput>+</template>diff --git a/src/constants.ts b/src/constants.tsindex 46ba0e45a..8f7ea77ab 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -84,6 +84,8 @@ export const WEB_APP_ORIGIN = 'https://app.openpencil.dev'export const PRIVACY_URL = 'https://openpencil.dev/overview/privacy'/** The OpenPencil Cloud section of the website, with its waitlist form. */export const CLOUD_WAITLIST_URL = 'https://openpencil.dev/#cloud'+/** The hosted OpenPencil Cloud server, offered first when connecting. */+export const OFFICIAL_CLOUD_URL = 'https://cloud.openpencil.dev'/** Where the desktop app's installers are published. */export const DESKTOP_DOWNLOAD_URL = 'https://github.com/open-pencil/open-pencil/releases/latest'export const NODE_DOWNLOAD_URL = 'https://nodejs.org/en/download'@@ -94,6 +96,8 @@ export const NODE_DOWNLOAD_URL = 'https://nodejs.org/en/download'*/const DOCS_ORIGIN = 'https://openpencil.dev'export const MCP_SERVER_DOCS_URL = `${DOCS_ORIGIN}/programmable/mcp-server`+/** The guide to OpenPencil Cloud, linked from the Cloud server's own pages. */+export const CLOUD_DOCS_URL = `${DOCS_ORIGIN}/user-guide/openpencil-cloud`export const WEBMCP_DOCS_URL = `${MCP_SERVER_DOCS_URL}#webmcp`export const MCP_CONNECTIONS_DOCS_URL = `${DOCS_ORIGIN}/programmable/ai-chat#external-mcp-connections`export const CODING_AGENTS_GUIDE_URL = `${DOCS_ORIGIN}/programmable/coding-agents`diff --git a/src/router.ts b/src/router.tsindex eeed39002..feefe326d 100644--- a/src/router.ts+++ b/src/router.ts@@ -1,14 +1,26 @@import { createRouter, createWebHistory } from 'vue-router'+import { homeLocation } from '@/app/home/location'+import WorkspaceView from './views/WorkspaceView.vue'const router = createRouter({history: createWebHistory(),routes: [{ path: '/', component: WorkspaceView },- { path: '/storage', redirect: '/' },+ {+ // Links to the storage workspace open Home on it.+ path: '/storage',+ redirect: (to) => {+ homeLocation.value = { kind: 'storage' }+ return { path: '/', query: to.query }+ }+ },{ path: '/demo', component: WorkspaceView, meta: { demo: true } },- { path: '/share/:roomId', component: WorkspaceView }+ { 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 }]})diff --git a/src/theme/button/icon-button.ts b/src/theme/button/icon-button.tsindex 4be0ee664..61d08641c 100644--- a/src/theme/button/icon-button.ts+++ b/src/theme/button/icon-button.ts@@ -4,7 +4,8 @@ export default {size: {xs: 'size-6 rounded border border-transparent text-sm leading-none',sm: 'size-7 rounded-md border border-transparent text-sm leading-none',- md: 'size-8 rounded-md border border-transparent text-base leading-none'+ md: 'size-8 rounded-md border border-transparent text-base leading-none',+ lg: 'size-9 rounded-md border border-transparent text-base leading-none'},active: {true: 'border-accent text-primary'diff --git a/src/theme/cloud-portal/form.ts b/src/theme/cloud-portal/form.tsindex a84c711ec..e8ef0776e 100644--- a/src/theme/cloud-portal/form.ts+++ b/src/theme/cloud-portal/form.ts@@ -1,16 +1,39 @@import { tv } from 'tailwind-variants'+/** Cloud's sign-in fields: compact in the editor's dialogs, larger on the server's own pages. */export const portalForm = tv({slots: {form: 'flex flex-col gap-3',field: 'flex flex-col gap-1.5',labelRow: 'flex items-center justify-between',- label: 'text-[11px] font-medium text-muted',- hint: 'text-[11px] text-muted',+ label: 'font-medium',+ hint: 'text-muted',+ error: 'text-error',methods: 'flex flex-col gap-1.5',- divider: 'flex items-center gap-3 text-[11px] text-muted',+ divider: 'flex items-center gap-3 text-muted',dividerLine: 'h-px flex-1 bg-border',submit: 'w-full justify-center',+ inlineLink: '',code: 'w-full text-center font-mono text-base tracking-[0.4em]'- }+ },+ variants: {+ size: {+ md: {+ label: 'text-[11px] text-muted',+ hint: 'text-[11px]',+ error: 'text-[11px]',+ divider: 'text-[11px]'+ },+ lg: {+ form: 'gap-4',+ label: 'text-sm text-surface',+ hint: 'text-xs',+ error: 'text-xs',+ methods: 'gap-2',+ divider: 'text-xs',+ inlineLink: 'h-auto px-0'+ }+ }+ },+ defaultVariants: { size: 'md' }})diff --git a/src/theme/cloud-portal/layout.ts b/src/theme/cloud-portal/layout.tsindex 202296e47..32702fd7c 100644--- a/src/theme/cloud-portal/layout.ts+++ b/src/theme/cloud-portal/layout.ts@@ -1,6 +1,6 @@import { tv } from 'tailwind-variants'-/** Cloud's own pages outside the editor: a centered card for sign-in, a sidebar for the console. */+/** The Cloud console: a bar with the server and account, sections in a sidebar. */export const portalLayout = tv({slots: {page: 'flex h-full min-h-0 flex-col overflow-hidden bg-canvas text-surface',@@ -8,12 +8,6 @@ export const portalLayout = tv({barTitle: 'text-xs font-semibold whitespace-nowrap',barHost: 'truncate text-[11px] text-muted max-sm:hidden',barEnd: 'ml-auto flex items-center gap-2',- center: 'flex flex-1 items-start justify-center overflow-y-auto px-4 py-12 sm:items-center',- card: 'flex w-full max-w-sm flex-col gap-5 rounded-xl border border-border bg-panel p-6 shadow-[0_8px_30px_rgb(0_0_0/0.18)]',- cardHeader: 'flex flex-col gap-1',- cardTitle: 'text-sm font-semibold text-surface',- cardDescription: 'text-xs leading-relaxed text-muted',- cardFooter: 'border-t border-border pt-4 text-center text-[11px] text-muted',console: 'flex min-h-0 flex-1 max-md:flex-col',// Narrow screens turn the section list into one scrolling row above the page.nav: 'max-md:h-auto max-md:w-full max-md:flex-row max-md:overflow-x-auto max-md:border-r-0 max-md:border-b max-md:pb-0',diff --git a/src/theme/cloud-portal/public.ts b/src/theme/cloud-portal/public.tsnew file mode 100644index 000000000..30dd44853--- /dev/null+++ b/src/theme/cloud-portal/public.ts@@ -0,0 +1,33 @@+import { tv } from 'tailwind-variants'++/**+ * Cloud's pages for signing in and answering requests, laid out as the app's startup notice: one+ * narrow column a little above the middle, under the app icon, with a quiet footer.+ */+export const portalPublic = tv({+ slots: {+ page: 'flex h-full min-h-0 flex-col overflow-y-auto bg-canvas text-surface',+ main: 'flex flex-1 flex-col items-center justify-center px-4 pt-12 pb-[12vh]',+ column: 'flex w-full max-w-[360px] flex-col gap-6',+ header: 'flex flex-col items-center gap-4 text-center',+ icon: 'size-12 rounded-xl',+ headingGroup: 'flex flex-col gap-1.5',+ title: 'text-xl font-semibold text-balance',+ description: 'text-sm text-pretty text-muted',+ body: 'flex flex-col gap-4',+ aside: 'flex flex-wrap items-center justify-center gap-1 text-sm text-muted',+ footer:+ 'flex flex-wrap items-center justify-center gap-x-4 gap-y-1 px-4 pb-6 text-xs text-muted',+ footerLink: 'hover:text-surface hover:underline',+ tile: 'flex size-12 items-center justify-center rounded-xl bg-panel-field text-muted',+ actions: 'flex flex-col gap-2'+ },+ variants: {+ tone: {+ neutral: {},+ success: { tile: 'bg-success/10 text-success' },+ waiting: {}+ }+ },+ defaultVariants: { tone: 'neutral' }+})diff --git a/src/theme/cloud/conflict.ts b/src/theme/cloud/conflict.tsnew file mode 100644index 000000000..5ed555f29--- /dev/null+++ b/src/theme/cloud/conflict.ts@@ -0,0 +1,21 @@+import { tv } from 'tailwind-variants'++export const cloudConflict = tv({+ slots: {+ versions: 'grid grid-cols-2 gap-3',+ version: 'm-0 min-w-0',+ preview:+ 'flex aspect-video items-center justify-center overflow-hidden rounded-lg border border-border bg-panel-field',+ image: 'size-full object-cover',+ caption: 'mt-2 flex flex-col',+ versionLabel: 'text-xs font-medium text-surface',+ versionMeta: 'truncate text-[11px] text-muted',+ options: 'mt-4 flex flex-col gap-1.5',+ option:+ 'group flex w-full items-start gap-2.5 rounded-lg border border-border px-3 py-2.5 text-left outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent/50 data-[state=checked]:border-panel-focus data-[state=checked]:bg-panel-selected-muted data-[tone=danger]:data-[state=checked]:border-error-border data-[tone=danger]:data-[state=checked]:bg-error-bg',+ optionMark:+ 'mt-0.5 size-3.5 shrink-0 rounded-full border border-muted/60 group-data-[state=checked]:border-4 group-data-[state=checked]:border-accent group-data-[tone=danger]:group-data-[state=checked]:border-error',+ optionLabel: 'block text-xs font-medium text-surface',+ optionDescription: 'mt-0.5 block text-[11px] leading-relaxed text-muted'+ }+})diff --git a/src/theme/cloud/connect.ts b/src/theme/cloud/connect.tsnew file mode 100644index 000000000..fd93af453--- /dev/null+++ b/src/theme/cloud/connect.ts@@ -0,0 +1,33 @@+import { tv } from 'tailwind-variants'++export const cloudConnect = tv({+ slots: {+ choices: 'flex flex-col gap-2',+ choice:+ 'group flex w-full items-center gap-3 rounded-lg border border-border bg-panel-field px-3 py-2.5 text-left outline-none hover:bg-panel-field-hover focus-visible:ring-2 focus-visible:ring-accent/50 data-[state=checked]:border-panel-focus data-[state=checked]:bg-panel-selected-muted',+ choiceIcon:+ 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel text-muted group-data-[state=checked]:text-primary',+ choiceBody: 'min-w-0 flex-1',+ choiceLabel: 'block text-xs font-medium text-surface',+ choiceDescription: 'mt-0.5 block truncate text-[11px] text-muted',+ choiceMark:+ 'size-3.5 shrink-0 rounded-full border border-border group-data-[state=checked]:border-4 group-data-[state=checked]:border-accent',+ address: 'mt-3 flex flex-col gap-1.5',+ addressAlone: 'flex flex-col gap-1.5',+ addressLabel: 'text-[11px] font-medium text-muted',+ stack: 'flex flex-col gap-3',+ methods: 'flex flex-col gap-1.5',+ divider: 'flex items-center gap-3 text-[11px] text-muted',+ dividerLine: 'h-px flex-1 bg-border',+ note: 'text-[11px] text-muted',+ switch: 'flex items-center justify-center gap-1 text-[11px] text-muted',+ verify: 'flex items-start gap-3',+ verifyIcon:+ 'flex size-10 shrink-0 items-center justify-center rounded-full bg-panel-field text-muted',+ verifyText: 'pt-1 text-xs leading-relaxed text-muted',+ device: 'flex flex-col items-center gap-3 py-2',+ deviceLabel: 'text-[11px] font-medium text-muted',+ deviceStatus: 'flex items-center gap-2 text-[11px] text-muted',+ spinner: 'size-3.5 shrink-0 animate-spin motion-reduce:animate-none'+ }+})diff --git a/src/theme/cloud/invitation.ts b/src/theme/cloud/invitation.tsnew file mode 100644index 000000000..6b1fd047d--- /dev/null+++ b/src/theme/cloud/invitation.ts@@ -0,0 +1,20 @@+import { tv } from 'tailwind-variants'++/** The document an invitation opens, shown before anyone signs in or accepts. */+export const cloudInvitation = tv({+ slots: {+ document: 'flex items-center gap-3 rounded-lg border border-border bg-panel-field px-3 py-3',+ documentIcon: 'flex size-9 shrink-0 items-center justify-center rounded-md bg-panel text-muted',+ documentBody: 'min-w-0 flex-1',+ documentName: 'block truncate text-xs font-medium text-surface',+ documentMeta: 'mt-0.5 block truncate text-[11px] text-muted',+ permission: 'shrink-0 rounded bg-panel px-1.5 py-0.5 text-[10px] font-medium text-muted',+ stack: 'flex flex-col gap-3',+ unavailable: 'flex flex-col items-center gap-3 py-4 text-center',+ unavailableIcon:+ 'flex size-10 items-center justify-center rounded-full bg-panel-field text-muted',+ unavailableDescription: 'max-w-xs text-[11px] leading-relaxed text-muted',+ loading: 'flex items-center justify-center gap-2 py-6 text-[11px] text-muted',+ spinner: 'size-3.5 shrink-0 animate-spin motion-reduce:animate-none'+ }+})diff --git a/src/theme/cloud/save.ts b/src/theme/cloud/save.tsnew file mode 100644index 000000000..af1158d21--- /dev/null+++ b/src/theme/cloud/save.ts@@ -0,0 +1,24 @@+import { tv } from 'tailwind-variants'++/** Choosing where on Cloud a document from this device goes. */+export const cloudSave = tv({+ slots: {+ field: 'flex flex-col gap-1.5',+ label: 'text-[11px] font-medium text-muted',+ server: 'mt-1 text-[11px] font-medium text-muted',+ choices: 'flex flex-col gap-1.5',+ choice:+ 'group flex w-full items-center gap-3 rounded-lg border border-border bg-panel-field px-3 py-2 text-left outline-none hover:bg-panel-field-hover focus-visible:ring-2 focus-visible:ring-accent/50 disabled:cursor-default disabled:opacity-50 disabled:hover:bg-panel-field data-[state=checked]:border-panel-focus data-[state=checked]:bg-panel-selected-muted',+ choiceIcon: 'size-3.5 shrink-0 text-muted group-data-[state=checked]:text-primary',+ choiceLabel: 'min-w-0 flex-1 truncate text-xs text-surface',+ choiceRole: 'shrink-0 text-[11px] text-muted',+ choiceMark:+ 'size-3.5 shrink-0 rounded-full border border-border group-data-[state=checked]:border-4 group-data-[state=checked]:border-accent',+ stack: 'flex flex-col gap-4',+ note: 'text-[11px] leading-relaxed text-muted',+ progress: 'flex flex-col gap-1.5',+ progressTrack: 'h-1 overflow-hidden rounded-full bg-panel-field',+ progressBar: 'h-full rounded-full bg-accent transition-[width] motion-reduce:transition-none',+ progressText: 'text-[11px] text-muted tabular-nums'+ }+})diff --git a/src/theme/cloud/servers.ts b/src/theme/cloud/servers.tsnew file mode 100644index 000000000..af4000268--- /dev/null+++ b/src/theme/cloud/servers.ts@@ -0,0 +1,23 @@+import { tv } from 'tailwind-variants'++/** Connected Cloud servers in Settings, one row each with its account and session. */+export const cloudServers = tv({+ slots: {+ row: 'flex items-center gap-3 px-3 py-2.5',+ icon: 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel-field text-muted',+ body: 'min-w-0 flex-1',+ titleRow: 'flex min-w-0 items-center gap-1.5',+ title: 'truncate text-xs font-medium text-surface',+ host: 'truncate text-[11px] text-muted',+ badge: 'shrink-0 rounded bg-panel-field px-1.5 py-0.5 text-[10px] font-medium text-muted',+ account: 'mt-0.5 flex min-w-0 items-center gap-1.5 text-[11px] text-muted',+ accountText: 'truncate',+ expired: 'mt-0.5 flex items-center gap-1 text-[11px] text-warning',+ trailing: 'flex shrink-0 items-center gap-1',+ choices: 'flex flex-col gap-1.5',+ choiceIcon: 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel text-muted',+ waitlist: 'flex flex-col gap-3 rounded border border-border p-3',+ waitlistHeader: 'flex items-start gap-3',+ waitlistDescription: 'mt-0.5 text-[11px] text-muted'+ }+})diff --git a/src/theme/cloud/share.ts b/src/theme/cloud/share.tsnew file mode 100644index 000000000..ee1fb08c2--- /dev/null+++ b/src/theme/cloud/share.ts@@ -0,0 +1,25 @@+import { tv } from 'tailwind-variants'++export const cloudShare = tv({+ slots: {+ invite: 'flex items-center gap-2',+ heading: 'mb-2 text-[11px] font-semibold text-muted',+ list: 'flex flex-col',+ row: 'flex min-h-11 items-center gap-3 py-1.5',+ rowBody: 'min-w-0 flex-1',+ rowName: 'flex min-w-0 items-center gap-1.5 truncate text-xs font-medium text-surface',+ rowDetail: 'block truncate text-[11px] text-muted',+ rowRole: 'shrink-0 px-2 text-[11px] text-muted',+ pendingAvatar:+ 'flex size-7 shrink-0 items-center justify-center rounded-full border border-dashed border-border text-muted',+ groupAvatar:+ 'flex size-7 shrink-0 items-center justify-center rounded-full bg-panel-field text-muted',+ access: 'flex items-center gap-3 rounded-lg border border-border px-3 py-2.5',+ accessIcon:+ 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel-field text-muted data-[access=link]:bg-success/10 data-[access=link]:text-success',+ accessBody: 'min-w-0 flex-1',+ accessLabel: 'text-xs font-medium text-surface',+ accessDetail: 'text-[11px] text-muted',+ footnote: 'text-[11px] text-muted'+ }+})diff --git a/src/theme/cloud/status.ts b/src/theme/cloud/status.tsnew file mode 100644index 000000000..cee5fb40c--- /dev/null+++ b/src/theme/cloud/status.ts@@ -0,0 +1,17 @@+import { tv } from 'tailwind-variants'++export const cloudStatus = tv({+ slots: {+ trigger:+ 'flex h-6 shrink-0 items-center gap-1 rounded px-1 text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent/50 data-[state=open]:bg-hover data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:text-error data-[state-sync=view]:bg-panel-field data-[state-sync=view]:text-surface',+ triggerLabel: 'text-[11px] font-medium',+ header: 'flex items-start gap-2.5',+ headerIcon:+ 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel-field text-muted data-[state-sync=synced]:text-primary data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:bg-error-bg data-[state-sync=error]:text-error',+ title: 'text-xs font-medium text-surface',+ detail: 'mt-0.5 text-[11px] leading-relaxed text-muted',+ facts: 'mt-3 flex flex-col gap-1 rounded-md bg-panel-field px-2.5 py-2 text-[11px]',+ fact: 'flex justify-between gap-3 [&_dt]:text-muted [&_dd]:truncate [&_dd]:text-surface',+ actions: 'mt-3 flex flex-wrap items-center gap-2'+ }+})diff --git a/src/theme/cloud/workspace.ts b/src/theme/cloud/workspace.tsnew file mode 100644index 000000000..1d2c86be8--- /dev/null+++ b/src/theme/cloud/workspace.ts@@ -0,0 +1,30 @@+import { tv } from 'tailwind-variants'++/** Creating a Cloud workspace and managing who belongs to it. */+export const cloudWorkspace = tv({+ slots: {+ form: 'flex flex-col gap-1.5',+ label: 'text-[11px] font-medium text-muted',+ stack: 'flex flex-col gap-4',+ inline: 'flex items-center gap-2',+ section: 'flex flex-col gap-2',+ sectionTitle: 'text-[11px] font-medium text-muted',+ sent: 'flex flex-col gap-1.5',+ note: 'text-[11px] text-muted',+ list: 'flex flex-col divide-y divide-border rounded border border-border',+ row: 'flex items-center gap-3 px-3 py-2',+ person: 'flex min-w-0 flex-1 flex-col',+ personName: 'truncate text-xs text-surface',+ personEmail: 'truncate text-[11px] text-muted',+ you: 'ml-1 text-[11px] text-muted',+ role: 'shrink-0 text-[11px] text-muted',+ roleSelect: 'w-28 shrink-0',+ dangerTitle: 'text-[11px] font-medium text-error',+ dangerList: 'flex flex-col divide-y divide-error-border rounded border border-error-border',+ dangerRow: 'flex items-center gap-3 px-3 py-2.5',+ dangerDescription: 'text-[11px] text-pretty text-muted',+ confirmName: 'mt-3 flex flex-col gap-1.5',+ pendingIcon:+ 'flex size-6 shrink-0 items-center justify-center rounded-full bg-panel-field text-muted'+ }+})diff --git a/src/theme/control.ts b/src/theme/control.tsindex 769b1942c..0e50ecfc7 100644--- a/src/theme/control.ts+++ b/src/theme/control.ts@@ -1,13 +1,15 @@-export type ControlSize = 'xs' | 'sm' | 'md'+export type ControlSize = 'xs' | 'sm' | 'md' | 'lg'export const controlHeight = {xs: 'h-6',sm: 'h-7',- md: 'h-8'+ md: 'h-8',+ lg: 'h-9'} satisfies Record<ControlSize, string>export const squareControlSize = {xs: 'size-6',sm: 'size-7',- md: 'size-8'+ md: 'size-8',+ lg: 'size-9'} satisfies Record<ControlSize, string>diff --git a/src/theme/home/document-entry.ts b/src/theme/home/document-entry.tsindex 7f1a992c8..d83636c5b 100644--- a/src/theme/home/document-entry.ts+++ b/src/theme/home/document-entry.ts@@ -11,7 +11,9 @@ export const documentEntry = tv({fallback: 'size-8 text-muted/40',icon: 'size-4 shrink-0 text-primary',body: 'min-w-0 flex-1',- name: 'block truncate text-xs font-medium',+ title: 'flex min-w-0 items-center gap-1.5',+ name: 'block min-w-0 truncate text-xs font-medium',+ status: 'flex shrink-0 items-center gap-1 text-muted',metadata: 'mt-0.5 block truncate text-[10px] text-muted',trailingMetadata: 'hidden shrink-0 text-[10px] text-muted sm:inline',actions: 'flex shrink-0 items-center gap-1'diff --git a/src/theme/home/location-menu.ts b/src/theme/home/location-menu.tsnew file mode 100644index 000000000..14b9b798a--- /dev/null+++ b/src/theme/home/location-menu.ts@@ -0,0 +1,17 @@+import { tv } from 'tailwind-variants'++/** The home tab's location picker on phones, in place of the sidebar. */+export const homeLocationMenu = tv({+ slots: {+ trigger:+ 'flex h-10 w-full items-center gap-2 rounded-lg border border-border bg-panel-field px-3 text-left text-sm text-surface outline-none hover:bg-panel-field-hover focus-visible:ring-2 focus-visible:ring-accent/50',+ icon: 'size-4 shrink-0 text-muted',+ label: 'min-w-0 flex-1 truncate font-medium',+ chevron: 'size-4 shrink-0 text-muted',+ content: 'w-[var(--reka-dropdown-menu-trigger-width)]',+ itemLabel: 'min-w-0 flex-1 truncate',+ count: 'shrink-0 text-[11px] text-muted tabular-nums',+ check: 'size-3.5 shrink-0 text-surface',+ attention: 'size-3.5 shrink-0 text-warning'+ }+})diff --git a/src/theme/input/input-group.ts b/src/theme/input/input-group.tsindex aceff2fc4..07ca746de 100644--- a/src/theme/input/input-group.ts+++ b/src/theme/input/input-group.ts@@ -13,7 +13,8 @@ export default {size: {xs: { toolbar: controlHeight.xs },sm: { toolbar: controlHeight.sm },- md: { toolbar: controlHeight.md }+ md: { toolbar: controlHeight.md },+ lg: { toolbar: controlHeight.lg }},disabled: {true: { root: 'opacity-60' }diff --git a/src/theme/input/input.ts b/src/theme/input/input.tsindex 8326ed615..67c5dbe83 100644--- a/src/theme/input/input.ts+++ b/src/theme/input/input.ts@@ -19,7 +19,8 @@ export default {size: {xs: 'h-6 px-2 text-[11px]',sm: 'h-7 px-2.5 text-xs',- md: 'h-8 px-3 text-xs'+ md: 'h-8 px-3 text-xs',+ lg: 'h-9 px-3 text-sm'},density: {compact: '',diff --git a/src/theme/list/side-list.ts b/src/theme/list/side-list.tsindex 9e6d4638e..263d04ad9 100644--- a/src/theme/list/side-list.ts+++ b/src/theme/list/side-list.ts@@ -7,6 +7,7 @@ export const sideList = tv({group: 'flex flex-col',header: 'flex h-8 shrink-0 items-center justify-between pr-1.5 pl-3',title: 'text-[11px] font-semibold text-surface',+ actions: 'flex items-center gap-0.5',items: 'flex flex-col px-1 pb-1',item: 'group flex h-6 w-full cursor-pointer items-center gap-1.5 rounded border-none bg-transparent px-2 text-left text-[11px] text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-1 focus-visible:ring-panel-focus data-[active=true]:bg-hover data-[active=true]:text-surface',icon: 'size-3 shrink-0 opacity-70',diff --git a/src/views/cloud/CheckEmailView.vue b/src/views/cloud/CheckEmailView.vueindex daadcd5c4..2aa83bad0 100644--- a/src/views/cloud/CheckEmailView.vue+++ b/src/views/cloud/CheckEmailView.vue@@ -44,18 +44,26 @@ async function sendAgain() {:heading="messages.checkEmailTitle":description="messages.checkEmailDescription({ email })">- <template #icon><icon-lucide-mail-check class="size-5" /></template>+ <template #icon><icon-lucide-mail-check class="size-6" /></template><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><template #actions><AppButton- variant="outline"+ size="lg"+ color="primary"+ variant="solid"+ class="w-full":loading="state === 'sending'":disabled="state === 'sent' || !email"@click="sendAgain">{{ state === 'sent' ? messages.sent : messages.sendAgain }}</AppButton>- <AppButton variant="ghost" @click="router.replace({ name: 'sign-up', query: { redirect } })">+ <AppButton+ size="lg"+ variant="outline"+ class="w-full"+ @click="router.replace({ name: 'sign-up', query: { redirect } })"+ >{{ messages.useAnotherEmail }}</AppButton></template>diff --git a/src/views/cloud/DeviceView.vue b/src/views/cloud/DeviceView.vueindex 7b1171537..7f80cc4a1 100644--- a/src/views/cloud/DeviceView.vue+++ b/src/views/cloud/DeviceView.vue@@ -62,7 +62,7 @@ const {:heading="messages.deviceApprovedTitle":description="messages.deviceApprovedDescription">- <template #icon><icon-lucide-check class="size-5" /></template>+ <template #icon><icon-lucide-check class="size-6" /></template></PortalNotice><PortalNoticev-else-if="state === 'denied'"@@ -70,9 +70,14 @@ const {:heading="messages.deviceDeniedTitle":description="messages.deviceDeniedDescription">- <template #icon><icon-lucide-monitor-x class="size-5" /></template>+ <template #icon><icon-lucide-monitor-x class="size-6" /></template><template #actions>- <AppButton variant="outline" @click="router.push({ name: 'security' })">+ <AppButton+ size="lg"+ variant="outline"+ class="w-full"+ @click="router.push({ name: 'security' })"+ >{{ messages.accountSettings }}</AppButton></template>@@ -83,6 +88,6 @@ const {:heading="messages.deviceExpiredTitle":description="messages.deviceExpiredDescription">- <template #icon><icon-lucide-timer-off class="size-5" /></template>+ <template #icon><icon-lucide-timer-off class="size-6" /></template></PortalNotice></template>diff --git a/src/views/cloud/ResetPasswordView.vue b/src/views/cloud/ResetPasswordView.vueindex 5fb908b2a..ef26e50a6 100644--- a/src/views/cloud/ResetPasswordView.vue+++ b/src/views/cloud/ResetPasswordView.vue@@ -19,7 +19,7 @@ const { failure } = usePortalFailureMessages()const token = computed(() => (typeof route.query.token === 'string' ? route.query.token : null))const redirect = computed(() => continuationPath(route.query.redirect))const minimum = computed(- () => portal.discovery.authentication.emailPassword?.minimumPasswordLength ?? 15+ () => portal.discovery.authentication.emailPassword?.minimumPasswordLength ?? 8)const submitting = ref(false)const error = ref<string | null>(@@ -60,9 +60,14 @@ async function choose(password: string) {:heading="messages.resetSentTitle":description="messages.resetSentDescription({ email: sentTo })">- <template #icon><icon-lucide-mail-check class="size-5" /></template>+ <template #icon><icon-lucide-mail-check class="size-6" /></template><template #actions>- <AppButton variant="ghost" @click="router.replace({ name: 'sign-in', query: { redirect } })">+ <AppButton+ size="lg"+ variant="outline"+ class="w-full"+ @click="router.replace({ name: 'sign-in', query: { redirect } })"+ >{{ messages.backToSignIn }}</AppButton></template>diff --git a/src/views/cloud/SignInView.vue b/src/views/cloud/SignInView.vueindex 3da979b9a..31debbbc5 100644--- a/src/views/cloud/SignInView.vue+++ b/src/views/cloud/SignInView.vue@@ -1,5 +1,6 @@<script setup lang="ts">-import { computed, ref } from 'vue'+import { omit } from 'es-toolkit'+import { computed, onMounted, ref } from 'vue'import { useRoute, useRouter } from 'vue-router'import type { CloudSocialProvider } from '@open-pencil/cloud/client'@@ -59,6 +60,14 @@ async function submit(input: { name: string; email: string; password: string })return}const result = await portal.auth.withEmail({ email: input.email, password: input.password })+ if (!result.ok && result.failure === 'email-not-verified') {+ // The page explains it and sends the link again on request.+ await router.push({+ name: 'check-email',+ query: { email: input.email, redirect: redirect.value }+ })+ return+ }if (!result.ok) {error.value = failure(result.failure)return@@ -74,6 +83,17 @@ async function submit(input: { name: string; email: string; password: string })}}+// The editor's sign-in sends a provider along when the person already chose one there.+onMounted(() => {+ const provider = authentication.value.socialProviders.find(+ (candidate) => candidate === route.query.provider+ )+ if (!provider || error.value || mode.value !== 'sign-in') return+ // Without the provider in the address, Back from the provider's page shows this page again+ // instead of sending the person straight back to the provider.+ void router.replace({ query: omit(route.query, ['provider']) }).then(() => withProvider(provider))+})+function switchMode() {error.value = nullvoid router.replace({diff --git a/src/views/cloud/StandingView.vue b/src/views/cloud/StandingView.vueindex 6e734fa12..4e488f292 100644--- a/src/views/cloud/StandingView.vue+++ b/src/views/cloud/StandingView.vue@@ -30,11 +30,13 @@ async function signOut() {:description="pending ? messages.pendingDescription({ email }) : messages.closedDescription"><template #icon>- <icon-lucide-clock v-if="pending" class="size-5" />- <icon-lucide-ban v-else class="size-5" />+ <icon-lucide-clock v-if="pending" class="size-6" />+ <icon-lucide-ban v-else class="size-6" /></template><template v-if="portal.account.value" #actions>- <AppButton variant="ghost" @click="signOut">{{ messages.signOut }}</AppButton>+ <AppButton size="lg" variant="outline" class="w-full" @click="signOut">+ {{ messages.signOut }}+ </AppButton></template></PortalNotice></template>diff --git a/src/views/cloud/VerifiedView.vue b/src/views/cloud/VerifiedView.vuenew file mode 100644index 000000000..24843a47a--- /dev/null+++ b/src/views/cloud/VerifiedView.vue@@ -0,0 +1,21 @@+<script setup lang="ts">+import { useCloudPortalMessages } from '@open-pencil/vue'++import { usePortal } from '@/app/cloud-portal/context'+import PortalNotice from '@/components/cloud-portal/auth/PortalNotice.vue'++/** Where a verification link started in the editor lands: the editor finishes the sign-in. */+const portal = usePortal()+const messages = useCloudPortalMessages()+</script>++<template>+ <PortalNotice+ :host="portal.host"+ :heading="messages.verifiedTitle"+ :description="messages.verifiedDescription"+ tone="success"+ >+ <template #icon><icon-lucide-circle-check class="size-6" /></template>+ </PortalNotice>+</template>diff --git a/tests/app/cloud/availability.test.ts b/tests/app/cloud/availability.test.tsnew file mode 100644index 000000000..f071cead7--- /dev/null+++ b/tests/app/cloud/availability.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, spyOn, test } from 'bun:test'++import {+ cloudOfficialListed,+ checkCloudAvailability,+ isVersionAtLeast+} from '@/app/cloud/availability'+import { OFFICIAL_CLOUD_URL } from '@/constants'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'+import { fetchStub } from '#tests/helpers/fetch'++const EDITOR = 'https://app.example.com/'++function officialServer(answer: () => Response) {+ spyOn(globalThis, 'fetch').mockImplementation(fetchStub(async () => answer()))+}++afterEach(async () => {+ officialServer(() => Response.error())+ await checkCloudAvailability(`${EDITOR}?cloud=off`)+})++describe('Cloud availability', () => {+ test('compares editor versions by number, not by text', () => {+ expect(isVersionAtLeast('0.14.0', '0.14.0')).toBe(true)+ expect(isVersionAtLeast('0.14.2', '0.14.0')).toBe(true)+ expect(isVersionAtLeast('0.10.0', '0.9.5')).toBe(true)+ expect(isVersionAtLeast('0.9.5', '0.10.0')).toBe(false)+ expect(isVersionAtLeast('1.0.0-beta.1', '1.0.0')).toBe(true)+ expect(isVersionAtLeast('next', '1.0.0')).toBe(false)+ })++ test('stays hidden while the official server is unreachable or unlisted', async () => {+ officialServer(() => Response.error())+ await checkCloudAvailability(EDITOR)+ expect(cloudOfficialListed.value).toBe(false)+ })++ test('a preview link shows Cloud on this device until it is turned off', async () => {+ officialServer(() => Response.error())+ await checkCloudAvailability(`${EDITOR}?cloud=preview`)+ expect(cloudOfficialListed.value).toBe(true)+ await checkCloudAvailability(EDITOR)+ expect(cloudOfficialListed.value).toBe(true)+ await checkCloudAvailability(`${EDITOR}?cloud=off`)+ expect(cloudOfficialListed.value).toBe(false)+ })++ test('shows Cloud once the official server lists itself for this editor version', async () => {+ officialServer(() =>+ Response.json({+ ...cloudDiscoveryFixture(OFFICIAL_CLOUD_URL),+ deployment: 'official',+ // Tests run as editor version 0.0.0.+ listing: { minimumEditorVersion: '0.0.0' }+ })+ )+ await checkCloudAvailability(EDITOR)+ expect(cloudOfficialListed.value).toBe(true)+ })+})diff --git a/tests/app/cloud/documents/status.test.ts b/tests/app/cloud/documents/status.test.tsnew file mode 100644index 000000000..cd7a00ed4--- /dev/null+++ b/tests/app/cloud/documents/status.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { cloudSyncState, unsentCloudDocumentCount } from '@/app/cloud/documents/status'+import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import { createMemoryLocalCanvasStore } from '@/app/storage/local-store'+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'++afterEach(() => resetLocalCanvasStoreForTests())++describe('Cloud document status', () => {+ test('puts a choice to make or a failure ahead of anything in flight', () => {+ expect(cloudSyncState({ syncStatus: 'conflict' }, true, true)).toBe('conflict')+ expect(cloudSyncState({ syncStatus: 'error' }, true, true)).toBe('error')+ })++ test('shows an upload in flight, then waiting changes, offline or not', () => {+ expect(cloudSyncState({ syncStatus: 'pending' }, true, true)).toBe('uploading')+ expect(cloudSyncState({ syncStatus: 'pending' }, false, true)).toBe('pending')+ expect(cloudSyncState({ syncStatus: 'pending' }, false, false)).toBe('offline')+ })++ test('calls everything else saved', () => {+ expect(cloudSyncState({ syncStatus: 'synced' }, false, false)).toBe('synced')+ expect(cloudSyncState(null, false, true)).toBe('synced')+ })+})++describe('Removing a Cloud server', () => {+ test('counts this server’s documents whose changes have not reached it', async () => {+ const store = createMemoryLocalCanvasStore()+ resetLocalCanvasStoreForTests(store)+ const document = (id: string, profileId: string, syncStatus: 'synced' | 'pending' | 'error') =>+ store.writeCanvas({+ id,+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId,+ name: id,+ figBytes: new Uint8Array([1]),+ syncStatus+ })+ await document('saved', 'server-a', 'synced')+ await document('waiting', 'server-a', 'pending')+ await document('failed', 'server-a', 'error')+ await document('elsewhere', 'server-b', 'pending')+ await store.writeCanvas({+ id: 'bucket',+ providerId: 's3-compatible',+ name: 'bucket',+ figBytes: new Uint8Array([1]),+ syncStatus: 'pending'+ })++ expect(await unsentCloudDocumentCount('server-a')).toBe(2)+ expect(await unsentCloudDocumentCount('server-c')).toBe(0)+ })+})diff --git a/tests/app/cloud/invitations/flow.test.ts b/tests/app/cloud/invitations/flow.test.tsnew file mode 100644index 000000000..80620cf89--- /dev/null+++ b/tests/app/cloud/invitations/flow.test.ts@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'++import {+ acceptCloudInvitation,+ beginCloudInvitation,+ checkCloudInvitation,+ cloudInvitation,+ cloudInvitationState,+ dismissCloudInvitation+} from '@/app/cloud/invitations/flow'+import { addCloudServer, cloudServers, removeCloudServer } from '@/app/cloud/servers/store'+import { refreshCloudConnection } from '@/app/cloud/sessions/connection'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'+import { fetchStub } from '#tests/helpers/fetch'++const ORIGIN = 'https://invite.example.com'+const INVITATION = '6f1c6c1e-7a4d-4d1b-9a2e-1f0b6a3c2d11'+let answers: Record<string, { status: number; body?: unknown }> = {}++beforeEach(() => {+ answers = {+ [`/api/invitations/${INVITATION}/preview`]: {+ status: 200,+ body: {+ invitation: {+ kind: 'document',+ documentName: 'Pricing page',+ inviterName: 'Ana',+ permission: 'edit',+ expiresAt: '2030-01-01T00:00:00.000Z',+ recipientHint: 'b•••@example.com'+ }+ }+ }+ }+ spyOn(globalThis, 'fetch').mockImplementation(+ fetchStub(async (input) => {+ const url = new URL(input instanceof Request ? input.url : String(input))+ if (url.pathname === '/.well-known/openpencil')+ return Response.json(cloudDiscoveryFixture(ORIGIN))+ const answer = answers[url.pathname]+ if (!answer) return Response.json({ error: { code: 'not_found' } }, { status: 404 })+ return Response.json(answer.body ?? {}, { status: answer.status })+ })+ )+})++afterEach(() => {+ dismissCloudInvitation()+ for (const server of cloudServers.value) removeCloudServer(server.id)+})++async function signedIn() {+ answers['/api/account/status'] = {+ status: 200,+ body: { user: { userId: 'user-1', email: '[email protected]', name: 'Ben' }, state: 'active' }+ }+ answers['/api/workspaces'] = { status: 200, body: { workspaces: [] } }+ await refreshCloudConnection(await addCloudServer({ kind: 'self-hosted', url: ORIGIN }))+}++describe('Cloud invitations', () => {+ test('ask to sign in to a server this app has never used, and warn about it', async () => {+ beginCloudInvitation(INVITATION, ORIGIN, 'token'.repeat(8))+ await checkCloudInvitation()+ expect(cloudInvitationState.value).toBe('sign-in')+ expect(cloudInvitation.value).toMatchObject({+ documentName: 'Pricing page',+ unknownServer: true+ })+ })++ test('are ready to accept once signed in to their server', async () => {+ await signedIn()+ beginCloudInvitation(INVITATION, ORIGIN, 'token'.repeat(8))+ await checkCloudInvitation()+ expect(cloudInvitationState.value).toBe('ready')+ expect(cloudInvitation.value?.unknownServer).toBe(false)+ })++ test('call an invitation the server refuses right after a valid preview another account’s', async () => {+ await signedIn()+ beginCloudInvitation(INVITATION, ORIGIN, 'token'.repeat(8))+ await checkCloudInvitation()+ await acceptCloudInvitation()+ expect(cloudInvitationState.value).toBe('wrong-account')+ })++ test('say when the link is for a whole workspace', async () => {+ answers[`/api/invitations/${INVITATION}/preview`] = {+ status: 200,+ body: {+ invitation: {+ kind: 'workspace',+ workspaceName: 'Studio',+ role: 'editor',+ inviterName: 'Ana',+ expiresAt: '2030-01-01T00:00:00.000Z',+ recipientHint: 'b•••@example.com'+ }+ }+ }+ await signedIn()+ beginCloudInvitation(INVITATION, ORIGIN, 'token'.repeat(8))+ await checkCloudInvitation()+ expect(cloudInvitationState.value).toBe('ready')+ expect(cloudInvitation.value).toMatchObject({ kind: 'workspace', workspaceName: 'Studio' })+ })++ test('are unavailable when the preview is refused', async () => {+ delete answers[`/api/invitations/${INVITATION}/preview`]+ beginCloudInvitation(INVITATION, ORIGIN, 'token'.repeat(8))+ await checkCloudInvitation()+ expect(cloudInvitationState.value).toBe('unavailable')+ })+})diff --git a/tests/app/cloud/rooms/saver.test.ts b/tests/app/cloud/rooms/saver.test.tsnew file mode 100644index 000000000..53ba0bf77--- /dev/null+++ b/tests/app/cloud/rooms/saver.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from 'bun:test'++import { electCloudSaver } from '@/app/cloud/rooms/live'++const editor = { cloud: { kind: 'user', permission: 'edit' } }+const viewer = { cloud: { kind: 'user', permission: 'view' } }+const guest = { cloud: { kind: 'guest', permission: 'edit' } }++describe('the room saver', () => {+ test('is the editor with the lowest presence client, this tab included', () => {+ const presence = new Map<number, Record<string, unknown>>([+ [30, {}],+ [12, editor],+ [8, viewer]+ ])+ expect(electCloudSaver(presence, { clientId: 30, canSave: true })).toBe(12)+ const withSelfFirst = new Map<number, Record<string, unknown>>([+ [5, {}],+ [12, editor]+ ])+ expect(electCloudSaver(withSelfFirst, { clientId: 5, canSave: true })).toBe(5)+ })++ test('is never a guest from a link, who has no account to save with', () => {+ const presence = new Map<number, Record<string, unknown>>([+ [2, guest],+ [9, {}]+ ])+ expect(electCloudSaver(presence, { clientId: 9, canSave: true })).toBe(9)+ })++ test('is never a viewer', () => {+ const presence = new Map<number, Record<string, unknown>>([+ [3, {}],+ [8, viewer]+ ])+ expect(electCloudSaver(presence, { clientId: 3, canSave: false })).toBeNull()+ })+})diff --git a/tests/app/cloud/servers/store.test.ts b/tests/app/cloud/servers/store.test.tsnew file mode 100644index 000000000..faccba789--- /dev/null+++ b/tests/app/cloud/servers/store.test.ts@@ -0,0 +1,72 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { normalizeCloudServerURL } from '@/app/cloud/servers/address'+import {+ addCloudServer,+ cloudServers,+ homeCloudServer,+ removeCloudServer,+ showCloudServerOnHome+} from '@/app/cloud/servers/store'+import { OFFICIAL_CLOUD_URL } from '@/constants'++afterEach(() => {+ for (const server of cloudServers.value) removeCloudServer(server.id)+})++describe('Cloud server addresses', () => {+ test('read what people type as the server’s canonical address', () => {+ expect(normalizeCloudServerURL('cloud.example.com')).toBe('https://cloud.example.com')+ expect(normalizeCloudServerURL(' https://cloud.example.com/ ')).toBe(+ 'https://cloud.example.com'+ )+ expect(normalizeCloudServerURL('http://localhost:8787/?x=1#y')).toBe('http://localhost:8787')+ })++ test('refuse what cannot be a server', () => {+ for (const input of [+ '',+ 'ftp://cloud.example.com',+ 'https://user:[email protected]',+ // Its session token would cross the network in the clear.+ 'http://cloud.example.com',+ 'http://192.168.1.20:8787'+ ])+ expect(normalizeCloudServerURL(input)).toBeNull()+ expect(normalizeCloudServerURL('http://127.0.0.1:8787')).toBe('http://127.0.0.1:8787')+ })+})++describe('Cloud servers', () => {+ test('get the same credential-safe id for the same address', async () => {+ const first = await addCloudServer({ kind: 'self-hosted', url: 'design.acme.example' })+ const again = await addCloudServer({ kind: 'self-hosted', url: 'https://design.acme.example/' })+ expect(again.id).toBe(first.id)+ expect(first.id).toMatch(/^[0-9a-f]{32}$/)+ expect(cloudServers.value).toHaveLength(1)+ })++ test('add a server once when two sign-ins for it overlap', async () => {+ const [first, second] = await Promise.all([+ addCloudServer({ kind: 'self-hosted', url: 'design.acme.example' }),+ addCloudServer({ kind: 'self-hosted', url: 'design.acme.example' })+ ])+ expect(second.id).toBe(first.id)+ expect(cloudServers.value).toHaveLength(1)+ })++ test('put the first server on Home and move Home on when it is removed', async () => {+ const official = await addCloudServer({ kind: 'official' })+ const team = await addCloudServer({ kind: 'self-hosted', url: 'design.acme.example' })+ expect(official.url).toBe(OFFICIAL_CLOUD_URL)+ expect(homeCloudServer.value?.id).toBe(official.id)+ showCloudServerOnHome(team.id)+ expect(homeCloudServer.value?.id).toBe(team.id)+ removeCloudServer(team.id)+ expect(homeCloudServer.value?.id).toBe(official.id)+ })++ test('reject an address that cannot be a server', async () => {+ await expect(addCloudServer({ kind: 'self-hosted', url: 'ftp://nope' })).rejects.toThrow()+ })+})diff --git a/tests/app/cloud/sessions/connection.test.ts b/tests/app/cloud/sessions/connection.test.tsnew file mode 100644index 000000000..e5771b74c--- /dev/null+++ b/tests/app/cloud/sessions/connection.test.ts@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'++import { addCloudServer, cloudServers, removeCloudServer } from '@/app/cloud/servers/store'+import { cloudConnection, refreshCloudConnection } from '@/app/cloud/sessions/connection'+import { readCloudSessionToken, saveCloudSessionToken } from '@/app/cloud/sessions/token'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'+import { fetchStub } from '#tests/helpers/fetch'++const ORIGIN = 'https://cloud.example.com'+const user = { userId: 'user-1', email: '[email protected]', name: 'Ada' }+const workspace = {+ id: '6f1c6c1e-7a4d-4d1b-9a2e-1f0b6a3c2d10',+ name: 'Design',+ slug: 'design',+ role: 'editor',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z'+}++type Answer = { status: number; body?: unknown }+let answers: Record<string, Answer> = {}+let authorization: (string | null)[] = []++beforeEach(() => {+ answers = {}+ authorization = []+ spyOn(globalThis, 'fetch').mockImplementation(+ fetchStub(async (input, init) => {+ const url = new URL(input instanceof Request ? input.url : String(input))+ authorization.push(new Headers(init?.headers).get('Authorization'))+ if (url.pathname === '/.well-known/openpencil')+ return Response.json(cloudDiscoveryFixture(ORIGIN))+ const answer = answers[url.pathname]+ if (!answer) return new Response(null, { status: 404 })+ return Response.json(answer.body ?? { error: { code: 'unauthorized' } }, {+ status: answer.status+ })+ })+ )+})++afterEach(() => {+ for (const server of cloudServers.value) removeCloudServer(server.id)+})++async function server() {+ return addCloudServer({ kind: 'self-hosted', url: ORIGIN })+}++describe('Cloud connections', () => {+ test('list workspaces for an approved account and remember who it is', async () => {+ answers['/api/account/status'] = { status: 200, body: { user, state: 'active' } }+ answers['/api/workspaces'] = { status: 200, body: { workspaces: [workspace] } }+ const target = await server()+ const connection = await refreshCloudConnection(target)+ expect(connection.state).toBe('signed-in')+ expect(connection.workspaces.map((entry) => entry.name)).toEqual(['Design'])+ expect(cloudServers.value[0]?.account).toEqual({+ id: 'user-1',+ name: 'Ada',+ email: '[email protected]'+ })+ })++ test('tell an account waiting for an administrator from one signed out', async () => {+ answers['/api/account/status'] = { status: 200, body: { user, state: 'pending' } }+ expect((await refreshCloudConnection(await server())).state).toBe('pending')+ })++ test('send the device-code token and drop it once the server stops accepting it', async () => {+ const target = await server()+ await saveCloudSessionToken(target.id, 'device-token')+ answers['/api/account/status'] = { status: 401 }+ const connection = await refreshCloudConnection(target)+ expect(authorization).toContain('Bearer device-token')+ expect(connection.state).toBe('signed-out')+ expect(await readCloudSessionToken(target.id)).toBeNull()+ })++ test('call a remembered account whose session ended expired', async () => {+ answers['/api/account/status'] = { status: 200, body: { user, state: 'active' } }+ answers['/api/workspaces'] = { status: 200, body: { workspaces: [] } }+ const target = await server()+ await refreshCloudConnection(target)+ answers['/api/account/status'] = { status: 401 }+ const remembered = cloudServers.value[0]+ if (!remembered) throw new Error('Expected the server to be saved')+ expect((await refreshCloudConnection(remembered)).state).toBe('expired')+ expect(cloudConnection(target.id).account?.email).toBe('[email protected]')+ })+})diff --git a/tests/app/cloud/sessions/device.test.ts b/tests/app/cloud/sessions/device.test.tsnew file mode 100644index 000000000..be7dd2bab--- /dev/null+++ b/tests/app/cloud/sessions/device.test.ts@@ -0,0 +1,97 @@+import { describe, expect, test } from 'bun:test'++import { CloudDeviceAuthorizationError } from '@open-pencil/cloud/client'++import {+ createCloudDeviceSignIn,+ type CloudDeviceSignInDependencies+} from '@/app/cloud/sessions/device'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'++const discovery = cloudDiscoveryFixture()+const authorization = {+ device_code: 'device',+ user_code: 'ABCD-EFGH',+ verification_uri: 'https://cloud.example/cloud/device',+ verification_uri_complete: 'https://cloud.example/cloud/device?user_code=ABCD-EFGH',+ expires_in: 900,+ interval: 5+}++function dependencies(poll: CloudDeviceSignInDependencies['poll']) {+ const saved = new Map<string, string>()+ const opened: string[] = []+ const deps: CloudDeviceSignInDependencies = {+ request: async () => authorization,+ poll,+ open: async (url) => {+ opened.push(url)+ },+ save: async (id, token) => {+ saved.set(id, token)+ },+ clear: async (id) => {+ saved.delete(id)+ }+ }+ return { deps, saved, opened }+}++const token = { access_token: 'token', token_type: 'Bearer' as const, expires_in: 60, scope: '' }++describe('device-code sign-in', () => {+ test('opens the approval page, waits, and keeps the token', async () => {+ const { deps, saved, opened } = dependencies(async () => token)+ const signIn = createCloudDeviceSignIn(deps)+ expect(await signIn.start('server', discovery)).toBe(true)+ expect(opened).toEqual([authorization.verification_uri_complete])+ expect(saved.get('server')).toBe('token')+ expect(signIn.state.value.status).toBe('signed-in')+ })++ test('shows the code while it waits', async () => {+ let release: () => void = () => undefined+ const { deps } = dependencies(+ () =>+ new Promise((resolve) => {+ release = () => resolve(token)+ })+ )+ const signIn = createCloudDeviceSignIn(deps)+ const done = signIn.start('server', discovery)+ await Promise.resolve()+ await Promise.resolve()+ expect(signIn.state.value).toMatchObject({ status: 'waiting', code: 'ABCD-EFGH' })+ release()+ await done+ })++ test('reports a denied or expired code', async () => {+ const { deps } = dependencies(async () => {+ throw new CloudDeviceAuthorizationError('denied')+ })+ const signIn = createCloudDeviceSignIn(deps)+ expect(await signIn.start('server', discovery)).toBe(false)+ expect(signIn.state.value.status).toBe('denied')+ })++ test('drops a token that arrives after the person cancelled', async () => {+ let release: () => void = () => undefined+ const { deps, saved } = dependencies(+ () =>+ new Promise((resolve) => {+ release = () => resolve(token)+ })+ )+ const signIn = createCloudDeviceSignIn(deps)+ const done = signIn.start('server', discovery)+ await Promise.resolve()+ await Promise.resolve()+ signIn.cancel()+ release()+ expect(await done).toBe(false)+ expect(saved.has('server')).toBe(false)+ expect(signIn.state.value.status).toBe('idle')+ })+})diff --git a/tests/app/collab/route.test.ts b/tests/app/collab/route.test.tsnew file mode 100644index 000000000..cdae035dc--- /dev/null+++ b/tests/app/collab/route.test.ts@@ -0,0 +1,23 @@+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/integrations/storage/cloud/adapter.test.ts b/tests/app/integrations/storage/cloud/adapter.test.tsnew file mode 100644index 000000000..5e634d75b--- /dev/null+++ b/tests/app/integrations/storage/cloud/adapter.test.ts@@ -0,0 +1,218 @@+import { describe, expect, test } from 'bun:test'++import { fromUint8Array } from 'js-base64'++import { createCloudAPIClient } from '@open-pencil/cloud/client'++import { StorageRevisionConflictError } from '@/app/integrations/storage'+import { createCloudStorageAdapter } from '@/app/integrations/storage/cloud/adapter'++const WORKSPACE = '0b5a4e0a-2d1c-4d6e-9f1a-6b2c3d4e5f60'++async function sha256(bytes: Uint8Array): Promise<string> {+ return fromUint8Array(+ new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes)))+ )+}++/** Just enough of a Cloud server and its object store to save and open documents. */+function cloudServer() {+ type Doc = { name: string; revision: string | null; version: number; checksum?: string }+ const documents = new Map<string, Doc>()+ const objects = new Map<string, Uint8Array>()+ const uploads = new Map<string, { documentId: string; base: string | null }>()+ const summary = (id: string, doc: Doc) => ({+ id,+ workspaceId: WORKSPACE,+ name: doc.name,+ currentRevisionId: doc.revision,+ version: doc.version,+ createdAt: '2026-10-10T00:00:00.000Z',+ updatedAt: '2026-10-10T00:00:00.000Z'+ })+ const json = (body: unknown, status = 200) => Response.json(body, { status })++ type Body = Record<string, unknown>+ type Route = [+ method: string,+ path: RegExp,+ handle: (match: string[], body: Body) => Promise<Response> | Response+ ]+ const documentsPath = new RegExp(`^/workspaces/${WORKSPACE}/documents$`)+ const routes: Route[] = [+ [+ 'GET',+ documentsPath,+ () => json({ documents: [...documents].map(([id, doc]) => summary(id, doc)) })+ ],+ [+ 'POST',+ documentsPath,+ (_match, body) => {+ const id = String(body.id)+ const doc = { name: String(body.name), revision: null, version: 0 }+ documents.set(id, doc)+ return json({ document: summary(id, doc) }, 201)+ }+ ],+ [+ 'POST',+ /^\/documents\/([^/]+)\/uploads$/,+ ([, documentId = ''], body) => {+ const base = typeof body.baseRevisionId === 'string' ? body.baseRevisionId : null+ if ((documents.get(documentId)?.revision ?? null) !== base) {+ return json({ error: { code: 'revision_conflict' } }, 409)+ }+ const id = crypto.randomUUID()+ uploads.set(id, { documentId, base })+ const upload = {+ kind: 'single',+ url: `https://objects.test/${id}`,+ method: 'PUT',+ headers: {}+ }+ return json({ id, upload: { ...upload, expiresAt: '2030-01-01T00:00:00.000Z' } }, 201)+ }+ ],+ [+ 'POST',+ /^\/uploads\/([^/]+)\/commit$/,+ ([, uploadId = ''], body) => {+ const upload = uploads.get(uploadId)+ const doc = upload ? documents.get(upload.documentId) : undefined+ if (!upload || !doc) return json({ error: { code: 'not_found' } }, 404)+ if (doc.revision !== upload.base) return json({ error: { code: 'revision_conflict' } }, 409)+ const revision = crypto.randomUUID()+ objects.set(revision, objects.get(uploadId) ?? new Uint8Array())+ Object.assign(doc, { revision, version: doc.version + 1, checksum: String(body.checksum) })+ return json({ document: summary(upload.documentId, doc) })+ }+ ],+ [+ 'GET',+ /^\/documents\/([^/]+)$/,+ async ([, id = '']) => {+ const doc = documents.get(id)+ const bytes = doc?.revision ? objects.get(doc.revision) : undefined+ if (!doc?.revision || !bytes) return json({ error: { code: 'not_found' } }, 404)+ const download = { url: `https://objects.test/${doc.revision}`, method: 'GET', headers: {} }+ return json({+ document: {+ document: summary(id, doc),+ revisionId: doc.revision,+ byteSize: bytes.byteLength,+ checksum: doc.checksum ?? (await sha256(bytes)),+ contentType: 'application/octet-stream',+ download: { ...download, expiresAt: '2030-01-01T00:00:00.000Z' }+ }+ })+ }+ ]+ ]++ async function api(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {+ const request = new Request(input, init)+ const path = new URL(request.url).pathname.replace(/^\/api/, '')+ const body: Body = request.method === 'POST' ? await request.json() : {}+ for (const [method, pattern, handle] of routes) {+ const match = request.method === method ? path.match(pattern) : null+ if (match) return handle([...match], body)+ }+ return json({ error: { code: 'not_found' } }, 404)+ }++ async function objectFetch(input: string, init: RequestInit): Promise<Response> {+ const key = new URL(input).pathname.slice(1)+ if (init.method === 'PUT') {+ objects.set(key, new Uint8Array(await new Response(init.body).arrayBuffer()))+ return new Response(null, { status: 200 })+ }+ const bytes = objects.get(key)+ return bytes ? new Response(Uint8Array.from(bytes)) : new Response(null, { status: 404 })+ }++ /** Someone else saves the document, moving its revision on. */+ function saveElsewhere(id: string) {+ const doc = documents.get(id)+ if (doc) doc.revision = crypto.randomUUID()+ }++ const client = createCloudAPIClient('https://cloud.test/api', { fetch: api })+ return { client, objectFetch, saveElsewhere, objects }+}++function adapter(server: ReturnType<typeof cloudServer>) {+ return createCloudStorageAdapter(+ {+ preferences: {},+ resolveCredential: async () => null,+ profileId: 'server',+ containerId: WORKSPACE+ },+ { client: async () => server.client, objectFetch: server.objectFetch }+ )+}++describe('Cloud storage adapter', () => {+ test('creates the document on its first save and opens what it saved', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const bytes = new TextEncoder().encode('design')+ const saved = await storage.putDocument(id, bytes, { name: 'Landing page', updatedAt: '' })+ expect(saved.revision).toBeString()+ expect((await storage.listDocuments()).map((document) => document.name)).toEqual([+ 'Landing page'+ ])+ const opened = await storage.getDocument(id)+ expect(new TextDecoder().decode(opened.bytes)).toBe('design')+ expect(opened.revision).toBe(saved.revision)+ })++ test('saves on top of the revision it was edited from', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const first = await storage.putDocument(id, new Uint8Array([1]), { name: 'Doc', updatedAt: '' })+ const second = await storage.putDocument(+ id,+ new Uint8Array([2]),+ { name: 'Doc', updatedAt: '' },+ undefined,+ {+ baseRevision: first.revision+ }+ )+ expect(second.revision).not.toBe(first.revision)+ })++ test('refuses a save based on a revision someone else replaced', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const first = await storage.putDocument(id, new Uint8Array([1]), { name: 'Doc', updatedAt: '' })+ server.saveElsewhere(id)+ const stale = storage.putDocument(+ id,+ new Uint8Array([3]),+ { name: 'Doc', updatedAt: '' },+ undefined,+ {+ baseRevision: first.revision+ }+ )+ await expect(stale).rejects.toBeInstanceOf(StorageRevisionConflictError)+ })++ test('rejects bytes that do not match what the server stored', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const saved = await storage.putDocument(id, new Uint8Array([1, 2, 3]), {+ name: 'Doc',+ updatedAt: ''+ })+ server.objects.set(saved.revision ?? '', new Uint8Array([9, 9, 9]))+ await expect(storage.getDocument(id)).rejects.toThrow('does not match')+ })+})diff --git a/tests/app/storage/sync/revisions.test.ts b/tests/app/storage/sync/revisions.test.tsnew file mode 100644index 000000000..7da221f8f--- /dev/null+++ b/tests/app/storage/sync/revisions.test.ts@@ -0,0 +1,239 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import {+ resetStorageProviderRegistryForTests,+ StorageProviderRegistry,+ StorageRevisionConflictError,+ type StorageAdapter,+ type StorageLocation+} from '@/app/integrations/storage'+import { createMemoryLocalCanvasStore, type LocalCanvasStore } from '@/app/storage/local-store'+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'+import {+ createMemoryOutbox,+ getOutbox,+ keepBothVersions,+ kickSyncEngine,+ persistStorageCanvasLocally,+ replaceStoredVersion,+ resetOutboxForTests,+ takeStoredVersion+} from '@/app/storage/sync'++const location: StorageLocation = {+ providerId: 'test-provider',+ profileId: 'server-a',+ containerId: 'workspace-1'+}++/** A provider that keeps revisions and refuses writes based on a stale one, as Cloud does. */+function revisionedProvider() {+ const documents = new Map<string, { bytes: Uint8Array; revision: string; name: string }>()+ let counter = 0+ const writes: { id: string; base: string | null }[] = []+ // The Cloud adapter can report a conflict without being able to name the newer revision.+ let conflictsNameRevision = true+ const adapter: StorageAdapter = {+ async testConnection() {+ return { ok: true, message: '' }+ },+ async listDocuments() {+ return [...documents].map(([id, document]) => ({+ id,+ name: document.name,+ updatedAt: '',+ revision: document.revision+ }))+ },+ async getDocument(id) {+ const document = documents.get(id)+ if (!document) throw new Error('missing')+ return { bytes: document.bytes, revision: document.revision }+ },+ async putDocument(id, bytes, metadata, _progress, options) {+ const current = documents.get(id)+ const base = options?.baseRevision ?? null+ writes.push({ id, base })+ if (current && current.revision !== base) {+ throw new StorageRevisionConflictError(conflictsNameRevision ? current.revision : null)+ }+ counter += 1+ documents.set(id, { bytes, revision: `r${counter}`, name: metadata.name })+ return { revision: `r${counter}` }+ },+ async deleteDocument(id) {+ documents.delete(id)+ },+ async getUsage() {+ return { bytesUsed: 0, objectCount: 0, documentCount: documents.size }+ }+ }+ return {+ adapter,+ documents,+ writes,+ hideConflictRevisions() {+ conflictsNameRevision = false+ },+ /** Someone else saves a new revision on the provider. */+ saveElsewhere(id: string, bytes: Uint8Array) {+ counter += 1+ const name = documents.get(id)?.name ?? id+ documents.set(id, { bytes, revision: `r${counter}`, name })+ }+ }+}++let store: LocalCanvasStore+let provider: ReturnType<typeof revisionedProvider>++beforeEach(() => {+ store = createMemoryLocalCanvasStore()+ provider = revisionedProvider()+ resetLocalCanvasStoreForTests(store)+ resetOutboxForTests(createMemoryOutbox())+ resetStorageProviderRegistryForTests(+ new StorageProviderRegistry([+ {+ id: location.providerId,+ label: 'Test provider',+ description: '',+ preferenceFields: [],+ credentialFields: [],+ createAdapter: () => provider.adapter+ }+ ])+ )+})++afterEach(() => {+ resetLocalCanvasStoreForTests()+ resetOutboxForTests()+ resetStorageProviderRegistryForTests()+})++async function save(canvasId: string, bytes: number[], name = 'Design') {+ await persistStorageCanvasLocally({+ ...location,+ canvasId,+ name,+ figBytes: new Uint8Array(bytes)+ })+ await drain()+}++/** Runs the sync engine until the outbox has no work it can do now. */+async function drain() {+ for (let round = 0; round < 200; round++) {+ await kickSyncEngine()+ const ready = (await getOutbox().list()).filter((job) => job.nextAttemptAt <= Date.now())+ if (ready.length === 0) return+ // A pump already in flight owns the queue; let it finish before checking again.+ await new Promise((resolve) => {+ setTimeout(resolve, 1)+ })+ }+ throw new Error('The sync engine did not settle')+}++describe('storage revisions', () => {+ test('uploads each edit on top of the revision the previous upload created', async () => {+ await save('canvas-1', [1])+ await save('canvas-1', [1, 2])++ expect(provider.writes).toEqual([+ { id: 'canvas-1', base: null },+ { id: 'canvas-1', base: 'r1' }+ ])+ expect(await store.getMeta('canvas-1')).toMatchObject({+ syncStatus: 'synced',+ remoteRevision: 'r2',+ profileId: 'server-a',+ containerId: 'workspace-1'+ })+ })++ test('keeps both versions and waits for a choice when someone else saved first', async () => {+ await save('canvas-1', [1])+ provider.saveElsewhere('canvas-1', new Uint8Array([9]))+ await save('canvas-1', [1, 2])+ await save('canvas-2', [5])++ expect(await store.getMeta('canvas-1')).toMatchObject({+ syncStatus: 'conflict',+ remoteRevision: 'r1',+ conflictRevision: 'r2'+ })+ expect([...((await store.readFig('canvas-1')) ?? [])]).toEqual([1, 2])+ expect([...(provider.documents.get('canvas-1')?.bytes ?? [])]).toEqual([9])+ expect(await store.getMeta('canvas-2')).toMatchObject({ syncStatus: 'synced' })+ const parked = (await getOutbox().list()).filter((job) => job.canvasId === 'canvas-1')+ expect(parked.map((job) => job.nextAttemptAt)).toEqual([Number.MAX_SAFE_INTEGER])+ })++ test('taking the stored version discards local edits and their pending upload', async () => {+ await save('canvas-1', [1])+ provider.saveElsewhere('canvas-1', new Uint8Array([9]))+ await save('canvas-1', [1, 2])++ await takeStoredVersion('canvas-1')++ expect([...((await store.readFig('canvas-1')) ?? [])]).toEqual([9])+ expect(await store.getMeta('canvas-1')).toMatchObject({+ syncStatus: 'synced',+ remoteRevision: 'r2',+ conflictRevision: null+ })+ expect(await getOutbox().list()).toEqual([])+ })++ test('keeping both saves local edits as a new document beside the stored version', async () => {+ await save('canvas-1', [1])+ provider.saveElsewhere('canvas-1', new Uint8Array([9]))+ await save('canvas-1', [1, 2])++ const copyId = await keepBothVersions('canvas-1', 'Design (your copy)')+ await drain()++ expect(copyId).not.toBe('canvas-1')+ expect([...(provider.documents.get('canvas-1')?.bytes ?? [])]).toEqual([9])+ expect(provider.documents.get(copyId)).toMatchObject({ name: 'Design (your copy)' })+ expect([...(provider.documents.get(copyId)?.bytes ?? [])]).toEqual([1, 2])+ expect(await store.getMeta(copyId)).toMatchObject({ containerId: 'workspace-1' })+ })++ test('replacing uploads local edits over the newer stored version', async () => {+ await save('canvas-1', [1])+ provider.saveElsewhere('canvas-1', new Uint8Array([9]))+ await save('canvas-1', [1, 2])++ await replaceStoredVersion('canvas-1')+ await drain()++ expect([...(provider.documents.get('canvas-1')?.bytes ?? [])]).toEqual([1, 2])+ expect(await store.getMeta('canvas-1')).toMatchObject({+ syncStatus: 'synced',+ remoteRevision: 'r3',+ conflictRevision: null+ })+ })++ test('replacing looks up the newer revision when the conflict could not name it', async () => {+ provider.hideConflictRevisions()+ await save('canvas-1', [1])+ provider.saveElsewhere('canvas-1', new Uint8Array([9]))+ await save('canvas-1', [1, 2])+ expect(await store.getMeta('canvas-1')).toMatchObject({ conflictRevision: null })++ await replaceStoredVersion('canvas-1')+ await drain()++ expect([...(provider.documents.get('canvas-1')?.bytes ?? [])]).toEqual([1, 2])+ expect(await store.getMeta('canvas-1')).toMatchObject({ syncStatus: 'synced' })+ })++ test('refuses to resolve a document that has no conflict', async () => {+ await save('canvas-1', [1])+ await expect(takeStoredVersion('canvas-1')).rejects.toThrow()+ })+})diff --git a/tests/engine/app/integrations/storage/cancellation.test.ts b/tests/engine/app/integrations/storage/cancellation.test.tsindex 1a0ec0d53..c144affd3 100644--- a/tests/engine/app/integrations/storage/cancellation.test.ts+++ b/tests/engine/app/integrations/storage/cancellation.test.ts@@ -57,6 +57,7 @@ test('external storage cancellation remains an AbortError rather than a timeout'test('pre-aborted storage downloads do not resolve credentials or start network work', async () => {let credentialResolutions = 0const adapter = createS3StorageAdapter({+ profileId: 'default',preferences: {endpoint: 'https://storage.example.com',bucket: 'designs',diff --git a/tests/engine/app/integrations/storage/registry.test.ts b/tests/engine/app/integrations/storage/registry.test.tsindex bf076dad8..ee107a5f3 100644--- a/tests/engine/app/integrations/storage/registry.test.ts+++ b/tests/engine/app/integrations/storage/registry.test.ts@@ -24,11 +24,11 @@ class TestStorageAdapter implements StorageAdapter {}getDocument() {- return Promise.resolve(new Uint8Array())+ return Promise.resolve({ bytes: new Uint8Array(), revision: null })}putDocument() {- return Promise.resolve()+ return Promise.resolve({ revision: null })}deleteDocument() {diff --git a/tests/engine/app/recent-files/store.test.ts b/tests/engine/app/recent-files/store.test.tsindex 3a13cea15..1535c8694 100644--- a/tests/engine/app/recent-files/store.test.ts+++ b/tests/engine/app/recent-files/store.test.ts@@ -29,7 +29,10 @@ describe('recent documents', () => {test('tracks storage documents alongside local files', () => {rememberRecentFile('/tmp/local.fig')- rememberRecentStorageDocument('s3-compatible', 'remote-1', 'Remote design')+ rememberRecentStorageDocument(+ { providerId: 's3-compatible', documentId: 'remote-1' },+ 'Remote design'+ )expect(recentFiles.value.map(({ id, kind, name }) => ({ id, kind, name }))).toEqual([{@@ -42,6 +45,25 @@ describe('recent documents', () => {expect(recentLocalFileAt(0)).toBe('/tmp/local.fig')})+ test('keeps documents of different server profiles apart', () => {+ const document = {+ providerId: 'openpencil-cloud',+ containerId: 'workspace-1',+ documentId: 'doc-1'+ }+ rememberRecentStorageDocument({ ...document, profileId: 'server-a' }, 'On A')+ rememberRecentStorageDocument({ ...document, profileId: 'server-b' }, 'On B')++ expect(recentFiles.value.map(({ id, name }) => ({ id, name }))).toEqual([+ { id: 'storage:openpencil-cloud:server-b:doc-1', name: 'On B' },+ { id: 'storage:openpencil-cloud:server-a:doc-1', name: 'On A' }+ ])+ expect(recentFiles.value[0]).toMatchObject({+ profileId: 'server-b',+ containerId: 'workspace-1'+ })+ })+test('forgets missing local files and clears the list', () => {rememberRecentFile('/tmp/first.fig')rememberRecentFile('/tmp/second.fig')diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.tsindex 9674172ef..c92188810 100644--- a/tests/engine/app/shell/menu/schema.test.ts+++ b/tests/engine/app/shell/menu/schema.test.ts@@ -49,7 +49,7 @@ describe('APP_MENU_SCHEMA', () => {).filter((entry) => !('type' in entry) && entry.handler === 'shell')expect(shellEntries.map((entry) => ('type' in entry ? '' : entry.id))).toEqual([- 'open-storage-workspace',+ 'browse-files','open-tour','settings','view-design-issues',@@ -62,13 +62,15 @@ describe('APP_MENU_SCHEMA', () => {])})- test('includes storage workspace navigation in the shared File menu', () => {+ test('browses and saves to places from one File menu item each', () => {const fileMenu = APP_MENU_SCHEMA.find((group) => group.label === 'File')- const entries = fileMenu ? actionItems(fileMenu.items) : []-- expect(entries).toContainEqual(- expect.objectContaining({ id: 'open-storage-workspace', label: 'Open Storage Workspace…' })+ const ids = (fileMenu ? actionItems(fileMenu.items) : []).map((entry) =>+ 'type' in entry ? '' : entry.id)++ expect(ids).toContain('browse-files')+ expect(ids).toContain('save-to')+ expect(ids).not.toContain('save-to-cloud')})test('exposes recent files through the native File menu', () => {diff --git a/tests/engine/app/tabs/open-file-dedup.test.ts b/tests/engine/app/tabs/open-file-dedup.test.tsindex 2de2e7dd2..a345c4e1b 100644--- a/tests/engine/app/tabs/open-file-dedup.test.ts+++ b/tests/engine/app/tabs/open-file-dedup.test.ts@@ -56,7 +56,7 @@ function acknowledgePendingPresentation(): void {type FileOpenOutcome = { status: 'fulfilled' } | { status: 'rejected'; reason: unknown }-async function settleFileOpen(opening: Promise<void>): Promise<void> {+async function settleFileOpen(opening: Promise<unknown>): Promise<void> {const outcome: Promise<FileOpenOutcome> = opening.then(() => ({ status: 'fulfilled' }),(reason: unknown) => ({ status: 'rejected', reason })diff --git a/tests/engine/text/fonts/web-fonts.test.ts b/tests/engine/text/fonts/web-fonts.test.tsindex a99f707b3..f8b3743b1 100644--- a/tests/engine/text/fonts/web-fonts.test.ts+++ b/tests/engine/text/fonts/web-fonts.test.ts@@ -52,6 +52,39 @@ describe('web font coverage requests', () => {blocked.resolve(new Response('{}', { status: 200 }))})+ test('proxies only font provider requests while a provider resolves', async () => {+ const resolver = new WebFontResolver()+ resolver.setEnabled({ google: true })+ const started = Promise.withResolvers<undefined>()+ const blocked = Promise.withResolvers<Response>()+ const proxied: string[] = []+ resolver.setRemoteFetch(async (url) => {+ proxied.push(url)+ started.resolve(undefined)+ return blocked.promise+ })+ const originalFetch = globalThis.fetch+ const direct: string[] = []+ globalThis.fetch = Object.assign(+ async (input: RequestInfo | URL) => {+ direct.push(input instanceof Request ? input.url : input.toString())+ return new Response('{}')+ },+ { preconnect: originalFetch.preconnect }+ )+ try {+ const loading = resolver.listFamilies('google')+ await started.promise+ await fetch('https://cloud.example.com/api/session')+ expect(direct).toEqual(['https://cloud.example.com/api/session'])+ expect(proxied).not.toContain('https://cloud.example.com/api/session')+ blocked.resolve(new Response('{}', { status: 200 }))+ await loading+ } finally {+ globalThis.fetch = originalFetch+ }+ })+test('requests script-specific subsets instead of Latin only', () => {expect(webFontSubsetsForText('مرحبا')).toContain('arabic')expect(webFontSubsetsForText('한글')).toContain('korean')diff --git a/tests/helpers/cloud/discovery.ts b/tests/helpers/cloud/discovery.tsnew file mode 100644index 000000000..ea59ad24b--- /dev/null+++ b/tests/helpers/cloud/discovery.ts@@ -0,0 +1,22 @@+import { CLOUD_PROTOCOL_VERSION, type CloudDiscovery } from '@open-pencil/cloud/contract'++/** A Cloud server's discovery at `origin`, with email sign-in and an editor at `appURL`. */+export function cloudDiscoveryFixture(+ origin = 'https://cloud.example.com',+ appURL = 'https://app.example.com'+): CloudDiscovery {+ return {+ protocolVersion: CLOUD_PROTOCOL_VERSION,+ deployment: 'self-hosted',+ apiURL: `${origin}/api`,+ authURL: `${origin}/api/auth`,+ appURL,+ authentication: {+ socialProviders: ['google'],+ enterpriseSSO: false,+ enrollmentMode: 'approval',+ emailPassword: { signIn: true, signUp: true, minimumPasswordLength: 8 }+ },+ capabilities: { documents: true, workspaces: true, collaboration: true }+ }+}diff --git a/tests/helpers/collab/relay-server.ts b/tests/helpers/collab/relay-server.tsnew file mode 100644index 000000000..567cc17c0--- /dev/null+++ b/tests/helpers/collab/relay-server.ts@@ -0,0 +1,73 @@+import { createServer } from 'node:http'++import { RELAY_PATH, type DocumentPermission } from '@open-pencil/cloud/contract'+import { attachCollaborationRelay } from '@open-pencil/cloud/runtime/node'+import {+ createCollaborationRelay,+ signCollaborationTicket,+ type CollaborationStateStore+} from '@open-pencil/cloud/server'++import { createCloudRelayJoin } from '@/app/collab/transport/cloud'++const AUTH_SECRET = 'relay-integration-secret-at-least-32-characters'++/** A Cloud relay on a loopback port, keeping room state in memory; `close` stops it. */+export async function startTestRelay() {+ const states = new Map<string, Uint8Array>()+ const store: CollaborationStateStore = {+ load: async (room) => states.get(`${room.documentId}:${room.roomEpoch}`) ?? null,+ store: async (room, state) => {+ states.set(`${room.documentId}:${room.roomEpoch}`, state)+ }+ }+ const relay = createCollaborationRelay({+ authSecret: AUTH_SECRET,+ store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 10,+ persistDelayMs: 0+ })+ const server = createServer()+ const attached = attachCollaborationRelay(server, relay, 1_048_576)+ await new Promise<void>((resolve) => {+ server.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address()+ if (!address || typeof address === 'string') throw new Error('Expected a TCP address')+ const url = `ws://127.0.0.1:${address.port}${RELAY_PATH}`+ return {+ url,+ states,+ /** Joins a document's room with the given permission, as a guest or a signed-in user. */+ join(+ documentId: string,+ name: string,+ permission: DocumentPermission,+ kind: 'guest' | 'user' = 'guest'+ ) {+ const principal =+ kind === 'user'+ ? { kind, userId: crypto.randomUUID(), name, email: `${name.toLowerCase()}@example.com` }+ : { kind, guestId: crypto.randomUUID(), name }+ return createCloudRelayJoin({+ url,+ ticket: async () =>+ signCollaborationTicket({+ authSecret: AUTH_SECRET,+ documentId,+ principal,+ permission,+ roomEpoch: 0,+ relayURL: url+ })+ })+ },+ async close() {+ await attached.close()+ await new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ }+ }+}diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.tsindex 3af326e0a..e5684e832 100644--- a/tests/integration/collab/cloud-relay.test.ts+++ b/tests/integration/collab/cloud-relay.test.ts@@ -1,21 +1,22 @@+import 'fake-indexeddb/auto'import { afterEach, describe, expect, test } from 'bun:test'-import { createServer } from 'node:http'+import { compact } from 'es-toolkit'import * as awarenessProtocol from 'y-protocols/awareness'import * as Y from 'yjs'-import { RELAY_PATH, type DocumentPermission } from '@open-pencil/cloud/contract'-import { attachCollaborationRelay } from '@open-pencil/cloud/runtime/node'-import {- createCollaborationRelay,- signCollaborationTicket,- type CollaborationStateStore-} from '@open-pencil/cloud/server'+import type { DocumentPermission } from '@open-pencil/cloud/contract'+import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'+import { openCloudDocumentRoom } from '@/app/cloud/rooms/live'import { connectCollabRoom } from '@/app/collab/room/connection'-import { createCloudRelayJoin } from '@/app/collab/transport/cloud'+import { createEditorStore } from '@/app/editor/session'++import { startTestRelay } from '#tests/helpers/collab/relay-server'++type Relay = Awaited<ReturnType<typeof startTestRelay>>-const authSecret = 'relay-integration-secret-at-least-32-characters'const documentId = crypto.randomUUID()const roomId = `cloud:${documentId}:0`@@ -36,51 +37,15 @@ async function until(condition: () => boolean, attempts = 500): Promise<void> {}async function startRelay() {- const states = new Map<string, Uint8Array>()- const store: CollaborationStateStore = {- load: async (room) => states.get(`${room.documentId}:${room.roomEpoch}`) ?? null,- store: async (room, state) => {- states.set(`${room.documentId}:${room.roomEpoch}`, state)- }- }- const relay = createCollaborationRelay({- authSecret,- store,- maximumMessageBytes: 1_048_576,- maximumConnectionsPerRoom: 10,- persistDelayMs: 0- })- const server = createServer()- const attached = attachCollaborationRelay(server, relay, 1_048_576)- await new Promise<void>((resolve) => {- server.listen(0, '127.0.0.1', resolve)- })- const address = server.address()- if (!address || typeof address === 'string') throw new Error('Expected a TCP address')- cleanups.push(async () => {- await attached.close()- await new Promise<void>((resolve) => {- server.close(() => resolve())- })- })- return { url: `ws://127.0.0.1:${address.port}${RELAY_PATH}`, states }+ const relay = await startTestRelay()+ cleanups.push(() => relay.close())+ return relay}-function joinAs(url: string, name: string, permission: DocumentPermission) {+function joinAs(relay: Relay, name: string, permission: DocumentPermission) {const ydoc = new Y.Doc()const awareness = new awarenessProtocol.Awareness(ydoc)- const join = createCloudRelayJoin({- url,- ticket: async () =>- signCollaborationTicket({- authSecret,- documentId,- principal: { kind: 'guest', guestId: crypto.randomUUID(), name },- permission,- roomEpoch: 0,- relayURL: url- })- })+ const join = relay.join(documentId, name, permission)const connection = connectCollabRoom({roomId,ydoc,@@ -105,26 +70,27 @@ function joinAs(url: string, name: string, permission: DocumentPermission) {describe('collaboration through the Cloud relay', () => {test('editors sync live and newcomers get the document from the relay', async () => {- const { url } = await startRelay()- const alice = joinAs(url, 'Alice', 'edit')+ const relay = await startRelay()+ const alice = joinAs(relay, 'Alice', 'edit')await until(() => alice.connection.room.signalingConnected())alice.ydoc.getText('t').insert(0, 'hello')- const bob = joinAs(url, 'Bob', 'edit')+ const bob = joinAs(relay, 'Bob', 'edit')await until(() => bob.text() === 'hello')bob.ydoc.getText('t').insert(5, ' world')await until(() => alice.text() === 'hello world')await alice.leave()await bob.leave()- const carol = joinAs(url, 'Carol', 'view')+ const carol = joinAs(relay, 'Carol', 'view')await until(() => carol.text() === 'hello world')})test('viewers receive edits but their own never reach anyone', async () => {- const { url, states } = await startRelay()- const editor = joinAs(url, 'Editor', 'edit')- const viewer = joinAs(url, 'Viewer', 'view')+ const relay = await startRelay()+ const { states } = relay+ const editor = joinAs(relay, 'Editor', 'edit')+ const viewer = joinAs(relay, 'Viewer', 'view')await until(() =>editor.connection.room.signalingConnected() && viewer.connection.room.signalingConnected()@@ -143,9 +109,9 @@ describe('collaboration through the Cloud relay', () => {})test('presence carries the name on the ticket, not the one a peer claims', async () => {- const { url } = await startRelay()- const editor = joinAs(url, 'Editor', 'edit')- const guest = joinAs(url, 'Grace', 'view')+ const relay = await startRelay()+ const editor = joinAs(relay, 'Editor', 'edit')+ const guest = joinAs(relay, 'Grace', 'view')await until(() =>editor.connection.room.signalingConnected() && guest.connection.room.signalingConnected()@@ -158,3 +124,144 @@ describe('collaboration through the Cloud relay', () => {})})})++/** Tabs that each opened the same stored file, which gives each its own root. */+async function openedTwice() {+ await initCodec()+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected a page')+ graph.createNode('RECTANGLE', page.id, { name: 'Card' })+ const bytes = await exportFigFile(graph)+ const open = async () => createEditorStore(await parseFigFile(Uint8Array.from(bytes).buffer))+ const stores = [await open(), await open()] as const+ for (const store of stores) cleanups.push(() => store.preparationController.dispose())+ return stores+}++describe('Cloud document rooms', () => {+ test('tabs that opened the stored file edit one document, and one of them saves', async () => {+ const relay = await startRelay()+ // Rooms keep a saved copy per room, so each test gets a document of its own.+ const documentId = crypto.randomUUID()+ const roomId = `cloud:${documentId}:0`+ const [grace, ada] = await openedTwice()+ const first = openCloudDocumentRoom(grace, {+ roomId,+ transport: relay.join(documentId, 'Grace', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ first.stop()+ first.session.dispose()+ })+ await until(() => first.session.roomHasDocument())+ const second = openCloudDocumentRoom(ada, {+ roomId,+ transport: relay.join(documentId, 'Ada', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ second.stop()+ second.session.dispose()+ })+ await until(() => second.session.hasDocument.value && second.session.peers.value.length > 0)++ const page = ada.graph.getPages()[0]+ if (!page) throw new Error('Expected a page')+ ada.graph.createNode('ELLIPSE', page.id, { id: 'from:ada', name: 'Dot' })+ await until(() => grace.graph.getNode('from:ada') !== undefined)+ await until(() => first.session.peers.value.length > 0)+ expect(compact([grace.state.autosaveEnabled, ada.state.autosaveEnabled])).toHaveLength(1)+ })+})++describe('Cloud document rooms, live order', () => {+ test('a shape drawn before someone joins is still there for both', async () => {+ const relay = await startRelay()+ // Rooms keep a saved copy per room, so each test gets a document of its own.+ const documentId = crypto.randomUUID()+ const roomId = `cloud:${documentId}:0`+ await initCodec()+ const grace = createEditorStore(new SceneGraph())+ cleanups.push(() => grace.preparationController.dispose())+ const first = openCloudDocumentRoom(grace, {+ roomId,+ transport: relay.join(documentId, 'Grace', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ first.stop()+ first.session.dispose()+ })+ await until(() => first.session.roomHasDocument())+ const page = grace.graph.getPages()[0]+ if (!page) throw new Error('Expected a page')+ grace.graph.createNode('RECTANGLE', page.id, { name: 'Card' })++ const bytes = await exportFigFile(grace.graph)+ const ada = createEditorStore(await parseFigFile(Uint8Array.from(bytes).buffer))+ cleanups.push(() => ada.preparationController.dispose())+ const second = openCloudDocumentRoom(ada, {+ roomId,+ transport: relay.join(documentId, 'Ada', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ second.stop()+ second.session.dispose()+ })+ // A joiner keeps its own earlier copy outside the document; only the document's layers count.+ const rectangles = (store: typeof grace) =>+ [...store.graph.getAllNodes()].filter(+ (node) =>+ node.type === 'RECTANGLE' &&+ store.graph.closest(node.id, (ancestor) => ancestor.id === store.graph.rootId)+ ).length+ await until(() => second.session.hasDocument.value && rectangles(ada) === 1)+ // Ada's updates arrive in order, so a copy pushed into the room would land before this marker.+ const adaPage = ada.graph.getPages()[0]+ if (!adaPage) throw new Error('Expected a page')+ ada.graph.createNode('ELLIPSE', adaPage.id, { id: 'from:ada', name: 'Marker' })+ await until(() => grace.graph.getNode('from:ada') !== undefined)+ expect(rectangles(grace)).toBe(1)+ expect(rectangles(ada)).toBe(1)+ })+})++describe('Cloud document rooms, drawing early', () => {+ test('a shape drawn before the relay answers is in the room once it is seeded', async () => {+ const relay = await startRelay()+ const documentId = crypto.randomUUID()+ const roomId = `cloud:${documentId}:0`+ const grace = createEditorStore(new SceneGraph())+ cleanups.push(() => grace.preparationController.dispose())+ const first = openCloudDocumentRoom(grace, {+ roomId,+ transport: relay.join(documentId, 'Grace', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ first.stop()+ first.session.dispose()+ })+ const page = grace.graph.getPages()[0]+ if (!page) throw new Error('Expected a page')+ grace.graph.createNode('RECTANGLE', page.id, { id: 'early:card', name: 'Card' })+ await until(() => first.session.roomHasDocument())+ expect(grace.graph.getNode('early:card')?.parentId).toBe(page.id)++ const watcher = createEditorStore(new SceneGraph())+ cleanups.push(() => watcher.preparationController.dispose())+ const second = openCloudDocumentRoom(watcher, {+ roomId,+ transport: relay.join(documentId, 'Ada', 'edit', 'user'),+ permission: 'edit'+ })+ cleanups.push(() => {+ second.stop()+ second.session.dispose()+ })+ await until(() => watcher.graph.getNode('early:card') !== undefined)+ })+})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 06414fe0d..46090bc54 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -446,6 +446,7 @@ zh-cn:storage.waitlistUnavailablezh-cn:statuses.figmaShowszh-cn:statuses.presetHandoffja:cloudPortal.signInTitle+ja:cloudPortal.newHereja:cloudPortal.returnsToDesktopja:cloudPortal.continueWithGoogleja:cloudPortal.continueWithApple@@ -456,6 +457,7 @@ ja:cloudPortal.deviceApprovedDescriptionja:cloudPortal.deviceExpiredDescriptionja:cloudPortal.authenticatorOffzh-cn:cloudPortal.signInTitle+zh-cn:cloudPortal.newHerezh-cn:cloudPortal.returnsToDesktopzh-cn:cloudPortal.continueWithGooglezh-cn:cloudPortal.continueWithApple@@ -465,3 +467,35 @@ zh-cn:cloudPortal.deviceWarningDescriptionzh-cn:cloudPortal.deviceApprovedDescriptionzh-cn:cloudPortal.deviceExpiredDescriptionzh-cn:cloudPortal.authenticatorOff+ja:cloud.connectHeading+ja:cloud.connectServerDescription+ja:cloud.officialDescription+ja:cloud.selfHostedDescription+ja:cloud.errorInvalidAddressDescription+ja:cloud.errorNotCloudHeading+ja:cloud.errorNotCloudDescription+ja:cloud.errorOutdatedDescription+ja:cloud.continueWithGoogle+ja:cloud.continueWithApple+ja:cloud.shareDescriptionInWorkspace+ja:cloud.shareDescription+ja:cloud.settingsOfficialDescription+ja:cloud.settingsSelfHostedDescription+ja:cloudPortal.errorEmailInvalid+ja:cloudPortal.verifiedDescription+zh-cn:cloud.connectHeading+zh-cn:cloud.connectServerDescription+zh-cn:cloud.officialDescription+zh-cn:cloud.selfHostedDescription+zh-cn:cloud.errorInvalidAddressDescription+zh-cn:cloud.errorNotCloudHeading+zh-cn:cloud.errorNotCloudDescription+zh-cn:cloud.errorOutdatedDescription+zh-cn:cloud.continueWithGoogle+zh-cn:cloud.continueWithApple+zh-cn:cloud.shareDescriptionInWorkspace+zh-cn:cloud.shareDescription+zh-cn:cloud.settingsOfficialDescription+zh-cn:cloud.settingsSelfHostedDescription+zh-cn:cloudPortal.errorEmailInvalid+zh-cn:cloudPortal.verifiedDescriptiondiff --git a/tools/checks/i18n/src/check-locales.ts b/tools/checks/i18n/src/check-locales.tsindex 52e176532..efaf53df6 100644--- a/tools/checks/i18n/src/check-locales.ts+++ b/tools/checks/i18n/src/check-locales.ts@@ -1,6 +1,6 @@#!/usr/bin/env bunimport { existsSync, readFileSync, readdirSync } from 'node:fs'-import { join } from 'node:path'+import { join, relative, sep } from 'node:path'import { compact } from 'es-toolkit/array'import * as v from 'valibot'@@ -16,10 +16,16 @@ import {import { hasMixedLatinAndCjk, placeholders } from './quality'const LOCALES_DIR = 'packages/vue/src/i18n/locales'+/**+ * Where a namespace's translations live under each locale, when not at `<namespace>.json`.+ * Namespaces of one domain share a folder (`cloud/editor`, `cloud/portal`), not a file prefix.+ */const LOCALE_FILE_NAMES: Record<string, string> = {- cloudPortal: 'cloud-portal',+ cloud: 'cloud/editor',+ cloudPortal: 'cloud/portal',designCheck: 'design-check',- variableTypes: 'variable-types'+ variables: 'variables/panel',+ variableTypes: 'variables/types'}const REQUIRED_INDEX_FILE = 'index.ts'const TRANSLATION_BASELINE_PATH = 'tools/checks/i18n/translation-baseline.txt'@@ -125,7 +131,10 @@ for (const [locale, dir] of expectedLocaleDirs) {const localeDir = join(LOCALES_DIR, dir)if (!existsSync(localeDir)) continue- const files = readdirSync(localeDir)+ // Paths below the locale folder, with `/` separators on every platform.+ const files = readdirSync(localeDir, { recursive: true, withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => relative(localeDir, join(entry.parentPath, entry.name)).split(sep).join('/'))if (!files.includes(REQUIRED_INDEX_FILE)) {report(`\n${locale}: missing ${REQUIRED_INDEX_FILE}`)}diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 5ccc44680..83def7027 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -440,3 +440,35 @@ ru:cloudPortal.providerAppleru:cloudPortal.deploymentOfficialru:cloudPortal.emailTransportSMTPru:cloudPortal.emailTransportCloudflare+de:settings.cloud+fr:settings.cloud+it:settings.cloud+es:cloud.productName+es:cloud.roleEditor+es:cloud.homeCloudOnHost+it:cloud.productName+it:cloud.server+it:cloud.roleEditor+it:cloud.homeAccount+it:cloud.homeCloudOnHost+it:cloud.settingsTitle+ja:cloud.productName+ja:cloud.homeCloudOnHost+ja:cloud.inviteEmailPlaceholder+zh-cn:cloud.productName+zh-cn:cloud.homeCloudOnHost+zh-cn:cloud.inviteEmailPlaceholder+de:cloud.productName+de:cloud.server+de:cloud.saveName+de:cloud.homeCloudOnHost+de:cloud.inviteEmailPlaceholder+de:cloud.settingsTitle+fr:cloud.productName+fr:cloud.homeCloudOnHost+fr:cloud.settingsTitle+pl:cloud.productName+pl:cloud.homeCloudOnHost+ru:cloud.productName+ru:cloud.homeCloudOnHost+ru:cloud.inviteEmailPlaceholderdiff --git a/tools/generate/tauri-menu/src/menu.ts b/tools/generate/tauri-menu/src/menu.tsindex 760da433f..671715809 100644--- a/tools/generate/tauri-menu/src/menu.ts+++ b/tools/generate/tauri-menu/src/menu.ts@@ -27,6 +27,7 @@ function cleanEntry(entry: AppMenuEntry): unknown | null {label: entry.label,accelerator: entryAccelerator(entry),checkbox: entry.checkbox,+ feature: entry.feature,sub: entry.sub ? compact(entry.sub.map(cleanEntry)) : undefined}}