#265 add grouping by day as well as month

This commit is contained in:
Alan Grainger
2026-07-17 14:27:51 +12:00
parent 4e7af0ab57
commit c2fcb81807
11 changed files with 180 additions and 22 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ function init () {
state.items = params.items || [] state.items = params.items || []
state.lightboxConfig = params.lightboxConfig || {} state.lightboxConfig = params.lightboxConfig || {}
if (params.metadataConfig) state.metadataConfig = params.metadataConfig if (params.metadataConfig) state.metadataConfig = params.metadataConfig
state.groupByDate = !!params.groupByDate state.groupByDate = params.groupByDate || false
state.metaBase = params.metaBase || '' state.metaBase = params.metaBase || ''
state.container = document.getElementById('gallery') state.container = document.getElementById('gallery')
if (!state.container) return if (!state.container) return
+17 -9
View File
@@ -14,6 +14,7 @@ import {
type HeaderEntry, type HeaderEntry,
type GroupSpec type GroupSpec
} from './state.js' } from './state.js'
import type { GroupByDateMode } from '../shared/types.js'
export interface LayoutResult { export interface LayoutResult {
layout: LayoutEntry[] layout: LayoutEntry[]
@@ -37,7 +38,7 @@ export function computeLayout (containerW: number): LayoutResult {
const tileLayout: LayoutEntry[] = new Array(state.items.length) const tileLayout: LayoutEntry[] = new Array(state.items.length)
const newHeaders: HeaderEntry[] = [] const newHeaders: HeaderEntry[] = []
const groups: GroupSpec[] = state.groupByDate const groups: GroupSpec[] = state.groupByDate
? groupItemsByMonth() ? groupItemsByDate(state.groupByDate)
: [{ label: null, indices: itemIndices() }] : [{ label: null, indices: itemIndices() }]
const isMobile = containerW < MOBILE_BREAKPOINT const isMobile = containerW < MOBILE_BREAKPOINT
let y = 0 let y = 0
@@ -65,14 +66,19 @@ function itemIndices (): number[] {
return out return out
} }
function groupItemsByMonth (): GroupSpec[] { function groupItemsByDate (mode: GroupByDateMode): GroupSpec[] {
// Preserve item order (already sorted desc by render.ts when grouping is on) // 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<string, GroupSpec>() const map = new Map<string, GroupSpec>()
for (let i = 0; i < state.items.length; i++) { 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) let g = map.get(key)
if (!g) { if (!g) {
g = { label: monthLabel(key), indices: [] } g = { label: dateLabel(key, mode), indices: [] }
map.set(key, g) map.set(key, g)
} }
g.indices.push(i) g.indices.push(i)
@@ -85,19 +91,21 @@ function groupItemsByMonth (): GroupSpec[] {
return Array.from(map.values()) return Array.from(map.values())
} }
function monthLabel (key: string): string { function dateLabel (key: string, mode: GroupByDateMode): string {
if (key === 'undated') return 'Undated' if (key === 'undated') return 'Undated'
const parts = key.split('-') const parts = key.split('-')
const y = Number(parts[0]) const y = Number(parts[0])
const m = Number(parts[1]) const m = Number(parts[1])
const d = Number(parts[2])
if (!y || !m) return key if (!y || !m) return key
// Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps // Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps the
// the displayed month consistent with the UTC YYYY-MM bucket key. // displayed date consistent with the bucket key (which is already local).
return new Intl.DateTimeFormat(undefined, { return new Intl.DateTimeFormat(undefined, {
year: 'numeric', year: 'numeric',
month: 'long', month: 'long',
...(mode === 'day' ? { day: 'numeric' } : {}),
timeZone: 'UTC' timeZone: 'UTC'
}).format(new Date(Date.UTC(y, m - 1, 1))) }).format(new Date(Date.UTC(y, m - 1, mode === 'day' ? (d || 1) : 1)))
} }
/** /**
+2 -2
View File
@@ -3,7 +3,7 @@
// top-level `let`s. Layout / scroll-tuning constants live here too because // 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`. // 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 ---------------------------------------------- // ----- layout / scroll tuning ----------------------------------------------
@@ -56,7 +56,7 @@ export const state = {
items: [] as GalleryItem[], items: [] as GalleryItem[],
layout: [] as LayoutEntry[], layout: [] as LayoutEntry[],
headers: [] as HeaderEntry[], headers: [] as HeaderEntry[],
groupByDate: false, groupByDate: false as GroupByDateMode | false,
container: null as HTMLElement | null, container: null as HTMLElement | null,
lightbox: null as PhotoSwipeLightboxInstance, lightbox: null as PhotoSwipeLightboxInstance,
lightboxConfig: {} as Partial<LightboxConfig>, lightboxConfig: {} as Partial<LightboxConfig>,
+19 -3
View File
@@ -11,6 +11,7 @@ import { toString } from '../utils/text'
import { h } from 'preact' import { h } from 'preact'
import { renderPage } from '../view/render' import { renderPage } from '../view/render'
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery' import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
import type { GroupByDateMode } from '../shared/types'
import { downloadFilename } from './filename' import { downloadFilename } from './filename'
import { requiresOriginal } from './sizing' import { requiresOriginal } from './sizing'
import { metadataGroupActive, pickExif } from './exif' 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) const publicBaseUrl = process.env.PUBLIC_BASE_URL || (res.req.protocol + '://' + res.req.headers.host)
// Date grouping needs chronological order; sort newest-first when enabled // Date grouping needs chronological order; sort newest-first when enabled
// (overrides any album.order the upstream applied). // (overrides any album.order the upstream applied). Sort by the same local
const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false) // timestamp the grouping buckets on, so buckets stay contiguous / ordered.
const groupByDate = groupByDateMode()
if (groupByDate) { 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 // 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, height,
thumbhash: asset.thumbhash, thumbhash: asset.thumbhash,
fileCreatedAt: asset.fileCreatedAt, fileCreatedAt: asset.fileCreatedAt,
localDateTime: asset.localDateTime,
exif: shareMetadataAllowed ? pickExif(asset) : undefined, exif: shareMetadataAllowed ? pickExif(asset) : undefined,
// Album grid items carry no exif / description / real filename yet; the // Album grid items carry no exif / description / real filename yet; the
// client fetches them from `metaBase` the first time the item opens. // 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) { function description (share: SharedLink) {
return share?.album?.description || '' 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
}
+19 -1
View File
@@ -371,18 +371,36 @@ function ratioToDimensions (ratio: number): { width: number, height: number } {
* filename / mime are filled in lazily on lightbox open (`needsDetail`). * filename / mime are filled in lazily on lightbox open (`needsDetail`).
* `key` / `keyType` / `password` are stamped by the caller. * `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[] { function timelineBucketToAssets (bucket: TimelineBucketAssets): Asset[] {
const assets: Asset[] = [] const assets: Asset[] = []
const count = bucket?.id?.length || 0 const count = bucket?.id?.length || 0
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const { width, height } = ratioToDimensions(bucket.ratio?.[i]) const { width, height } = ratioToDimensions(bucket.ratio?.[i])
const fileCreatedAt = bucket.fileCreatedAt?.[i]
assets.push({ assets.push({
id: bucket.id[i], id: bucket.id[i],
key: '', key: '',
keyType: KeyType.key, keyType: KeyType.key,
type: bucket.isImage?.[i] ? AssetType.image : AssetType.video, type: bucket.isImage?.[i] ? AssetType.image : AssetType.video,
isTrashed: !!bucket.isTrashed?.[i], 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, thumbhash: bucket.thumbhash?.[i] || undefined,
width, width,
height, height,
+7 -1
View File
@@ -11,6 +11,9 @@
* `.location.enableAll`) or the field's own per-field flag is true. * `.location.enableAll`) or the field's own per-field flag is true.
* Strings are plain text (the client uses `textContent`, not `innerHTML`). * Strings are plain text (the client uses `textContent`, not `innerHTML`).
*/ */
export type GroupByDateMode = 'month' | 'day'
export interface GalleryExif { export interface GalleryExif {
dateTimeOriginal?: string // ISO date string; client formats with Intl.DateTimeFormat dateTimeOriginal?: string // ISO date string; client formats with Intl.DateTimeFormat
fileName?: string fileName?: string
@@ -48,6 +51,9 @@ export interface GalleryItem {
height?: number height?: number
thumbhash?: string thumbhash?: string
fileCreatedAt?: 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 exif?: GalleryExif
// True for album "grid" items whose exif / description / real download // True for album "grid" items whose exif / description / real download
// filename haven't been loaded yet. The client fetches them from the // filename haven't been loaded yet. The client fetches them from the
@@ -98,6 +104,6 @@ export interface InitParams {
openItem?: number openItem?: number
lightboxConfig?: LightboxConfig lightboxConfig?: LightboxConfig
metadataConfig?: MetadataConfig metadataConfig?: MetadataConfig
groupByDate?: boolean groupByDate?: GroupByDateMode | false
metaBase?: string metaBase?: string
} }
+8
View File
@@ -48,6 +48,11 @@ export interface Asset {
originalMimeType?: string; originalMimeType?: string;
password?: string; password?: string;
fileCreatedAt?: string; // May not exist - see https://github.com/alangrainger/immich-public-proxy/issues/61 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; type: AssetType;
isTrashed: boolean; isTrashed: boolean;
exifInfo?: ExifInfo; exifInfo?: ExifInfo;
@@ -92,6 +97,9 @@ export interface TimelineBucketAssets {
thumbhash: (string | null)[]; thumbhash: (string | null)[];
isTrashed: boolean[]; isTrashed: boolean[];
fileCreatedAt: string[]; 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 { export interface SharedLink {
+3 -3
View File
@@ -1,9 +1,9 @@
import { AssetType } from '../types' import { AssetType } from '../types'
import { ThemeScript } from './theme' import { ThemeScript } from './theme'
import { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types' import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
import { ASSET_VERSION } from '../version' import { ASSET_VERSION } from '../version'
export type { GalleryItem, LightboxConfig, MetadataConfig } export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
export interface GalleryProps { export interface GalleryProps {
items: GalleryItem[] items: GalleryItem[]
@@ -17,7 +17,7 @@ export interface GalleryProps {
ogImageItem?: GalleryItem ogImageItem?: GalleryItem
lightboxConfig: LightboxConfig lightboxConfig: LightboxConfig
metadataConfig: MetadataConfig metadataConfig: MetadataConfig
groupByDate: boolean groupByDate: GroupByDateMode | false
metaBase?: string metaBase?: string
} }
+12 -1
View File
@@ -52,7 +52,8 @@ const bucketResponse = {
ratio: [1.5, 0.5, 1], ratio: [1.5, 0.5, 1],
thumbhash: ['hashA', null, 'hashC'], thumbhash: ['hashA', null, 'hashC'],
isTrashed: [false, true, false], 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) { function routeFetch (sharedLink: unknown) {
@@ -100,6 +101,16 @@ describe('album timeline enumeration (Immich 3.0)', () => {
expect(assets[0].width!).toBeGreaterThan(assets[0].height!) 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 () => { it('stamps the share key/keyType onto every asset', async () => {
vi.stubGlobal('fetch', routeFetch(sharedLinkResponse())) vi.stubGlobal('fetch', routeFetch(sharedLinkResponse()))
const key = uniqueKey() const key = uniqueKey()
+91
View File
@@ -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>): 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<string> {
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([])
})
})
+1 -1
View File
@@ -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`. | | `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. | | `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. | | `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. | | `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. Example: show the gallery title and group photos by month.