Repository navigation
Expand file tree
/
Copy pathschedule.js
More file actions
391 lines (350 loc) · 12 KB
/
Copy pathschedule.js
File metadata and controls
391 lines (350 loc) · 12 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
export const SCHEDULE_URL = "https://coscup.org/2026/api/session";
export const SESSION_PAGE_ROOT = "https://coscup.org/2026/session/";
export const FORM_CONFIG = Object.freeze({
baseUrl:
"https://docs.google.com/forms/d/e/1FAIpQLSdZo95aSE3XKTxmkNiIuT9UCb8KYXuzISmMBdCrCklVb8Hptg/viewform",
titleEntry: "entry.1246257474",
trackEntry: "entry.2060906697",
});
const TAIPEI_TIME_ZONE = "Asia/Taipei";
function firstValue(...values) {
return values.find((value) => value !== undefined && value !== null && value !== "");
}
function asArray(value) {
if (Array.isArray(value)) return value;
if (value === undefined || value === null || value === "") return [];
return [value];
}
function localizedText(value, key = "name") {
if (value === undefined || value === null) return "";
if (typeof value === "string" || typeof value === "number") return String(value).trim();
if (typeof value === "object") {
const localizedValue = (candidate) =>
candidate && typeof candidate === "object" ? candidate[key] : candidate;
if (value[key] && typeof value[key] === "object") {
const nested = localizedText(value[key], key);
if (nested) return nested;
}
return String(
firstValue(
localizedValue(value.zh),
localizedValue(value["zh-hant"]),
localizedValue(value["zh-Hant"]),
localizedValue(value.zh_TW),
value.zh?.title,
value.zh?.name,
typeof value[key] === "object" ? undefined : value[key],
value.title,
value.name,
localizedValue(value.en),
value.en?.title,
value.en?.name,
"",
),
).trim();
}
return "";
}
function referenceId(value) {
if (value && typeof value === "object") {
return String(firstValue(value.id, value.code, value.value, ""));
}
return value === undefined || value === null ? "" : String(value);
}
function collectionIndex(collection) {
const index = new Map();
for (const item of asArray(collection)) {
const id = referenceId(item);
if (id) index.set(id, item);
}
return index;
}
function resolveName(value, index, key = "name") {
if (value && typeof value === "object") return localizedText(value, key);
const id = referenceId(value);
return localizedText(index.get(id), key) || id;
}
function toEpoch(value) {
if (typeof value === "number") {
return value < 10_000_000_000 ? value * 1000 : value;
}
if (typeof value !== "string" || !value.trim()) return Number.NaN;
const numeric = Number(value);
if (Number.isFinite(numeric) && /^\d+(\.\d+)?$/.test(value.trim())) {
return numeric < 10_000_000_000 ? numeric * 1000 : numeric;
}
return Date.parse(value);
}
function taipeiDateKey(epoch) {
if (!Number.isFinite(epoch)) return "";
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: TAIPEI_TIME_ZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(epoch);
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
return `${values.year}-${values.month}-${values.day}`;
}
function resolveTrackName(session, tagsIndex, sessionTypesIndex) {
const direct = firstValue(
session.track_name,
session.trackName,
session.community_name,
session.communityName,
session.community,
session.track,
);
const directName = localizedText(direct, "name");
if (directName) return directName;
const trackId = firstValue(session.track_id, session.trackId, session.community_id);
if (trackId) {
const resolved =
resolveName(trackId, tagsIndex, "name") || resolveName(trackId, sessionTypesIndex, "name");
if (resolved) return resolved;
}
// OPass `tags` currently contains language and difficulty labels, not the
// program track. The authoritative track is hydrated from the public
// session detail page instead of guessing from the first tag.
return "";
}
export function normalizeSchedule(rawData) {
const data = rawData?.data && !rawData.sessions ? rawData.data : rawData;
const groupedSessions =
data && typeof data === "object"
? Object.entries(data)
.filter(([key, value]) => /^\d{4}-\d{2}-\d{2}$/.test(key) && Array.isArray(value))
.flatMap(([, value]) => value)
: [];
const sessions = asArray(data?.sessions ?? data?.session ?? data?.schedule ?? groupedSessions);
const roomsIndex = collectionIndex(data?.rooms ?? data?.room);
const tagsIndex = collectionIndex(data?.tags ?? data?.tracks ?? data?.communities);
const sessionTypesIndex = collectionIndex(data?.session_types ?? data?.sessionTypes);
const speakersIndex = collectionIndex(data?.speakers ?? data?.speaker);
return sessions
.map((session, sourceIndex) => {
const id = String(
firstValue(
session.id,
session.session_id,
session.sessionId,
session.code,
session.proposal_code,
"",
),
).trim();
const roomValue = firstValue(
session.room,
session.room_id,
session.roomId,
session.venue,
session.location,
);
const roomId = referenceId(roomValue);
const roomName = resolveName(roomValue, roomsIndex, "name") || "未標示場地";
const startAt = toEpoch(
firstValue(session.start, session.start_at, session.startAt, session.begin),
);
const endAt = toEpoch(firstValue(session.end, session.end_at, session.endAt, session.finish));
const speakerNames = asArray(session.speakers ?? session.speaker)
.map((speaker) => resolveName(speaker, speakersIndex, "name"))
.filter(Boolean);
const trackValue = firstValue(
session.track,
session.track_id,
session.trackId,
session.community_id,
);
return {
id,
sourceIndex,
title:
localizedText(session, "title") ||
localizedText(session.title, "title") ||
"未命名議程",
trackName: resolveTrackName(session, tagsIndex, sessionTypesIndex),
trackId: referenceId(trackValue),
speakerNames,
roomId,
roomName,
startAt,
endAt,
dateKey: taipeiDateKey(startAt),
raw: session,
};
})
.filter((session) => session.id);
}
export function findSession(sessions, sessionId) {
const target = String(sessionId ?? "").trim();
if (!target) return null;
return sessions.find((session) => session.id === target) ?? null;
}
export function findPreviousSession(sessions, currentSession) {
if (!currentSession) return null;
const sameRoom = (session) => {
if (currentSession.roomId && session.roomId) return session.roomId === currentSession.roomId;
return session.roomName === currentSession.roomName;
};
if (Number.isFinite(currentSession.startAt)) {
return (
sessions
.filter(
(session) =>
session.id !== currentSession.id &&
sameRoom(session) &&
session.dateKey === currentSession.dateKey &&
Number.isFinite(session.startAt) &&
session.startAt < currentSession.startAt,
)
.sort((a, b) => b.startAt - a.startAt)[0] ?? null
);
}
return (
sessions
.filter(
(session) =>
session.id !== currentSession.id &&
sameRoom(session) &&
session.sourceIndex < currentSession.sourceIndex,
)
.sort((a, b) => b.sourceIndex - a.sourceIndex)[0] ?? null
);
}
export function findNextSession(sessions, currentSession) {
if (!currentSession) return null;
const sameRoom = (session) => {
if (currentSession.roomId && session.roomId) return session.roomId === currentSession.roomId;
return session.roomName === currentSession.roomName;
};
if (Number.isFinite(currentSession.startAt)) {
return (
sessions
.filter(
(session) =>
session.id !== currentSession.id &&
sameRoom(session) &&
session.dateKey === currentSession.dateKey &&
Number.isFinite(session.startAt) &&
session.startAt > currentSession.startAt,
)
.sort((a, b) => a.startAt - b.startAt)[0] ?? null
);
}
return (
sessions
.filter(
(session) =>
session.id !== currentSession.id &&
sameRoom(session) &&
session.sourceIndex > currentSession.sourceIndex,
)
.sort((a, b) => a.sourceIndex - b.sourceIndex)[0] ?? null
);
}
export function buildFeedbackUrl(session, config = FORM_CONFIG) {
const url = new URL(config.baseUrl);
url.searchParams.set("usp", "pp_url");
url.searchParams.set(config.titleEntry, session.title);
if (session.trackName) url.searchParams.set(config.trackEntry, session.trackName);
return url.toString();
}
function decodeHtmlText(value) {
const namedEntities = {
amp: "&",
apos: "'",
gt: ">",
lt: "<",
nbsp: " ",
quot: '"',
};
return value
.replace(/<[^>]*>/g, " ")
.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi, (match, entity) => {
if (entity[0] !== "#") return namedEntities[entity.toLowerCase()] ?? match;
const hexadecimal = entity[1]?.toLowerCase() === "x";
const codePoint = Number.parseInt(entity.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10);
return Number.isFinite(codePoint) ? String.fromCodePoint(codePoint) : match;
})
.replace(/\s+/g, " ")
.trim();
}
export function trackNameFromSessionHtml(html) {
if (typeof html !== "string") return "";
const match = html.match(
/<a\b[^>]*href=["'][^"']*\/2026\/(?:[a-z]{2}(?:-[a-z]+)?\/)?track\/[^"']+["'][^>]*>([\s\S]*?)<\/a>/i,
);
return match ? decodeHtmlText(match[1].replace(/<span\b[\s\S]*?<\/span>/gi, " ")) : "";
}
export async function fetchTrackName(
session,
{
fetchImpl = fetch,
timeoutMs = 12_000,
sessionPageRoot = SESSION_PAGE_ROOT,
} = {},
) {
if (session?.trackName) return session.trackName;
if (!session?.id) return "";
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
const url = new URL(`${encodeURIComponent(session.id)}/`, sessionPageRoot);
try {
const response = await fetchImpl(url, {
headers: { Accept: "text/html" },
cache: "no-store",
signal: controller.signal,
});
if (!response.ok) throw new Error(`讀取議程軌失敗(HTTP ${response.status})`);
return trackNameFromSessionHtml(await response.text());
} finally {
clearTimeout(timeout);
}
}
export function sessionIdFromLocation(locationLike) {
const url = new URL(locationLike.href);
const value = firstValue(
url.searchParams.get("session"),
url.searchParams.get("id"),
url.searchParams.get("session_id"),
url.searchParams.get("sessionId"),
url.hash ? decodeURIComponent(url.hash.slice(1)) : "",
);
return String(value ?? "").trim();
}
export async function fetchSchedule(
url = SCHEDULE_URL,
{ fetchImpl = fetch, timeoutMs = 12_000 } = {},
) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchImpl(url, {
headers: { Accept: "application/json" },
cache: "no-store",
signal: controller.signal,
});
if (!response.ok) throw new Error(`讀取議程資料失敗(HTTP ${response.status})`);
return normalizeSchedule(await response.json());
} finally {
clearTimeout(timeout);
}
}
export function formatSessionTime(session) {
if (!Number.isFinite(session.startAt)) return "時間未定";
const date = new Intl.DateTimeFormat("en-CA", {
timeZone: TAIPEI_TIME_ZONE,
year: "numeric",
month: "numeric",
day: "numeric",
}).format(session.startAt);
const timeFormatter = new Intl.DateTimeFormat("en-GB", {
timeZone: TAIPEI_TIME_ZONE,
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
const start = timeFormatter.format(session.startAt);
const end = Number.isFinite(session.endAt) ? timeFormatter.format(session.endAt) : "";
return `${date} ${start}${end ? `–${end}` : ""} (UTC+8)`;
}