hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { For, Show, Suspense, createEffect, createSignal, onCleanup } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { getAiCapabilities } from "@/api/ai"; |
| 4 | import { |
| 5 | getPodcastJobById, |
| 6 | getPodcastJobResultById, |
| 7 | podcastAudioUrl, |
| 8 | postPodcastJob, |
| 9 | postPodcastJobCancel, |
| 10 | } from "@/api/podcast"; |
| 11 | import { formatApiError, type PodcastFormat, type PodcastJobArtifacts, type PodcastJobStatus } from "@/api/client"; |
| 12 | import { Alert } from "@/components/ui/alert"; |
| 13 | import { Button, buttonVariants } from "@/components/ui/button"; |
| 14 | import { IconDownload, IconWaveform, IconX } from "@/components/ui/icons"; |
| 15 | import { Label } from "@/components/ui/label"; |
| 16 | import { Select } from "@/components/ui/select"; |
| 17 | import { PodcastHistory } from "@/components/notes/podcast-history"; |
| 18 | import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download"; |
| 19 | import { cn } from "@/lib/cn"; |
| 20 | import { createLivePoll } from "@/lib/create-live-poll"; |
| 21 | import { useT } from "@/stores/preferences-context"; |
| 22 | |
| 23 | const POLL_MS = 2_000; |
| 24 | |
| 25 | export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitle?: string }) { |
| 26 | const t = useT(); |
| 27 | const downloadT = usePodcastDownloadT(); |
| 28 | const [format, setFormat] = createSignal<PodcastFormat>("duz_okuma"); |
| 29 | const [jobId, setJobId] = createSignal(""); |
| 30 | const [status, setStatus] = createSignal<PodcastJobStatus | null>(null); |
| 31 | const [artifacts, setArtifacts] = createSignal<PodcastJobArtifacts | null>(null); |
| 32 | const [error, setError] = createSignal(""); |
| 33 | const [submitting, setSubmitting] = createSignal(false); |
| 34 | const [cancelling, setCancelling] = createSignal(false); |
| 35 | // The service's own estimate, taken from the submit receipt. It is never |
| 36 | // restated by the status door, so it is shown as the one estimate it is and |
| 37 | // never recomputed into a countdown the backend did not promise. |
| 38 | const [etaSecs, setEtaSecs] = createSignal<number | null>(null); |
| 39 | let generation = 0; |
| 40 | |
| 41 | // Declared before the resource below: its source runs during setup, so a |
| 42 | // later `const active` would be read in its temporal dead zone. |
| 43 | const active = () => props.active !== false; |
| 44 | const [capabilities] = createResource(() => (active() ? getAiCapabilities() : null)); |
| 45 | const storageKey = () => `hezarfen.podcast.${props.noteId}`; |
| 46 | // A cancelled or finished job is simply not polled again; the ticker below |
| 47 | // asks whether there is live work rather than being torn down. |
| 48 | const stopPolling = () => { |
| 49 | generation += 1; |
| 50 | }; |
| 51 | |
| 52 | const poll = async (id: string, token: number) => { |
| 53 | try { |
| 54 | const next = await getPodcastJobById(id); |
| 55 | if (token !== generation || !active()) return; |
| 56 | setStatus(next); |
| 57 | if (next.state === "done") { |
| 58 | const result = await getPodcastJobResultById(id); |
| 59 | if (token === generation) setArtifacts(result); |
| 60 | return; |
| 61 | } |
| 62 | if (next.state === "failed") { |
| 63 | setError(t("podcast.failed")); |
| 64 | } |
| 65 | } catch (err) { |
| 66 | if (token === generation) setError(formatApiError(err)); |
| 67 | } |
| 68 | }; |
| 69 | |
| 70 | createEffect(() => { |
| 71 | const noteId = props.noteId; |
| 72 | const enabled = active(); |
| 73 | generation += 1; |
| 74 | const token = generation; |
| 75 | setJobId(""); |
| 76 | setStatus(null); |
| 77 | setArtifacts(null); |
| 78 | setEtaSecs(null); |
| 79 | setError(""); |
| 80 | if (!enabled || !noteId || typeof sessionStorage === "undefined") return; |
| 81 | const stored = sessionStorage.getItem(storageKey()); |
| 82 | if (stored) { |
| 83 | setJobId(stored); |
| 84 | void poll(stored, token); |
| 85 | } |
| 86 | }); |
| 87 | |
| 88 | onCleanup(() => { |
| 89 | generation += 1; |
| 90 | }); |
| 91 | |
| 92 | const submit = async () => { |
| 93 | if (submitting()) return; |
| 94 | generation += 1; |
| 95 | const token = generation; |
| 96 | setSubmitting(true); |
| 97 | setError(""); |
| 98 | setArtifacts(null); |
| 99 | try { |
| 100 | const receipt = await postPodcastJob({ source_id: props.noteId, format: format() }); |
| 101 | if (token !== generation) return; |
| 102 | setJobId(receipt.job_id); |
| 103 | setStatus({ job_id: receipt.job_id, state: receipt.state, stage: "queued", progress: 0 }); |
| 104 | setEtaSecs(receipt.eta_secs); |
| 105 | if (typeof sessionStorage !== "undefined") sessionStorage.setItem(storageKey(), receipt.job_id); |
| 106 | } catch (err) { |
| 107 | setError(formatApiError(err)); |
| 108 | } finally { |
| 109 | if (token === generation) setSubmitting(false); |
| 110 | } |
| 111 | }; |
| 112 | |
| 113 | const cancel = async () => { |
| 114 | const id = jobId(); |
| 115 | if (!id || cancelling()) return; |
| 116 | setCancelling(true); |
| 117 | setError(""); |
| 118 | try { |
| 119 | await postPodcastJobCancel(id); |
| 120 | stopPolling(); |
| 121 | setStatus((current) => current ? { ...current, state: "cancelled" } : current); |
| 122 | if (typeof sessionStorage !== "undefined") sessionStorage.removeItem(storageKey()); |
| 123 | } catch (err) { |
| 124 | setError(formatApiError(err)); |
| 125 | } finally { |
| 126 | setCancelling(false); |
| 127 | } |
| 128 | }; |
| 129 | |
| 130 | const progress = () => Math.round(Math.min(1, Math.max(0, status()?.progress ?? 0)) * 100); |
| 131 | const working = () => ["queued", "running"].includes(status()?.state ?? ""); |
| 132 | |
| 133 | // Poll through the shared primitive so a parked tab stops asking and a |
| 134 | // tab-back is fresh at once — the hand-rolled timeout chain did neither. |
| 135 | createLivePoll(() => { |
| 136 | const id = jobId(); |
| 137 | if (id && working() && active()) void poll(id, generation); |
| 138 | }, POLL_MS); |
| 139 | const available = () => { |
| 140 | const current = capabilities(); |
| 141 | if (!current || capabilities.error) return true; |
| 142 | return current.enabled && current.capabilities.some((item) => item.capability === "podcast.submit" && item.workers > 0); |
| 143 | }; |
| 144 | const stateLabel = (state: string) => { |
| 145 | if (state === "queued") return t("podcast.state.queued"); |
| 146 | if (state === "running") return t("podcast.state.running"); |
| 147 | if (state === "done") return t("podcast.state.done"); |
| 148 | if (state === "failed") return t("podcast.state.failed"); |
| 149 | if (state === "cancelled") return t("podcast.state.cancelled"); |
| 150 | return t("podcast.state.running"); |
| 151 | }; |
| 152 | const formatOptions = () => [ |
| 153 | { value: "duz_okuma", label: t("podcast.format.duz_okuma") }, |
| 154 | { value: "tek_ogretici", label: t("podcast.format.tek_ogretici") }, |
| 155 | { value: "ogrenci_hoca", label: t("podcast.format.ogrenci_hoca") }, |
| 156 | ]; |
| 157 | |
| 158 | return ( |
| 159 | <Suspense |
| 160 | fallback={ |
| 161 | <section class="flex min-h-44 items-center justify-center rounded-xl border border-border-line bg-surface-base p-4"> |
| 162 | <p class="text-sm text-muted-foreground">{t("common.loading")}</p> |
| 163 | </section> |
| 164 | } |
| 165 | > |
| 166 | <section class="space-y-4 rounded-xl border border-border-line bg-surface-base p-4"> |
| 167 | <div class="flex items-start gap-3"> |
| 168 | <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary-text"> |
| 169 | <IconWaveform class="h-5 w-5" /> |
| 170 | </div> |
| 171 | <div> |
| 172 | <h2 class="font-semibold">{t("podcast.title")}</h2> |
| 173 | <p class="mt-0.5 text-sm text-muted-foreground">{t("podcast.description")}</p> |
| 174 | </div> |
| 175 | </div> |
| 176 | |
| 177 | <Show when={error()}>{(message) => <Alert variant="destructive">{message()}</Alert>}</Show> |
| 178 | <Show when={!available()}> |
| 179 | <Alert variant="warning">{t("podcast.unavailable")}</Alert> |
| 180 | </Show> |
| 181 | |
| 182 | <div class="grid gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end"> |
| 183 | <div class="space-y-1.5"> |
| 184 | <Label for={`podcast-format-${props.noteId}`}>{t("podcast.format")}</Label> |
| 185 | <Select |
| 186 | id={`podcast-format-${props.noteId}`} |
| 187 | class="h-10" |
| 188 | value={format()} |
| 189 | disabled={!available() || working() || submitting()} |
| 190 | onChange={(event) => setFormat(event.currentTarget.value as PodcastFormat)} |
| 191 | > |
| 192 | <For each={formatOptions()}> |
| 193 | {(option) => <option value={option.value}>{option.label}</option>} |
| 194 | </For> |
| 195 | </Select> |
| 196 | </div> |
| 197 | <Button type="button" class="h-10 rounded-lg" disabled={!available() || working() || submitting()} onClick={() => void submit()}> |
| 198 | <IconWaveform class="h-4 w-4" /> |
| 199 | {submitting() ? t("podcast.submitting") : t("podcast.create")} |
| 200 | </Button> |
| 201 | </div> |
| 202 | |
| 203 | <Show when={status()}> |
| 204 | {(current) => ( |
| 205 | <div class="space-y-3 rounded-lg border border-border/70 bg-muted/20 p-3"> |
| 206 | <div class="flex items-center justify-between gap-3 text-sm"> |
| 207 | <span class="font-medium">{stateLabel(current().state)}</span> |
| 208 | <span class="font-mono text-xs tabular-nums text-muted-foreground">{progress()}%</span> |
| 209 | </div> |
| 210 | <div class="h-2 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuenow={progress()} aria-valuemin="0" aria-valuemax="100"> |
| 211 | <div class="h-full rounded-full bg-primary transition-[width]" style={{ width: `${progress()}%` }} /> |
| 212 | </div> |
| 213 | {/* The stage names itself in the service's own vocabulary and is not |
| 214 | an enumerated set, so only the prefix is translated — the value |
| 215 | is shown as it came rather than guessed at. */} |
| 216 | <div class="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs text-muted-foreground"> |
| 217 | <Show when={current().stage}> |
| 218 | {(stage) => ( |
| 219 | <span> |
| 220 | {t("podcast.stageLabel")} <span class="font-medium text-foreground">{stage()}</span> |
| 221 | </span> |
| 222 | )} |
| 223 | </Show> |
| 224 | <Show when={working() && etaSecs() != null}> |
| 225 | <span class="tabular-nums">{t("podcast.etaHint", { secs: etaSecs()! })}</span> |
| 226 | </Show> |
| 227 | </div> |
| 228 | <Show when={working()}> |
| 229 | <Button type="button" size="sm" variant="outline" class="rounded-lg" disabled={cancelling()} onClick={() => void cancel()}> |
| 230 | <IconX class="h-4 w-4" />{t("podcast.cancel")} |
| 231 | </Button> |
| 232 | </Show> |
| 233 | </div> |
| 234 | )} |
| 235 | </Show> |
| 236 | |
| 237 | <Show when={artifacts()}> |
| 238 | {(result) => ( |
| 239 | <div class="space-y-2 rounded-lg border border-success/25 bg-success/5 p-3"> |
| 240 | <p class="text-sm font-medium">{t("podcast.ready")}</p> |
| 241 | <audio class="w-full" controls preload="metadata" src={podcastAudioUrl(result().job_id)}> |
| 242 | {t("podcast.audioUnsupported")} |
| 243 | </audio> |
| 244 | <a |
| 245 | href={podcastAudioUrl(result().job_id)} |
| 246 | download={podcastDownloadFilename(props.noteTitle, downloadT("podcast.download.fallback"))} |
| 247 | aria-label={downloadT("podcast.download.aria")} |
| 248 | class={cn(buttonVariants({ variant: "outline", size: "sm" }), "rounded-lg")} |
| 249 | > |
| 250 | <IconDownload class="h-4 w-4" /> |
| 251 | {downloadT("podcast.download.label")} |
| 252 | </a> |
| 253 | </div> |
| 254 | )} |
| 255 | </Show> |
| 256 | |
| 257 | <PodcastHistory |
| 258 | noteId={props.noteId} |
| 259 | active={active()} |
| 260 | refetchKey={status()?.state === "done" ? jobId() : ""} |
| 261 | /> |
| 262 | </section> |
| 263 | </Suspense> |
| 264 | ); |
| 265 | } |