File size: 12,056 Bytes
f0b240d 7e7e06a f0b240d 38ee3c1 7e7e06a 0b2fee5 7e7e06a f0b240d 46cc63a f0b240d 38ee3c1 f0b240d 46cc63a f0b240d 7e7e06a f0b240d 7e7e06a 73c3af5 7e7e06a 73c3af5 7e7e06a f0b240d 7e7e06a f0b240d 38ee3c1 7e7e06a f0b240d 7e7e06a 0b2fee5 73c3af5 7e7e06a 0b2fee5 7e7e06a 38ee3c1 7e7e06a 0b2fee5 7e7e06a 38ee3c1 7e7e06a 73c3af5 f0b240d 7e7e06a f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 46cc63a f0b240d 46cc63a 38ee3c1 46cc63a 38ee3c1 46cc63a f0b240d 38ee3c1 f0b240d 46cc63a 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 7e7e06a 38ee3c1 f0b240d 7e7e06a 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 38ee3c1 f0b240d 73c3af5 7e7e06a f0b240d 7e7e06a 38ee3c1 7e7e06a f0b240d | 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 | import { useCallback, useEffect, useState } from "react";
import {
getSuggestedVideos,
listPredictions,
predict,
predictVideo,
} from "../api/client";
import { CommentRow } from "../components/CommentRow";
import { SuggestedRail } from "../components/SuggestedRail";
import { useApp } from "../context/AppContext";
import { useDebouncedPredict } from "../hooks/useDebouncedPredict";
import { useI18n } from "../i18n/I18nContext";
import type {
CommentItem,
PredictionRecord,
SuggestedVideo,
} from "../types/api";
import {
formatPct,
newId,
randomTeamMember,
randomUsername,
relativeTime,
toxicityColor,
truncate,
} from "../utils/toxicity";
const DEFAULT_EMBED_VIDEO_ID = "A1uxPRUgimk";
function isPlaceholderTitle(title: string, id: string): boolean {
return title === `Video ${id}`;
}
export function WatchPage() {
const { t } = useI18n();
const { threshold, addHubEntry } = useApp();
const [draft, setDraft] = useState("");
const [sessionComments, setSessionComments] = useState<CommentItem[]>([]);
const [suggested, setSuggested] = useState<SuggestedVideo[]>([]);
const [maxComments, setMaxComments] = useState(15);
const [activeVideo, setActiveVideo] = useState<SuggestedVideo | null>(null);
const [youtubeComments, setYoutubeComments] = useState<CommentItem[]>([]);
const [loadingVideoId, setLoadingVideoId] = useState<string | null>(null);
const [fetchError, setFetchError] = useState<string | null>(null);
const [demoBanner, setDemoBanner] = useState(false);
const [dismissDemoBanner, setDismissDemoBanner] = useState(false);
const [posting, setPosting] = useState(false);
const [recentActivity, setRecentActivity] = useState<PredictionRecord[]>([]);
const [recentLoading, setRecentLoading] = useState(false);
const { result, loading, error } = useDebouncedPredict(draft, threshold);
const refreshRecent = useCallback(async (videoId?: string) => {
if (!videoId) {
setRecentActivity([]);
return;
}
setRecentLoading(true);
try {
const res = await listPredictions(videoId, 200, "user_comment");
setRecentActivity(Array.isArray(res?.predictions) ? res.predictions : []);
} catch {
// Degrade gracefully if endpoint is missing or DB not configured
setRecentActivity([]);
} finally {
setRecentLoading(false);
}
}, []);
useEffect(() => {
void refreshRecent(activeVideo?.id);
}, [activeVideo?.id, refreshRecent]);
useEffect(() => {
getSuggestedVideos()
.then((r) => {
setSuggested(r.videos);
setMaxComments(r.max_comments);
// Auto-load first video so the user sees comments on initial render.
if (r.videos.length > 0) {
void loadVideo(r.videos[0]);
}
})
.catch(() => setFetchError(t.watch.couldNotLoadVideos));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handlePost = useCallback(async () => {
const text = draft.trim();
if (!text || posting) return;
setPosting(true);
try {
const author = randomTeamMember();
const analysis = await predict(text, threshold, {
videoId: activeVideo?.id,
author,
persist: true,
});
const item: CommentItem = {
id: newId(),
user: author,
text,
time: t.watch.justNow,
is_toxic: analysis.is_toxic,
probability: analysis.probability,
labels: analysis.labels,
source: "manual",
};
setSessionComments((prev) => [...prev, item]);
addHubEntry({
user: `@${author}`,
snippet: text.slice(0, 45),
score: analysis.probability,
action: analysis.is_toxic
? `${t.watch.posted} (${t.badges.toxic.toLowerCase()})`
: t.badges.safe,
});
setDraft("");
void refreshRecent(activeVideo?.id);
} finally {
setPosting(false);
}
}, [draft, posting, threshold, addHubEntry, refreshRecent, activeVideo?.id, t]);
const loadVideo = async (video: SuggestedVideo) => {
setActiveVideo(video);
setYoutubeComments([]);
setSessionComments([]);
setFetchError(null);
setDismissDemoBanner(false);
setLoadingVideoId(video.id);
try {
const res = await predictVideo(video.watch_url, maxComments, threshold);
setDemoBanner(res.source === "demo");
setYoutubeComments(
res.results.map((r, i) => ({
id: `yt-${video.id}-${i}`,
user: randomUsername(`yt-${video.id}-${i}`),
text: r.text,
time: t.watch.fromYoutube,
is_toxic: r.is_toxic,
probability: r.probability,
labels: r.labels,
source: "youtube" as const,
}))
);
} catch (e) {
setFetchError(e instanceof Error ? e.message : t.watch.failedToLoadComments);
setYoutubeComments([]);
setDemoBanner(false);
} finally {
setLoadingVideoId(null);
}
};
const toxicManual = sessionComments.filter((c) => c.is_toxic).length;
const toxicYt = youtubeComments.filter((c) => c.is_toxic).length;
const totalComments = sessionComments.length + youtubeComments.length;
const channelInitial = activeVideo?.channel_title?.charAt(0).toUpperCase() ?? "Y";
return (
<div className="watch-page">
<div className="watch-grid">
<section className="primary-column">
<div className="staged-player">
{activeVideo && !activeVideo.embeddable ? (
<a
className="player-fallback"
href={activeVideo.watch_url}
target="_blank"
rel="noopener noreferrer"
>
<img
src={activeVideo.thumbnail_url}
alt=""
className="player-fallback-thumb"
/>
<span className="player-fallback-cta">{t.watch.watchOnYoutube}</span>
</a>
) : (
<iframe
className="player-iframe"
src={`https://www.youtube.com/embed/${
activeVideo?.id ?? DEFAULT_EMBED_VIDEO_ID
}?rel=0`}
title={activeVideo?.title ?? "YouTube video player"}
allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerPolicy="strict-origin-when-cross-origin"
allowFullScreen
loading="lazy"
/>
)}
</div>
<h1 className="video-title">
{activeVideo?.title ?? t.watch.defaultTitle}
</h1>
<p className="video-meta">
{activeVideo
? activeVideo.channel_title
: t.watch.defaultMeta}
</p>
{activeVideo && isPlaceholderTitle(activeVideo.title, activeVideo.id) && (
<p className="info-banner">{t.watch.placeholderTitleBanner}</p>
)}
<div className="channel-row">
<div className="channel-avatar">{channelInitial}</div>
<div>
<p className="channel-name">{activeVideo?.channel_title ?? t.watch.channelFallback}</p>
{activeVideo && <p className="video-meta">{t.watch.suggestedVideo}</p>}
</div>
</div>
<div className="comments-header">
<span>
{t.watch.commentsCount(totalComments)}
{toxicManual + toxicYt > 0 && (
<span className="toxic-count">{t.watch.toxicDetected(toxicManual + toxicYt)}</span>
)}
</span>
</div>
<div className="comment-compose">
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void handlePost();
}
}}
placeholder={t.watch.composePlaceholder}
rows={3}
aria-label={t.watch.composeAriaLabel}
/>
{draft.trim() && (
<div className="live-analysis">
<span>{loading ? t.watch.analyzing : t.watch.liveScore}</span>
{result && (
<>
<span className={`badge ${result.is_toxic ? "badge-toxic" : "badge-safe"}`}>
{result.is_toxic ? t.badges.toxic : t.badges.safe}
</span>
<span style={{ color: toxicityColor(result.probability) }}>
{`${t.watch.toxicity}: ${formatPct(result.probability)}`}
</span>
</>
)}
{error && <span className="error-text">{error}</span>}
</div>
)}
<div className="compose-actions">
<button
type="button"
className="btn-secondary"
onClick={() => setDraft("")}
disabled={posting}
>
{t.watch.cancel}
</button>
<button
type="button"
className="btn-primary"
onClick={() => void handlePost()}
disabled={posting || !draft.trim()}
>
{posting ? t.watch.analyzing : t.watch.comment}
</button>
</div>
</div>
{fetchError && <p className="error-banner">{fetchError}</p>}
{demoBanner && !dismissDemoBanner && (
<div className="info-banner dismissible">
<span>{t.watch.demoBanner}</span>
<button
type="button"
className="btn-dismiss"
onClick={() => setDismissDemoBanner(true)}
aria-label={t.watch.dismiss}
>
×
</button>
</div>
)}
{loadingVideoId && youtubeComments.length === 0 && (
<p className="loading-comments">{t.watch.loadingComments}</p>
)}
<div className="comment-list">
{/* Persisted user comments for this video — always at the top (newest first) */}
{recentActivity
.filter((rec) => rec.source === "user_comment")
.map((rec, idx) => (
<CommentRow
key={`recent-${rec.id ?? idx}`}
comment={{
id: `recent-${rec.id ?? idx}`,
user: rec.author ?? randomUsername(`supa-${rec.id ?? idx}`),
text: truncate(rec.text, 140),
time: relativeTime(rec.created_at),
is_toxic: rec.is_toxic,
probability: rec.probability,
labels: rec.labels ?? [],
source: "recent",
}}
/>
))}
{/* Optimistic local additions until refresh from Supabase completes */}
{[...sessionComments]
.reverse()
.filter(
(c) =>
!recentActivity.some(
(r) => r.text === c.text && r.author === c.user,
),
)
.map((c) => (
<CommentRow key={c.id} comment={c} />
))}
{/* YouTube fetched comments — below */}
{youtubeComments.map((c) => (
<CommentRow key={c.id} comment={c} />
))}
</div>
{recentLoading && recentActivity.length === 0 && youtubeComments.length === 0 && (
<p className="loading-comments">{t.watch.loadingRecent}</p>
)}
</section>
<SuggestedRail
videos={suggested}
activeId={activeVideo?.id ?? null}
loadingId={loadingVideoId}
onSelect={(v) => void loadVideo(v)}
/>
</div>
</div>
);
}
|