-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharchive.ts
More file actions
391 lines (321 loc) · 10.2 KB
/
archive.ts
File metadata and controls
391 lines (321 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import data from "@/db/media_contents.json";
export const BING_BASE_URL = process.env.BASE_URL || "https://www.bing.com";
export const PAGE_SIZE = 12;
export interface WallpaperItem {
Ssd: string;
FullDateString?: string;
ImageContent?: {
Title?: string;
Description?: string;
Copyright?: string;
Image?: {
Url?: string;
Wallpaper?: string;
Downloadable?: boolean;
};
};
}
interface WallpaperArchive {
mediaContents: WallpaperItem[];
}
const wallpaperArchive = data as WallpaperArchive;
const sortedWallpapers = [...wallpaperArchive.mediaContents].sort((a, b) =>
b.Ssd.localeCompare(a.Ssd)
);
const wallpaperBySsd = new Map(
sortedWallpapers.map((wallpaper) => [wallpaper.Ssd, wallpaper] as const)
);
interface DateParts {
year: string;
month: string;
day: string;
}
export function toAbsoluteUrl(path?: string) {
if (!path) return "";
return path.startsWith("http") ? path : `${BING_BASE_URL}${path}`;
}
export function toProxyImageUrl(path?: string) {
const absoluteUrl = toAbsoluteUrl(path);
if (!absoluteUrl) return "";
const params = new URLSearchParams({
url: absoluteUrl,
});
return `/api/image?${params.toString()}`;
}
export function getAllWallpapers() {
return sortedWallpapers;
}
export function getWallpaperBySsd(ssd: string) {
return wallpaperBySsd.get(ssd);
}
export function getRelatedWallpapers(ssd: string, limit = 3) {
return getRelatedWallpapersFromList(getAllWallpapers(), ssd, limit);
}
export function getRelatedWallpapersFromList(
wallpapers: WallpaperItem[],
ssd: string,
limit = 3
) {
const currentIndex = wallpapers.findIndex((wallpaper) => wallpaper.Ssd === ssd);
if (currentIndex === -1) {
return wallpapers.filter((wallpaper) => wallpaper.Ssd !== ssd).slice(0, limit);
}
const related: WallpaperItem[] = [];
for (let offset = 2; related.length < limit; offset += 1) {
const newerWallpaper = wallpapers[currentIndex - offset];
const olderWallpaper = wallpapers[currentIndex + offset];
if (!newerWallpaper && !olderWallpaper) {
break;
}
if (newerWallpaper) {
related.push(newerWallpaper);
}
if (related.length < limit && olderWallpaper) {
related.push(olderWallpaper);
}
}
return related;
}
export function getAdjacentWallpapers(ssd: string) {
const wallpapers = getAllWallpapers()
return getAdjacentWallpapersFromList(wallpapers, ssd)
}
export function getAdjacentWallpapersFromList(
wallpapers: WallpaperItem[],
ssd: string
) {
const currentIndex = wallpapers.findIndex((wallpaper) => wallpaper.Ssd === ssd)
if (currentIndex === -1) {
return {
previous: null,
next: null,
}
}
return {
previous: wallpapers[currentIndex + 1] ?? null,
next: wallpapers[currentIndex - 1] ?? null,
}
}
export function getDateParts(ssd: string): DateParts | null {
const match = ssd.match(/^(\d{4})(\d{2})(\d{2})/);
if (!match) return null;
const [, year, month, day] = match;
return { year, month, day };
}
export function getYearOptions(wallpapers: WallpaperItem[]) {
const years = wallpapers
.map((item) => getDateParts(item.Ssd)?.year)
.filter((value): value is string => Boolean(value));
return [...new Set(years)].sort((a, b) => Number(b) - Number(a));
}
export function getMonthOptions(wallpapers: WallpaperItem[], year?: string) {
const months = wallpapers
.map((item) => getDateParts(item.Ssd))
.filter((parts): parts is DateParts => Boolean(parts))
.filter((parts) => !year || parts.year === year)
.map((parts) => parts.month);
return [...new Set(months)].sort((a, b) => Number(a) - Number(b));
}
export function filterWallpapersByDate(
wallpapers: WallpaperItem[],
year?: string,
month?: string
) {
if (!year && !month) return wallpapers;
return wallpapers.filter((wallpaper) => {
const parts = getDateParts(wallpaper.Ssd);
if (!parts) return false;
if (year && parts.year !== year) return false;
if (month && parts.month !== month) return false;
return true;
});
}
type SearchField = "title" | "desc" | "copyright" | "date" | "ssd";
interface SearchClause {
excludes: string[];
fields: Array<{ field: SearchField; value: string }>;
phrase: string;
}
interface SearchHighlightTerms {
title: string[];
description: string[];
}
function normalizeSearchValue(value?: string) {
return value?.normalize("NFKC").trim().toLowerCase() ?? "";
}
function parseSearchClause(clause: string): SearchClause {
const excludes: string[] = [];
const fields: Array<{ field: SearchField; value: string }> = [];
let remaining = clause;
remaining = remaining.replace(
/(^|\s)-(("[^"]+")|(\S+))/g,
(_match, leadingWhitespace: string, token: string) => {
const normalizedToken = normalizeSearchValue(token.replace(/^"|"$/g, ""));
if (normalizedToken) {
excludes.push(normalizedToken);
}
return leadingWhitespace;
}
);
remaining = remaining.replace(
/(^|\s)(title|desc|description|copyright|date|ssd):(("[^"]+")|(\S+))/g,
(
_match,
leadingWhitespace: string,
rawField: string,
token: string
) => {
const field =
rawField === "description" ? "desc" : (rawField as SearchField);
const normalizedToken = normalizeSearchValue(token.replace(/^"|"$/g, ""));
if (normalizedToken) {
fields.push({ field, value: normalizedToken });
}
return leadingWhitespace;
}
);
return {
excludes,
fields,
phrase: normalizeSearchValue(remaining),
};
}
function matchesSearchClause(wallpaper: WallpaperItem, clause: SearchClause) {
const haystack = [
wallpaper.Ssd,
wallpaper.FullDateString,
wallpaper.ImageContent?.Title,
wallpaper.ImageContent?.Description,
wallpaper.ImageContent?.Copyright,
]
.filter(Boolean)
.join(" ")
.toLowerCase();
const fieldHaystacks: Record<SearchField, string> = {
title: normalizeSearchValue(wallpaper.ImageContent?.Title),
desc: normalizeSearchValue(wallpaper.ImageContent?.Description),
copyright: normalizeSearchValue(wallpaper.ImageContent?.Copyright),
date: normalizeSearchValue(wallpaper.FullDateString ?? wallpaper.Ssd),
ssd: normalizeSearchValue(wallpaper.Ssd),
};
if (clause.excludes.some((term) => haystack.includes(term))) {
return false;
}
if (
clause.fields.some(({ field, value }) => !fieldHaystacks[field].includes(value))
) {
return false;
}
if (clause.phrase && !haystack.includes(clause.phrase)) {
return false;
}
return clause.fields.length > 0 || clause.excludes.length > 0 || Boolean(clause.phrase);
}
function scoreSearchClause(wallpaper: WallpaperItem, clause: SearchClause) {
const title = normalizeSearchValue(wallpaper.ImageContent?.Title);
const description = normalizeSearchValue(wallpaper.ImageContent?.Description);
const copyright = normalizeSearchValue(wallpaper.ImageContent?.Copyright);
const date = normalizeSearchValue(wallpaper.FullDateString ?? wallpaper.Ssd);
const ssd = normalizeSearchValue(wallpaper.Ssd);
let score = 0;
if (clause.phrase) {
if (title === clause.phrase) score += 120;
else if (title.includes(clause.phrase)) score += 90;
else if (description.includes(clause.phrase)) score += 60;
else if (copyright.includes(clause.phrase)) score += 40;
else if (date.includes(clause.phrase) || ssd.includes(clause.phrase)) score += 30;
}
for (const { field, value } of clause.fields) {
if (field === "title") {
score += title === value ? 110 : title.includes(value) ? 85 : 0;
}
if (field === "desc") {
score += description.includes(value) ? 65 : 0;
}
if (field === "copyright") {
score += copyright.includes(value) ? 45 : 0;
}
if (field === "date") {
score += date.includes(value) ? 35 : 0;
}
if (field === "ssd") {
score += ssd.includes(value) ? 35 : 0;
}
}
return score;
}
export function getSearchHighlightTerms(query?: string): SearchHighlightTerms {
const normalizedQuery = normalizeSearchValue(query);
if (!normalizedQuery) {
return {
title: [],
description: [],
};
}
const titleTerms = new Set<string>();
const descriptionTerms = new Set<string>();
const clauses = normalizedQuery
.split(",")
.map((term) => parseSearchClause(term.trim()))
.filter(Boolean);
for (const clause of clauses) {
if (clause.phrase) {
titleTerms.add(clause.phrase);
descriptionTerms.add(clause.phrase);
}
for (const fieldEntry of clause.fields) {
if (fieldEntry.field === "title") {
titleTerms.add(fieldEntry.value);
}
if (fieldEntry.field === "desc") {
descriptionTerms.add(fieldEntry.value);
}
if (fieldEntry.field === "date" || fieldEntry.field === "ssd") {
titleTerms.add(fieldEntry.value);
descriptionTerms.add(fieldEntry.value);
}
}
}
return {
title: [...titleTerms].sort((a, b) => b.length - a.length),
description: [...descriptionTerms].sort((a, b) => b.length - a.length),
};
}
export function searchWallpapers(wallpapers: WallpaperItem[], query?: string) {
const normalizedQuery = normalizeSearchValue(query);
if (!normalizedQuery) return wallpapers;
const clauses = normalizedQuery
.split(",")
.map((term) => parseSearchClause(term.trim()))
.filter(Boolean);
return wallpapers
.map((wallpaper) => {
const matchingClauses = clauses.filter((clause) => matchesSearchClause(wallpaper, clause));
const score = matchingClauses.reduce(
(highest, clause) => Math.max(highest, scoreSearchClause(wallpaper, clause)),
0
);
return {
wallpaper,
score,
};
})
.filter(({ score }) => score > 0)
.sort((left, right) => {
if (right.score !== left.score) {
return right.score - left.score;
}
return right.wallpaper.Ssd.localeCompare(left.wallpaper.Ssd);
})
.map(({ wallpaper }) => wallpaper);
}
export function paginateWallpapers(wallpapers: WallpaperItem[], page: number) {
const totalPages = Math.max(1, Math.ceil(wallpapers.length / PAGE_SIZE));
const currentPage = Math.min(Math.max(1, page), totalPages);
const start = (currentPage - 1) * PAGE_SIZE;
return {
currentPage,
totalPages,
items: wallpapers.slice(start, start + PAGE_SIZE),
};
}