Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(cloud): preserve outgoing page state during navigation

Timothy Yin64fe8b526254
diff --git a/apps/cloud/app/components/CloudSiteHeader.vue b/apps/cloud/app/components/CloudSiteHeader.vue
index a51a886a..74733e9b 100644
--- a/apps/cloud/app/components/CloudSiteHeader.vue
+++ b/apps/cloud/app/components/CloudSiteHeader.vue
@@ -1,7 +1,12 @@
<script setup lang="ts">
import { ArrowUpRight, Settings, Globe } from 'lucide-vue-next'
-const context = useEntryContext(),
- { admin, busy, photos, publish } = useCloudSiteMedia()
+const activeContext = useEntryContext()
+const context = shallowRef(activeContext.value)
+// Preserve the outgoing header, while accepting live updates for this Site only.
+watch(activeContext, (next) => {
+ if (next?.scope === context.value?.scope) context.value = next
+})
+const { admin, busy, photos, publish } = useCloudSiteMedia()
const { data } = useFetch<{ site: { slug: string | null } }>(
`/api/sites/${context.value?.siteId}/settings`,
)
diff --git a/apps/cloud/app/components/CloudUploadDrawer.vue b/apps/cloud/app/components/CloudUploadDrawer.vue
index ec782253..c7f74028 100644
--- a/apps/cloud/app/components/CloudUploadDrawer.vue
+++ b/apps/cloud/app/components/CloudUploadDrawer.vue
@@ -13,7 +13,7 @@ const {
usage,
admin,
} = useCloudSiteMedia()
-const context = useEntryContext(),
+const context = useEntryContext().value,
input = ref<HTMLInputElement>()
async function dropFiles(event: DragEvent) {
if (
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index 8304df25..63e39efa 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -5,19 +5,10 @@ import type {
export default defineNuxtRouteMiddleware(async (to) => {
const path = to.path.toLowerCase()
const context = useEntryContext()
- const detail =
- /^\/sites\/([1-9][0-9]*)(?:\/(?:photos|albums|settings))?$/.exec(path)
- if (
- !detail ||
- context.value?.siteId !== Number(detail[1]) ||
- context.value?.audience !== 'portal'
- )
- context.value = null
const catalog = useState<EntrySiteCatalog | null>(
'platform-site-catalog',
() => null,
)
- catalog.value = null
if (path === '/' && useRequestURL().hostname === 'app.chronoframe.art')
return navigateTo('/sites', { redirectCode: 302 })
if (path === '/dashboard' || path.startsWith('/dashboard/'))
@@ -77,4 +68,7 @@ export default defineNuxtRouteMiddleware(async (to) => {
}
}
}
+ // Keep the current view intact while authorization and destination data load.
+ // The next page must still start without a previous Site's authority.
+ if (!path.startsWith('/sites/')) context.value = null
})
diff --git a/apps/cloud/app/pages/signin.vue b/apps/cloud/app/pages/signin.vue
index e9d8ad90..9c3ecffd 100644
--- a/apps/cloud/app/pages/signin.vue
+++ b/apps/cloud/app/pages/signin.vue
@@ -71,7 +71,6 @@ async function submit() {
return
}
}
- clearNuxtData()
await navigateTo('/sites', { external: true })
} catch (cause) {
error.value = accountError(cause)
@@ -89,7 +88,6 @@ async function passkeySignIn() {
try {
const result = await useCloudAccount().signIn.passkey()
if (result.error) throw result.error
- clearNuxtData()
await navigateTo('/sites', { external: true })
} catch {
error.value =
diff --git a/apps/cloud/app/pages/signup.vue b/apps/cloud/app/pages/signup.vue
index 69d3597e..0a85bdcf 100644
--- a/apps/cloud/app/pages/signup.vue
+++ b/apps/cloud/app/pages/signup.vue
@@ -32,7 +32,6 @@ async function submit() {
method: 'POST',
body: { email: email.value, otp: code.value },
})
- clearNuxtData()
await navigateTo('/sites', { external: true })
}
} catch (cause) {
diff --git a/apps/cloud/app/pages/sites/[siteId]/settings.vue b/apps/cloud/app/pages/sites/[siteId]/settings.vue
index 72c9c953..b66f2b06 100644
--- a/apps/cloud/app/pages/sites/[siteId]/settings.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/settings.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
definePageMeta({ layout: 'portal' })
useSeoMeta({ title: 'Site settings — ChronoFrame Cloud', robots: 'noindex' })
-const context = useEntryContext()
+const context = useEntryContext().value
</script>
<template>
<div class="cf-site-settings-stack">
diff --git a/apps/cloud/app/pages/sites/index.vue b/apps/cloud/app/pages/sites/index.vue
index 39d1784c..98bac6f9 100644
--- a/apps/cloud/app/pages/sites/index.vue
+++ b/apps/cloud/app/pages/sites/index.vue
@@ -26,7 +26,8 @@ const catalog = useState<EntrySiteCatalog | null>(
'platform-site-catalog',
() => null,
)
-const sites = computed(() =>
+// This page owns its catalog until it unmounts; middleware prepares the next route.
+const sites = ref(
catalog.value?.userId === userId.value ? catalog.value.sites : [],
)
</script>
diff --git a/packages/gallery/app/composables/useEntryApi.ts b/packages/gallery/app/composables/useEntryApi.ts
index fef95b7d..76d07281 100644
--- a/packages/gallery/app/composables/useEntryApi.ts
+++ b/packages/gallery/app/composables/useEntryApi.ts
@@ -20,13 +20,14 @@ export function useEntryFetch(
options: Record<string, unknown> | undefined,
baseURL: string,
) {
- const context = useEntryContext()
+ // A mounted consumer belongs to its creating Site, including while leaving.
+ const snapshot = useEntryContext().value
const path = computed(() =>
- entryRequestPath(String(toValue(request as string)), context.value),
+ entryRequestPath(String(toValue(request as string)), snapshot),
)
const key = computed(
() =>
- `${context.value?.scope ?? 'self-hosted'}:fetch:${String(toValue(options?.key as string) ?? path.value)}`,
+ `${snapshot?.scope ?? 'self-hosted'}:fetch:${String(toValue(options?.key as string) ?? path.value)}`,
)
const fetcher = useFetch as (
request: unknown,
diff --git a/packages/gallery/app/plugins/entry-context.ts b/packages/gallery/app/plugins/entry-context.ts
index 2fb1281f..cc395639 100644
--- a/packages/gallery/app/plugins/entry-context.ts
+++ b/packages/gallery/app/plugins/entry-context.ts
@@ -1,9 +1,19 @@
import { clearImageLoaderCache } from '../libs/image-loader-manager'
/** Drop tenant-owned client state before another Site is rendered. Preferences stay local. */
-export default defineNuxtPlugin(() => {
+export default defineNuxtPlugin((nuxtApp) => {
const context = useEntryContext()
const settings = useSettingsStore()
const viewer = useViewerState()
+ const retiredScopes = new Set<string>()
+ // Suspense keeps the outgoing page mounted until the destination is ready.
+ // Clearing its async data earlier changes its visible content during navigation.
+ nuxtApp.hook('page:finish', () => {
+ for (const scope of retiredScopes) {
+ if (scope !== context.value?.scope)
+ clearNuxtData((key) => key.startsWith(`${scope}:fetch:`))
+ }
+ retiredScopes.clear()
+ })
watch(
() => context.value?.scope,
(scope, previous) => {
@@ -15,7 +25,7 @@ export default defineNuxtPlugin(() => {
viewer.currentPhotoIndex = 0
viewer.isDirectAccess = false
viewer.clearReturnRoute()
- clearNuxtData((key) => key.startsWith(`${previous}:fetch:`))
+ if (previous) retiredScopes.add(previous)
},
{ flush: 'sync' },
)
diff --git a/tests/ui-api.test.ts b/tests/ui-api.test.ts
index 1e714aba..7e6ea9b1 100644
--- a/tests/ui-api.test.ts
+++ b/tests/ui-api.test.ts
@@ -119,7 +119,12 @@ test('public gallery unwraps resource envelopes without changing scoped SSR requ
: v
const code = ts.transpileModule(
readFileSync('packages/gallery/app/composables/useGalleryApi.ts', 'utf8'),
- { compilerOptions: { module: ts.ModuleKind.CommonJS } },
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ },
).outputText
vm.runInNewContext(code, {
exports,
@@ -162,3 +167,106 @@ test('public gallery unwraps resource envelopes without changing scoped SSR requ
1,
)
})
+
+test('mounted entry fetch keeps its Site path and cache key while the next route changes context', () => {
+ const context: { value: any } = {
+ value: { siteId: 1, scope: 'site:1:portal:user1', audience: 'portal' },
+ }
+ let captured: any
+ const exports: Record<string, any> = {}
+ const code = ts.transpileModule(
+ readFileSync('packages/gallery/app/composables/useEntryApi.ts', 'utf8'),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ },
+ ).outputText
+ vm.runInNewContext(code, {
+ exports,
+ require: () => ({ useEntryContext: () => context, entryRequestPath }),
+ toValue: (value: any) => value?.value ?? value,
+ computed: (getter: () => unknown) => ({
+ get value() {
+ return getter()
+ },
+ }),
+ useFetch: (path: any, options: any) => {
+ captured = { path, options }
+ },
+ })
+ exports.useEntryFetch('/api/albums', undefined, '')
+ const outgoing = captured
+ context.value = null
+ assert.equal(outgoing.path.value, '/api/sites/1/albums')
+ assert.equal(
+ outgoing.options.key.value,
+ 'site:1:portal:user1:fetch:/api/sites/1/albums',
+ )
+ context.value = {
+ siteId: 2,
+ scope: 'site:2:portal:user2',
+ audience: 'portal',
+ }
+ exports.useEntryFetch('/api/albums', undefined, '')
+ assert.equal(captured.path.value, '/api/sites/2/albums')
+ assert.notEqual(captured.options.key.value, outgoing.options.key.value)
+ assert.equal(outgoing.path.value, '/api/sites/1/albums')
+})
+
+test('retired Site async data is cleared after page completion, preserving a reactivated scope', () => {
+ const context: { value: any } = { value: { scope: 'site:1' } }
+ let changed: (scope: string, previous: string) => void = () => {}
+ let finish: () => void = () => {}
+ const cleared: string[] = []
+ const keys = ['site:1:fetch:photos', 'site:2:fetch:photos', 'auth-status']
+ const code = ts.transpileModule(
+ readFileSync(
+ 'packages/gallery/app/plugins/entry-context.ts',
+ 'utf8',
+ ).replace('import.meta.client', 'false'),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ },
+ ).outputText
+ vm.runInNewContext(code, {
+ exports: {},
+ require: () => ({ clearImageLoaderCache() {} }),
+ defineNuxtPlugin: (setup: any) =>
+ setup({
+ hook: (name: string, callback: () => void) => {
+ assert.equal(name, 'page:finish')
+ finish = callback
+ },
+ }),
+ useEntryContext: () => context,
+ useSettingsStore: () => ({ $reset() {} }),
+ useViewerState: () => ({ clearReturnRoute() {} }),
+ watch: (_: any, callback: any) => {
+ changed = callback
+ },
+ clearNuxtData: (predicate: (key: string) => boolean) => {
+ cleared.push(...keys.filter(predicate))
+ },
+ })
+ context.value = { scope: 'site:2' }
+ changed('site:2', 'site:1')
+ assert.deepEqual(cleared, [], 'outgoing component data remains available')
+ finish()
+ assert.deepEqual(cleared, ['site:1:fetch:photos'])
+ cleared.length = 0
+ context.value = { scope: 'site:1' }
+ changed('site:1', 'site:2')
+ context.value = { scope: 'site:2' }
+ changed('site:2', 'site:1')
+ finish()
+ assert.deepEqual(
+ cleared,
+ ['site:1:fetch:photos'],
+ 'active scope and unrelated auth data survive',
+ )
+})