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.

feat(saas): configure shared maps and restore gallery navigation

Timothy Yind4c791851b8b
diff --git a/apps/cloud/app/app.vue b/apps/cloud/app/app.vue
index 792e3454..d4d629b2 100644
--- a/apps/cloud/app/app.vue
+++ b/apps/cloud/app/app.vue
@@ -6,6 +6,7 @@ const componentLocale = computed(() =>
)
useHead(() => ({
htmlAttrs: { lang: locale.value === 'zh-Hans' ? 'zh-CN' : 'en' },
+ link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
bodyAttrs: { class: 'cf-cloud-body' },
}))
</script>
diff --git a/apps/cloud/app/components/CloudMapSettings.vue b/apps/cloud/app/components/CloudMapSettings.vue
new file mode 100644
index 00000000..9b7faa01
--- /dev/null
+++ b/apps/cloud/app/components/CloudMapSettings.vue
@@ -0,0 +1,152 @@
+<script setup lang="ts">
+const props = defineProps<{ siteId: number }>()
+const { locale } = useI18n()
+const store = useSettingsStore()
+const context = useEntryContext()
+const t = (en: string, zh: string) => (locale.value === 'zh-Hans' ? zh : en)
+const { data, error, refresh } = await useFetch(
+ `/api/sites/${props.siteId}/map`,
+ { key: `site-maps-${props.siteId}` },
+)
+const own = ref(!!data.value?.config)
+const draft = ref({
+ provider: 'maplibre',
+ 'mapbox.token': '',
+ 'mapbox.style': '',
+ 'maplibre.token': '',
+ 'maplibre.style': '',
+ ...data.value?.config,
+})
+const busy = ref(false),
+ message = ref(''),
+ failed = ref(false)
+async function save() {
+ if (!data.value || busy.value) return
+ busy.value = true
+ message.value = ''
+ failed.value = false
+ try {
+ await $fetch(`/api/sites/${props.siteId}/map`, {
+ method: 'PUT',
+ body: {
+ revision: data.value.revision,
+ config: own.value ? draft.value : null,
+ },
+ })
+ await refresh()
+ if (context.value?.siteId === props.siteId && data.value)
+ store.data.map = { ...data.value.effective }
+ message.value = t('Map settings saved.', '地图设置已保存。')
+ } catch {
+ failed.value = true
+ message.value = t(
+ 'Unable to save. Check public tokens and style URLs, then reload if someone else changed these settings.',
+ '保存失败,请检查公共令牌和样式地址;如设置已被他人更改,请刷新后重试。',
+ )
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <section class="cf-card cf-card-pad">
+ <h2 class="cf-section-title">{{ t('Maps', '地图') }}</h2>
+ <p class="cf-muted">
+ {{
+ t(
+ 'Use platform maps or your own Mapbox / MapTiler browser keys for this site. These keys and style URLs are public. Restrict them to your gallery domains; never enter a secret key.',
+ '此站点可使用平台地图,或配置自己的 Mapbox/MapTiler 浏览器公共密钥。密钥及样式地址会公开发送到浏览器,请限制允许的图库域名,切勿填写服务端密钥。',
+ )
+ }}
+ </p>
+ <CfAlert
+ v-if="error"
+ tone="error"
+ >{{ t('Unable to load map settings.', '无法加载地图设置。') }}</CfAlert
+ >
+ <form
+ v-else-if="data"
+ class="map-form"
+ @submit.prevent="save"
+ >
+ <fieldset :disabled="busy || data.role !== 'admin'">
+ <label
+ ><CfSelect
+ :model-value="String(own)"
+ @update:model-value="own = $event === 'true'"
+ ><option value="false">
+ {{ t('Use platform defaults', '使用平台默认配置') }}
+ </option>
+ <option value="true">
+ {{ t('Use my own configuration', '使用自定义配置') }}
+ </option></CfSelect
+ ></label
+ >
+ <template v-if="own">
+ <label
+ >{{ t('Provider', '地图服务')
+ }}<CfSelect v-model="draft.provider"
+ ><option value="mapbox">Mapbox</option>
+ <option value="maplibre">MapTiler (MapLibre)</option></CfSelect
+ ></label
+ >
+ <label
+ >{{ t('Mapbox public token (pk.)', 'Mapbox 公共令牌(pk.)')
+ }}<CfInput
+ v-model="draft['mapbox.token']"
+ autocomplete="off"
+ maxlength="1024"
+ /></label>
+ <label
+ >{{ t('Mapbox style (optional)', 'Mapbox 样式(可选)')
+ }}<CfInput
+ v-model="draft['mapbox.style']"
+ placeholder="mapbox://styles/mapbox/standard"
+ maxlength="2048"
+ /></label>
+ <label
+ >{{ t('MapTiler public key', 'MapTiler 公共密钥')
+ }}<CfInput
+ v-model="draft['maplibre.token']"
+ autocomplete="off"
+ maxlength="256"
+ /></label>
+ <label
+ >{{ t('MapLibre style URL (optional)', 'MapLibre 样式地址(可选)')
+ }}<CfInput
+ v-model="draft['maplibre.style']"
+ placeholder="https://…"
+ maxlength="2048"
+ /></label>
+ </template>
+ <CfButton
+ type="submit"
+ :loading="busy"
+ >{{ t('Save maps', '保存地图设置') }}</CfButton
+ >
+ </fieldset>
+ <CfAlert
+ v-if="message"
+ :tone="failed ? 'error' : 'info'"
+ >{{ message }}</CfAlert
+ >
+ </form>
+ </section>
+</template>
+<style scoped>
+.map-form {
+ margin-top: 1.5rem;
+}
+fieldset {
+ border: 0;
+ padding: 0;
+ margin: 0;
+ display: grid;
+ gap: 1rem;
+ max-width: 44rem;
+}
+label {
+ display: grid;
+ gap: 0.5rem;
+}
+</style>
diff --git a/apps/cloud/app/components/CloudSiteWorkspace.vue b/apps/cloud/app/components/CloudSiteWorkspace.vue
index 06453217..018ba3a2 100644
--- a/apps/cloud/app/components/CloudSiteWorkspace.vue
+++ b/apps/cloud/app/components/CloudSiteWorkspace.vue
@@ -3,12 +3,20 @@ import { PUBLIC_GALLERY_DEFAULTS } from '@chronoframe/contracts/gallery-settings
import type { SettingValue } from '@chronoframe/contracts/settings'
const props = defineProps<{ siteId: number; role?: string }>()
const settings = useSettingsStore()
+const context = useEntryContext()
+const scope = context.value?.scope
settings.data = structuredClone(PUBLIC_GALLERY_DEFAULTS) as Record<
string,
Record<string, SettingValue>
>
settings.data.app!.title = useEntryContext().value?.name ?? 'ChronoFrame'
-settings.isInitialized = true
+const { data: maps } = await useFetch(`/api/sites/${props.siteId}/map`, {
+ key: `site-maps-${props.siteId}`,
+})
+if (context.value?.scope === scope) {
+ if (maps.value) settings.data.map = { ...maps.value.effective }
+ settings.isInitialized = true
+}
const media = provideCloudSiteMedia(props)
const { photos, loading, message, failed, reload, loadError, refreshMedia } =
media
diff --git a/apps/cloud/app/pages/sites/[siteId]/information.vue b/apps/cloud/app/pages/sites/[siteId]/information.vue
index 62f4bfcf..ec1c0083 100644
--- a/apps/cloud/app/pages/sites/[siteId]/information.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/information.vue
@@ -21,5 +21,6 @@ const site = useEntryContext().value!
</div>
</div>
<CloudSiteSettings :site-id="site.siteId" />
+ <CloudMapSettings :site-id="site.siteId" />
</div>
</template>
diff --git a/apps/cloud/public/favicon.ico b/apps/cloud/public/favicon.ico
new file mode 100644
index 00000000..87172380
Binary files /dev/null and b/apps/cloud/public/favicon.ico differ
diff --git a/apps/cloud/server/api/sites/[siteId]/map.get.ts b/apps/cloud/server/api/sites/[siteId]/map.get.ts
new file mode 100644
index 00000000..767d67b5
--- /dev/null
+++ b/apps/cloud/server/api/sites/[siteId]/map.get.ts
@@ -0,0 +1,16 @@
+import { getRouterParam } from 'h3'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../../shared/platform/runtime'
+import { siteManagement } from '../../../utils/site-management'
+import { siteMaps } from '../../../../../../packages/platform/src/maps'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event)
+ const siteId = Number(getRouterParam(event, 'siteId'))
+ const site = await store.get(userId, siteId)
+ return {
+ ...(await siteMaps(platformDatabase(event), siteId)),
+ role: site.role,
+ }
+})
diff --git a/apps/cloud/server/api/sites/[siteId]/map.put.ts b/apps/cloud/server/api/sites/[siteId]/map.put.ts
new file mode 100644
index 00000000..0fb61b37
--- /dev/null
+++ b/apps/cloud/server/api/sites/[siteId]/map.put.ts
@@ -0,0 +1,20 @@
+import { getRouterParam } from 'h3'
+import {
+ definePlatformHandler,
+ platformDatabase,
+} from '../../../../../shared/platform/runtime'
+import {
+ siteManagement,
+ siteManagementBody,
+} from '../../../utils/site-management'
+import { saveSiteMaps } from '../../../../../../packages/platform/src/maps'
+export default definePlatformHandler(async (event) => {
+ const { userId, store } = await siteManagement(event, true)
+ const siteId = Number(getRouterParam(event, 'siteId'))
+ await store.get(userId, siteId)
+ const body = await siteManagementBody(event, 8192)
+ return saveSiteMaps(platformDatabase(event), userId, siteId, {
+ config: body.config,
+ revision: body.revision,
+ })
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index b2a61ab8..9756b612 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -29,7 +29,7 @@ export default defineEventHandler((event) => {
'/api/workspaces/default',
].includes(path) ||
/^\/api\/webhooks\/dodo\/[a-z][a-z0-9_-]{0,63}$/.test(path) ||
- /^\/api\/sites\/[1-9][0-9]*\/(?:context|events|settings|domains)$/.test(
+ /^\/api\/sites\/[1-9][0-9]*\/(?:context|events|settings|domains|map)$/.test(
path,
)
if (
diff --git a/apps/site/app/router.options.ts b/apps/site/app/router.options.ts
new file mode 100644
index 00000000..5d38fce0
--- /dev/null
+++ b/apps/site/app/router.options.ts
@@ -0,0 +1,19 @@
+import type { RouterConfig } from 'nuxt/schema'
+
+export default <RouterConfig>{
+ scrollBehavior(to, from, savedPosition) {
+ if (savedPosition) {
+ return savedPosition
+ }
+
+ if (to.name === 'slug') {
+ return false
+ }
+
+ if (from.name === 'slug' && (to.path === '/photos' || to.path === '/')) {
+ return false
+ }
+
+ return { top: 0 }
+ },
+}
diff --git a/apps/site/nuxt.config.ts b/apps/site/nuxt.config.ts
index c154141a..dccc1789 100644
--- a/apps/site/nuxt.config.ts
+++ b/apps/site/nuxt.config.ts
@@ -6,7 +6,12 @@ export default defineNuxtConfig({
modules: [...sharedUi.modules, '@nuxt/fonts'],
fonts: { families: galleryFontFamilies },
devServer: { port: 3002 },
- app: { head: { htmlAttrs: { lang: 'en' } } },
+ app: {
+ head: {
+ htmlAttrs: { lang: 'en' },
+ link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
+ },
+ },
nitro: {
...sharedUi.nitro,
cloudflare: {
diff --git a/apps/site/public/favicon.ico b/apps/site/public/favicon.ico
new file mode 100644
index 00000000..87172380
Binary files /dev/null and b/apps/site/public/favicon.ico differ
diff --git a/apps/site/server/api/public/system/settings/all.get.ts b/apps/site/server/api/public/system/settings/all.get.ts
index d5a5a3e1..36fef764 100644
--- a/apps/site/server/api/public/system/settings/all.get.ts
+++ b/apps/site/server/api/public/system/settings/all.get.ts
@@ -1,3 +1,4 @@
+import { siteMaps } from '../../../../../../../packages/platform/src/maps'
import {
PUBLIC_GALLERY_DEFAULTS,
parseGalleryPresentation,
@@ -39,5 +40,8 @@ export default definePlatformHandler(async (event) => {
data.app!['appearance.homeHeaderLayout'] = presentation.homeHeaderLayout
data.app!.socialLinks = presentation.socialLinks
}
+ data.map = {
+ ...(await siteMaps(platformDatabase(event), context.siteId)).effective,
+ }
return { timestamp: Date.now(), data }
})
diff --git a/packages/gallery/app/pages/[...slug].vue b/packages/gallery/app/pages/[...slug].vue
index c6ae1047..a23ae351 100644
--- a/packages/gallery/app/pages/[...slug].vue
+++ b/packages/gallery/app/pages/[...slug].vue
@@ -15,14 +15,22 @@ const { photos } = usePhotos()
const slug = computed(() => (route.params.slug as string[]) || [])
const photoId = computed(() => slug.value[0] || null)
+const { t } = useI18n()
+// Register one reactive head entry so unmount disposes it and every close restores
+// the layout title; watcher-created entries can outlive their photo route.
+useHead(() => ({
+ title: photoId.value
+ ? (scopedPhotos.value ?? photos.value).find(
+ (photo) => photo.id === photoId.value,
+ )?.title || t('title.fallback.photo')
+ : '',
+}))
+
watch(
[photoId, photos],
([currentPhotoId, globalPhotos]) => {
if (!currentPhotoId) {
closeViewer()
- useHead({
- title: '',
- })
return
}
@@ -41,10 +49,6 @@ watch(
)
if (foundIndex === -1) return
- useHead({
- title: activePhotos[foundIndex]?.title || $t('title.fallback.photo'),
- })
-
if (!isViewerOpen.value) {
// Direct access to a photo detail page: don't set a returnRoute (pass null)
openViewer(foundIndex, null)
diff --git a/packages/platform/migrations/0035_map_settings.sql b/packages/platform/migrations/0035_map_settings.sql
new file mode 100644
index 00000000..26bd6d57
--- /dev/null
+++ b/packages/platform/migrations/0035_map_settings.sql
@@ -0,0 +1,3 @@
+CREATE TABLE platform_map_settings(id INTEGER PRIMARY KEY CHECK(id=1),config_json TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1);
+INSERT INTO platform_map_settings(id) VALUES(1);
+CREATE TABLE platform_site_maps(site_id INTEGER PRIMARY KEY REFERENCES platform_sites(id) ON DELETE CASCADE,config_json TEXT,revision INTEGER NOT NULL DEFAULT 1);
diff --git a/packages/platform/src/maps.ts b/packages/platform/src/maps.ts
new file mode 100644
index 00000000..5e1798a9
--- /dev/null
+++ b/packages/platform/src/maps.ts
@@ -0,0 +1,129 @@
+import type { PlatformD1 } from './index.ts'
+import { SubscriptionError } from './subscriptions.ts'
+export interface PublicMapConfig {
+ provider: 'mapbox' | 'maplibre'
+ 'mapbox.token': string
+ 'mapbox.style': string
+ 'maplibre.token': string
+ 'maplibre.style': string
+}
+export const EMPTY_MAP: PublicMapConfig = {
+ provider: 'maplibre',
+ 'mapbox.token': '',
+ 'mapbox.style': '',
+ 'maplibre.token': '',
+ 'maplibre.style': '',
+}
+/** These are browser-visible keys, never secret server-side credentials. */
+export function parsePublicMap(value: unknown): PublicMapConfig {
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw new SubscriptionError(400, 'map_config_invalid')
+ const input = value as Record<string, unknown>
+ if (Object.keys(input).some((k) => !Object.hasOwn(EMPTY_MAP, k)))
+ throw new SubscriptionError(400, 'map_config_invalid')
+ const result = { ...EMPTY_MAP }
+ if (!['mapbox', 'maplibre'].includes(String(input.provider)))
+ throw new SubscriptionError(400, 'map_provider_invalid')
+ result.provider = input.provider as PublicMapConfig['provider']
+ for (const key of [
+ 'mapbox.token',
+ 'mapbox.style',
+ 'maplibre.token',
+ 'maplibre.style',
+ ] as const) {
+ if (
+ typeof input[key] !== 'string' ||
+ input[key].length > 2048 ||
+ /[\x00-\x1f\x7f]/.test(input[key])
+ )
+ throw new SubscriptionError(400, 'map_config_invalid')
+ result[key] = input[key].trim()
+ }
+ if (
+ result['mapbox.token'] &&
+ !/^pk\.[A-Za-z0-9._-]{10,1024}$/.test(result['mapbox.token'])
+ )
+ throw new SubscriptionError(400, 'map_public_token_required')
+ if (
+ result['maplibre.token'] &&
+ !/^[A-Za-z0-9_-]{8,256}$/.test(result['maplibre.token'])
+ )
+ throw new SubscriptionError(400, 'map_public_token_required')
+ for (const key of ['mapbox.style', 'maplibre.style'] as const) {
+ const style = result[key]
+ if (!style) continue
+ if (
+ key === 'mapbox.style' &&
+ /^mapbox:\/\/styles\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+$/.test(style)
+ )
+ continue
+ try {
+ const url = new URL(style)
+ if (url.protocol !== 'https:' || url.username || url.password)
+ throw new Error()
+ } catch {
+ throw new SubscriptionError(400, 'map_style_invalid')
+ }
+ }
+ return result
+}
+export async function mapDefaults(db: PlatformD1) {
+ const row = await db
+ .prepare(
+ 'SELECT config_json,revision FROM platform_map_settings WHERE id=1',
+ )
+ .first<{ config_json: string; revision: number }>()
+ return {
+ config: {
+ ...EMPTY_MAP,
+ ...JSON.parse(row!.config_json),
+ } as PublicMapConfig,
+ revision: row!.revision,
+ }
+}
+export async function siteMaps(db: PlatformD1, siteId: number) {
+ const row = await db
+ .prepare(
+ 'SELECT config_json,revision FROM platform_site_maps WHERE site_id=?',
+ )
+ .bind(siteId)
+ .first<{ config_json: string | null; revision: number }>()
+ const defaults = await mapDefaults(db)
+ const config = row?.config_json
+ ? parsePublicMap(JSON.parse(row.config_json))
+ : null
+ return {
+ config,
+ effective: config ?? defaults.config,
+ revision: row?.revision ?? 0,
+ }
+}
+export async function saveSiteMaps(
+ db: PlatformD1,
+ userId: number,
+ siteId: number,
+ input: { config: unknown; revision: unknown },
+) {
+ if (!Number.isSafeInteger(input.revision) || Number(input.revision) < 0)
+ throw new SubscriptionError(400, 'map_revision_invalid')
+ const revision = Number(input.revision)
+ const config = input.config === null ? null : parsePublicMap(input.config)
+ const result = await db
+ .prepare(
+ `INSERT INTO platform_site_maps(site_id,config_json,revision) SELECT ?,?,1 WHERE EXISTS(SELECT 1 FROM platform_sites s JOIN platform_memberships m ON m.workspace_id=s.workspace_id WHERE s.id=? AND s.suspended=0 AND m.user_id=? AND m.role='admin') AND (?=0 OR EXISTS(SELECT 1 FROM platform_site_maps WHERE site_id=? AND revision=?)) ON CONFLICT(site_id) DO UPDATE SET config_json=excluded.config_json,revision=platform_site_maps.revision+1 WHERE platform_site_maps.revision=?`,
+ )
+ .bind(
+ siteId,
+ config ? JSON.stringify(config) : null,
+ siteId,
+ userId,
+ revision,
+ siteId,
+ revision,
+ revision,
+ )
+ .run()
+ if (!result.meta.changes)
+ throw new SubscriptionError(409, 'map_settings_changed_or_forbidden')
+ return siteMaps(db, siteId)
+}
diff --git a/tests/saas-maps.test.ts b/tests/saas-maps.test.ts
new file mode 100644
index 00000000..ca11f8bd
--- /dev/null
+++ b/tests/saas-maps.test.ts
@@ -0,0 +1,105 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFile, readdir } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import {
+ EMPTY_MAP,
+ parsePublicMap,
+ siteMaps,
+ saveSiteMaps,
+} from '../packages/platform/src/maps.ts'
+const require = createRequire(import.meta.url)
+const { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+)('miniflare')
+test('public map defaults, per-site overrides, membership and optimistic revisions stay isolated', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-26',
+ script: 'export default {fetch(){return new Response("ok")}}',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ for (const file of (await readdir('packages/platform/migrations'))
+ .filter((f) => f.endsWith('.sql'))
+ .sort())
+ for (const sql of (
+ await readFile('packages/platform/migrations/' + file, 'utf8')
+ )
+ .replace(/^--.*$/gm, '')
+ .match(/\s*CREATE TRIGGER[\s\S]+?END;|[^;]+;/g) ?? [])
+ await db.prepare(sql).run()
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,created_at) VALUES(1,'[email protected]',1),(2,'[email protected]',1)",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_workspaces(id,name) VALUES(1,'One'),(2,'Two')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_memberships VALUES(1,1,'admin'),(2,1,'member'),(2,2,'admin')",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_sites(id,workspace_id,name) VALUES(1,1,'One'),(2,2,'Two')",
+ )
+ .run()
+ const defaults = { ...EMPTY_MAP, 'maplibre.token': 'public_default_key' }
+ await db
+ .prepare('UPDATE platform_map_settings SET config_json=? WHERE id=1')
+ .bind(JSON.stringify(defaults))
+ .run()
+ assert.deepEqual((await siteMaps(db, 1)).effective, defaults)
+ const own = {
+ ...EMPTY_MAP,
+ provider: 'mapbox',
+ 'mapbox.token': 'pk.public_browser_token',
+ }
+ const saved = await saveSiteMaps(db, 1, 1, { revision: 0, config: own })
+ assert.equal(saved.revision, 1)
+ assert.deepEqual(saved.effective, own)
+ assert.deepEqual((await siteMaps(db, 2)).effective, defaults)
+ await assert.rejects(
+ saveSiteMaps(db, 2, 1, { revision: 1, config: null }),
+ { statusCode: 409 },
+ )
+ await assert.rejects(saveSiteMaps(db, 1, 2, { revision: 0, config: own }), {
+ statusCode: 409,
+ })
+ await assert.rejects(
+ saveSiteMaps(db, 1, 1, { revision: 0, config: null }),
+ { statusCode: 409 },
+ )
+ assert.deepEqual(
+ (await saveSiteMaps(db, 1, 1, { revision: 1, config: null })).effective,
+ defaults,
+ )
+ assert.throws(
+ () =>
+ parsePublicMap({ ...own, 'mapbox.token': 'sk.secret_server_token' }),
+ { code: 'map_public_token_required' },
+ )
+ assert.throws(
+ () => parsePublicMap({ ...own, 'maplibre.style': 'javascript:alert(1)' }),
+ { code: 'map_style_invalid' },
+ )
+ assert.throws(
+ () =>
+ parsePublicMap({
+ ...own,
+ 'maplibre.style': 'https://user:[email protected]/style',
+ }),
+ { code: 'map_style_invalid' },
+ )
+ } finally {
+ await mf.dispose()
+ }
+})
diff --git a/tests/site-viewer-navigation.test.ts b/tests/site-viewer-navigation.test.ts
new file mode 100644
index 00000000..89848168
--- /dev/null
+++ b/tests/site-viewer-navigation.test.ts
@@ -0,0 +1,104 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import vm from 'node:vm'
+import ts from 'typescript'
+import { computed, reactive, ref, watch, effectScope, nextTick } from 'vue'
+function compile(source: string, context: Record<string, unknown>) {
+ const exports: Record<string, any> = {}
+ vm.runInNewContext(
+ ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+ }).outputText,
+ { exports, ...context },
+ )
+ return exports
+}
+test('Site viewer route keeps scroll on open/close and preserves normal navigation', () => {
+ const router = compile(
+ readFileSync('apps/site/app/router.options.ts', 'utf8'),
+ {},
+ ).default
+ assert.equal(
+ router.scrollBehavior({ name: 'slug' }, { path: '/' }, null),
+ false,
+ )
+ assert.equal(
+ router.scrollBehavior({ path: '/' }, { name: 'slug' }, null),
+ false,
+ )
+ assert.equal(
+ router.scrollBehavior({ path: '/photos' }, { name: 'slug' }, null),
+ false,
+ )
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ router.scrollBehavior({ path: '/albums' }, { path: '/' }, null),
+ ),
+ ),
+ { top: 0 },
+ )
+ const saved = { left: 0, top: 900 }
+ assert.equal(
+ router.scrollBehavior({ path: '/' }, { name: 'slug' }, saved),
+ saved,
+ )
+})
+test('photo route owns exactly one reactive title across repeated viewer open/close', async () => {
+ const route = reactive({ params: { slug: ['first'] } as { slug?: string[] } })
+ const photos = ref([
+ { id: 'first', title: 'First photo' },
+ { id: 'second', title: 'Second photo' },
+ ])
+ const state = { isViewerOpen: ref(true), scopedPhotos: ref(null) }
+ let head: (() => { title: string }) | undefined,
+ entries = 0
+ const scope = effectScope()
+ try {
+ scope.run(() =>
+ compile(
+ readFileSync('packages/gallery/app/pages/[...slug].vue', 'utf8')
+ .split('<script lang="ts" setup>')[1]!
+ .split('</script>')[0]!,
+ {
+ ref,
+ computed,
+ watch,
+ definePageMeta: () => {},
+ useRoute: () => route,
+ useViewerState: () => ({
+ closeViewer: () => {
+ state.isViewerOpen.value = false
+ },
+ openViewer: () => {
+ state.isViewerOpen.value = true
+ },
+ switchToIndex: () => {},
+ }),
+ storeToRefs: () => state,
+ usePhotos: () => ({ photos }),
+ useI18n: () => ({ t: () => 'Photo' }),
+ useHead: (value: () => { title: string }) => {
+ head = value
+ entries++
+ },
+ onBeforeRouteLeave: () => {},
+ },
+ ),
+ )
+ assert.equal(head!().title, 'First photo')
+ route.params = {}
+ await nextTick()
+ assert.equal(head!().title, '')
+ route.params = { slug: ['second'] }
+ await nextTick()
+ assert.equal(head!().title, 'Second photo')
+ route.params = {}
+ await nextTick()
+ assert.equal(head!().title, '')
+ assert.equal(entries, 1)
+ } finally {
+ scope.stop()
+ }
+})