-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeline.tsx
More file actions
383 lines (336 loc) · 12.9 KB
/
Copy pathTimeline.tsx
File metadata and controls
383 lines (336 loc) · 12.9 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
"use client";
import { useLayoutEffect, useEffect, useMemo, useRef, useState, Fragment } from "react";
import { useTranslations, useLocale } from "next-intl";
import type { MarkerData, SegmentData } from "@/lib/types";
import { formatMonthDayYear, createUTCDate, currentYear } from "@/lib/date-utils";
import TimelineMarker from "./TimelineMarker";
import TimelinePart from "./TimelinePart";
import styles from "@/styles/Timeline.module.css";
interface TimelineProps {
markers: MarkerData[];
segments: SegmentData[];
onRemove?: (eventKey: string) => void;
onToggleDeath?: (eventKey: string) => void;
canRemoveNow?: boolean;
zoomed?: boolean;
}
function makeNowMarker(name: string, locale: string = "en-US"): MarkerData {
return {
event: {
id: "0", name, description: null, year: currentYear(),
month: null, day: null, type: "", link: null, dateProperty: null,
deathYear: null, deathMonth: null, deathDay: null, useDeath: false,
},
label: formatMonthDayYear(createUTCDate(), locale),
position: 100,
};
}
// Module-level: survives component remounts during client navigation
let prevMarkerPositions: Map<string, number> | null = null;
let prevTimelineData: { markers: MarkerData[]; segments: SegmentData[] } | null = null;
interface AnimatedTimelineProps extends TimelineProps {
exit?: boolean;
zoomed?: boolean;
}
function eventKey(marker: MarkerData): string {
return `${marker.event.id}${marker.event.useDeath ? "~d" : ""}`;
}
function AnimatedTimeline({ markers, segments, exit = false, onRemove, onToggleDeath, canRemoveNow, zoomed }: AnimatedTimelineProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [flippedKeys, setFlippedKeys] = useState<Set<string>>(new Set());
const zoomedWidth = useMemo(() => {
if (!zoomed || markers.length < 2) return undefined;
if (typeof window !== "undefined" && window.innerWidth <= 640) return undefined;
// Normalize positions to the actual visible range
const first = markers[0].position;
const last = markers[markers.length - 1].position;
const range = last - first;
if (range <= 0) return undefined;
let minGap = Infinity;
for (let i = 1; i < markers.length; i++) {
const gap = markers[i].position - markers[i - 1].position;
if (gap > 0 && gap < minGap) minGap = gap;
}
if (minGap === Infinity || minGap === 0) return undefined;
// Express minGap as percentage of the visible range
const normalizedGap = (minGap / range) * 100;
const requiredVw = Math.ceil((12 * 100) / normalizedGap);
return `max(100%, ${requiredVw}vw)`;
}, [zoomed, markers]);
const zoomedHeight = useMemo(() => {
if (!zoomed || markers.length < 2) return undefined;
if (typeof window === "undefined" || window.innerWidth > 640) return undefined;
const first = markers[0].position;
const last = markers[markers.length - 1].position;
const range = last - first;
if (range <= 0) return undefined;
let minGap = Infinity;
for (let i = 1; i < markers.length; i++) {
const gap = markers[i].position - markers[i - 1].position;
if (gap > 0 && gap < minGap) minGap = gap;
}
if (minGap === Infinity || minGap === 0) return undefined;
const normalizedGap = (minGap / range) * 100;
// Each smallest gap needs ~120px visible height for cards to breathe;
// express as svh so the container scales with the viewport
const pxPerGap = 120;
const svh = pxPerGap / (window.innerHeight / 100);
const requiredSvh = Math.ceil((svh * 100) / normalizedGap);
return `${requiredSvh}svh`;
}, [zoomed, markers]);
// Re-measure after fonts load (card sizes depend on the serif font)
const [fontsReady, setFontsReady] = useState(false);
useEffect(() => {
document.fonts.ready.then(() => setFontsReady(true));
}, []);
// Detect overlapping info cards and flip alternating ones above/beside the line
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
if (exit) {
if (flippedKeys.size > 0) setFlippedKeys(new Set());
return;
}
const isVertical = window.matchMedia("(max-width: 640px)").matches;
const markerEls = Array.from(
container.querySelectorAll<HTMLElement>(`:scope > .${styles.marker}`)
);
const rects = markerEls.map((el) => {
const info = el.querySelector<HTMLElement>(`.${styles.markerInfo}`);
return info?.getBoundingClientRect() ?? null;
});
const flipped = new Set<string>();
if (isVertical) {
// Vertical layout: check vertical overlap, flip to left side of timeline
let lastRightBottom = -Infinity;
let lastLeftBottom = -Infinity;
for (let i = 0; i < markers.length; i++) {
const rect = rects[i];
if (!rect) continue;
const overlapRight = rect.top < lastRightBottom;
const overlapLeft = rect.top < lastLeftBottom;
if (!overlapRight) {
lastRightBottom = rect.bottom;
} else if (!overlapLeft) {
flipped.add(eventKey(markers[i]));
lastLeftBottom = rect.bottom;
} else {
if (lastLeftBottom - rect.top < lastRightBottom - rect.top) {
flipped.add(eventKey(markers[i]));
lastLeftBottom = rect.bottom;
} else {
lastRightBottom = rect.bottom;
}
}
}
} else {
// Horizontal layout: check horizontal overlap, flip above the line
let lastBelowRight = -Infinity;
let lastAboveRight = -Infinity;
for (let i = 0; i < markers.length; i++) {
const rect = rects[i];
if (!rect) continue;
const overlapBelow = rect.left < lastBelowRight;
const overlapAbove = rect.left < lastAboveRight;
if (!overlapBelow) {
lastBelowRight = rect.right;
} else if (!overlapAbove) {
flipped.add(eventKey(markers[i]));
lastAboveRight = rect.right;
} else {
// Both tracks overlap — pick the less crowded one
if (lastAboveRight - rect.left < lastBelowRight - rect.left) {
flipped.add(eventKey(markers[i]));
lastAboveRight = rect.right;
} else {
lastBelowRight = rect.right;
}
}
}
}
setFlippedKeys(flipped);
}, [markers, segments, exit, fontsReady, zoomed]);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const markerEls = Array.from(
container.querySelectorAll<HTMLElement>(`:scope > .${styles.marker}`)
);
const partEls = Array.from(
container.querySelectorAll<HTMLElement>(`:scope > .${styles.part}`)
);
if (markerEls.length < 2) return;
const isVertical = window.matchMedia("(max-width: 640px)").matches;
const containerRect = container.getBoundingClientRect();
const posProp = isVertical ? "offsetTop" : "offsetLeft";
const axis = isVertical ? "Y" : "X";
const scaleAxis = isVertical ? "scaleY" : "scaleX";
const duration = 1200;
const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const currentPositions = new Map<string, number>();
markers.forEach((marker, i) => {
currentPositions.set(marker.event.id, markerEls[i][posProp]);
});
if (prefersReducedMotion) {
if (!exit) prevMarkerPositions = currentPositions;
return;
}
const hasPrev = prevMarkerPositions !== null && prevMarkerPositions.size > 0;
const center = isVertical
? containerRect.height / 2
: containerRect.width / 2;
const elCenterPos = (el: HTMLElement) => {
const r = el.getBoundingClientRect();
return isVertical
? r.top - containerRect.top + r.height / 2
: r.left - containerRect.left + r.width / 2;
};
if (exit) {
// ── EXIT: converge to center, line shrinks ──
markerEls.forEach((el) => {
el.animate(
[
{ transform: `translate${axis}(0)` },
{ transform: `translate${axis}(${center - elCenterPos(el)}px)` },
],
{ duration: 800, easing: "ease-in", fill: "forwards" }
);
});
partEls.forEach((el) => {
el.style.transformOrigin = "center";
el.animate(
[
{ transform: `translate${axis}(0) ${scaleAxis}(1)` },
{ transform: `translate${axis}(${center - elCenterPos(el)}px) ${scaleAxis}(0)` },
],
{ duration: 800, easing: "ease-in", fill: "forwards" }
);
});
} else if (!hasPrev) {
// ── FIRST APPEARANCE: grow from center ──
markerEls.forEach((el) => {
el.animate(
[
{ transform: `translate${axis}(${center - elCenterPos(el)}px)` },
{ transform: `translate${axis}(0)` },
],
{ duration, easing: "ease-out" }
);
});
partEls.forEach((el) => {
el.style.transformOrigin = "center";
el.animate(
[
{ transform: `translate${axis}(${center - elCenterPos(el)}px) ${scaleAxis}(0)` },
{ transform: `translate${axis}(0) ${scaleAxis}(1)` },
],
{ duration, easing: "ease-out" }
);
});
} else {
// ── SUBSEQUENT: new markers slide from Now, existing FLIP ──
const nowMarkerIdx = markers.findIndex(m => m.event.id === "0");
const nowPos = nowMarkerIdx >= 0 ? markerEls[nowMarkerIdx][posProp] : markerEls[markerEls.length - 1][posProp];
markers.forEach((marker, i) => {
const el = markerEls[i];
const currentPos = el[posProp];
let offset = 0;
if (prevMarkerPositions!.has(marker.event.id)) {
offset = prevMarkerPositions!.get(marker.event.id)! - currentPos;
} else {
offset = nowPos - currentPos;
}
if (Math.abs(offset) > 1) {
el.animate(
[
{ transform: `translate${axis}(${offset}px)` },
{ transform: `translate${axis}(0)` },
],
{ duration, easing: "ease-out" }
);
}
});
}
if (!exit) {
prevMarkerPositions = currentPositions;
}
}, [markers, segments, exit]);
return (
<div
ref={containerRef}
className={`${styles.timeline}${zoomed ? ` ${styles.timelineZoomed}` : ""}`}
style={zoomedWidth ? { width: zoomedWidth } : zoomedHeight ? { height: zoomedHeight } : undefined}
>
{markers.map((marker, i) => (
<Fragment key={marker.event.id}>
<TimelineMarker
marker={marker}
flipped={flippedKeys.has(eventKey(marker))}
onRemove={onRemove && (marker.event.id !== "0" || canRemoveNow) ? () => onRemove(eventKey(marker)) : undefined}
onToggleDeath={onToggleDeath && marker.event.id !== "0" ? () => onToggleDeath(eventKey(marker)) : undefined}
/>
{i < segments.length && <TimelinePart segment={segments[i]} zoomed={zoomed} />}
</Fragment>
))}
</div>
);
}
export default function Timeline({ markers, segments, onRemove, onToggleDeath, canRemoveNow, zoomed }: TimelineProps) {
const t = useTranslations("common");
const locale = useLocale();
const hasMarkers = markers.length > 0;
const nowMarker = useMemo(() => makeNowMarker(t("now"), locale), [t, locale]);
// Initialize exiting from module-level state (survives remounts)
const [exiting, setExiting] = useState(
() => !hasMarkers && prevTimelineData !== null
);
const exitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Store data while we have markers
if (hasMarkers) {
prevTimelineData = { markers, segments };
}
// Handle enter/exit transitions
useLayoutEffect(() => {
if (hasMarkers) {
if (exitTimerRef.current) {
clearTimeout(exitTimerRef.current);
exitTimerRef.current = null;
}
if (exiting) setExiting(false);
} else if (exiting && !exitTimerRef.current) {
const exitDuration = window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 900;
exitTimerRef.current = setTimeout(() => {
setExiting(false);
prevMarkerPositions = null;
prevTimelineData = null;
exitTimerRef.current = null;
}, exitDuration);
}
}, [hasMarkers, exiting]);
// Cleanup timer on unmount
useEffect(() => {
return () => {
if (exitTimerRef.current) clearTimeout(exitTimerRef.current);
};
}, []);
// Exit: render old timeline with shrink animation
if (exiting && prevTimelineData) {
return (
<AnimatedTimeline
markers={prevTimelineData.markers}
segments={prevTimelineData.segments}
exit
/>
);
}
// Empty state
if (!hasMarkers) {
prevMarkerPositions = null;
return (
<div className={`${styles.timeline} ${styles.timelineEmpty}`}>
<TimelineMarker marker={nowMarker} />
</div>
);
}
return <AnimatedTimeline markers={markers} segments={segments} onRemove={onRemove} onToggleDeath={onToggleDeath} canRemoveNow={canRemoveNow} zoomed={zoomed} />;
}