From c2fcb81807c03f91bc2ae94bf2221dd271fc30fe Mon Sep 17 00:00:00 2001 From: Alan Grainger Date: Fri, 17 Jul 2026 14:27:51 +1200 Subject: [PATCH] #265 add grouping by day as well as month --- app/src/client/init.ts | 2 +- app/src/client/layout.ts | 26 ++++++--- app/src/client/state.ts | 4 +- app/src/gallery/builder.ts | 22 +++++++- app/src/immich.ts | 20 ++++++- app/src/shared/types.ts | 8 ++- app/src/types.ts | 8 +++ app/src/view/gallery.tsx | 6 +- app/tests/albumTimeline.test.ts | 13 ++++- app/tests/galleryGrouping.test.ts | 91 +++++++++++++++++++++++++++++++ docs/configuration.md | 2 +- 11 files changed, 180 insertions(+), 22 deletions(-) create mode 100644 app/tests/galleryGrouping.test.ts diff --git a/app/src/client/init.ts b/app/src/client/init.ts index 9eb651e..824e919 100644 --- a/app/src/client/init.ts +++ b/app/src/client/init.ts @@ -24,7 +24,7 @@ function init () { state.items = params.items || [] state.lightboxConfig = params.lightboxConfig || {} if (params.metadataConfig) state.metadataConfig = params.metadataConfig - state.groupByDate = !!params.groupByDate + state.groupByDate = params.groupByDate || false state.metaBase = params.metaBase || '' state.container = document.getElementById('gallery') if (!state.container) return diff --git a/app/src/client/layout.ts b/app/src/client/layout.ts index e084118..fe54a35 100644 --- a/app/src/client/layout.ts +++ b/app/src/client/layout.ts @@ -14,6 +14,7 @@ import { type HeaderEntry, type GroupSpec } from './state.js' +import type { GroupByDateMode } from '../shared/types.js' export interface LayoutResult { layout: LayoutEntry[] @@ -37,7 +38,7 @@ export function computeLayout (containerW: number): LayoutResult { const tileLayout: LayoutEntry[] = new Array(state.items.length) const newHeaders: HeaderEntry[] = [] const groups: GroupSpec[] = state.groupByDate - ? groupItemsByMonth() + ? groupItemsByDate(state.groupByDate) : [{ label: null, indices: itemIndices() }] const isMobile = containerW < MOBILE_BREAKPOINT let y = 0 @@ -65,14 +66,19 @@ function itemIndices (): number[] { return out } -function groupItemsByMonth (): GroupSpec[] { - // Preserve item order (already sorted desc by render.ts when grouping is on) +function groupItemsByDate (mode: GroupByDateMode): GroupSpec[] { + // Bucket key length: YYYY-MM (month) or YYYY-MM-DD (day). We slice the local + // timestamp, so no timezone maths is needed - the string already reads as + // the photographer's wall-clock (matching Immich's own timeline grouping). + const keyLen = mode === 'day' ? 10 : 7 + // Preserve item order (already sorted desc by builder.ts when grouping is on) const map = new Map() for (let i = 0; i < state.items.length; i++) { - const key = (state.items[i].fileCreatedAt || '').slice(0, 7) || 'undated' + const item = state.items[i] + const key = (item.localDateTime || item.fileCreatedAt || '').slice(0, keyLen) || 'undated' let g = map.get(key) if (!g) { - g = { label: monthLabel(key), indices: [] } + g = { label: dateLabel(key, mode), indices: [] } map.set(key, g) } g.indices.push(i) @@ -85,19 +91,21 @@ function groupItemsByMonth (): GroupSpec[] { return Array.from(map.values()) } -function monthLabel (key: string): string { +function dateLabel (key: string, mode: GroupByDateMode): string { if (key === 'undated') return 'Undated' const parts = key.split('-') const y = Number(parts[0]) const m = Number(parts[1]) + const d = Number(parts[2]) if (!y || !m) return key - // Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps - // the displayed month consistent with the UTC YYYY-MM bucket key. + // Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps the + // displayed date consistent with the bucket key (which is already local). return new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'long', + ...(mode === 'day' ? { day: 'numeric' } : {}), timeZone: 'UTC' - }).format(new Date(Date.UTC(y, m - 1, 1))) + }).format(new Date(Date.UTC(y, m - 1, mode === 'day' ? (d || 1) : 1))) } /** diff --git a/app/src/client/state.ts b/app/src/client/state.ts index 69dcd30..1016e0f 100644 --- a/app/src/client/state.ts +++ b/app/src/client/state.ts @@ -3,7 +3,7 @@ // top-level `let`s. Layout / scroll-tuning constants live here too because // they are read by multiple modules. SVG icon strings live in `icons.ts`. -import type { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types.js' +import type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js' // ----- layout / scroll tuning ---------------------------------------------- @@ -56,7 +56,7 @@ export const state = { items: [] as GalleryItem[], layout: [] as LayoutEntry[], headers: [] as HeaderEntry[], - groupByDate: false, + groupByDate: false as GroupByDateMode | false, container: null as HTMLElement | null, lightbox: null as PhotoSwipeLightboxInstance, lightboxConfig: {} as Partial, diff --git a/app/src/gallery/builder.ts b/app/src/gallery/builder.ts index bc78ea1..d361ef3 100644 --- a/app/src/gallery/builder.ts +++ b/app/src/gallery/builder.ts @@ -11,6 +11,7 @@ import { toString } from '../utils/text' import { h } from 'preact' import { renderPage } from '../view/render' import { Gallery, GalleryItem, GalleryProps } from '../view/gallery' +import type { GroupByDateMode } from '../shared/types' import { downloadFilename } from './filename' import { requiresOriginal } from './sizing' import { metadataGroupActive, pickExif } from './exif' @@ -28,10 +29,12 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb const publicBaseUrl = process.env.PUBLIC_BASE_URL || (res.req.protocol + '://' + res.req.headers.host) // Date grouping needs chronological order; sort newest-first when enabled - // (overrides any album.order the upstream applied). - const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false) + // (overrides any album.order the upstream applied). Sort by the same local + // timestamp the grouping buckets on, so buckets stay contiguous / ordered. + const groupByDate = groupByDateMode() if (groupByDate) { - share.assets.sort((a, b) => (b.fileCreatedAt || '').localeCompare(a.fileCreatedAt || '')) + const sortKey = (a: typeof share.assets[number]) => a.localDateTime || a.fileCreatedAt || '' + share.assets.sort((a, b) => sortKey(b).localeCompare(sortKey(a))) } // Metadata display flags. Read once here and forwarded to the client via @@ -107,6 +110,7 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb height, thumbhash: asset.thumbhash, fileCreatedAt: asset.fileCreatedAt, + localDateTime: asset.localDateTime, exif: shareMetadataAllowed ? pickExif(asset) : undefined, // Album grid items carry no exif / description / real filename yet; the // client fetches them from `metaBase` the first time the item opens. @@ -171,3 +175,15 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb function description (share: SharedLink) { return share?.album?.description || '' } + +/** + * Normalise the operator's `ipp.gallery.groupByDate` config into a grouping + * mode. Accepts `false` (off), `true` / `'month'` (legacy = month buckets) or + * `'day'` (day buckets); anything else is treated as off. + */ +function groupByDateMode (): GroupByDateMode | false { + const v = getConfigOption('ipp.gallery.groupByDate', false) + if (v === 'day') return 'day' + if (v === true || v === 'month') return 'month' + return false +} diff --git a/app/src/immich.ts b/app/src/immich.ts index 515719c..2dacc78 100644 --- a/app/src/immich.ts +++ b/app/src/immich.ts @@ -371,18 +371,36 @@ function ratioToDimensions (ratio: number): { width: number, height: number } { * filename / mime are filled in lazily on lightbox open (`needsDetail`). * `key` / `keyType` / `password` are stamped by the caller. */ +/** + * Reconstruct an asset's timezone-agnostic local timestamp from its UTC + * `fileCreatedAt` and `localOffsetHours`. Returns an ISO string whose date / + * time portion reads as the photographer's local wall-clock (the `Z` suffix is + * nominal, as with Immich's own `localDateTime`). Undefined if no timestamp. + */ +function localDateTimeFromOffset (fileCreatedAt?: string, offsetHours?: number): string | undefined { + if (!fileCreatedAt) return undefined + const ms = Date.parse(fileCreatedAt) + if (isNaN(ms)) return undefined + return new Date(ms + (offsetHours || 0) * 3600_000).toISOString() +} + function timelineBucketToAssets (bucket: TimelineBucketAssets): Asset[] { const assets: Asset[] = [] const count = bucket?.id?.length || 0 for (let i = 0; i < count; i++) { const { width, height } = ratioToDimensions(bucket.ratio?.[i]) + const fileCreatedAt = bucket.fileCreatedAt?.[i] assets.push({ id: bucket.id[i], key: '', keyType: KeyType.key, type: bucket.isImage?.[i] ? AssetType.image : AssetType.video, isTrashed: !!bucket.isTrashed?.[i], - fileCreatedAt: bucket.fileCreatedAt?.[i], + fileCreatedAt, + // The bucket response has no localDateTime; reconstruct it from the UTC + // timestamp plus the per-asset offset, matching what Immich's own + // timeline does when grouping by local day / month. + localDateTime: localDateTimeFromOffset(fileCreatedAt, bucket.localOffsetHours?.[i]), thumbhash: bucket.thumbhash?.[i] || undefined, width, height, diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts index 1c9a1f8..b218d58 100644 --- a/app/src/shared/types.ts +++ b/app/src/shared/types.ts @@ -11,6 +11,9 @@ * `.location.enableAll`) or the field's own per-field flag is true. * Strings are plain text (the client uses `textContent`, not `innerHTML`). */ + +export type GroupByDateMode = 'month' | 'day' + export interface GalleryExif { dateTimeOriginal?: string // ISO date string; client formats with Intl.DateTimeFormat fileName?: string @@ -48,6 +51,9 @@ export interface GalleryItem { height?: number thumbhash?: string fileCreatedAt?: string + // Photographer's local wall-clock timestamp, used for date grouping. See + // Asset.localDateTime. Falls back to fileCreatedAt when absent. + localDateTime?: string exif?: GalleryExif // True for album "grid" items whose exif / description / real download // filename haven't been loaded yet. The client fetches them from the @@ -98,6 +104,6 @@ export interface InitParams { openItem?: number lightboxConfig?: LightboxConfig metadataConfig?: MetadataConfig - groupByDate?: boolean + groupByDate?: GroupByDateMode | false metaBase?: string } diff --git a/app/src/types.ts b/app/src/types.ts index 3972a0e..6a60ff7 100644 --- a/app/src/types.ts +++ b/app/src/types.ts @@ -48,6 +48,11 @@ export interface Asset { originalMimeType?: string; password?: string; fileCreatedAt?: string; // May not exist - see https://github.com/alangrainger/immich-public-proxy/issues/61 + // Timezone-agnostic "taken" timestamp (photographer's local wall-clock). + // Immich groups its own timeline by this field. For individual shares it + // comes straight from the asset DTO; for album grid items it is synthesised + // from fileCreatedAt + localOffsetHours (see timelineBucketToAssets). + localDateTime?: string; type: AssetType; isTrashed: boolean; exifInfo?: ExifInfo; @@ -92,6 +97,9 @@ export interface TimelineBucketAssets { thumbhash: (string | null)[]; isTrashed: boolean[]; fileCreatedAt: string[]; + // UTC offset (hours, may be fractional) at the time each photo was taken. + // Applying it to fileCreatedAt yields the photographer's local time. + localOffsetHours: number[]; } export interface SharedLink { diff --git a/app/src/view/gallery.tsx b/app/src/view/gallery.tsx index 68eeb8d..c88a609 100644 --- a/app/src/view/gallery.tsx +++ b/app/src/view/gallery.tsx @@ -1,9 +1,9 @@ import { AssetType } from '../types' import { ThemeScript } from './theme' -import { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types' +import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' import { ASSET_VERSION } from '../version' -export type { GalleryItem, LightboxConfig, MetadataConfig } +export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } export interface GalleryProps { items: GalleryItem[] @@ -17,7 +17,7 @@ export interface GalleryProps { ogImageItem?: GalleryItem lightboxConfig: LightboxConfig metadataConfig: MetadataConfig - groupByDate: boolean + groupByDate: GroupByDateMode | false metaBase?: string } diff --git a/app/tests/albumTimeline.test.ts b/app/tests/albumTimeline.test.ts index 4814293..f75fb12 100644 --- a/app/tests/albumTimeline.test.ts +++ b/app/tests/albumTimeline.test.ts @@ -52,7 +52,8 @@ const bucketResponse = { ratio: [1.5, 0.5, 1], thumbhash: ['hashA', null, 'hashC'], isTrashed: [false, true, false], - fileCreatedAt: ['2026-06-03T00:00:00.000Z', '2026-06-02T00:00:00.000Z', '2026-06-01T00:00:00.000Z'] + fileCreatedAt: ['2026-06-03T00:00:00.000Z', '2026-06-02T00:00:00.000Z', '2026-06-01T00:00:00.000Z'], + localOffsetHours: [5.5, -8, 0] } function routeFetch (sharedLink: unknown) { @@ -100,6 +101,16 @@ describe('album timeline enumeration (Immich 3.0)', () => { expect(assets[0].width!).toBeGreaterThan(assets[0].height!) }) + it('synthesises localDateTime from fileCreatedAt + localOffsetHours', async () => { + vi.stubGlobal('fetch', routeFetch(sharedLinkResponse())) + const result = await getShareByKey(uniqueKey(), undefined, KeyType.key) + const assets = result.link!.assets + // aaa: 2026-06-03T00:00Z + 5.5h -> 05:30 local + expect(assets[0].localDateTime).toBe('2026-06-03T05:30:00.000Z') + // ccc: 2026-06-01T00:00Z + 0h -> unchanged + expect(assets[1].localDateTime).toBe('2026-06-01T00:00:00.000Z') + }) + it('stamps the share key/keyType onto every asset', async () => { vi.stubGlobal('fetch', routeFetch(sharedLinkResponse())) const key = uniqueKey() diff --git a/app/tests/galleryGrouping.test.ts b/app/tests/galleryGrouping.test.ts new file mode 100644 index 0000000..4f40434 --- /dev/null +++ b/app/tests/galleryGrouping.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { state } from '../src/client/state' +import { computeLayout } from '../src/client/layout' +import type { GalleryItem, GroupByDateMode } from '../src/shared/types' + +/* + * Exercises the date-grouping generalisation in client/layout.ts: month vs day + * bucketing, the localDateTime-over-fileCreatedAt precedence (the timezone + * boundary case), and the "all undated" header suppression. We assert on the + * bucket structure (header count / order) rather than the localised label + * strings, which vary with the test runner's locale. + */ + +function item (partial: Partial): GalleryItem { + return { + id: partial.id || Math.random().toString(), + type: 'IMAGE', + previewUrl: '', + thumbnailUrl: '', + downloadFilename: '', + width: 1000, + height: 800, + ...partial + } +} + +function labelsFor (items: GalleryItem[], mode: GroupByDateMode | false): Array { + state.items = items + state.groupByDate = mode + // Desktop width so the justified-rows path runs; grouping is width-agnostic. + return computeLayout(1200).headers.map(h => h.label) +} + +describe('gallery date grouping', () => { + beforeEach(() => { + state.items = [] + state.groupByDate = false + }) + + it('produces no headers when grouping is off', () => { + const items = [ + item({ localDateTime: '2024-12-25T10:00:00.000Z' }), + item({ localDateTime: '2024-11-01T10:00:00.000Z' }) + ] + expect(labelsFor(items, false)).toEqual([]) + }) + + it('buckets by month, collapsing same-month days into one header', () => { + const items = [ + item({ localDateTime: '2024-12-25T10:00:00.000Z' }), + item({ localDateTime: '2024-12-02T10:00:00.000Z' }), + item({ localDateTime: '2024-11-30T10:00:00.000Z' }) + ] + // Dec + Nov = 2 month headers + expect(labelsFor(items, 'month')).toHaveLength(2) + }) + + it('buckets by day, giving each distinct day its own header', () => { + const items = [ + item({ localDateTime: '2024-12-25T10:00:00.000Z' }), + item({ localDateTime: '2024-12-02T10:00:00.000Z' }), + item({ localDateTime: '2024-11-30T10:00:00.000Z' }) + ] + expect(labelsFor(items, 'day')).toHaveLength(3) + }) + + it('prefers localDateTime over fileCreatedAt for the bucket (timezone boundary)', () => { + // Shot at 23:00 local on the 25th; stored UTC ticks over to the 26th. + // Day grouping must follow the local date, so both land under the 25th. + const items = [ + item({ localDateTime: '2024-12-25T23:00:00.000Z', fileCreatedAt: '2024-12-26T04:00:00.000Z' }), + item({ localDateTime: '2024-12-25T21:00:00.000Z', fileCreatedAt: '2024-12-26T02:00:00.000Z' }) + ] + expect(labelsFor(items, 'day')).toHaveLength(1) + }) + + it('falls back to fileCreatedAt when localDateTime is absent', () => { + const items = [ + item({ fileCreatedAt: '2024-12-25T10:00:00.000Z' }), + item({ fileCreatedAt: '2024-11-30T10:00:00.000Z' }) + ] + expect(labelsFor(items, 'month')).toHaveLength(2) + }) + + it('suppresses the lone header when every item is undated', () => { + const items = [item({}), item({})] + // One "undated" bucket, but its header is dropped -> label is null + const labels = labelsFor(items, 'day') + expect(labels).toEqual([]) + }) +}) diff --git a/docs/configuration.md b/docs/configuration.md index 593a036..1a2056c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -84,7 +84,7 @@ Options that control how the gallery page is rendered. Configured under `ipp.gal | `singleItemAutoOpen` | `bool` | When a share contains a single item and is opened on its gallery page, automatically open the lightbox on the asset. Default `true`. | | `showTitle` | `bool` | Show a title on the gallery page. This is taken from the album title if it is an album being shared, otherwise the "Description" from the shared link will be used. | | `showDescription` | `bool` | Show the album description below the title. This only applies if it is an album which is being shared. | -| `groupByDate` | `bool` | Group the gallery's thumbnails by month, with headers like "December 2024" above each group. Sorts photos newest-first. Items missing a creation date end up under an "Undated" bucket at the end (or render without any header when the whole gallery is undated). **Requires "Show metadata" to be enabled on the share in Immich** - when that's off, Immich strips creation dates from the assets it returns to IPP, so grouping won't work. Default `false`. | +| `groupByDate` | `bool` or `string` | Group the gallery's thumbnails by date, with a header above each group. Set to `false` (default, no grouping), `true` / `"month"` for month headers like "December 2024", or `"day"` for day headers like "25 December 2024". Grouping uses each photo's local "taken" date (matching Immich's own timeline), and sorts photos newest-first. Items missing a creation date end up under an "Undated" bucket at the end (or render without any header when the whole gallery is undated). **Requires "Show metadata" to be enabled on the share in Immich** - when that's off, Immich strips creation dates from the assets it returns to IPP, so grouping won't work. | | `cacheTime` | `int` | How long (in seconds) browsers and any CDN may cache the gallery **page** before revalidating. Set this longer to reduce load on your server, but be aware that if you add new photos to a gallery they won't show up until the cache times out or you manually clear any downstream caches. | Example: show the gallery title and group photos by month.