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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
|
import { useCallback, useEffect, useMemo, useState } from "react";
import type {
ColumnSnapshot,
ColumnState,
ColumnView,
DeckAccount,
DeckColumn,
FullscreenState,
TimelineState,
} from "../types/app";
import type { Tweet } from "../lib/fetching/types";
import { twitterClient } from "../lib/client/twitterClient";
import { TweetCard } from "./TweetCard";
export type TimelineConfig = DeckColumn & {
kind: Exclude<DeckColumn["kind"], "chat">;
};
type TimelineView = Extract<ColumnView, { type: "timeline" }>;
interface TimelineColumnProps {
column: TimelineConfig;
account: DeckAccount;
onRemove: () => void;
onStateChange: (columnId: string, state: ColumnState) => void;
onSnapshot: (columnId: string, snapshot: ColumnSnapshot) => void;
onEnterFullscreen: (payload: FullscreenState) => void;
columnIndex: number;
}
export function TimelineColumn({
column,
account,
onRemove,
onStateChange,
onSnapshot,
onEnterFullscreen,
columnIndex,
}: TimelineColumnProps) {
const [state, setState] = useState<TimelineState>({
tweets: [],
cursorTop: "",
cursorBottom: "",
isLoading: false,
isAppending: false,
});
const [error, setError] = useState<string | undefined>();
const [transitionDirection, setTransitionDirection] = useState<
"forward" | "backward" | null
>(null);
const baseView = useMemo(
() => createBaseView(column),
[column.kind, column.title, column.listId, column.listName],
);
const initialStack = useMemo<ColumnView[]>(() => {
return column.state?.stack?.length ? column.state.stack : [baseView];
}, [column.state, baseView]);
const [viewStack, setViewStack] = useState<ColumnView[]>(initialStack);
useEffect(() => {
setViewStack(initialStack);
}, [initialStack]);
const activeView = viewStack[viewStack.length - 1] ?? baseView;
const canGoBack = viewStack.length > 1;
const descriptor = useMemo(
() => describeView(column, activeView),
[column, activeView],
);
const handleMaximize = useCallback(() => {
onEnterFullscreen({
column: column,
columnLabel: descriptor.label,
accent: account.accent,
tweets: state.tweets,
index: 0,
columnIndex,
});
}, [
state.tweets,
onEnterFullscreen,
column.id,
descriptor.label,
account.accent,
columnIndex,
]);
const handleAnimationEnd = useCallback(() => {
setTransitionDirection(null);
}, []);
const pushView = useCallback((view: ColumnView) => {
setTransitionDirection("forward");
setViewStack((prev) => [...prev, view]);
}, []);
const popView = useCallback(() => {
setViewStack((prev) => {
if (prev.length <= 1) return prev;
setTransitionDirection("backward");
return prev.slice(0, -1);
});
}, []);
useEffect(() => {
onStateChange(column.id, { stack: viewStack });
}, [column.id, onStateChange, viewStack]);
useEffect(() => {
onSnapshot(column.id, { tweets: state.tweets, label: descriptor.label });
}, [column.id, state.tweets, descriptor.label, onSnapshot]);
const fetchPage = useCallback(
async (cursor?: string) => {
const payload: Record<string, unknown> = { cookie: account.cookie };
//
let mode: string;
if (activeView.type === "thread") {
mode = "thread";
payload.tweetId = activeView.tweetId;
} else if (activeView.type === "user") {
mode = "user";
payload.userId = activeView.userId;
} else {
mode = activeView.mode;
if (activeView.mode === "list" && activeView.listId) {
payload.listId = activeView.listId;
}
}
if (cursor) payload.cursor = cursor;
return twitterClient.timeline(mode, payload);
},
[account.cookie, activeView],
);
const refresh = useCallback(async () => {
if (
activeView.type === "timeline" &&
activeView.mode === "list" &&
!activeView.listId
) {
setError("Select a list for this column");
return;
}
setState((prev) => ({ ...prev, isLoading: true }));
setError(undefined);
try {
const data = await fetchPage(state.cursorTop);
setState({
tweets: data.tweets,
cursorTop: data.cursorTop,
cursorBottom: data.cursorBottom,
isLoading: false,
isAppending: false,
});
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : "Failed to load timeline");
setState((prev) => ({ ...prev, isLoading: false, isAppending: false }));
}
}, [activeView, fetchPage]);
useEffect(() => {
setState({
tweets: [],
cursorTop: "",
cursorBottom: "",
isLoading: true,
isAppending: false,
});
}, [activeView]);
useEffect(() => {
refresh();
}, [refresh]);
const loadMore = useCallback(async () => {
if (!state.cursorBottom) return;
setState((prev) => ({ ...prev, isAppending: true }));
try {
const data = await fetchPage(state.cursorBottom);
setState((prev) => ({
tweets: [...prev.tweets, ...data.tweets],
cursorTop: prev.cursorTop || data.cursorTop,
cursorBottom: data.cursorBottom,
isLoading: false,
isAppending: false,
}));
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : "Failed to load more");
setState((prev) => ({ ...prev, isAppending: false }));
}
}, [fetchPage, state.cursorBottom, state.cursorTop]);
const updateTweetById = useCallback(
(tweetId: string, updater: (tweet: Tweet) => Tweet) => {
setState((prev) => ({
...prev,
tweets: prev.tweets.map((tweet) =>
tweet.id === tweetId ? updater(tweet) : tweet,
),
}));
},
[],
);
const handleRemoveBookmark = useCallback(
async (tweetId: string) => {
try {
await twitterClient.removeBookmark({ cookie: account.cookie, tweetId });
setState((prev) => ({
...prev,
tweets: prev.tweets.filter((tweet) => tweet.id !== tweetId),
}));
} catch (err) {
setError(
err instanceof Error
? err.message
: "Unable to remove bookmark right now",
);
}
},
[account.cookie],
);
const likeTweet = useCallback(
async (tweetId: string, nextState: boolean) => {
try {
await twitterClient.like(tweetId, {
cookie: account.cookie,
undo: !nextState,
});
updateTweetById(tweetId, (tweet) => ({ ...tweet, liked: nextState }));
} catch (err) {
setError(err instanceof Error ? err.message : "Unable to update like");
}
},
[account.cookie, updateTweetById],
);
const retweet = useCallback(
async (tweetId: string, nextState: boolean) => {
try {
await twitterClient.retweet(tweetId, {
cookie: account.cookie,
undo: !nextState,
});
updateTweetById(tweetId, (tweet) => ({ ...tweet, rted: nextState }));
} catch (err) {
setError(
err instanceof Error ? err.message : "Unable to update retweet",
);
}
},
[account.cookie, updateTweetById],
);
const bookmarkTweet = useCallback(
async (tweetId: string, nextState: boolean) => {
try {
await twitterClient.bookmark(tweetId, {
cookie: account.cookie,
undo: !nextState,
});
if (column.kind === "bookmarks" && !nextState) {
setState((prev) => ({
...prev,
tweets: prev.tweets.filter((tweet) => tweet.id !== tweetId),
}));
} else {
updateTweetById(tweetId, (tweet) => ({
...tweet,
bookmarked: nextState,
}));
}
} catch (err) {
setError(
err instanceof Error ? err.message : "Unable to update bookmark",
);
}
},
[account.cookie, column.kind, updateTweetById],
);
const replyToTweet = useCallback(
(tweetId: string, text: string) =>
twitterClient.reply(tweetId, {
cookie: account.cookie,
text,
}),
[account.cookie],
);
const handleOpenAuthor = useCallback(
(author: Tweet["author"]) => {
if (!author?.id) return;
pushView({
type: "user",
userId: author.id,
username: author.username,
title: author.name || `@${author.username}`,
});
},
[pushView],
);
const handleOpenThread = useCallback(
(tweet: Tweet) => {
pushView({
type: "thread",
tweetId: tweet.id,
title: `Thread · ${tweet.author.name}`,
});
},
[pushView],
);
const breadcrumbs = useMemo(
() => viewStack.map((view) => labelForView(view)).join(" / "),
[viewStack],
);
return (
<article className="column">
<header>
<div>
<p className="eyebrow">{descriptor.badge}</p>
<h3>{descriptor.label}</h3>
<p className="muted tiny">
{descriptor.description} · {account.label}
</p>
{viewStack.length > 1 && <p className="muted tiny">{breadcrumbs}</p>}
</div>
<div className="column-actions">
<button
className="ghost"
onClick={handleMaximize}
aria-label="Maximize column"
>
⤢
</button>
{canGoBack && (
<button className="ghost" onClick={popView} aria-label="Go back">
←
</button>
)}
<button
className="ghost"
onClick={refresh}
aria-label="Refresh column"
>
↻
</button>
<button
className="ghost"
onClick={onRemove}
aria-label="Remove column"
>
×
</button>
</div>
</header>
<div
className={`column-content ${transitionDirection ? `slide-${transitionDirection}` : ""}`}
onAnimationEnd={handleAnimationEnd}
>
{error && <p className="error">{error}</p>}
{state.isLoading && !state.tweets.length ? (
<div className="column-loading">Loading…</div>
) : (
<div className="tweet-stack">
{state.tweets
.filter((t) => t.language === "th")
.slice(0, 10)
.map((tweet) => (
<TweetCard
key={tweet.id}
tweet={tweet}
accent={account.accent}
allowBookmarkRemoval={column.kind === "bookmarks"}
onRemoveBookmark={handleRemoveBookmark}
onToggleLike={likeTweet}
onToggleRetweet={retweet}
onToggleBookmark={bookmarkTweet}
onReply={replyToTweet}
onOpenAuthor={handleOpenAuthor}
onOpenThread={handleOpenThread}
/>
))}
{!state.tweets.length && !state.isLoading && (
<p className="muted">No tweets yet. Try refreshing.</p>
)}
{state.cursorBottom ? (
<div className="load-more-row">
<button
className="ghost"
disabled={state.isAppending}
onClick={loadMore}
>
{state.isAppending ? "Loading…" : "Load more"}
</button>
</div>
) : (
state.tweets.length > 0 && (
<div className="load-more-row">
<p className="muted">End of feed</p>
</div>
)
)}
</div>
)}
</div>
</article>
);
}
function createBaseView(column: TimelineConfig): TimelineView {
return {
type: "timeline",
mode: column.kind,
title: column.title || describeTimeline(column.kind).label,
listId: column.listId,
listName: column.listName,
};
}
function labelForView(view: ColumnView): string {
if (view.type === "timeline") {
return view.title || describeTimeline(view.mode).label;
}
if (view.type === "user") {
return view.title || `@${view.username}`;
}
return view.title || "Thread";
}
function describeView(column: TimelineConfig, view: ColumnView) {
if (view.type === "timeline") {
const base = describeTimeline(view.mode);
if (view.mode === "list" && view.listName) {
return {
...base,
label: view.title || view.listName,
description: `Tweets from ${view.listName}`,
};
}
return {
...base,
label: view.title || base.label,
};
}
if (view.type === "user") {
return {
label: view.title || `@${view.username}`,
badge: "Profile",
description: `Posts from @${view.username}`,
};
}
return {
label: view.title || "Thread",
badge: "Thread",
description: "Deep dive into the conversation",
};
}
function describeTimeline(kind: TimelineConfig["kind"]) {
switch (kind) {
case "following":
return {
label: "Following",
badge: "Chrono",
description: "Latest posts from people you follow",
};
case "bookmarks":
return {
label: "Bookmarks",
badge: "Library",
description: "Saved gems queued for later",
};
case "list":
return {
label: "List",
badge: "Curated",
description: "Tweets from a Twitter List",
};
default:
return {
label: "For You",
badge: "Ranked",
description: "AI-ranked home timeline",
};
}
}
|