mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
ui: render archived X threads as conversations
This commit is contained in:
parent
63b0480fd8
commit
13cae5174f
8 changed files with 516 additions and 80 deletions
|
|
@ -145,6 +145,8 @@ A separate auth database (`archivr-auth.sqlite`, path set in TOML) holds users,
|
|||
| Snapchat | Direct URL · `snapchat:ID` |
|
||||
| Arbitrary URL / web page | Any `https://` URL |
|
||||
|
||||
Thread previews follow archived reply relationships, group each reply branch under its parent post, and show captured quoted or linked posts inside the post that references them. Long or media-heavy quoted and linked posts start as compact previews; **Show full post** reveals their complete archived content. Links to posts already in the conversation jump to their place in the thread; press Esc or click/tap beside the thread to clear the focused post. Posts with missing relationship data remain available under “Other archived posts”.
|
||||
|
||||
X Articles are titled `<article title> — @handle` from the article's own title instead of the tweet text (usually a
|
||||
bare `t.co` link). Article entries archived before this change are retitled on the next `archivr-server` start, but only
|
||||
while their title still equals the old auto-generated bare-link title; a renamed entry is left alone. Titles have no
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useEffect } from 'react'
|
|||
import PreviewPanel from './PreviewPanel'
|
||||
|
||||
export default function PreviewModal({ archiveId, entry, detail, onClose }) {
|
||||
const entityKind = detail?.summary?.entity_kind
|
||||
// Close on Escape key
|
||||
useEffect(() => {
|
||||
const handler = (e) => { if (e.key === 'Escape') onClose() }
|
||||
|
|
@ -13,11 +14,8 @@ export default function PreviewModal({ archiveId, entry, detail, onClose }) {
|
|||
<div className="preview-modal-backdrop" onClick={onClose}>
|
||||
<div
|
||||
className={`preview-modal${
|
||||
detail?.summary?.entity_kind === 'tweet' ||
|
||||
detail?.summary?.entity_kind === 'tweet_thread'
|
||||
? ''
|
||||
: ' preview-modal--full'
|
||||
}`}
|
||||
entityKind === 'tweet' || entityKind === 'tweet_thread' ? '' : ' preview-modal--full'
|
||||
}${entityKind === 'tweet_thread' ? ' preview-modal--thread' : ''}`}
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<div className="preview-modal-header">
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ export default function PreviewPage({ archiveId, entryUid }) {
|
|||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{ color: xArticle ? '#71767b' : 'var(--muted)', textDecoration: 'none', fontSize: '13px', flexShrink: 0 }}
|
||||
>Original ↗</a>
|
||||
>Original</a>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ export default function PreviewPanel({ archiveId, entry, detail, fullPage, onXAr
|
|||
entryUid={entryUid}
|
||||
artifacts={artifacts}
|
||||
entityKind={entityKind}
|
||||
originalUrl={summary.original_url}
|
||||
fullPage={fullPage}
|
||||
onXArticle={onXArticle}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { fetchEntryArtifacts, resolveTcoUrls } from '../api';
|
||||
import { buildTweetThread, linkedStatusIds, resolveEntityBounds, statusIdFromUrl } from './tweetThread';
|
||||
|
||||
// ── Date helper ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -12,6 +13,10 @@ function fmtDate(secs) {
|
|||
}).format(new Date(secs * 1000));
|
||||
}
|
||||
|
||||
function focusedTweetIdFromHash() {
|
||||
return window.location.hash.match(/^#tweet-(\d+)$/)?.[1] || null;
|
||||
}
|
||||
|
||||
// Decode common HTML entities Twitter stores in full_text.
|
||||
// MUST be called on already-sliced segments, not on the raw string before
|
||||
// entity-offset arithmetic, because entity offsets are into the stored text.
|
||||
|
|
@ -40,15 +45,6 @@ const S = {
|
|||
margin: '0 auto',
|
||||
fontFamily: 'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)',
|
||||
},
|
||||
threadOuter: {
|
||||
border: '1px solid var(--line)',
|
||||
borderRadius: '12px',
|
||||
overflow: 'hidden',
|
||||
maxWidth: '560px',
|
||||
margin: '0 auto',
|
||||
background: 'var(--paper)',
|
||||
fontFamily: 'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)',
|
||||
},
|
||||
tweetRow: {
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
|
|
@ -86,14 +82,6 @@ const S = {
|
|||
background: 'var(--line)',
|
||||
flexShrink: 0,
|
||||
},
|
||||
threadLine: {
|
||||
flex: 1,
|
||||
width: '2px',
|
||||
background: 'var(--line-soft, var(--line))',
|
||||
margin: '4px 0',
|
||||
minHeight: '12px',
|
||||
borderRadius: '1px',
|
||||
},
|
||||
authorRow: {
|
||||
display: 'flex',
|
||||
alignItems: 'baseline',
|
||||
|
|
@ -536,24 +524,6 @@ function XLogo() {
|
|||
// links and @mentions with x.com links. Returns an array of React nodes.
|
||||
// white-space: pre-line on the container preserves newlines in plain segments.
|
||||
|
||||
// Resolve start/end offsets for a URL or mention entity, handling three
|
||||
// storage formats: camelCase fromIndex/toIndex (article inline), Twitter
|
||||
// native indices:[s,e] array, and fallback exact-string search in fullText.
|
||||
function resolveEntityBounds(ent, fullText, ...candidates) {
|
||||
if (ent.fromIndex != null && ent.toIndex != null)
|
||||
return { s: ent.fromIndex, e: ent.toIndex };
|
||||
if (ent.indices?.length === 2)
|
||||
return { s: ent.indices[0], e: ent.indices[1] };
|
||||
if (fullText) {
|
||||
for (const c of candidates) {
|
||||
if (!c) continue;
|
||||
const idx = fullText.indexOf(c);
|
||||
if (idx !== -1) return { s: idx, e: idx + c.length };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build a canonical URL annotation from any entity format.
|
||||
// Search candidates: short url first (appears in fullText), then expanded.
|
||||
function normalizeUrlAnn(u, fullText) {
|
||||
|
|
@ -578,7 +548,7 @@ function normalizeMentionAnn(m, fullText) {
|
|||
const URL_RE = /https?:\/\/[^\s<>"'\])]+/g;
|
||||
// Characters that commonly trail a URL but aren't part of it
|
||||
const TRAIL_PUNCT = /[.,;:!?)()]+$/;
|
||||
function linkifyText(text, linkStyle) {
|
||||
function linkifyText(text, linkStyle, mainIds) {
|
||||
const parts = [];
|
||||
let last = 0;
|
||||
let m;
|
||||
|
|
@ -586,8 +556,11 @@ function linkifyText(text, linkStyle) {
|
|||
while ((m = URL_RE.exec(text)) !== null) {
|
||||
if (m.index > last) parts.push(text.slice(last, m.index));
|
||||
let href = m[0].replace(TRAIL_PUNCT, '');
|
||||
const linkedId = statusIdFromUrl(href);
|
||||
const local = linkedId && mainIds?.has(linkedId);
|
||||
parts.push(
|
||||
<a key={m.index} href={href} target="_blank" rel="noopener noreferrer" style={linkStyle}>
|
||||
<a key={m.index} href={local ? `#tweet-${linkedId}` : href}
|
||||
target={local ? undefined : '_blank'} rel={local ? undefined : 'noopener noreferrer'} style={linkStyle}>
|
||||
{href}
|
||||
</a>
|
||||
);
|
||||
|
|
@ -601,7 +574,7 @@ function linkifyText(text, linkStyle) {
|
|||
return parts;
|
||||
}
|
||||
|
||||
function renderTweetTextJSX(fullText, entities, skipSpans = []) {
|
||||
function renderTweetTextJSX(fullText, entities, skipSpans = [], mainIds) {
|
||||
if (!fullText) return null;
|
||||
|
||||
const anns = [
|
||||
|
|
@ -610,7 +583,7 @@ function renderTweetTextJSX(fullText, entities, skipSpans = []) {
|
|||
];
|
||||
|
||||
// If there are no annotations and no spans to skip, fast path.
|
||||
if (anns.length === 0 && skipSpans.length === 0) return linkifyText(decodeEnt(fullText), S.link);
|
||||
if (anns.length === 0 && skipSpans.length === 0) return linkifyText(decodeEnt(fullText), S.link, mainIds);
|
||||
|
||||
const pts = new Set([0, fullText.length]);
|
||||
for (const a of anns) {
|
||||
|
|
@ -637,8 +610,11 @@ function renderTweetTextJSX(fullText, entities, skipSpans = []) {
|
|||
|
||||
const url = active.find(a => a.kind === 'url');
|
||||
if (url) {
|
||||
const linkedId = statusIdFromUrl(url.href);
|
||||
const local = linkedId && mainIds?.has(linkedId);
|
||||
return (
|
||||
<a key={i} href={url.href} target="_blank" rel="noopener noreferrer" style={S.link}>
|
||||
<a key={i} href={local ? `#tweet-${linkedId}` : url.href}
|
||||
target={local ? undefined : '_blank'} rel={local ? undefined : 'noopener noreferrer'} style={S.link}>
|
||||
{url.display || seg}
|
||||
</a>
|
||||
);
|
||||
|
|
@ -659,7 +635,7 @@ function renderTweetTextJSX(fullText, entities, skipSpans = []) {
|
|||
);
|
||||
}
|
||||
|
||||
return <span key={i}>{linkifyText(decodeEnt(seg), S.link)}</span>;
|
||||
return <span key={i}>{linkifyText(decodeEnt(seg), S.link, mainIds)}</span>;
|
||||
}).filter(n => n !== null);
|
||||
}
|
||||
|
||||
|
|
@ -1009,8 +985,7 @@ function ArticleRenderer({ article, tweetAuthor, artifactMap, fullPage, onXArtic
|
|||
}
|
||||
|
||||
// ── Tweet card ─────────────────────────────────────────────────────────────────
|
||||
// Renders one tweet. When isInThread, omits bottom padding from the row and
|
||||
// shows a thread connector line below the avatar (except on the last card).
|
||||
// Renders one status, including archived quote and linked-post context.
|
||||
|
||||
|
||||
// ── Photo grid ─────────────────────────────────────────────────────────────────
|
||||
|
|
@ -1089,7 +1064,7 @@ function MediaLightbox({ items, startIndex, onClose }) {
|
|||
|
||||
const item = items[idx];
|
||||
return (
|
||||
<div style={S.lightboxBackdrop} onClick={onClose}>
|
||||
<div className="tw-media-lightbox" style={S.lightboxBackdrop} onClick={onClose}>
|
||||
<div style={S.lightboxContent} onClick={e => e.stopPropagation()}>
|
||||
<div style={S.lightboxToolbar}>
|
||||
{items.length > 1 && (
|
||||
|
|
@ -1101,7 +1076,7 @@ function MediaLightbox({ items, startIndex, onClose }) {
|
|||
rel="noopener noreferrer"
|
||||
style={S.lightboxLink}
|
||||
title="Open in new tab"
|
||||
>↗</a>
|
||||
>Open image</a>
|
||||
<button style={S.lightboxBtn} onClick={onClose} aria-label="Close">×</button>
|
||||
</div>
|
||||
<img src={item.src} alt={item.alt || ''} style={S.lightboxImg} />
|
||||
|
|
@ -1124,17 +1099,36 @@ function MediaLightbox({ items, startIndex, onClose }) {
|
|||
);
|
||||
}
|
||||
|
||||
function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
||||
function TweetCard({ tweet, isInThread, artifactMap, byId, mainIds, embedded = false, trail = [] }) {
|
||||
const [lightboxIdx, setLightboxIdx] = useState(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const author = tweet.author || {};
|
||||
const date = tweet.created_at_secs ? fmtDate(tweet.created_at_secs) : '';
|
||||
const entities = tweet.entities || {};
|
||||
const avatarSrc = resolveUrl(author.avatar_local_path, author.avatar_url, artifactMap);
|
||||
const showConnector = isInThread && !isLast;
|
||||
const isQT = tweet.is_quote_status === true;
|
||||
const rowStyle = isInThread ? S.tweetRowThread : S.tweetRow;
|
||||
const rowStyle = embedded
|
||||
? { ...S.tweetRowThread, padding: '9px 11px' }
|
||||
: isInThread ? S.tweetRowThread : S.tweetRow;
|
||||
const ft = tweet.full_text || '';
|
||||
const tweetId = String(tweet.id || '');
|
||||
const quoteId = String(tweet.quoted_status_id || '');
|
||||
const quoted = byId?.get(quoteId);
|
||||
const replyTo = byId?.get(String(tweet.in_reply_to_status_id || ''));
|
||||
const canEmbed = trail.length < 4 && !trail.includes(tweetId);
|
||||
const sourceUrl = tweet.id
|
||||
? `https://x.com/${encodeURIComponent(author.screen_name || 'i')}/status/${tweetId}`
|
||||
: null;
|
||||
|
||||
// Linked X posts already in the archive get a local preview if they are not
|
||||
// part of the reply timeline. Posts on the timeline remain in-place links.
|
||||
const linked = new Map();
|
||||
for (const id of linkedStatusIds(tweet)) {
|
||||
if (id && id !== quoteId && id !== tweetId && byId?.has(id) && !mainIds?.has(id)) {
|
||||
linked.set(id, byId.get(id));
|
||||
}
|
||||
}
|
||||
|
||||
// Build resolved media lists first; skip the grid entirely if every item resolves to null.
|
||||
const rawMedia = (tweet.extended_entities?.media?.length
|
||||
|
|
@ -1158,7 +1152,12 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
if (src) videoItems.push({ kind: m.type === 'animated_gif' ? 'gif' : 'video', src });
|
||||
}
|
||||
}
|
||||
|
||||
const canCollapse = embedded && (ft.length > 220 || photos.length > 0 || videoItems.length > 0 || !!quoteId || linked.size > 0);
|
||||
const collapsed = canCollapse && !expanded;
|
||||
const mediaSummary = [
|
||||
photos.length && `${photos.length} ${photos.length === 1 ? 'photo' : 'photos'}`,
|
||||
videoItems.length && `${videoItems.length} ${videoItems.length === 1 ? 'video' : 'videos'}`,
|
||||
].filter(Boolean).join(' · ');
|
||||
// Suppress media attachment t.co links from the tweet text when the media
|
||||
// actually rendered. Uses resolveEntityBounds (prefers indices/fromIndex,
|
||||
// falls back to indexOf) so the span is always precise.
|
||||
|
|
@ -1173,6 +1172,13 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
const b = resolveEntityBounds(m, ft, m.url);
|
||||
if (b) mediaSkipSpans.push([b.s, b.e]);
|
||||
}
|
||||
if (quoted) {
|
||||
for (const u of entities.urls || []) {
|
||||
if (statusIdFromUrl(u.expanded_url || u.url) !== quoteId) continue;
|
||||
const b = resolveEntityBounds(u, ft, u.url);
|
||||
if (b) mediaSkipSpans.push([b.s, b.e]);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
@ -1183,18 +1189,27 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
onClose={() => setLightboxIdx(null)}
|
||||
/>
|
||||
)}
|
||||
<div style={rowStyle}>
|
||||
<div style={rowStyle} className={embedded ? 'tw-embedded-post' : undefined}>
|
||||
<div style={S.leftCol}>
|
||||
{avatarSrc
|
||||
? <img src={avatarSrc} style={S.avatar} alt={author.name || ''} />
|
||||
: <div style={S.avatarPh} />
|
||||
}
|
||||
{showConnector && <div style={S.threadLine} />}
|
||||
</div>
|
||||
|
||||
<div style={S.rightCol}>
|
||||
{isInThread && tweet.in_reply_to_status_id && (
|
||||
<div className="tw-reply-context">
|
||||
Replying to {replyTo ? `@${replyTo.author?.screen_name || 'unknown'}` : 'a post outside this archive'}
|
||||
</div>
|
||||
)}
|
||||
<div style={S.authorRow}>
|
||||
<span style={S.authorName}>{author.name || author.screen_name || 'Unknown'}</span>
|
||||
{sourceUrl
|
||||
? <a className="tw-post-author-link" style={S.authorName} href={sourceUrl}
|
||||
target="_blank" rel="noopener noreferrer" title="Open original post on X">
|
||||
{author.name || author.screen_name || 'Unknown'}
|
||||
</a>
|
||||
: <span style={S.authorName}>{author.name || author.screen_name || 'Unknown'}</span>}
|
||||
{author.screen_name && (
|
||||
<span style={S.authorHandle}>@{author.screen_name}</span>
|
||||
)}
|
||||
|
|
@ -1204,17 +1219,17 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
)}
|
||||
</div>
|
||||
|
||||
<div style={S.tweetText}>
|
||||
{renderTweetTextJSX(ft, entities, mediaSkipSpans)}
|
||||
<div style={S.tweetText} className={collapsed ? 'tw-embedded-post__text--collapsed' : undefined}>
|
||||
{renderTweetTextJSX(ft, entities, mediaSkipSpans, mainIds)}
|
||||
</div>
|
||||
|
||||
{photos.length > 0 && (
|
||||
{!collapsed && photos.length > 0 && (
|
||||
<div style={S.mediaGrid}>
|
||||
<PhotoGrid photos={photos} onOpen={i => setLightboxIdx(i)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{videoItems.map((v, i) => (
|
||||
{!collapsed && videoItems.map((v, i) => (
|
||||
<div key={i} style={S.mediaGrid}>
|
||||
<video
|
||||
src={v.src}
|
||||
|
|
@ -1227,7 +1242,38 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
</div>
|
||||
))}
|
||||
|
||||
{(tweet.retweet_count > 0 || tweet.favorite_count > 0) && (
|
||||
{!collapsed && quoteId && (
|
||||
<div className="tw-related-post">
|
||||
<div className="tw-related-post__label">Quoted post</div>
|
||||
{quoted && mainIds?.has(quoteId)
|
||||
? <a className="tw-related-post__jump" href={`#tweet-${quoteId}`}>
|
||||
@{quoted.author?.screen_name || 'unknown'} · View in this conversation
|
||||
</a>
|
||||
: quoted && canEmbed
|
||||
? <TweetCard tweet={quoted} artifactMap={artifactMap} byId={byId} mainIds={mainIds}
|
||||
embedded trail={[...trail, tweetId]} />
|
||||
: <a className="tw-related-post__jump" href={`https://x.com/i/status/${quoteId}`}
|
||||
target="_blank" rel="noopener noreferrer">View quoted post on X</a>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!collapsed && canEmbed && [...linked].map(([id, post]) => (
|
||||
<div className="tw-related-post" key={id}>
|
||||
<div className="tw-related-post__label">Linked post</div>
|
||||
<TweetCard tweet={post} artifactMap={artifactMap} byId={byId} mainIds={mainIds}
|
||||
embedded trail={[...trail, tweetId]} />
|
||||
</div>
|
||||
))}
|
||||
|
||||
{canCollapse && (
|
||||
<button type="button" className="tw-embedded-post__expand"
|
||||
aria-expanded={expanded} onClick={() => setExpanded(value => !value)}>
|
||||
{expanded ? 'Show less' : 'Show full post'}
|
||||
{collapsed && mediaSummary && <span> · {mediaSummary}</span>}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{!collapsed && (tweet.retweet_count > 0 || tweet.favorite_count > 0) && (
|
||||
<div style={S.stats}>
|
||||
{tweet.favorite_count > 0 && (
|
||||
<span>❤️ {tweet.favorite_count.toLocaleString()}</span>
|
||||
|
|
@ -1243,12 +1289,88 @@ function TweetCard({ tweet, isInThread, isLast, artifactMap }) {
|
|||
);
|
||||
}
|
||||
|
||||
function ThreadNode({ node, artifactMap, byId, mainIds, focusedTweetId }) {
|
||||
const { tweet, children } = node;
|
||||
return (
|
||||
<>
|
||||
<article id={`tweet-${tweet.id}`}
|
||||
className={`tw-conversation__post${focusedTweetId === String(tweet.id) ? ' tw-conversation__post--focused' : ''}`}>
|
||||
<TweetCard tweet={tweet} isInThread artifactMap={artifactMap} byId={byId} mainIds={mainIds} />
|
||||
</article>
|
||||
{children.length === 1 && (
|
||||
<ThreadNode node={children[0]} artifactMap={artifactMap} byId={byId} mainIds={mainIds}
|
||||
focusedTweetId={focusedTweetId} />
|
||||
)}
|
||||
{children.length > 1 && (
|
||||
<section className="tw-fork" aria-label={`${children.length} reply branches`}>
|
||||
<div className="tw-fork__heading">{children.length} replies to this post</div>
|
||||
{children.map((child, index) => (
|
||||
<section key={child.tweet.id} className="tw-fork__branch"
|
||||
aria-label={`Branch ${index + 1} of ${children.length}`}>
|
||||
<div className="tw-fork__branch-label">
|
||||
<strong>Branch {index + 1} of {children.length}</strong>
|
||||
{child.tweet.author?.screen_name && <span>@{child.tweet.author.screen_name}</span>}
|
||||
</div>
|
||||
<ThreadNode node={child} artifactMap={artifactMap} byId={byId} mainIds={mainIds}
|
||||
focusedTweetId={focusedTweetId} />
|
||||
</section>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ── TweetPreview ───────────────────────────────────────────────────────────────
|
||||
|
||||
export default function TweetPreview({ archiveId, entryUid, artifacts, entityKind, fullPage, onXArticle }) {
|
||||
export default function TweetPreview({ archiveId, entryUid, artifacts, entityKind, originalUrl, fullPage, onXArticle }) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [tweets, setTweets] = useState([]);
|
||||
const [focusedTweetId, setFocusedTweetId] = useState(focusedTweetIdFromHash);
|
||||
|
||||
useEffect(() => {
|
||||
if (entityKind !== 'tweet_thread') return;
|
||||
|
||||
const syncFocus = () => setFocusedTweetId(focusedTweetIdFromHash());
|
||||
const clearFocus = () => {
|
||||
window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search);
|
||||
setFocusedTweetId(null);
|
||||
};
|
||||
const onKeyDown = event => {
|
||||
if (event.key !== 'Escape' || !focusedTweetIdFromHash()) return;
|
||||
if (document.querySelector('.tw-media-lightbox')) return;
|
||||
event.preventDefault();
|
||||
clearFocus();
|
||||
};
|
||||
const onClick = event => {
|
||||
if (!focusedTweetIdFromHash()) return;
|
||||
const target = event.target;
|
||||
if (target instanceof Element && target.closest(
|
||||
'.tw-conversation__post, .tw-media-lightbox, a, button, input, textarea, select'
|
||||
)) return;
|
||||
clearFocus();
|
||||
};
|
||||
|
||||
syncFocus();
|
||||
window.addEventListener('hashchange', syncFocus);
|
||||
window.addEventListener('popstate', syncFocus);
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
document.addEventListener('click', onClick);
|
||||
return () => {
|
||||
window.removeEventListener('hashchange', syncFocus);
|
||||
window.removeEventListener('popstate', syncFocus);
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
document.removeEventListener('click', onClick);
|
||||
};
|
||||
}, [entityKind, entryUid]);
|
||||
|
||||
// The archived JSON arrives after the initial page load. A direct link's
|
||||
// target is absent when the browser first processes its fragment.
|
||||
useEffect(() => {
|
||||
if (entityKind !== 'tweet_thread' || loading || !focusedTweetId) return;
|
||||
document.getElementById(`tweet-${focusedTweetId}`)?.scrollIntoView({ block: 'start' });
|
||||
}, [entityKind, loading, focusedTweetId, tweets]);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
|
|
@ -1284,10 +1406,8 @@ export default function TweetPreview({ archiveId, entryUid, artifacts, entityKin
|
|||
const coveredRanges = tweet => {
|
||||
const ft = tweet.full_text || '';
|
||||
return (tweet.entities?.urls || []).map(u => {
|
||||
if (u.fromIndex != null && u.toIndex != null) return [u.fromIndex, u.toIndex];
|
||||
if (u.indices?.length === 2) return [u.indices[0], u.indices[1]];
|
||||
if (u.url) { const i = ft.indexOf(u.url); if (i !== -1) return [i, i + u.url.length]; }
|
||||
return null;
|
||||
const bounds = resolveEntityBounds(u, ft, u.url, u.text, u.display_url, u.expanded_url);
|
||||
return bounds && [bounds.s, bounds.e];
|
||||
}).filter(Boolean);
|
||||
};
|
||||
const isCovered = (ranges, s, e) => ranges.some(([cs, ce]) => cs <= s && ce >= e);
|
||||
|
|
@ -1338,17 +1458,23 @@ export default function TweetPreview({ archiveId, entryUid, artifacts, entityKin
|
|||
const artifactMap = buildArtifactMap(archiveId, entryUid, artifacts);
|
||||
|
||||
if (entityKind === 'tweet_thread') {
|
||||
const requestedId = statusIdFromUrl(originalUrl);
|
||||
const { tree, rows, byId, mainIds, extra } = buildTweetThread(tweets, requestedId);
|
||||
return (
|
||||
<div style={S.threadOuter}>
|
||||
{tweets.map((tweet, i) => (
|
||||
<TweetCard
|
||||
key={tweet.id || i}
|
||||
tweet={tweet}
|
||||
isInThread
|
||||
isLast={i === tweets.length - 1}
|
||||
artifactMap={artifactMap}
|
||||
/>
|
||||
))}
|
||||
<div className="tw-conversation">
|
||||
<div className="tw-conversation__intro">Conversation · {rows.length} {rows.length === 1 ? 'post' : 'posts'}</div>
|
||||
{tree && <ThreadNode node={tree} artifactMap={artifactMap} byId={byId} mainIds={mainIds}
|
||||
focusedTweetId={focusedTweetId} />}
|
||||
{extra.length > 0 && (
|
||||
<section className="tw-conversation__extra" aria-label="Other archived posts">
|
||||
<div className="tw-conversation__intro">Other archived posts</div>
|
||||
{extra.map(tweet => (
|
||||
<article key={tweet.id} className="tw-conversation__post">
|
||||
<TweetCard tweet={tweet} isInThread artifactMap={artifactMap} byId={byId} mainIds={mainIds} />
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1360,7 +1486,7 @@ export default function TweetPreview({ archiveId, entryUid, artifacts, entityKin
|
|||
|
||||
return (
|
||||
<div style={S.card}>
|
||||
<TweetCard tweet={tweet} isInThread={false} isLast artifactMap={artifactMap} />
|
||||
<TweetCard tweet={tweet} artifactMap={artifactMap} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
109
frontend/src/components/tweetThread.js
Normal file
109
frontend/src/components/tweetThread.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// A thread capture contains the requested post, its reply ancestors, and often
|
||||
// extra posts fetched only because they were quoted. Archive order is not a
|
||||
// conversation order, so keep reply and quote relationships separate.
|
||||
export function buildTweetThread(tweets, requestedId) {
|
||||
const byId = new Map();
|
||||
tweets.forEach(tweet => {
|
||||
if (tweet?.id && !byId.has(String(tweet.id))) byId.set(String(tweet.id), tweet);
|
||||
});
|
||||
|
||||
const seed = byId.get(String(requestedId)) || [...byId.values()].at(-1);
|
||||
if (!seed) return { tree: null, rows: [], byId, mainIds: new Set(), extra: [] };
|
||||
|
||||
const children = new Map();
|
||||
for (const tweet of byId.values()) {
|
||||
const parentId = String(tweet.in_reply_to_status_id || '');
|
||||
if (parentId && parentId !== String(tweet.id) && byId.has(parentId)) {
|
||||
if (!children.has(parentId)) children.set(parentId, []);
|
||||
children.get(parentId).push(tweet);
|
||||
}
|
||||
}
|
||||
|
||||
// Walk towards the earliest archived reply ancestor, then down every branch
|
||||
// in that conversation. Quoted posts from elsewhere stay inside quote cards.
|
||||
let root = seed;
|
||||
const ancestors = new Set([String(seed.id)]);
|
||||
while (byId.has(String(root.in_reply_to_status_id || '')) &&
|
||||
!ancestors.has(String(root.in_reply_to_status_id))) {
|
||||
root = byId.get(String(root.in_reply_to_status_id));
|
||||
ancestors.add(String(root.id));
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
const mainIds = new Set();
|
||||
function visit(tweet, depth) {
|
||||
const id = String(tweet.id);
|
||||
if (mainIds.has(id)) return null;
|
||||
mainIds.add(id);
|
||||
rows.push({ tweet, depth });
|
||||
return {
|
||||
tweet,
|
||||
children: (children.get(id) || []).map(child => visit(child, depth + 1)).filter(Boolean),
|
||||
};
|
||||
}
|
||||
const tree = visit(root, 0);
|
||||
|
||||
const referenced = new Set();
|
||||
function markReferences(tweet) {
|
||||
const ids = [String(tweet.quoted_status_id || '')];
|
||||
ids.push(...linkedStatusIds(tweet));
|
||||
for (const id of ids) {
|
||||
if (!id || !byId.has(id) || referenced.has(id)) continue;
|
||||
referenced.add(id);
|
||||
markReferences(byId.get(id));
|
||||
}
|
||||
}
|
||||
rows.forEach(({ tweet }) => markReferences(tweet));
|
||||
|
||||
// Keep any disconnected archived posts accessible, even if the scraper
|
||||
// returned incomplete relationship fields.
|
||||
const extra = [...byId.values()].filter(tweet =>
|
||||
!mainIds.has(String(tweet.id)) && !referenced.has(String(tweet.id))
|
||||
);
|
||||
return { tree, rows, byId, mainIds, extra };
|
||||
}
|
||||
|
||||
export function statusIdFromUrl(value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (!/^(?:www\.|mobile\.)?(?:x\.com|twitter\.com)$/i.test(url.hostname)) return null;
|
||||
return url.pathname.match(/\/(?:status|statuses)\/(\d+)(?:\/|$)/)?.[1] || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function linkedStatusIds(tweet) {
|
||||
const urls = (tweet.entities?.urls || []).map(url => url.expanded_url || url.url);
|
||||
urls.push(...((tweet.full_text || '').match(/https?:\/\/[^\s<>"'\])]+/g) || []));
|
||||
return [...new Set(urls.map(url => statusIdFromUrl(url?.replace(/[.,;:!?)()]+$/, ''))).filter(Boolean))];
|
||||
}
|
||||
|
||||
// X offsets sometimes count Unicode code points; JS slices UTF-16 units.
|
||||
export function resolveEntityBounds(ent, fullText, ...candidates) {
|
||||
const raw = ent.fromIndex != null && ent.toIndex != null
|
||||
? { s: ent.fromIndex, e: ent.toIndex }
|
||||
: ent.indices?.length === 2
|
||||
? { s: ent.indices[0], e: ent.indices[1] }
|
||||
: null;
|
||||
const matches = bounds => candidates.some(c => c && fullText.slice(bounds.s, bounds.e) === c);
|
||||
if (raw && matches(raw)) return raw;
|
||||
|
||||
if (raw) {
|
||||
const points = Array.from(fullText);
|
||||
if (raw.s >= 0 && raw.e <= points.length) {
|
||||
const adjusted = {
|
||||
s: points.slice(0, raw.s).join('').length,
|
||||
e: points.slice(0, raw.e).join('').length,
|
||||
};
|
||||
if (matches(adjusted)) return adjusted;
|
||||
}
|
||||
}
|
||||
|
||||
for (const c of candidates) {
|
||||
if (!c) continue;
|
||||
const idx = fullText.indexOf(c);
|
||||
if (idx !== -1) return { s: idx, e: idx + c.length };
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
78
frontend/src/components/tweetThread.test.js
Normal file
78
frontend/src/components/tweetThread.test.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { buildTweetThread, linkedStatusIds, resolveEntityBounds, statusIdFromUrl } from './tweetThread';
|
||||
|
||||
const post = (id, reply, quote, urls = []) => ({
|
||||
id, in_reply_to_status_id: reply, quoted_status_id: quote,
|
||||
entities: { urls: urls.map(expanded_url => ({ expanded_url })) },
|
||||
});
|
||||
|
||||
describe('buildTweetThread', () => {
|
||||
test('keeps reply forks in their own branches and embeds a quote of an earlier reply', () => {
|
||||
const tweets = [
|
||||
post('root'), post('question', 'root'), post('answer', 'question'),
|
||||
post('followup', 'answer'), post('other-branch', 'answer'),
|
||||
post('response', 'other-branch'), post('last', 'response', 'followup'),
|
||||
];
|
||||
const view = buildTweetThread(tweets, 'last');
|
||||
expect(view.rows.map(row => [row.tweet.id, row.depth])).toEqual([
|
||||
['root', 0], ['question', 1], ['answer', 2], ['followup', 3],
|
||||
['other-branch', 3], ['response', 4], ['last', 5],
|
||||
]);
|
||||
expect(view.extra).toEqual([]);
|
||||
expect(view.mainIds.has('followup')).toBe(true);
|
||||
const fork = view.tree.children[0].children[0];
|
||||
expect(fork.tweet.id).toBe('answer');
|
||||
expect(fork.children.map(node => node.tweet.id)).toEqual(['followup', 'other-branch']);
|
||||
expect(fork.children[1].children[0].children[0].tweet.id).toBe('last');
|
||||
});
|
||||
|
||||
test('keeps quoted and linked posts out of the reply timeline', () => {
|
||||
const tweets = [
|
||||
post('quoted'), post('123'),
|
||||
post('seed', null, 'quoted', ['https://x.com/user/status/123']),
|
||||
];
|
||||
const view = buildTweetThread(tweets, 'seed');
|
||||
expect(view.rows.map(row => row.tweet.id)).toEqual(['seed']);
|
||||
expect(view.extra).toEqual([]);
|
||||
expect(view.byId.has('quoted')).toBe(true);
|
||||
});
|
||||
|
||||
test('retains disconnected posts when relationship data is incomplete', () => {
|
||||
const view = buildTweetThread([post('orphan'), post('seed', 'missing')], 'seed');
|
||||
expect(view.rows.map(row => row.tweet.id)).toEqual(['seed']);
|
||||
expect(view.extra.map(tweet => tweet.id)).toEqual(['orphan']);
|
||||
});
|
||||
|
||||
test('handles cyclic references without looping', () => {
|
||||
const view = buildTweetThread([post('a', 'b', 'b'), post('b', 'a', 'a')], 'a');
|
||||
expect(view.rows).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
test('statusIdFromUrl accepts only X/Twitter post URLs', () => {
|
||||
expect(statusIdFromUrl('https://x.com/name/status/123?x=1')).toBe('123');
|
||||
expect(statusIdFromUrl('https://mobile.twitter.com/i/status/456')).toBe('456');
|
||||
expect(statusIdFromUrl('https://notx.com/name/status/123')).toBeNull();
|
||||
expect(statusIdFromUrl('https://x.com/name')).toBeNull();
|
||||
});
|
||||
|
||||
test('linkedStatusIds finds entity and bare post links once', () => {
|
||||
expect(linkedStatusIds({
|
||||
full_text: 'See https://x.com/a/status/123 and https://twitter.com/b/status/456.',
|
||||
entities: { urls: [{ expanded_url: 'https://x.com/a/status/123' }] },
|
||||
})).toEqual(['123', '456']);
|
||||
});
|
||||
|
||||
test('tweet entity offsets align after a leading emoji', () => {
|
||||
const text = '🫡 https://t.co/zpuXCIpS6x';
|
||||
expect(resolveEntityBounds(
|
||||
{ indices: [2, 25] }, text, 'https://t.co/zpuXCIpS6x'
|
||||
)).toEqual({ s: 3, e: 26 });
|
||||
});
|
||||
|
||||
test('tweet entity offsets preserve matching UTF-16 positions', () => {
|
||||
const text = 'hello https://t.co/abc';
|
||||
expect(resolveEntityBounds(
|
||||
{ fromIndex: 6, toIndex: 22 }, text, 'https://t.co/abc'
|
||||
)).toEqual({ s: 6, e: 22 });
|
||||
});
|
||||
|
|
@ -2552,7 +2552,7 @@ google-cast-launcher.video-tv-btn {
|
|||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 12px 16px;
|
||||
padding: 8px 12px;
|
||||
background: var(--paper-2);
|
||||
/* styled scrollbar matching the workspace rail */
|
||||
scrollbar-width: thin;
|
||||
|
|
@ -2573,6 +2573,127 @@ google-cast-launcher.video-tv-btn {
|
|||
}
|
||||
|
||||
/* ── Tweet card ───────────────────────────────────────────────────── */
|
||||
.tw-conversation {
|
||||
width: min(100%, 620px);
|
||||
margin: 8px auto 24px;
|
||||
padding: 0 12px;
|
||||
box-sizing: border-box;
|
||||
font-family: var(--sans);
|
||||
}
|
||||
.tw-conversation__intro {
|
||||
padding: 0 4px 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.tw-conversation__post {
|
||||
margin: 0 0 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--paper);
|
||||
overflow: hidden;
|
||||
scroll-margin-top: 16px;
|
||||
}
|
||||
.tw-conversation__post--focused {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.tw-conversation__extra {
|
||||
margin-top: 24px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 18px;
|
||||
}
|
||||
.tw-fork {
|
||||
margin: 4px 0 22px 12px;
|
||||
padding-left: 16px;
|
||||
border-left: 2px solid var(--line);
|
||||
}
|
||||
.tw-fork__heading {
|
||||
padding: 2px 0 12px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .02em;
|
||||
}
|
||||
.tw-fork__branch {
|
||||
--branch-color: var(--accent);
|
||||
margin: 0 0 16px;
|
||||
padding: 9px 10px 2px 14px;
|
||||
border-left: 3px solid var(--branch-color);
|
||||
border-radius: 0 8px 8px 0;
|
||||
background: var(--paper-2);
|
||||
}
|
||||
.tw-fork__branch:nth-of-type(even) { --branch-color: var(--muted); }
|
||||
.tw-fork__branch-label {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
margin: 0 0 8px;
|
||||
color: var(--branch-color);
|
||||
font-size: 12px;
|
||||
}
|
||||
.tw-fork__branch-label span { color: var(--muted); }
|
||||
@media (max-width: 640px) {
|
||||
.tw-fork { margin-left: 4px; padding-left: 8px; }
|
||||
.tw-fork__branch { padding-left: 9px; padding-right: 6px; }
|
||||
}
|
||||
.tw-reply-context {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
margin: 0 0 5px;
|
||||
}
|
||||
.tw-post-author-link {
|
||||
text-decoration: none;
|
||||
}
|
||||
.tw-post-author-link:hover, .tw-post-author-link:focus-visible {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.tw-related-post__jump:hover { color: var(--accent); }
|
||||
.tw-related-post {
|
||||
margin: 7px 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--paper-2);
|
||||
}
|
||||
.tw-related-post__label {
|
||||
padding: 7px 9px 0;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
.tw-related-post__jump {
|
||||
display: block;
|
||||
padding: 8px 11px 11px;
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
}
|
||||
.tw-embedded-post__text--collapsed {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 3;
|
||||
overflow: hidden;
|
||||
}
|
||||
.tw-embedded-post__expand {
|
||||
display: block;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
.tw-embedded-post__expand:hover { text-decoration: underline; }
|
||||
.tw-embedded-post__expand span { color: var(--muted); font-weight: 400; }
|
||||
.tw-card {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
|
|
@ -2901,6 +3022,7 @@ google-cast-launcher.video-tv-btn {
|
|||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.preview-modal--thread { max-width: 720px; }
|
||||
/* Full-height variant for iframe/PDF/video/image (needs explicit height
|
||||
so flex children like <iframe style="flex:1"> have a concrete container). */
|
||||
.preview-modal--full {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue