| 1 | "use client"; |
| 2 | |
| 3 | import { useEffect, useState } from "react"; |
| 4 | import Link from "next/link"; |
| 5 | import { Section } from "@/components/page-header"; |
| 6 | import { Icon } from "@/components/icon"; |
| 7 | import { readBoundedBody } from "@/lib/bounded-body"; |
| 8 | import { COMPUTER_USE_REPO } from "@/lib/computer-use-release"; |
| 9 | import { RELEASE_UPDATES_COPY } from "@/lib/content/release-updates"; |
| 10 | import { getChrome, pickText } from "@/lib/i18n/dictionaries"; |
| 11 | import { REPO_RELEASES_URL } from "@/lib/i18n/links"; |
| 12 | import type { ReleaseUpdatesSnapshot } from "@/lib/release-updates"; |
| 13 | |
| 14 | const INTERVAL = 5 * 60 * 1000; |
| 15 | const SOURCES = { terminal: REPO_RELEASES_URL, computerUse: `${COMPUTER_USE_REPO}/releases` }; |
| 16 | const CHANNELS = ["terminal", "computerUse"] as const; |
| 17 | |
| 18 | function validSnapshot(value: unknown): value is ReleaseUpdatesSnapshot { |
| 19 | if (!value || typeof value !== "object") return false; |
| 20 | const snapshot = value as Record<string, unknown>; |
| 21 | if (snapshot.fetchedAt !== null && (typeof snapshot.fetchedAt !== "string" || !Number.isFinite(Date.parse(snapshot.fetchedAt)))) return false; |
| 22 | return CHANNELS.every((channel) => { |
| 23 | const item = snapshot[channel]; |
| 24 | if (!item || typeof item !== "object") return false; |
| 25 | const state = item as Record<string, unknown>; |
| 26 | if (!["current", "cached", "unavailable"].includes(String(state.status))) return false; |
| 27 | if (state.release === null) return state.status === "unavailable"; |
| 28 | if (state.status === "unavailable") return false; |
| 29 | if (!state.release || typeof state.release !== "object") return false; |
| 30 | const release = state.release as Record<string, unknown>; |
| 31 | return typeof release.tag === "string" && /^v\d+\.\d+\.\d+$/.test(release.tag) |
| 32 | && release.version === release.tag.slice(1) |
| 33 | && release.url === `${SOURCES[channel]}/tag/${release.tag}` |
| 34 | && typeof release.publishedAt === "string" && Number.isFinite(Date.parse(release.publishedAt)); |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | export function ReleaseUpdates({ locale, initial, showAllLink = true }: { locale: string; initial: ReleaseUpdatesSnapshot; showAllLink?: boolean }) { |
| 39 | const [snapshot, setSnapshot] = useState(initial); |
| 40 | const [failed, setFailed] = useState(false); |
| 41 | const text = (key: keyof typeof RELEASE_UPDATES_COPY) => pickText(RELEASE_UPDATES_COPY[key], locale); |
| 42 | const dateLocale = getChrome(locale).dateLocale; |
| 43 | |
| 44 | useEffect(() => { |
| 45 | let active = true; |
| 46 | let pending: AbortController | null = null; |
| 47 | let lastAttempt = CHANNELS.every((channel) => initial[channel].status === "current") ? Math.min(Date.now(), Date.parse(initial.fetchedAt ?? "") || 0) : 0; |
| 48 | const refresh = async () => { |
| 49 | if (document.visibilityState !== "visible" || pending || Date.now() - lastAttempt < INTERVAL) return; |
| 50 | lastAttempt = Date.now(); |
| 51 | pending = new AbortController(); |
| 52 | const timeout = window.setTimeout(() => pending?.abort(), 15_000); |
| 53 | try { |
| 54 | const response = await fetch("/api/releases", { cache: "no-store", credentials: "omit", signal: pending.signal }); |
| 55 | if (!response.ok) throw new Error("Release check unavailable"); |
| 56 | const next: unknown = JSON.parse(new TextDecoder().decode(await readBoundedBody(response, 32 * 1024))); |
| 57 | if (!validSnapshot(next)) throw new Error("Invalid release response"); |
| 58 | if (active) { |
| 59 | setSnapshot((previous) => { |
| 60 | const resolved = { ...next }; |
| 61 | for (const channel of CHANNELS) { |
| 62 | const before = previous[channel].release; |
| 63 | const after = next[channel].release; |
| 64 | if (before && next[channel].status !== "current" && (!after || Date.parse(before.publishedAt) > Date.parse(after.publishedAt))) { |
| 65 | resolved[channel] = { release: before, status: "cached" }; |
| 66 | } |
| 67 | } |
| 68 | return resolved; |
| 69 | }); |
| 70 | setFailed(false); |
| 71 | } |
| 72 | } catch { |
| 73 | if (active) setFailed(true); |
| 74 | } finally { |
| 75 | window.clearTimeout(timeout); |
| 76 | pending = null; |
| 77 | } |
| 78 | }; |
| 79 | void refresh(); |
| 80 | const interval = window.setInterval(() => void refresh(), INTERVAL); |
| 81 | const visible = () => void refresh(); |
| 82 | document.addEventListener("visibilitychange", visible); |
| 83 | window.addEventListener("focus", visible); |
| 84 | return () => { |
| 85 | active = false; |
| 86 | window.clearInterval(interval); |
| 87 | pending?.abort(); |
| 88 | document.removeEventListener("visibilitychange", visible); |
| 89 | window.removeEventListener("focus", visible); |
| 90 | }; |
| 91 | }, [initial]); |
| 92 | |
| 93 | return ( |
| 94 | <Section |
| 95 | id="release-updates" |
| 96 | title={text("title")} |
| 97 | className="home-section release-updates" |
| 98 | scope={text("source")} |
| 99 | link={showAllLink ? <Link href={`/${locale}/changelog`} className="section-link">{text("all")}<Icon name="arrow-right" className="icon icon-flip" /></Link> : undefined} |
| 100 | > |
| 101 | <div className="release-cards" data-checked-at={snapshot.fetchedAt ?? undefined}> |
| 102 | {CHANNELS.map((channel) => { |
| 103 | const { release, status } = snapshot[channel]; |
| 104 | return ( |
| 105 | <article className="release-card" key={channel} aria-label={text(channel)}> |
| 106 | <h3>{text(channel)}</h3> |
| 107 | <div className="release-version" aria-live="polite"> |
| 108 | {release ? <a href={release.url}>{release.tag}</a> : <a href={SOURCES[channel]}>{text("unavailable")}</a>} |
| 109 | {release?.publishedAt ? <time dateTime={release.publishedAt}>{new Date(release.publishedAt).toLocaleDateString(dateLocale, { year: "numeric", month: "short", day: "numeric", timeZone: "UTC" })}</time> : null} |
| 110 | {release && (status === "cached" || failed) ? <span className="release-cached">{text("cached")}</span> : null} |
| 111 | </div> |
| 112 | <div className="release-links"> |
| 113 | <a href={release?.url ?? SOURCES[channel]} className="section-link">{text("notes")}<Icon name="external" className="icon" /></a> |
| 114 | <a href={`${SOURCES[channel]}.atom`} className="section-link" aria-label={`${text(channel)} · ${text("rss")}`}>{text("rss")}</a> |
| 115 | </div> |
| 116 | </article> |
| 117 | ); |
| 118 | })} |
| 119 | </div> |
| 120 | {failed ? <p className="release-update-error" role="status">{text("refreshFailed")}</p> : null} |
| 121 | </Section> |
| 122 | ); |
| 123 | } |
| 124 |