#265 add grouping by day as well as month
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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<string, GroupSpec>()
|
||||
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)))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<LightboxConfig>,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+19
-1
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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([])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user