AI-native design editor. Open-source Figma alternative.
fix: share documents from the mobile Share button (#1310)
Danila Poyarkov2de6cf7a07e7
diff --git a/changes/1310/changed.md b/changes/1310/changed.mdnew file mode 100644index 000000000..53973f4c0--- /dev/null+++ b/changes/1310/changed.md@@ -0,0 +1 @@+- On phones, Share sends a room link through the system share sheet (Messages, Mail, AirDrop) instead of only copying it; browsers without a share sheet still copy the link.diff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonindex dc9d75842..f63747600 100644--- a/packages/vue/src/i18n/locales/de/cloud/editor.json+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -114,6 +114,7 @@"shareResetLink": "Link zurücksetzen","shareLinkCopied": "Link kopiert","shareCopyLink": "Link kopieren",+ "shareSendLink": "Link teilen","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",diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonindex d75e90734..7c917d9db 100644--- a/packages/vue/src/i18n/locales/es/cloud/editor.json+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -114,6 +114,7 @@"shareResetLink": "Restablecer enlace","shareLinkCopied": "Enlace copiado","shareCopyLink": "Copiar enlace",+ "shareSendLink": "Compartir 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",diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonindex be79cfa5a..9128f8e62 100644--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -114,6 +114,7 @@"shareResetLink": "Réinitialiser le lien","shareLinkCopied": "Lien copié","shareCopyLink": "Copier le lien",+ "shareSendLink": "Partager 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",diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonindex e48e0e6ab..6c97ba86b 100644--- a/packages/vue/src/i18n/locales/it/cloud/editor.json+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -114,6 +114,7 @@"shareResetLink": "Reimposta link","shareLinkCopied": "Link copiato","shareCopyLink": "Copia link",+ "shareSendLink": "Condividi 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",diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonindex 6397b1261..464f2a7e9 100644--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -113,6 +113,7 @@"shareResetLink": "リンクをリセット","shareLinkCopied": "リンクをコピーしました","shareCopyLink": "リンクをコピー",+ "shareSendLink": "リンクを共有","shareLoadFailed": "アクセスできるユーザーを読み込めませんでした。接続を確認して、もう一度お試しください。","shareChangeFailed": "変更を反映できませんでした。しばらくしてからもう一度お試しください。","conflictKeepBoth": "両方を残す",diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonindex 0e791227f..878141a19 100644--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -115,6 +115,7 @@"shareResetLink": "Zresetuj link","shareLinkCopied": "Skopiowano link","shareCopyLink": "Kopiuj link",+ "shareSendLink": "Udostępnij 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",diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonindex 2a0ef7b1c..9debbda31 100644--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -115,6 +115,7 @@"shareResetLink": "Сбросить ссылку","shareLinkCopied": "Ссылка скопирована","shareCopyLink": "Скопировать ссылку",+ "shareSendLink": "Поделиться ссылкой","shareLoadFailed": "Не удалось загрузить список доступа. Проверьте подключение и попробуйте снова.","shareChangeFailed": "Изменение не применилось. Попробуйте чуть позже.","conflictKeepBoth": "Оставить обе",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonindex 7f4e3c225..8b0fd1f8c 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -113,6 +113,7 @@"shareResetLink": "重置链接","shareLinkCopied": "链接已复制","shareCopyLink": "复制链接",+ "shareSendLink": "分享链接","shareLoadFailed": "无法加载访问权限列表。请检查网络连接后重试。","shareChangeFailed": "更改未能生效。请稍后重试。","conflictKeepBoth": "保留两者",diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsindex acb53e83f..400b0e3d1 100644--- a/packages/vue/src/i18n/messages/cloud/editor.ts+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -156,6 +156,7 @@ export const cloudMessageDefaults = {shareResetLink: 'Reset link',shareLinkCopied: 'Link copied',shareCopyLink: 'Copy link',+ shareSendLink: 'Share 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.',diff --git a/src/app/cloud/integration/index.ts b/src/app/cloud/integration/index.tsindex a84f34f52..fc002009a 100644--- a/src/app/cloud/integration/index.ts+++ b/src/app/cloud/integration/index.ts@@ -8,6 +8,7 @@ import { startCloudSessions } from '../sessions/startup'export { cloudDocumentAddress } from '../documents/link'export { isCloudBinding } from '../documents/status'+export { openCloudShare } from '../sharing/dialog'export { cloudSaveDestinations, cloudUploadFailure, signInToSaveTo } from '../documents/save'export { useHomeCloud } from '../home'export { CLOUD_STORAGE_PROVIDER_ID } from '../sessions/token'diff --git a/src/app/cloud/integration/off/index.ts b/src/app/cloud/integration/off/index.tsindex 5099b8bfa..57cd51101 100644--- a/src/app/cloud/integration/off/index.ts+++ b/src/app/cloud/integration/off/index.ts@@ -32,6 +32,9 @@ export function isVersionHistoryOpen(): boolean {return false}+export function openCloudShare(): boolean {+ return false+}export const openVersionDialog = noopexport const openVersionHistory = noopdiff --git a/src/app/cloud/sharing/dialog.ts b/src/app/cloud/sharing/dialog.tsindex 06838b0bb..21fcf50b2 100644--- a/src/app/cloud/sharing/dialog.ts+++ b/src/app/cloud/sharing/dialog.ts@@ -1,4 +1,19 @@import { ref } from 'vue'+import type { EditorStore } from '@/app/editor/session'++import { cloudShareTarget } from './document'+/** The open document's Cloud share dialog, opened from the Share button or its status. */export const cloudShareOpen = ref(false)++/**+ * Opens the share dialog of the Cloud document in `store`, as the mobile Share button does;+ * false when there is nothing to share yet, such as while signed out of its server.+ */+export function openCloudShare(store: EditorStore): boolean {+ const binding = store.getStorageBinding()+ if (!binding || !cloudShareTarget(binding)) return false+ cloudShareOpen.value = true+ return true+}diff --git a/src/app/cloud/sharing/use.ts b/src/app/cloud/sharing/use.tsnew file mode 100644index 000000000..754685d44--- /dev/null+++ b/src/app/cloud/sharing/use.ts@@ -0,0 +1,118 @@+import { ref, shallowRef, toValue, watch, type MaybeRefOrGetter } from 'vue'++import type { DocumentPermission } from '@open-pencil/cloud/contract'++import {+ changeCloudLink,+ changeCloudMember,+ cloudLinkURL,+ inviteToCloudDocument,+ readCloudSharing,+ resetCloudLink,+ type cloudShareTarget,+ type CloudShareLink,+ type CloudSharing+} from './document'++type ShareTarget = NonNullable<ReturnType<typeof cloudShareTarget>>++/** Which document on which server, for which account: what the sharing on show belongs to. */+function identityOf(target: ShareTarget | null): string | null {+ return target ? `${target.server.id}\u0000${target.accountId}\u0000${target.documentId}` : null+}++/**+ * Who can open a Cloud document and its link, as its server keeps them, and the changes the share+ * dialog makes. Each change reads the sharing again, so the dialog shows what the server kept;+ * operations report whether they worked and leave telling the person to the caller.+ */+export function useCloudSharing(target: MaybeRefOrGetter<ShareTarget | null>) {+ const sharing = shallowRef<CloudSharing | null>(null)+ /**+ * The document's link, ready before anyone asks: a share sheet opens only straight from a tap,+ * so the link cannot be fetched after it.+ */+ const linkURL = shallowRef<string | null>(null)+ const inviting = ref(false)+ // Each read is numbered so a slower earlier one never replaces a newer one.+ let latestRead = 0++ // Another document's members and link never show, or take changes, while this one's load.+ watch(+ () => identityOf(toValue(target)),+ () => {+ sharing.value = null+ linkURL.value = null+ }+ )++ /**+ * Reads the document's sharing, then its link; false when either could not be read. Members and+ * access show even when the link does not, which then stays empty rather than out of date.+ */+ async function refresh(): Promise<boolean> {+ const current = toValue(target)+ if (!current) return true+ const read = ++latestRead+ const still = () => read === latestRead && identityOf(toValue(target)) === identityOf(current)+ let next: CloudSharing+ try {+ next = await readCloudSharing(current)+ } catch {+ return !still()+ }+ if (!still()) return true+ sharing.value = next+ if (next.link.access !== 'link') {+ linkURL.value = null+ return true+ }+ try {+ const url = await cloudLinkURL(current)+ if (still()) linkURL.value = url+ return true+ } catch {+ if (still()) linkURL.value = null+ return !still()+ }+ }++ /**+ * Runs a change on the server and reads what it left; false when the change failed or what it+ * left could not be read. The link is dropped first, since a change such as a reset retires it.+ */+ async function change(run: (current: ShareTarget) => Promise<void>): Promise<boolean> {+ const current = toValue(target)+ if (!current) return true+ linkURL.value = null+ let changed = true+ try {+ await run(current)+ } catch {+ changed = false+ }+ const read = await refresh()+ return changed && read+ }++ async function invite(email: string, permission: DocumentPermission): Promise<boolean> {+ inviting.value = true+ try {+ return await change((current) => inviteToCloudDocument(current, email, permission))+ } finally {+ inviting.value = false+ }+ }++ return {+ sharing,+ linkURL,+ inviting,+ refresh,+ invite,+ changeMember: (id: string, permission: DocumentPermission | 'remove') =>+ change((current) => changeCloudMember(current, id, permission)),+ changeLink: (link: CloudShareLink) => change((current) => changeCloudLink(current, link)),+ resetLink: () => change((current) => resetCloudLink(current))+ }+}diff --git a/src/app/shell/share/link.ts b/src/app/shell/share/link.tsnew file mode 100644index 000000000..4535fdee8--- /dev/null+++ b/src/app/shell/share/link.ts@@ -0,0 +1,37 @@+import { useClipboard, useShare } from '@vueuse/core'+import { computed } from 'vue'++import { useViewportKind } from '@open-pencil/vue'++/** How a link went out: through the system share sheet, onto the clipboard, or not at all. */+export type SentLink = 'shared' | 'copied' | 'cancelled'++/**+ * Sends a link the way the device does: on a phone through the system share sheet, as other apps+ * send theirs, and elsewhere, or where the browser has no sheet, by copying it. Call it straight+ * from the tap, before anything awaits, since the sheet opens only then.+ */+export function useSendLink() {+ const { share, isSupported } = useShare()+ const { copy, copied } = useClipboard({ legacy: true })+ const { isMobile } = useViewportKind()+ const sendsLink = computed(() => isMobile.value && isSupported.value)++ async function send(url: string, title?: string): Promise<SentLink> {+ if (!sendsLink.value) {+ await copy(url)+ return 'copied'+ }+ try {+ await share({ title, url })+ return 'shared'+ } catch (error) {+ // Closing the sheet without sending is a choice; any other failure still gets the link out.+ if (error instanceof DOMException && error.name === 'AbortError') return 'cancelled'+ await copy(url)+ return 'copied'+ }+ }++ return { sendsLink, copied, send }+}diff --git a/src/components/MobileHud/context.ts b/src/components/MobileHud/context.tsindex 2e0cc0d09..ceda51f91 100644--- a/src/components/MobileHud/context.ts+++ b/src/components/MobileHud/context.ts@@ -1,4 +1,3 @@-import { useClipboard } from '@vueuse/core'import { computed, inject, provide, proxyRefs } from 'vue'import type { InjectionKey, ShallowUnwrapRef } from 'vue'import IconFilePlus from '~icons/lucide/file-plus'@@ -9,6 +8,7 @@ import IconZoomIn from '~icons/lucide/zoom-in'import { useEditorCommands, useI18n } from '@open-pencil/vue'+import { isCloudBinding, openCloudShare } from '@/app/cloud/integration'import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'import { useActiveEditorStoreRef, useEditorStore } from '@/app/editor/active-store'import { toolIcons } from '@/app/editor/icons'@@ -16,6 +16,7 @@ import { useNotificationMessages } from '@/app/i18n/notifications'import { presenceOf, renameAgent as renameLocalAgent } from '@/app/presence/registry'import type { FollowTarget } from '@/app/presence/types'import { openFileDialog } from '@/app/shell/menu/use'+import { useSendLink } from '@/app/shell/share/link'import { toast } from '@/app/shell/ui'import { roomStatusText } from '@/components/collab-room/statusText'import { presenceRows } from '@/components/presence/rows'@@ -27,7 +28,7 @@ type MenuAction = ToolbarActionItemfunction createMobileHudContext() {const collab = useCollabInjected()const store = useEditorStore()- const { copy } = useClipboard()+ const { send } = useSendLink()const { common, collaboration } = useI18n()const notifications = useNotificationMessages()const { getCommand } = useEditorCommands()@@ -83,13 +84,22 @@ function createMobileHudContext() {: '')- /** Copies the room's link; a tab not in a room is shared first, never a room it opened. */- function share() {+ /**+ * Shares the document. A Cloud document opens its share dialog, where its server decides who+ * may open it. Anything else goes into a room, shared first if it is not in one, never a room it+ * opened, and its link goes out through the system share sheet, or is copied without one.+ */+ async function share() {+ // A Cloud document shares through its server; signed out, there is nothing to open yet.+ if (isCloudBinding(store.getStorageBinding())) {+ openCloudShare(store)+ return+ }if (!collab) returnconst roomId = collabState.value.roomId ?? collab.shareCurrentDoc()if (!roomId) return- void copy(getShareURL(roomId))- toast.info(notifications.value.linkCopied)+ const sent = await send(getShareURL(roomId), store.state.documentName)+ if (sent === 'copied') toast.info(notifications.value.linkCopied)}function disconnect() {diff --git a/src/components/cloud/CloudHosts.vue b/src/components/cloud/CloudHosts.vueindex 38036838a..78c12a879 100644--- a/src/components/cloud/CloudHosts.vue+++ b/src/components/cloud/CloudHosts.vue@@ -1,15 +1,20 @@<script setup lang="ts">import CloudConnectHost from './connect/CloudConnectHost.vue'import CloudInvitationHost from './invitation/CloudInvitationHost.vue'+import CloudShareHost from './share/CloudShareHost.vue'import CloudNewWorkspaceHost from './workspace/CloudNewWorkspaceHost.vue'import CloudWorkspaceMembersHost from './workspace/CloudWorkspaceMembersHost.vue'-/** Cloud's app-wide dialogs: connecting a server, invitations, and managing workspaces. */+/**+ * Cloud's app-wide dialogs: connecting a server, invitations, sharing the open document, and+ * managing workspaces.+ */</script><template><CloudConnectHost /><CloudInvitationHost />+ <CloudShareHost /><CloudNewWorkspaceHost /><CloudWorkspaceMembersHost /></template>diff --git a/src/components/cloud/share/CloudShareButton.vue b/src/components/cloud/share/CloudShareButton.vueindex ea92a82c5..652512007 100644--- a/src/components/cloud/share/CloudShareButton.vue+++ b/src/components/cloud/share/CloudShareButton.vue@@ -1,120 +1,20 @@<script setup lang="ts">-import { useClipboard } from '@vueuse/core'-import { computed, ref, shallowRef, watch } from 'vue'+import { computed } from 'vue'-import type { DocumentPermission } from '@open-pencil/cloud/contract'-import { useCloudMessages, useI18n } from '@open-pencil/vue'+import { 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 { cloudShareTarget } 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. */+/** Opens the Cloud document's share dialog, which `CloudShareHost` shows for the app. */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 { collaboration } = useI18n()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>@@ -127,21 +27,4 @@ watch(<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.tsindex 156d2451d..5ed6581c0 100644--- a/src/components/cloud/share/CloudShareDialog.stories.ts+++ b/src/components/cloud/share/CloudShareDialog.stories.ts@@ -9,6 +9,7 @@ type Args = {link: ShareLinkStatecanManage: booleancopied: boolean+ sendsLink: booleanonInvite: (email: string, permission: string) => void}@@ -39,6 +40,7 @@ const meta = {link: { access: 'restricted' },canManage: true,copied: false,+ sendsLink: false,onInvite: fn()},render: (args) => ({@@ -54,6 +56,7 @@ const meta = {:link="args.link":can-manage="args.canManage":copied="args.copied"+ :sends-link="args.sendsLink"@invite="args.onInvite"/></div>`@@ -73,6 +76,11 @@ export const LinkCopied: Story = {args: { link: { access: 'link', permission: 'view', copyable: true }, copied: true }}+/** On a phone the link goes out through the system share sheet instead of the clipboard. */+export const LinkSentFromPhone: Story = {+ args: { link: { access: 'link', permission: 'view', copyable: true }, sendsLink: true }+}+export const LinkMadeOnAnotherDevice: Story = {args: { link: { access: 'link', permission: 'edit', copyable: false } }}diff --git a/src/components/cloud/share/CloudShareDialog.vue b/src/components/cloud/share/CloudShareDialog.vueindex b68079272..268ea538a 100644--- a/src/components/cloud/share/CloudShareDialog.vue+++ b/src/components/cloud/share/CloudShareDialog.vue@@ -30,6 +30,7 @@ const {canManage = true,inviting = false,copied = false,+ sendsLink = false,links = { allowed: true, edit: true }} = defineProps<{documentName: string@@ -40,6 +41,8 @@ const {canManage?: booleaninviting?: booleancopied?: boolean+ /** Whether the link goes out through the system share sheet rather than the clipboard. */+ sendsLink?: boolean/** What the workspace's plan allows for links: any link at all, and links that can edit. */links?: { allowed: boolean; edit: boolean }}>()@@ -246,10 +249,11 @@ function submitInvite() {</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-share-2 v-if="sendsLink" class="size-3.5" />+ <icon-lucide-check v-else-if="copied" class="size-3.5" /><icon-lucide-link v-else class="size-3.5" /></template>- {{ copied ? t.shareLinkCopied : t.shareCopyLink }}+ {{ sendsLink ? t.shareSendLink : copied ? t.shareLinkCopied : t.shareCopyLink }}</AppButton><span v-else /><AppButton color="primary" variant="solid" @click="open = false">{{ common.done }}</AppButton>diff --git a/src/components/cloud/share/CloudShareHost.vue b/src/components/cloud/share/CloudShareHost.vuenew file mode 100644index 000000000..9d7f7577f--- /dev/null+++ b/src/components/cloud/share/CloudShareHost.vue@@ -0,0 +1,106 @@+<script setup lang="ts">+import { computed, 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 { cloudShareTarget, type CloudShareLink } from '@/app/cloud/sharing/document'+import { useCloudSharing } from '@/app/cloud/sharing/use'+import { useActiveEditorStoreRef } from '@/app/editor/active-store'+import { useSendLink } from '@/app/shell/share/link'+import { toast } from '@/app/shell/ui'++import CloudShareDialog from './CloudShareDialog.vue'++/**+ * The active Cloud document's share dialog: who can open it and its link, managed on the server.+ * One for the app, so the header's Share button and the mobile one open the same dialog.+ */+const storeRef = useActiveEditorStoreRef()+const { locale } = useI18n()+const t = useCloudMessages()++const target = computed(() => {+ const binding = storeRef.value?.getStorageBinding()+ return binding ? cloudShareTarget(binding) : null+})+const cloudSharing = useCloudSharing(target)+const { sharing, linkURL, inviting } = cloudSharing+const { sendsLink, copied, send } = useSendLink()++const workspace = computed(() => {+ const binding = storeRef.value?.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+ }))+)++async function refresh() {+ if (!(await cloudSharing.refresh())) toast.error(t.value.shareLoadFailed)+}++/** Says when a change did not take; the dialog shows what the server kept either way. */+async function changed(outcome: Promise<boolean>) {+ if (!(await outcome)) toast.error(t.value.shareChangeFailed)+}++const invite = (email: string, permission: DocumentPermission) =>+ changed(cloudSharing.invite(email, permission))+const changeMember = (id: string, permission: DocumentPermission | 'remove') =>+ changed(cloudSharing.changeMember(id, permission))+const changeLink = (link: CloudShareLink) => changed(cloudSharing.changeLink(link))+const resetLink = () => changed(cloudSharing.resetLink())++/** Sends the link prepared with the sharing, so the share sheet opens straight from the tap. */+function sendLink() {+ const url = linkURL.value+ if (!url) {+ toast.error(t.value.shareLoadFailed)+ return+ }+ void send(url, storeRef.value?.state.documentName)+}++watch(+ () => [cloudShareOpen.value, target.value] as const,+ ([open, current]) => {+ // Nothing to share, such as after signing out, closes the dialog rather than leave it to pop+ // up later on its own.+ if (!current) cloudShareOpen.value = false+ else if (open) void refresh()+ }+)+</script>++<template>+ <CloudShareDialog+ v-if="target"+ v-model:open="cloudShareOpen"+ :document-name="storeRef?.state.documentName ?? ''"+ :workspace="workspace"+ :members="members"+ :link="sharing?.link ?? { access: 'restricted' }"+ :can-manage="sharing?.canManage ?? false"+ :links="sharing?.links"+ :inviting="inviting"+ :copied="copied"+ :sends-link="sendsLink"+ @invite="invite"+ @change-member="changeMember"+ @change-link="changeLink"+ @copy-link="sendLink"+ @reset-link="resetLink"+ />+</template>diff --git a/tests/app/cloud/sharing/use.test.ts b/tests/app/cloud/sharing/use.test.tsnew file mode 100644index 000000000..10c10cd40--- /dev/null+++ b/tests/app/cloud/sharing/use.test.ts@@ -0,0 +1,102 @@+import { describe, expect, test } from 'bun:test'++import { shallowRef } from 'vue'++import type { CloudAPIClient } from '@open-pencil/cloud/client'++import type { cloudShareTarget } from '@/app/cloud/sharing/document'+import { useCloudSharing } from '@/app/cloud/sharing/use'+import { createDeferred } from '@/app/runtime/deferred'++import { asDouble } from '#tests/helpers/doubles'++type ShareTarget = NonNullable<ReturnType<typeof cloudShareTarget>>++type Access = Awaited<ReturnType<CloudAPIClient['getDocumentAccess']>>++/** A document on a server that answers with `client`. */+function document(documentId: string, client: Partial<CloudAPIClient>, serverId = 'studio') {+ return asDouble<ShareTarget>({+ documentId,+ workspaceId: null,+ accountId: 'ada',+ server: { id: serverId },+ client+ })+}++/** Access for someone who may not manage sharing, so a read needs nothing else. */+const closed = asDouble<Access>({ canManageSharing: false })++describe('a Cloud document’s sharing', () => {+ test('drops a read that finishes after another document took its place', async () => {+ const slow = createDeferred<Access>()+ const target = shallowRef<ShareTarget | null>(+ document('first', { getDocumentAccess: () => slow.promise })+ )+ const sharing = useCloudSharing(target)+ const reading = sharing.refresh()+ target.value = document('second', { getDocumentAccess: async () => closed })+ slow.resolve(closed)+ expect(await reading).toBe(true)+ expect(sharing.sharing.value).toBeNull()+ })++ test('forgets what it showed when the same document id belongs to another server', async () => {+ const target = shallowRef<ShareTarget | null>(+ document('doc', { getDocumentAccess: async () => closed })+ )+ const sharing = useCloudSharing(target)+ await sharing.refresh()+ expect(sharing.sharing.value).not.toBeNull()+ target.value = document('doc', { getDocumentAccess: async () => closed }, 'other server')+ await Promise.resolve()+ expect(sharing.sharing.value).toBeNull()+ })++ test('says a change failed, and still shows what the server kept', async () => {+ let reads = 0+ const target = document('doc', {+ getDocumentAccess: async () => {+ reads += 1+ return closed+ },+ createDocumentInvitation: () => Promise.reject(new Error('Refused'))+ })+ const sharing = useCloudSharing(target)+ expect(await sharing.invite('[email protected]', 'edit')).toBe(false)+ expect(reads).toBe(1)+ expect(sharing.inviting.value).toBe(false)+ expect(sharing.sharing.value).toMatchObject({ canManage: false })+ })++ test('shows the members and access when the link cannot be read, leaving the link empty', async () => {+ let shareReads = 0+ const target = document('doc', {+ getDocumentAccess: async () => asDouble<Access>({ canManageSharing: true }),+ listDocumentGrants: async () => [],+ listDocumentInvitations: async () => [],+ listDocumentShares: async () => {+ shareReads += 1+ if (shareReads > 1) throw new Error('Offline')+ return asDouble<Awaited<ReturnType<CloudAPIClient['listDocumentShares']>>>([+ { id: 'share', permission: 'view', revokedAt: null }+ ])+ }+ })+ const sharing = useCloudSharing(target)+ expect(await sharing.refresh()).toBe(false)+ expect(sharing.sharing.value).toMatchObject({ canManage: true, link: { access: 'link' } })+ expect(sharing.linkURL.value).toBeNull()+ })++ test('says a change failed when what it left cannot be read', async () => {+ const target = document('doc', {+ createDocumentInvitation: async () => asDouble({}),+ getDocumentAccess: () => Promise.reject(new Error('Offline'))+ })+ const sharing = useCloudSharing(target)+ expect(await sharing.invite('[email protected]', 'view')).toBe(false)+ expect(sharing.linkURL.value).toBeNull()+ })+})