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(gallery): share map appearance and photo-time lighting across editions

Timothy Yin018cd4ddaadc
diff --git a/packages/gallery/app/components/map/Provider.vue b/packages/gallery/app/components/map/Provider.vue
index bc705fb2..8f6f607c 100644
--- a/packages/gallery/app/components/map/Provider.vue
+++ b/packages/gallery/app/components/map/Provider.vue
@@ -9,6 +9,11 @@ import type {
import { useMapSetupNotice } from '#gallery/composables/useMapSetupNotice'
import { isMapServiceConfigured } from '@chronoframe/gallery/shared/utils/map-service'
+import {
+ DEFAULT_MAPBOX_STYLE,
+ mapLightPreset,
+} from '@chronoframe/gallery/shared/utils/map-appearance'
+
import ChronoFrameLightStyle from '#gallery/assets/mapStyles/chronoframe_light.json'
import ChronoFrameDarkStyle from '#gallery/assets/mapStyles/chronoframe_dark.json'
@@ -22,6 +27,7 @@ const props = withDefaults(
attributionControl?: false | AttributionControlOptions
language?: string
setupNotice?: boolean
+ dateTaken?: string | null
}>(),
{
class: undefined,
@@ -32,6 +38,7 @@ const props = withDefaults(
attributionControl: false,
language: undefined,
setupNotice: false,
+ dateTaken: undefined,
},
)
@@ -41,6 +48,33 @@ const emit = defineEmits<{
}>()
const colorMode = useColorMode()
+const lightPreset = computed(() =>
+ mapLightPreset(props.dateTaken, colorMode.value),
+)
+const mapboxInstance = shallowRef<MapboxMap | null>(null)
+function syncMapboxAppearance() {
+ const map = mapboxInstance.value
+ if (!map || !map.isStyleLoaded()) return
+ // Custom styles without the Standard basemap do not expose its lighting controls.
+ if (
+ mapStyle.value === DEFAULT_MAPBOX_STYLE ||
+ map.getStyle().imports?.some((fragment) => fragment.id === 'basemap')
+ ) {
+ map.setConfigProperty('basemap', 'lightPreset', lightPreset.value)
+ }
+}
+function detachMapboxAppearance() {
+ mapboxInstance.value?.off('style.load', syncMapboxAppearance)
+ mapboxInstance.value = null
+}
+function onMapboxLoad(map: MapboxMap) {
+ detachMapboxAppearance()
+ mapboxInstance.value = map
+ map.on('style.load', syncMapboxAppearance)
+ syncMapboxAppearance()
+ emit('load', map)
+}
+watch(lightPreset, syncMapboxAppearance)
const mapConfig = computed(() => {
const config = getSetting('map')
@@ -48,6 +82,9 @@ const mapConfig = computed(() => {
})
const provider = computed(() => mapConfig.value.provider || 'maplibre')
+watch(provider, (value) => {
+ if (value !== 'mapbox') detachMapboxAppearance()
+})
const isConfigured = computed(() =>
isMapServiceConfigured(mapConfig.value as Record<string, unknown>),
)
@@ -69,13 +106,14 @@ watch([isConfigured, () => props.setupNotice], () => {
if (import.meta.client) syncMapSetupNotice()
})
onBeforeUnmount(() => {
+ detachMapboxAppearance()
if (!props.setupNotice) return
hideMapSetupNotice()
})
const mapStyle = computed(() => {
if (provider.value === 'mapbox') {
- return mapConfig.value['mapbox.style'] || `mapbox://styles/mapbox/standard`
+ return mapConfig.value['mapbox.style'] || DEFAULT_MAPBOX_STYLE
} else {
const styleConfig =
colorMode.value === 'dark' ? ChronoFrameDarkStyle : ChronoFrameLightStyle
@@ -134,14 +172,17 @@ const mapStyle = computed(() => {
interactive: interactive,
attributionControl: attributionControl,
language: language,
- config: {
- basemap: {
- lightPreset: $colorMode.value === 'dark' ? 'night' : 'day',
- colorThemes: 'faded',
- },
- },
+ config:
+ mapStyle === DEFAULT_MAPBOX_STYLE
+ ? {
+ basemap: {
+ lightPreset: lightPreset,
+ colorThemes: 'faded',
+ },
+ }
+ : undefined,
}"
- @load="emit('load', $event as MapboxMap)"
+ @load="onMapboxLoad($event as MapboxMap)"
@zoom="emit('zoom')"
>
<slot />
diff --git a/packages/gallery/app/components/photo/MiniMap.vue b/packages/gallery/app/components/photo/MiniMap.vue
index 95fc4d8f..ac9a2581 100644
--- a/packages/gallery/app/components/photo/MiniMap.vue
+++ b/packages/gallery/app/components/photo/MiniMap.vue
@@ -1,9 +1,6 @@
<script lang="ts" setup>
import { motion } from 'motion-v'
-import {
- isMapboxMap,
- type MapInstance,
-} from '@chronoframe/gallery/shared/types/map'
+import type { MapInstance } from '@chronoframe/gallery/shared/types/map'
const props = defineProps<{
photo: Photo
@@ -13,24 +10,29 @@ const props = defineProps<{
const MAPID = 'minimap-info-panel'
-const config = useRuntimeConfig()
-
const loaded = ref(false)
const isAnimating = ref(false)
-const mapInstance = ref<MapInstance | null>(null)
+const mapInstance = shallowRef<MapInstance | null>(null)
+let readyTimer: ReturnType<typeof setTimeout> | null = null
let animationTimer: ReturnType<typeof setTimeout> | null = null
const onMapLoad = (map: MapInstance) => {
mapInstance.value = map
map.setCenter([props.longitude, props.latitude])
- setTimeout(() => {
+ if (readyTimer) clearTimeout(readyTimer)
+ readyTimer = setTimeout(() => {
loaded.value = true
+ readyTimer = null
}, 100)
}
const moveMapTo = (newLat: number, newLng: number) => {
// 动画持续时间
const DURATION = 1000
+ if (mapInstance.value && !loaded.value) {
+ mapInstance.value.setCenter([newLng, newLat])
+ return
+ }
if (mapInstance.value && loaded.value) {
// 清除之前的计时器
if (animationTimer) {
@@ -56,25 +58,10 @@ const moveMapTo = (newLat: number, newLng: number) => {
watch([() => props.latitude, () => props.longitude], ([newLat, newLng]) => {
moveMapTo(newLat, newLng)
- const map = mapInstance.value
- // Only available with Mapbox
- if (map && isMapboxMap(map as any, config.public.map.provider)) {
- // 根据拍摄时间决定四种 lightPreset: dawn / day / dusk / night
- const photoDate = new Date(props.photo.dateTaken || 0)
- const hours = photoDate.getHours()
- if (hours >= 5 && hours < 7) {
- ;(map as any).setConfigProperty('basemap', 'lightPreset', 'dawn')
- } else if (hours >= 7 && hours < 17) {
- ;(map as any).setConfigProperty('basemap', 'lightPreset', 'day')
- } else if (hours >= 17 && hours < 21) {
- ;(map as any).setConfigProperty('basemap', 'lightPreset', 'dusk')
- } else {
- ;(map as any).setConfigProperty('basemap', 'lightPreset', 'night')
- }
- }
})
onUnmounted(() => {
+ if (readyTimer) clearTimeout(readyTimer)
if (animationTimer) {
clearTimeout(animationTimer)
animationTimer = null
@@ -90,6 +77,7 @@ onUnmounted(() => {
class="w-full h-full relative overflow-hidden"
:map-id="MAPID"
:zoom="12"
+ :date-taken="photo.dateTaken"
:interactive="false"
:language="$i18n.locale"
@load="onMapLoad"
diff --git a/packages/gallery/shared/utils/map-appearance.ts b/packages/gallery/shared/utils/map-appearance.ts
new file mode 100644
index 00000000..8805506b
--- /dev/null
+++ b/packages/gallery/shared/utils/map-appearance.ts
@@ -0,0 +1,16 @@
+export const DEFAULT_MAPBOX_STYLE = 'mapbox://styles/mapbox/standard'
+export type MapLightPreset = 'dawn' | 'day' | 'dusk' | 'night'
+
+/** Match the self-hosted photo map's capture-time bands in the viewer's local time. */
+export function mapLightPreset(
+ dateTaken: string | null | undefined,
+ theme: string,
+): MapLightPreset {
+ if (!dateTaken) return theme === 'dark' ? 'night' : 'day'
+ const hour = new Date(dateTaken).getHours()
+ if (!Number.isFinite(hour)) return theme === 'dark' ? 'night' : 'day'
+ if (hour >= 5 && hour < 7) return 'dawn'
+ if (hour >= 7 && hour < 17) return 'day'
+ if (hour >= 17 && hour < 21) return 'dusk'
+ return 'night'
+}
diff --git a/tests/map-appearance.test.ts b/tests/map-appearance.test.ts
new file mode 100644
index 00000000..aae41635
--- /dev/null
+++ b/tests/map-appearance.test.ts
@@ -0,0 +1,249 @@
+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,
+ shallowRef,
+ watch,
+ nextTick,
+ effectScope,
+} from 'vue'
+import {
+ DEFAULT_MAPBOX_STYLE,
+ mapLightPreset,
+} from '../packages/gallery/shared/utils/map-appearance.ts'
+import { isMapServiceConfigured } from '../packages/gallery/shared/utils/map-service.ts'
+
+test('shared capture-time presets keep the self-hosted time bands and theme fallbacks', () => {
+ for (const [time, preset] of [
+ ['04:59', 'night'],
+ ['05:00', 'dawn'],
+ ['06:59', 'dawn'],
+ ['07:00', 'day'],
+ ['16:59', 'day'],
+ ['17:00', 'dusk'],
+ ['20:59', 'dusk'],
+ ['21:00', 'night'],
+ ]) {
+ assert.equal(mapLightPreset(`2026-10-31T${time}:00`, 'light'), preset)
+ }
+ assert.equal(mapLightPreset(null, 'dark'), 'night')
+ assert.equal(mapLightPreset(undefined, 'light'), 'day')
+ assert.equal(mapLightPreset('invalid', 'dark'), 'night')
+})
+
+test('the shared provider applies lighting on load, same-location photo changes, theme and style reloads', async () => {
+ const props = reactive<{ dateTaken: string | null }>({
+ dateTaken: '2026-10-31T06:00:00',
+ })
+ const theme = reactive({ value: 'light' })
+ const config = reactive<Record<string, string>>({
+ provider: 'mapbox',
+ 'mapbox.token': 'pk.public',
+ 'mapbox.style': '',
+ 'maplibre.token': 'maptiler_public',
+ 'maplibre.style': '',
+ })
+ const light = JSON.parse(
+ readFileSync(
+ 'packages/gallery/app/assets/mapStyles/chronoframe_light.json',
+ 'utf8',
+ ),
+ )
+ const dark = JSON.parse(
+ readFileSync(
+ 'packages/gallery/app/assets/mapStyles/chronoframe_dark.json',
+ 'utf8',
+ ),
+ )
+ let styleListener: (() => void) | undefined,
+ detached = 0,
+ ready = true
+ const presets: string[] = []
+ const map = {
+ isStyleLoaded: () => ready,
+ getStyle: () => ({ imports: [] }),
+ setConfigProperty: (_fragment: string, _key: string, value: string) =>
+ presets.push(value),
+ on: (_event: string, fn: () => void) => {
+ styleListener = fn
+ },
+ off: () => {
+ detached++
+ styleListener = undefined
+ },
+ }
+ const scope = effectScope(),
+ unmount: Array<() => void> = []
+ const source = readFileSync(
+ 'packages/gallery/app/components/map/Provider.vue',
+ 'utf8',
+ )
+ .split('<script lang="ts" setup>')[1]!
+ .split('</script>')[0]!
+ .replace(/^import[\s\S]*?from ['"][^'"]+['"]\s*\n/gm, '')
+ const code = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText
+ try {
+ const component = scope.run(() =>
+ vm.runInNewContext(
+ `${code.replaceAll('import.meta.client', 'false')};({onMapboxLoad,mapStyle,lightPreset})`,
+ {
+ exports: {},
+ computed,
+ shallowRef,
+ watch,
+ defineProps: () => props,
+ withDefaults: (p: unknown) => p,
+ defineEmits: () => () => {},
+ useColorMode: () => theme,
+ getSetting: () => config,
+ DEFAULT_MAPBOX_STYLE,
+ mapLightPreset,
+ isMapServiceConfigured,
+ ChronoFrameLightStyle: light,
+ ChronoFrameDarkStyle: dark,
+ useMapSetupNotice: () => ({ show: () => {}, hide: () => {} }),
+ onMounted: () => {},
+ onBeforeUnmount: (fn: () => void) => unmount.push(fn),
+ },
+ ),
+ ) as {
+ onMapboxLoad: (map: unknown) => void
+ mapStyle: {
+ value:
+ | string
+ | {
+ name?: string
+ glyphs: string
+ sources: { openmaptiles: { url: string } }
+ }
+ }
+ }
+ assert.equal(component.mapStyle.value, DEFAULT_MAPBOX_STYLE)
+ component.onMapboxLoad(map)
+ assert.equal(presets.at(-1), 'dawn')
+ props.dateTaken = '2026-10-31T18:00:00'
+ await nextTick()
+ assert.equal(presets.at(-1), 'dusk')
+ ready = false
+ props.dateTaken = '2026-10-31T22:00:00'
+ await nextTick()
+ assert.equal(presets.at(-1), 'dusk')
+ ready = true
+ styleListener!()
+ assert.equal(presets.at(-1), 'night')
+ props.dateTaken = null
+ await nextTick()
+ theme.value = 'dark'
+ await nextTick()
+ assert.equal(presets.at(-1), 'night')
+ theme.value = 'light'
+ await nextTick()
+ assert.equal(presets.at(-1), 'day')
+ config['mapbox.style'] = 'mapbox://styles/example/custom'
+ await nextTick()
+ const count = presets.length
+ styleListener!()
+ assert.equal(
+ presets.length,
+ count,
+ 'custom styles without basemap imports must not receive Standard config',
+ )
+ config.provider = 'maplibre'
+ await nextTick()
+ assert.ok(detached > 0)
+ const dayStyle = component.mapStyle.value as {
+ name?: string
+ glyphs: string
+ sources: { openmaptiles: { url: string } }
+ }
+ assert.equal(dayStyle.name, light.name)
+ assert.ok(dayStyle.glyphs.includes('key=maptiler_public'))
+ assert.ok(dayStyle.sources.openmaptiles.url.includes('key=maptiler_public'))
+ theme.value = 'dark'
+ await nextTick()
+ assert.equal(
+ (component.mapStyle.value as { name?: string }).name,
+ dark.name,
+ )
+ config['maplibre.style'] = 'https://example.com/custom-style.json'
+ await nextTick()
+ assert.equal(component.mapStyle.value, config['maplibre.style'])
+ } finally {
+ for (const fn of unmount) fn()
+ scope.stop()
+ }
+})
+
+test('shared mini maps follow photo coordinates during initial loading and clean up their timers', async () => {
+ const props = reactive({
+ latitude: 1,
+ longitude: 2,
+ photo: { dateTaken: '2026-10-31T06:00:00' },
+ })
+ const timers = new Map<number, () => void>(),
+ centers: number[][] = [],
+ flights: unknown[] = []
+ let nextTimer = 0,
+ unmount: () => void = () => {}
+ const source = readFileSync(
+ 'packages/gallery/app/components/photo/MiniMap.vue',
+ 'utf8',
+ )
+ .split('<script lang="ts" setup>')[1]!
+ .split('</script>')[0]!
+ .replace(/^import[\s\S]*?from ['"][^'"]+['"]\s*\n/gm, '')
+ const code = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText
+ const scope = effectScope()
+ try {
+ const component = scope.run(() =>
+ vm.runInNewContext(`${code};({onMapLoad})`, {
+ exports: {},
+ ref: shallowRef,
+ shallowRef,
+ watch,
+ defineProps: () => props,
+ setTimeout: (fn: () => void) => {
+ timers.set(++nextTimer, fn)
+ return nextTimer
+ },
+ clearTimeout: (id: number) => timers.delete(id),
+ onUnmounted: (fn: () => void) => {
+ unmount = fn
+ },
+ }),
+ ) as { onMapLoad: (map: unknown) => void }
+ component.onMapLoad({
+ setCenter: (point: number[]) => centers.push(Array.from(point)),
+ flyTo: (options: unknown) => flights.push(options),
+ })
+ props.latitude = 3
+ props.longitude = 4
+ await nextTick()
+ assert.deepEqual(centers.at(-1), [4, 3])
+ assert.equal(flights.length, 0)
+ const ready = timers.get(1)!
+ timers.delete(1)
+ ready()
+ props.latitude = 5
+ await nextTick()
+ assert.equal(flights.length, 1)
+ unmount()
+ assert.equal(timers.size, 0)
+ } finally {
+ scope.stop()
+ }
+})