Files
Quic/ui/src/helpers/mediaCaption.ts
T

113 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export type MediaCaption = {
date: string
city: string | null
}
// City abbreviations used in media filenames, e.g. `20251115@GZ000001.jpg`.
// Mirrors the abbreviation table in `photos/_plan.py`.
const CITY_BY_CODE: Record<string, string> = {
GZ: '广州',
FS: '佛山',
DG: '东莞',
SZ: '深圳',
ZS: '中山',
ZH: '珠海',
JM: '江门',
QY: '清远',
ZQ: '肇庆',
SG: '韶关',
ST: '汕头',
ZJ: '湛江',
YC: '盐城',
NJ: '南京',
SH: '上海',
HZ: '杭州',
NB: '宁波',
CD: '成都',
CQ: '重庆',
LS: '拉萨',
CZ: '长治',
TY: '太原',
BJ: '北京',
TJ: '天津',
XA: '西安',
WH: '武汉',
CS: '长沙',
KM: '昆明',
XM: '厦门',
FZ: '福州',
QD: '青岛',
JN: '济南',
ZZ: '郑州',
WLMQ: '乌鲁木齐',
XN: '西宁',
LZ: '兰州',
GY: '贵阳',
NN: '南宁',
HK: '海口',
SY: '三亚',
DL: '大连',
HEB: '哈尔滨',
CC: '长春',
HHHT: '呼和浩特',
// `TD` means the city is still to be determined.
TD: 'TBD',
}
const CITY_NAMES = Array.from(new Set(Object.values(CITY_BY_CODE)))
function pad(value: number): string {
return value < 10 ? `0${value}` : `${value}`
}
function parseDate(
title: string
): [year: number, month: number, day: number] | null {
const compact = title.match(/^(\d{4})(\d{2})(\d{2})/)
if (compact) {
return [Number(compact[1]), Number(compact[2]), Number(compact[3])]
}
const chinese = title.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/)
if (chinese) {
return [Number(chinese[1]), Number(chinese[2]), Number(chinese[3])]
}
const separated = title.match(/(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})/)
if (separated) {
return [Number(separated[1]), Number(separated[2]), Number(separated[3])]
}
return null
}
// Early photos whose city could not be determined were tagged as `TD`
// ("to be determined") when they were renamed, so they are shown as `TBD`.
function parseCity(title: string): string | null {
// Some original filenames contain the city name directly.
const namedCity = CITY_NAMES.find(name => title.includes(name))
if (namedCity) return namedCity
const codeMatch = title.match(/[@@]([A-Za-z]{2,5})/)
if (!codeMatch) return null
const code = codeMatch[1].toUpperCase()
return CITY_BY_CODE[code] ?? null
}
/**
* Build the caption shown on a media card from its filename, e.g.
* `20251115@GZ000075.jpg` becomes `{ date: '2025/11/15', city: '广州' }`.
*/
export function mediaCaption(title?: string | null): MediaCaption | null {
if (!title) return null
const date = parseDate(title)
if (!date) return null
const [year, month, day] = date
return {
date: `${year}/${pad(month)}/${pad(day)}`,
city: parseCity(title),
}
}