ジョブトレイ
ひとつの Job 型を共有する 4 つのレイアウトのバックグラウンド処理キット。
使いどころ
- 保存、エンコード、書き出しを裏で続けたまま、エディターに戻ってもらいたいとき
- ユーザーの対応が必要なバックグラウンドの失敗を知らせたいとき
注意点
- 成功した処理は 8 秒で消え、すぐ終わる処理は表示されないので、ログ代わりにはしない
- 失敗した行は閉じられるまで残すこと。それがトレイの存在理由
エージェントに追加してもらう
インストールコマンド、使いどころ、props、デザインルールを一度にコピーできます。Claude Code、Cursor、Codex に貼り付けてください。
CLI でインストール
shadcn CLI を使います。ソースはプロジェクトにコピーされるので、すべての行があなたのものです。
$ npx shadcn@latest add https://sunui.synvize.com/r/jobs-tray.json手動でインストール
- 1. 依存パッケージをインストールします。
$ npm install clsx tailwind-merge framer-motion - 2.
cnヘルパーがなければlib/utils.tsに追加します。shadcn/ui を使っていない場合は、色のトークン用に sunui-theme.css も追加します(手順)。そのあとコンポーネントをコピーします。jobs-tray.tsx"use client"; import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react"; import { cn } from "@/lib/utils"; // Everything for background work: the shared Job type, progress and status text, four-language strings, plus the jobs tray JobsTray at the bottom right. // The other layouts (single row JobRow, sidebar JobPanel, grid JobTile, status dot JobStatusDot) are in ./job-views. /* ───────────── Language ───────────── */ export type SunLocale = "en" | "zh-TW" | "zh-CN" | "ja"; /** Maps any language tag to one of the four built-in languages, falling back to English */ export function resolveLocale(tag?: string): SunLocale { const t = (tag ?? "en").toLowerCase(); if (t.startsWith("zh")) return /hant|tw|hk|mo/.test(t) ? "zh-TW" : "zh-CN"; if (t.startsWith("ja")) return "ja"; return "en"; } /** Formats seconds as a short string such as "1m 5s", in the style of the target language */ export function formatSeconds(s: number, unit: { s: string; m: string; gap: string }) { const v = Math.max(0, Math.round(s)); if (v < 60) return `${v}${unit.s}`; const m = Math.floor(v / 60); const r = v % 60; return r ? `${m}${unit.m}${unit.gap}${r}${unit.s}` : `${m}${unit.m}`; } /* ───────────── Generation Job (shared by JobPanel, JobTile, JobRow) ───────────── */ // The percentage is not linear: queued 2, planning 6, loading 14, generating 15 plus 80 times the step ratio, checking 97. export type JobStatus = | "queued" | "planning" | "loading" | "sampling" | "decoding" | "refining" | "checking" | "done" | "blocked" | "error" | "canceled"; export interface Job { id: string; prompt: string; status: JobStatus; /** Current and total steps of sampling or refining */ step?: number; total?: number; /** Queue position, 1 means you are next */ queuePosition?: number; /** Estimated seconds remaining */ etaSeconds?: number | null; /** Elapsed seconds once finished */ durationSeconds?: number | null; /** Reference image: blurred as the base while generating, with a sweeping shine on top */ sourceSrc?: string; /** Live preview image (low resolution); replaces the shine when present */ previewSrc?: string; /** Aspect ratio, for example "2 / 3" */ aspect?: string; /** How many images one generation produces */ count?: number; /** Number of images when finished; 0 means awaiting review or deleted */ images?: number; /** Awaiting manual review */ held?: boolean; error?: string; hint?: string; /** Info under the sidebar title, for example creation time and style */ meta?: string[]; } export const ACTIVE: JobStatus[] = ["queued", "planning", "loading", "sampling", "decoding", "refining", "checking"]; export const isActive = (job: Pick<Job, "status">) => ACTIVE.includes(job.status); export function stepIndex(status: JobStatus) { if (status === "queued" || status === "planning") return 0; if (status === "loading") return 1; if (status === "sampling" || status === "decoding" || status === "refining") return 2; if (status === "checking") return 3; return 4; } export function jobPercent(job: Job) { const ratio = job.total ? (job.step ?? 0) / job.total : 0; switch (job.status) { case "queued": return 2; case "planning": return 6; case "loading": return 14; case "sampling": return 15 + 80 * ratio; case "decoding": return 94; case "refining": return 95 + ratio; case "checking": return 97; default: return 100; } } /** Collapses the fine-grained generation statuses into five coarse ones, for the tray and the status dot */ export function jobPhase(job: Pick<Job, "status">): BackgroundJobState { if (job.status === "queued") return "queued"; if (isActive(job)) return "running"; if (job.status === "done") return "completed"; if (job.status === "canceled") return "cancelled"; return "failed"; } /* ───────────── Strings ───────────── */ /** Status text and shared strings, used by both JobPanel and JobTile */ export interface JobStatusLabels { queued?: (ahead: number) => string; startingSoon?: string; planning?: string; loading?: string; sampling?: (step: number, total: number) => string; decoding?: string; refining?: (step: number, total: number) => string; checking?: string; done?: string; held?: string; deleted?: string; blocked?: string; error?: string; canceled?: string; eta?: (time: string) => string; took?: (time: string) => string; seconds?: (s: number) => string; progress?: string; heldNote?: string; cancel?: string; remove?: string; actionFailed?: string; } export interface JobPanelLabels extends JobStatusLabels { steps?: [string, string, string, string, string]; leaveNote?: string; deletedNote?: string; cancelAndEdit?: string; retry?: string; edit?: string; } export interface JobTileLabels extends JobStatusLabels { cancelAria?: string; removeAria?: string; openAria?: (prompt: string) => string; detailAria?: (prompt: string) => string; count?: (n: number) => string; reference?: string; previewAlt?: string; } export interface JobRowLabels { failedRow?: string; progress?: string; } export interface JobsTrayLabels { region?: string; running?: string; completed?: string; failed?: string; cancelled?: string; queued?: string; dismiss?: string; cancel?: string; } type PanelOnly = Required<Omit<JobPanelLabels, keyof JobStatusLabels>>; type TileOnly = Required<Omit<JobTileLabels, keyof JobStatusLabels>>; interface Messages { status: Required<JobStatusLabels>; panel: PanelOnly; tile: TileOnly; row: Required<JobRowLabels>; tray: Required<JobsTrayLabels>; } const MESSAGES: Record<SunLocale, Messages> = { en: { status: { queued: (ahead) => `In queue, ${ahead} ahead of you`, startingSoon: "Starting soon", planning: "AI is reading your prompt", loading: "Loading model", sampling: (s, t) => `Generating ${s}/${t}`, decoding: "Writing image", refining: (s, t) => (t ? `Refining faces ${s}/${t}` : "Refining faces"), checking: "Checking the result", done: "Done", held: "Waiting for manual review", deleted: "Images deleted", blocked: "Not run", error: "Generation didn't finish", canceled: "Canceled", eta: (time) => `About ${time} left`, took: (time) => `Took ${time}`, seconds: (s) => formatSeconds(s, { s: "s", m: "m", gap: " " }), progress: "Generation progress", heldNote: "These images are waiting for manual review. They haven't been deleted and will come back once cleared. Your quota has been refunded.", cancel: "Cancel", remove: "Remove record", actionFailed: "That didn't work. Please try again.", }, panel: { steps: ["Read prompt", "Load model", "Generate", "Safety check", "Done"], leaveNote: "Leaving this page won't stop generation. Finished images appear first on the create page.", deletedNote: "The images from this run have been deleted.", cancelAndEdit: "Cancel and edit prompt", retry: "Retry", edit: "Edit prompt", }, tile: { cancelAria: "Cancel this generation", removeAria: "Remove this record", openAria: (p) => `View progress: ${p}`, detailAria: (p) => `View details: ${p}`, count: (n) => `${n} images`, reference: "Reference", previewAlt: "Preview while generating", }, row: { failedRow: "Generation failed, open to view and retry", progress: "Generation progress" }, tray: { region: "Background jobs", running: "In progress", completed: "Done", failed: "Failed", cancelled: "Cancelled", queued: "Queued", dismiss: "Dismiss", cancel: "Cancel this job", }, }, "zh-TW": { status: { queued: (ahead) => `排隊中,前面還有 ${ahead} 位`, startingSoon: "即將開始", planning: "AI 正在理解你的描述", loading: "正在載入模型", sampling: (s, t) => `生成中 ${s}/${t}`, decoding: "正在輸出圖片", refining: (s, t) => (t ? `修飾臉部 ${s}/${t}` : "修飾臉部"), checking: "正在檢查結果", done: "完成", held: "等待人工複查", deleted: "圖片已刪除", blocked: "未執行", error: "生成沒有完成", canceled: "已取消", eta: (time) => `約剩 ${time}`, took: (time) => `耗時 ${time}`, seconds: (s) => formatSeconds(s, { s: " 秒", m: " 分", gap: " " }), progress: "生成進度", heldNote: "這些圖片正在等待人工複查,並沒有被刪除,通過後就會回來。額度已退還。", cancel: "取消", remove: "刪除紀錄", actionFailed: "操作沒有成功,請再試一次。", }, panel: { steps: ["理解描述", "載入模型", "生成", "安全檢查", "完成"], leaveNote: "離開這個頁面不會中斷生成,完成的圖片會優先出現在創作頁。", deletedNote: "這次生成的圖片已被刪除。", cancelAndEdit: "取消並修改描述", retry: "重試", edit: "修改描述", }, tile: { cancelAria: "取消這次生成", removeAria: "移除這筆紀錄", openAria: (p) => `查看進度:${p}`, detailAria: (p) => `查看詳情:${p}`, count: (n) => `${n} 張`, reference: "參考圖", previewAlt: "生成中的預覽", }, row: { failedRow: "生成失敗,點開查看並重試", progress: "生成進度" }, tray: { region: "背景工作", running: "進行中", completed: "完成", failed: "失敗", cancelled: "已取消", queued: "排隊中", dismiss: "關閉", cancel: "取消這項工作", }, }, "zh-CN": { status: { queued: (ahead) => `排队中,前面还有 ${ahead} 位`, startingSoon: "即将开始", planning: "AI 正在理解你的描述", loading: "正在加载模型", sampling: (s, t) => `生成中 ${s}/${t}`, decoding: "正在输出图片", refining: (s, t) => (t ? `修饰面部 ${s}/${t}` : "修饰面部"), checking: "正在检查结果", done: "完成", held: "等待人工复审", deleted: "图片已删除", blocked: "未执行", error: "生成未完成", canceled: "已取消", eta: (time) => `约剩 ${time}`, took: (time) => `耗时 ${time}`, seconds: (s) => formatSeconds(s, { s: " 秒", m: " 分", gap: " " }), progress: "生成进度", heldNote: "这些图片正在等待人工复审,并没有被删除,通过后就会恢复。额度已退还。", cancel: "取消", remove: "删除记录", actionFailed: "操作未成功,请重试。", }, panel: { steps: ["理解描述", "加载模型", "生成", "安全检查", "完成"], leaveNote: "离开此页面不会中断生成,完成的图片会优先显示在创作页。", deletedNote: "本次生成的图片已被删除。", cancelAndEdit: "取消并修改描述", retry: "重试", edit: "修改描述", }, tile: { cancelAria: "取消这次生成", removeAria: "移除这条记录", openAria: (p) => `查看进度:${p}`, detailAria: (p) => `查看详情:${p}`, count: (n) => `${n} 张`, reference: "参考图", previewAlt: "生成中的预览", }, row: { failedRow: "生成失败,点开查看并重试", progress: "生成进度" }, tray: { region: "后台任务", running: "进行中", completed: "完成", failed: "失败", cancelled: "已取消", queued: "排队中", dismiss: "关闭", cancel: "取消此任务", }, }, ja: { status: { queued: (ahead) => `順番待ち、あと ${ahead} 件`, startingSoon: "まもなく開始", planning: "AI がプロンプトを読んでいます", loading: "モデルを読み込み中", sampling: (s, t) => `生成中 ${s}/${t}`, decoding: "画像を書き出し中", refining: (s, t) => (t ? `顔を補正中 ${s}/${t}` : "顔を補正中"), checking: "結果をチェック中", done: "完了", held: "手動審査待ち", deleted: "画像は削除されました", blocked: "実行されませんでした", error: "生成が完了しませんでした", canceled: "キャンセル済み", eta: (time) => `残り約 ${time}`, took: (time) => `所要時間 ${time}`, seconds: (s) => formatSeconds(s, { s: "秒", m: "分", gap: "" }), progress: "生成の進捗", heldNote: "これらの画像は手動審査待ちです。削除されてはおらず、審査を通過すると戻ってきます。利用枠は返却済みです。", cancel: "キャンセル", remove: "履歴を削除", actionFailed: "うまくいきませんでした。もう一度お試しください。", }, panel: { steps: ["プロンプト解析", "モデル読込", "生成", "安全チェック", "完了"], leaveNote: "このページを離れても生成は止まりません。完成した画像は作成ページに先に表示されます。", deletedNote: "今回生成した画像は削除されました。", cancelAndEdit: "キャンセルして編集", retry: "再試行", edit: "プロンプトを編集", }, tile: { cancelAria: "この生成をキャンセル", removeAria: "この記録を削除", openAria: (p) => `進捗を見る:${p}`, detailAria: (p) => `詳細を見る:${p}`, count: (n) => `${n} 枚`, reference: "参考画像", previewAlt: "生成中のプレビュー", }, row: { failedRow: "生成に失敗しました。開いて確認し、再試行してください", progress: "生成の進行状況" }, tray: { region: "バックグラウンド処理", running: "処理中", completed: "完了", failed: "失敗", cancelled: "キャンセル済み", queued: "待機中", dismiss: "閉じる", cancel: "この処理をキャンセル", }, }, }; /** A full set of built-in strings for one language (five groups: status, panel, tile, row, tray) */ export function jobMessages(locale?: string): Messages { return MESSAGES[resolveLocale(locale)]; } export function jobStatusLabel(job: Job, labels?: JobStatusLabels, locale = "en") { const t = { ...jobMessages(locale).status, ...labels }; const step = job.step ?? 0; const total = job.total ?? 0; switch (job.status) { case "queued": return (job.queuePosition ?? 0) > 1 ? t.queued((job.queuePosition ?? 0) - 1) : t.startingSoon; case "planning": return t.planning; case "loading": return t.loading; case "sampling": return t.sampling(step, total); case "decoding": return t.decoding; case "refining": return t.refining(step, total); case "checking": return t.checking; case "done": return job.images ? t.done : job.held ? t.held : t.deleted; case "blocked": return t.blocked; case "error": return t.error; case "canceled": return t.canceled; } } /* ───────────── Jobs tray JobsTray ───────────── */ /* AutoLens dark tokens, bundled with the component and independent of the site theme */ const tokens = { "--al-bg-elevated": "#252525", "--al-border": "rgba(255, 255, 255, 0.06)", "--al-text-primary": "#e5e5e5", "--al-text-secondary": "#a3a3a3", "--al-text-muted": "#8a8a8a", "--al-danger": "#dc2626", } as CSSProperties; export type BackgroundJobState = "queued" | "running" | "completed" | "failed" | "cancelled"; export interface BackgroundJob { id: string; /** Only used to decide whether to show it; for example internal jobs like hash are shown only on failure */ type?: string; /** Name shown to the user, for example "Saving camera track" */ label: string; state: BackgroundJobState; /** 0 to 1; undefined when progress is unknown */ progress?: number; errorCode?: string; startedAt: number; endedAt?: number; /** A cancelable job gets an extra ✕ on the panel */ onCancel?: () => void; } /** A job that finishes faster than this is not worth a "done" notice afterwards */ const QUICK_JOB_MS = 1500; /** How long a finished job stays in the list before it is removed */ const COMPLETED_TTL_MS = 8000; /** * Whether this job should appear on the panel: failed and canceled jobs always show; hash jobs * show only on failure; a job that finishes quickly gets no "done" notice. */ export function isJobWorthShowing(job: BackgroundJob): boolean { if (job.state === "failed" || job.state === "cancelled") return true; if (job.type === "hash") return false; if (job.state === "completed") return (job.endedAt ?? job.startedAt) - job.startedAt >= QUICK_JOB_MS; return true; } /** Converts a generation Job into one tray row: the name is the prompt, progress comes from jobPercent, elapsed time from durationSeconds */ export function toBackgroundJob(job: Job, opts?: { label?: string; type?: string; onCancel?: () => void }): BackgroundJob { const state = jobPhase(job); const ended = state === "running" || state === "queued" ? undefined : job.durationSeconds != null ? job.durationSeconds * 1000 : QUICK_JOB_MS; return { id: job.id, type: opts?.type ?? "generation", label: opts?.label ?? job.prompt, state, ...(state === "running" ? { progress: jobPercent(job) / 100 } : {}), ...(job.error ? { errorCode: job.error } : {}), startedAt: 0, ...(ended !== undefined ? { endedAt: ended } : {}), ...(opts?.onCancel && isActive(job) ? { onCancel: opts.onCancel } : {}), }; } /** Background job registry: startJob, updateJob, finishJob, dismissJob, runJob, same behavior as the original service */ export function useBackgroundJobs(options?: { completedTtl?: number }) { const ttl = options?.completedTtl ?? COMPLETED_TTL_MS; const [jobs, setJobs] = useState<BackgroundJob[]>([]); const seq = useRef(0); const timers = useRef(new Set<ReturnType<typeof setTimeout>>()); useEffect(() => { const set = timers.current; return () => set.forEach(clearTimeout); }, []); const startJob = useCallback((type: string, label: string, opts?: { onCancel?: () => void }) => { seq.current += 1; const id = `${type}-${seq.current}`; const job: BackgroundJob = { id, type, label, state: "running", startedAt: Date.now(), ...(opts?.onCancel ? { onCancel: opts.onCancel } : {}) }; setJobs((prev) => [...prev, job]); return id; }, []); const updateJob = useCallback((id: string, patch: Partial<Pick<BackgroundJob, "progress" | "label">>) => { setJobs((prev) => prev.map((j) => (j.id === id ? { ...j, ...patch } : j))); }, []); const dismissJob = useCallback((id: string) => setJobs((prev) => prev.filter((j) => j.id !== id)), []); const finishJob = useCallback( (id: string, result: { success: boolean; errorCode?: string } = { success: true }) => { setJobs((prev) => prev.map((j) => j.id === id ? { ...j, state: result.success ? "completed" : "failed", ...(result.errorCode ? { errorCode: result.errorCode } : {}), endedAt: Date.now() } : j, ), ); // Successful jobs fade out on their own; failed ones stay so the user sees them if (result.success) { const timer = setTimeout(() => { timers.current.delete(timer); dismissJob(id); }, ttl); timers.current.add(timer); } }, [dismissJob, ttl], ); const cancelJob = useCallback((id: string) => { setJobs((prev) => prev.map((j) => (j.id === id ? { ...j, state: "cancelled", endedAt: Date.now(), onCancel: undefined } : j))); }, []); /** Wraps a piece of background work: registers it automatically and finishes it on success or failure */ const runJob = useCallback( async <T,>(type: string, label: string, fn: (report: (progress: number) => void) => Promise<T>) => { const id = startJob(type, label); try { const out = await fn((progress) => updateJob(id, { progress })); finishJob(id, { success: true }); return out; } catch (err) { finishJob(id, { success: false, errorCode: err instanceof Error ? err.message : String(err) }); throw err; } }, [finishJob, startJob, updateJob], ); return { jobs, startJob, updateJob, finishJob, dismissJob, cancelJob, runJob }; } export interface JobsTrayProps { jobs: BackgroundJob[]; /** The ✕ on a failed row */ onDismiss?: (id: string) => void; /** Defaults to fixed at the bottom right of the viewport; false switches to absolute so the parent positions it */ fixed?: boolean; /** Color of the in-progress dot, defaults to AutoLens gold */ accent?: string; /** UI language: en, zh-TW, zh-CN, ja. Tags like zh-Hant-HK and ja-JP are also accepted */ locale?: string; /** Overrides built-in strings, takes precedence over locale */ labels?: JobsTrayLabels; className?: string; } export function JobsTray({ jobs: allJobs, onDismiss, fixed = true, accent = "#eab308", locale = "en", labels, className }: JobsTrayProps) { const t = { ...jobMessages(locale).tray, ...labels }; const jobs = allJobs.filter(isJobWorthShowing); const stateLabel = (job: BackgroundJob) => { switch (job.state) { case "running": return job.progress !== undefined ? `${Math.round(job.progress * 100)}%` : t.running; case "completed": return t.completed; case "failed": return t.failed; case "cancelled": return t.cancelled; default: return t.queued; } }; // With no jobs the list is empty and takes no space, but the live region stays so screen readers catch the next one return ( <div role="region" aria-label={t.region} style={{ ...tokens, "--al-accent": accent } as CSSProperties} className={cn( fixed ? "fixed z-[9998]" : "absolute z-10", "right-4 bottom-4 flex w-64 max-w-[calc(100%-2rem)] flex-col gap-1 pointer-events-none", className, )} > <ul aria-live="polite" className="contents"> {jobs.map((job) => ( <li key={job.id} className={cn( "pointer-events-auto flex items-center gap-2 rounded-[8px] border px-3 py-2 text-xs shadow-lg backdrop-blur", job.state === "failed" ? "border-[var(--al-danger)] bg-[var(--al-bg-elevated)] text-[var(--al-text-primary)]" : "border-[var(--al-border)] bg-[var(--al-bg-elevated)] text-[var(--al-text-secondary)]", )} > {job.state === "running" && ( <span aria-hidden="true" className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-[var(--al-accent)] motion-reduce:animate-none" /> )} <span className="min-w-0 flex-1 truncate" title={job.errorCode ?? job.label}> {job.label} </span> <span className={cn("tabular-nums", job.state === "failed" ? "text-[var(--al-danger)]" : "text-[var(--al-text-muted)]")}> {stateLabel(job)} </span> {job.state === "running" && job.onCancel && ( <button type="button" onClick={job.onCancel} className="text-[var(--al-text-muted)] hover:text-[var(--al-danger)]" aria-label={t.cancel} title={t.cancel} > ✕ </button> )} {job.state === "failed" && ( <button type="button" onClick={() => onDismiss?.(job.id)} className="text-[var(--al-text-muted)] hover:text-[var(--al-text-primary)]" aria-label={t.dismiss} > ✕ </button> )} </li> ))} </ul> </div> ); }job-views.tsx"use client"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { useEffect, useState, type CSSProperties, type ReactNode } from "react"; import { cn } from "@/lib/utils"; import { isActive, jobMessages, jobPercent, jobStatusLabel, stepIndex, type Job, type JobPanelLabels, type JobRowLabels, type JobStatusLabels, type JobTileLabels, } from "./jobs-tray"; // Three layouts of the same Job: console single row JobRow, progress page sidebar JobPanel and grid tile JobTile, plus the status dot JobStatusDot. // The type, progress percentage, status text and four-language strings all come from ./jobs-tray. /* ───────────── Shared look ───────────── */ // zinc palette shared by the original projects (Yumecanvas / Vozmira), light and dark const tokens = "[--yc-bg:#FAFAFA] [--yc-card:#FFFFFF] [--yc-fg:#18181B] [--yc-muted:#F4F4F5] [--yc-muted-fg:#6B6B73] [--yc-border:#E4E4E7] [--yc-input:#D4D4D8] [--yc-primary:#18181B] [--yc-primary-fg:#FAFAFA] [--yc-ring:#71717A] [--yc-success:#15803D] [--yc-warning:#B45309] [--yc-destructive:#DC2626] " + "dark:[--yc-bg:#09090B] dark:[--yc-card:#111113] dark:[--yc-fg:#FAFAFA] dark:[--yc-muted:#27272A] dark:[--yc-muted-fg:#A1A1AA] dark:[--yc-border:rgba(255,255,255,0.08)] dark:[--yc-input:rgba(255,255,255,0.12)] dark:[--yc-primary:#FAFAFA] dark:[--yc-primary-fg:#18181B] dark:[--yc-ring:#A1A1AA] dark:[--yc-success:#4ADE80] dark:[--yc-warning:#FBBF24] dark:[--yc-destructive:#F87171]"; const ringFocus = "outline-none focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--yc-ring)_50%,transparent)]"; function Icon({ d, className }: { d: ReactNode; className?: string }) { return ( <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden className={cn("shrink-0", className)}> {d} </svg> ); } const P = { check: <path d="M20 6 9 17l-5-5" />, x: ( <> <path d="M18 6 6 18" /> <path d="m6 6 12 12" /> </> ), loader: <path d="M21 12a9 9 0 1 1-6.219-8.56" />, alert: ( <> <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" /> <path d="M12 9v4" /> <path d="M12 17h.01" /> </> ), pencil: ( <> <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" /> <path d="m15 5 4 4" /> </> ), refresh: ( <> <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" /> <path d="M21 3v5h-5" /> <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" /> <path d="M8 16H3v5" /> </> ), trash: ( <> <path d="M3 6h18" /> <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" /> <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" /> </> ), eyeOff: ( <> <path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" /> <path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" /> <path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" /> <path d="m2 2 20 20" /> </> ), image: ( <> <rect width="18" height="18" x="3" y="3" rx="2" ry="2" /> <circle cx="9" cy="9" r="2" /> <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" /> </> ), chevronRight: <path d="m9 18 6-6-6-6" />, globe: ( <> <circle cx="12" cy="12" r="10" /> <path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" /> <path d="M2 12h20" /> </> ), file: ( <> <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /> <path d="M14 2v4a2 2 0 0 0 2 2h4" /> <path d="M10 9H8" /> <path d="M16 13H8" /> <path d="M16 17H8" /> </> ), }; function Spinner({ className }: { className?: string }) { const reduce = useReducedMotion() ?? false; return <Icon d={P.loader} className={cn(!reduce && "animate-spin", className)} />; } /** Equivalent to the original shadcn Progress: h-1 grey track, the indicator advances with translateX */ function ProgressBar({ value, label, className }: { value: number; label: string; className?: string }) { return ( <div role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(value)} className={cn("relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-[var(--yc-muted)]", className)} > <div className="size-full flex-1 bg-[var(--yc-primary)] transition-all motion-reduce:transition-none" style={{ transform: `translateX(-${100 - (value || 0)}%)` }} /> </div> ); } type Kind = "cancel" | "rerun" | "delete"; type Action = (() => void | Promise<unknown>) | undefined; /** Equivalent to the original useJobActions: remembers which action is running, shows the error on failure and clears it after 4 seconds */ function useActions(fail: string) { const [pending, setPending] = useState<Kind | null>(null); const [error, setError] = useState<string | null>(null); useEffect(() => { if (!error) return; const id = window.setTimeout(() => setError(null), 4000); return () => window.clearTimeout(id); }, [error]); const run = async (kind: Kind, fn: Action) => { if (!fn) return false; setPending(kind); try { await fn(); return true; } catch (e) { setError(e instanceof Error && e.message ? e.message : fail); return false; } finally { setPending(null); } }; return { pending, error, run }; } /* ───────────── JobStatusDot ───────────── */ const RUNNING = "bg-[var(--yc-muted-fg)] animate-pulse motion-reduce:animate-none"; const WAITING = "bg-[var(--yc-muted-fg)]"; export type JobRowState = "running" | "waiting" | "completed" | "failed"; /** Maps a Job to a status dot: queued and canceled are grey, generating pulses, done is green, failed is red */ export function jobDotState(job: Pick<Job, "status">): JobRowState { if (job.status === "queued" || job.status === "canceled") return "waiting"; if (isActive(job)) return "running"; if (job.status === "done") return "completed"; return "failed"; } /** Dot plus text status, no solid badge: failed is a red dot, running is a pulsing ink dot, waiting is a grey dot */ export function JobStatusDot({ state, children, className }: { state: JobRowState; children: ReactNode; className?: string }) { const failed = state === "failed"; const dot = state === "completed" ? "bg-[var(--yc-success)]" : failed ? "bg-[var(--yc-destructive)]" : state === "running" ? RUNNING : WAITING; return ( <span className={cn(tokens, "inline-flex items-center gap-1.5 text-xs font-medium", failed ? "text-[var(--yc-destructive)]" : "text-[var(--yc-muted-fg)]", className)}> <span className={cn("inline-block size-1.5 shrink-0 rounded-full", dot)} /> {children} </span> ); } /* ───────────── JobRow ───────────── */ export interface JobRowProps { /** When a Job is passed, title, progress, label and failed are derived from it if not given */ job?: Job; title?: string; /** Source type, for example a URL or text */ source?: { kind: "url" | "text"; label: string }; /** 0 to 100 */ progress?: number; /** Status text next to the progress */ label?: string; failed?: boolean; href?: string; onClick?: () => void; /** UI language: en, zh-TW, zh-CN, ja. Tags like zh-Hant-HK and ja-JP are also accepted */ locale?: string; /** Overrides built-in strings, takes precedence over locale; also accepts status text (used for the label derived from a job) */ labels?: JobRowLabels & Omit<JobStatusLabels, "progress">; className?: string; } /** A single progress row in the console: deliberately not a card, so it reads as "work in progress that needs attention" */ export function JobRow({ job, title, source, progress, label, failed, href, onClick, locale = "en", labels, className }: JobRowProps) { const t = { ...jobMessages(locale).row, ...labels }; const isFailed = failed ?? (job ? job.status === "error" || job.status === "blocked" : false); const value = progress ?? (job ? (job.status === "canceled" ? 0 : jobPercent(job)) : 0); const text = label ?? (job ? jobStatusLabel(job, labels, locale) : ""); const width = Math.max(0, Math.min(100, value)); return ( <a href={href} onClick={onClick} className={cn( tokens, "group flex items-center gap-4 px-4 py-3 text-[var(--yc-fg)] transition-colors outline-none hover:bg-[var(--yc-muted)] focus-visible:bg-[var(--yc-muted)] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--yc-ring)]", className, )} > <div className="min-w-0 flex-1"> <div className="flex items-center gap-2"> <p className="truncate text-sm font-semibold">{title ?? job?.prompt}</p> {source ? ( <span className="inline-flex shrink-0 items-center gap-1 text-xs text-[var(--yc-muted-fg)]"> <Icon d={source.kind === "url" ? P.globe : P.file} className="size-3" /> {source.label} </span> ) : null} </div> {isFailed ? ( <p className="mt-1.5 inline-flex items-center gap-1 text-xs font-medium text-[var(--yc-destructive)]"> <Icon d={P.alert} className="size-3" /> {t.failedRow} </p> ) : ( <div className="mt-2 flex items-center gap-2.5"> <div className="min-w-0 flex-1"> <div role="progressbar" aria-label={t.progress} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(width)} className="h-2 overflow-hidden rounded-full border border-[var(--yc-border)] bg-[var(--yc-muted)]" > <div className="h-full w-full origin-left rounded-full bg-[var(--yc-fg)] transition-transform duration-500 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none" style={{ transform: `scaleX(${width / 100})` } as CSSProperties} /> </div> </div> <span className="shrink-0 text-[11px] font-medium text-[var(--yc-muted-fg)] tabular-nums"> {text} · {Math.round(width)}% </span> </div> )} </div> <Icon d={P.chevronRight} className="size-4 text-[var(--yc-muted-fg)] transition-transform group-hover:translate-x-0.5 motion-reduce:transition-none" /> </a> ); } /* ───────────── JobPanel ───────────── */ function ErrorNote({ text }: { text: string | null }) { const reduce = useReducedMotion() ?? false; return ( <div role="alert" aria-live="assertive"> <AnimatePresence> {text ? ( <motion.p initial={reduce ? false : { opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0 }} transition={{ duration: 0.2 }} className="flex items-center gap-1.5 text-xs text-[var(--yc-destructive)]" > <Icon d={P.alert} className="size-3.5" /> {text} </motion.p> ) : null} </AnimatePresence> </div> ); } const btn = "inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-[0.5rem] border border-transparent bg-clip-padding px-2.5 text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-[var(--yc-ring)] focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--yc-ring)_50%,transparent)] active:translate-y-px disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4"; const btnDefault = "bg-[var(--yc-primary)] text-[var(--yc-primary-fg)] hover:bg-[color-mix(in_oklab,var(--yc-primary)_80%,transparent)]"; const btnOutline = "border-[var(--yc-border)] bg-[var(--yc-bg)] hover:bg-[var(--yc-muted)] dark:border-[var(--yc-input)] dark:bg-[color-mix(in_oklab,var(--yc-input)_30%,transparent)] dark:hover:bg-[color-mix(in_oklab,var(--yc-input)_50%,transparent)]"; const btnGhost = "text-[var(--yc-muted-fg)] hover:bg-[var(--yc-muted)] hover:text-[var(--yc-fg)] dark:hover:bg-[color-mix(in_oklab,var(--yc-muted)_50%,transparent)]"; export interface JobPanelProps { job: Job; /** Cancel; if the returned Promise rejects, the error is shown */ onCancel?: () => void | Promise<unknown>; /** Return to the input with the original prompt */ onEdit?: () => void; onRerun?: () => void | Promise<unknown>; onRemove?: () => void | Promise<unknown>; /** Content between the steps and the actions, for example the prompt or an AI rewrite */ children?: ReactNode; /** UI language: en, zh-TW, zh-CN, ja. Tags like zh-Hant-HK and ja-JP are also accepted */ locale?: string; /** Overrides built-in strings, takes precedence over locale */ labels?: JobPanelLabels; className?: string; } /** Progress page sidebar: status title, progress bar with named steps, error explanation, cancel or retry */ export function JobPanel({ job, onCancel, onEdit, onRerun, onRemove, children, locale = "en", labels, className }: JobPanelProps) { const m = jobMessages(locale); const t = { ...m.status, ...m.panel, ...labels }; const actions = useActions(t.actionFailed); const active = isActive(job); const current = stepIndex(job.status); const meta = [ ...(job.meta ?? []), active && job.etaSeconds != null ? t.eta(t.seconds(job.etaSeconds)) : null, !active && job.durationSeconds != null ? t.took(t.seconds(job.durationSeconds)) : null, ].filter(Boolean); const cancelAndEdit = async () => { if (await actions.run("cancel", onCancel)) onEdit?.(); }; return ( <div className={cn(tokens, "flex min-w-0 flex-col gap-5 text-[var(--yc-fg)]", className)}> <div> <h2 className="text-lg font-semibold" aria-live="polite"> {jobStatusLabel(job, labels, locale)} </h2> {meta.length ? <p className="mt-1 text-xs text-[var(--yc-muted-fg)] tabular-nums">{meta.join("・")}</p> : null} </div> {active ? ( <div className="flex flex-col gap-2"> <ProgressBar value={jobPercent(job)} label={t.progress} /> <ol className="flex flex-wrap items-center justify-between gap-2 text-xs"> {t.steps.map((label, i) => ( <li key={label} aria-current={i === current ? "step" : undefined} className={cn("flex items-center gap-1", i < current ? "text-[var(--yc-fg)]" : i === current ? "font-medium text-[var(--yc-fg)]" : "text-[var(--yc-muted-fg)]")} > {i < current ? <Icon d={P.check} className="size-3" /> : null} {label} </li> ))} </ol> <p className="text-xs text-[var(--yc-muted-fg)]">{t.leaveNote}</p> </div> ) : null} {job.status === "blocked" || job.status === "error" ? ( <div className={cn( "flex items-start gap-3 rounded-[0.5rem] border px-4 py-3 text-sm", job.status === "blocked" ? "border-[color-mix(in_oklab,var(--yc-warning)_30%,transparent)] bg-[color-mix(in_oklab,var(--yc-warning)_10%,transparent)]" : "border-[color-mix(in_oklab,var(--yc-destructive)_25%,transparent)] bg-[color-mix(in_oklab,var(--yc-destructive)_5%,transparent)]", )} > <Icon d={P.alert} className={cn("mt-0.5 size-4", job.status === "blocked" ? "text-[var(--yc-warning)]" : "text-[var(--yc-destructive)]")} /> <div className="min-w-0"> <p className="font-medium">{job.error}</p> {job.hint ? <p className="mt-0.5 text-[var(--yc-muted-fg)]">{job.hint}</p> : null} </div> </div> ) : null} {job.status === "done" && !job.images ? <p className="text-sm text-[var(--yc-muted-fg)]">{job.held ? t.heldNote : t.deletedNote}</p> : null} {children} <div className="flex flex-col gap-2 border-t border-[var(--yc-border)] pt-4"> <div className="flex flex-wrap gap-2"> {active ? ( <> {onEdit && onCancel ? ( <button type="button" className={cn(btn, btnOutline)} onClick={cancelAndEdit} disabled={actions.pending === "cancel"}> <Icon d={P.pencil} /> {t.cancelAndEdit} </button> ) : null} {onCancel ? ( <button type="button" className={cn(btn, btnGhost)} onClick={() => actions.run("cancel", onCancel)} disabled={actions.pending === "cancel"}> {actions.pending === "cancel" ? <Spinner /> : <Icon d={P.x} />} {t.cancel} </button> ) : null} </> ) : ( <> {onRerun && job.status !== "blocked" && job.status !== "done" ? ( <button type="button" className={cn(btn, btnDefault)} onClick={() => actions.run("rerun", onRerun)} disabled={actions.pending === "rerun"}> {actions.pending === "rerun" ? <Spinner /> : <Icon d={P.refresh} />} {t.retry} </button> ) : null} {onEdit ? ( <button type="button" className={cn(btn, btnOutline)} onClick={onEdit}> <Icon d={P.pencil} /> {t.edit} </button> ) : null} {onRemove && job.status !== "done" ? ( <button type="button" className={cn(btn, btnGhost)} onClick={() => actions.run("delete", onRemove)} disabled={actions.pending === "delete"}> {actions.pending === "delete" ? <Spinner /> : <Icon d={P.trash} />} {t.remove} </button> ) : null} </> )} </div> <ErrorNote text={actions.error} /> </div> </div> ); } /* ───────────── JobTile ───────────── */ // From the original globals.css: shimmer, shimmer-over, gen-preview const css = ` @keyframes jt-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } .jt-shimmer { background: linear-gradient(100deg, var(--yc-muted) 30%, color-mix(in oklab, var(--yc-muted), var(--yc-fg) 6%) 50%, var(--yc-muted) 70%); background-size: 200% 100%; animation: jt-shimmer 1.8s linear infinite; } .jt-shimmer-over { background: linear-gradient(100deg, transparent 30%, color-mix(in oklab, var(--yc-bg) 35%, transparent) 50%, transparent 70%); background-size: 200% 100%; animation: jt-shimmer 1.8s linear infinite; } .jt-preview { image-rendering: auto; filter: blur(6px) saturate(1.05); transform: scale(1.04); transition: filter 600ms cubic-bezier(0.23,1,0.32,1), opacity 600ms cubic-bezier(0.23,1,0.32,1); } @media (prefers-reduced-motion: reduce) { .jt-shimmer, .jt-shimmer-over { animation: none; } .jt-preview { transition: none; } } `; function Styles() { return <style href="sunui-jobs-tray-tile" precedence="default">{css}</style>; } /** While generating with no live preview yet, uses the reference image as the base and overlays a sweeping shine */ function SourceUnderlay({ src }: { src: string }) { return ( <> <img src={src} alt="" aria-hidden className="absolute inset-0 size-full scale-105 object-cover blur-[2px] brightness-75 saturate-75" /> <div aria-hidden className="jt-shimmer-over absolute inset-0" /> </> ); } const glass = "bg-[color-mix(in_oklab,var(--yc-bg)_88%,transparent)] backdrop-blur-sm"; function SourceChip({ src, label }: { src: string; label: string }) { return ( <span className={cn("pointer-events-none flex items-center gap-1 rounded-[0.4rem] p-0.5 pr-1.5 text-[11px]", glass)}> <img src={src} alt="" className="size-6 rounded-[4px] object-cover" /> <Icon d={P.image} className="size-3 text-[var(--yc-muted-fg)]" /> <span>{label}</span> </span> ); } export interface JobTileProps { job: Job; /** Click a tile to open the progress page */ onOpen?: () => void; onCancel?: () => void | Promise<unknown>; onRemove?: () => void | Promise<unknown>; /** UI language: en, zh-TW, zh-CN, ja. Tags like zh-Hant-HK and ja-JP are also accepted */ locale?: string; /** Overrides built-in strings, takes precedence over locale */ labels?: JobTileLabels; className?: string; } /** A tile in the grid: one generation that is running, failed or awaiting review; click to open the progress page */ export function JobTile({ job, onOpen, onCancel, onRemove, locale = "en", labels, className }: JobTileProps) { const m = jobMessages(locale); const t = { ...m.status, ...m.tile, ...labels }; const actions = useActions(t.actionFailed); const active = isActive(job); if (active) { const showPreview = !!job.previewSrc && (job.status === "sampling" || job.status === "decoding"); return ( <div className={cn(tokens, "group relative overflow-hidden rounded-[0.5rem] bg-[var(--yc-muted)] text-[var(--yc-fg)]", !showPreview && !job.sourceSrc && "jt-shimmer", className)} style={{ aspectRatio: job.aspect ?? "2 / 3" }} aria-busy > <Styles /> {job.sourceSrc && !showPreview ? <SourceUnderlay src={job.sourceSrc} /> : null} {showPreview ? <img src={job.previewSrc} alt={t.previewAlt} className="jt-preview absolute inset-0 size-full object-cover" /> : null} <button type="button" onClick={onOpen} aria-label={t.openAria(job.prompt)} className="absolute inset-0 z-[1] outline-none focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--yc-ring)_50%,transparent)] focus-visible:ring-inset" /> <div className="pointer-events-none absolute top-2 left-2 z-[2] flex items-center gap-1"> {job.sourceSrc ? <SourceChip src={job.sourceSrc} label={t.reference} /> : null} {(job.count ?? 1) > 1 ? <span className={cn("rounded-[0.4rem] px-1.5 py-0.5 text-[11px] whitespace-nowrap tabular-nums", glass)}>{t.count(job.count ?? 1)}</span> : null} </div> {onCancel ? ( <button type="button" onClick={() => actions.run("cancel", onCancel)} disabled={actions.pending === "cancel"} aria-label={t.cancelAria} title={t.cancel} className={cn("absolute top-2 right-2 z-[2] flex size-7 items-center justify-center rounded-full text-[var(--yc-muted-fg)] hover:text-[var(--yc-fg)]", glass, ringFocus)} > {actions.pending === "cancel" ? <Spinner className="size-3.5" /> : <Icon d={P.x} className="size-3.5" />} </button> ) : null} <div className="pointer-events-none absolute inset-x-0 bottom-0 z-[2] flex flex-col gap-1.5 bg-gradient-to-t from-[color-mix(in_oklab,var(--yc-bg)_95%,transparent)] via-[color-mix(in_oklab,var(--yc-bg)_75%,transparent)] to-transparent px-2.5 pt-8 pb-2.5"> <p className="truncate text-xs font-medium" aria-live="polite"> {jobStatusLabel(job, t)} </p> <ProgressBar value={jobPercent(job)} label={t.progress} /> {job.etaSeconds != null ? <p className="text-[11px] text-[var(--yc-muted-fg)] tabular-nums">{t.eta(t.seconds(job.etaSeconds))}</p> : null} {actions.error ? ( <p className="text-[11px] text-[var(--yc-destructive)]" role="alert"> {actions.error} </p> ) : null} </div> </div> ); } const held = job.status === "done"; const tone = job.status === "error" ? "text-[var(--yc-destructive)]" : job.status === "blocked" ? "text-[var(--yc-warning)]" : "text-[var(--yc-muted-fg)]"; const glyph = held ? P.eyeOff : job.status === "canceled" ? P.x : P.alert; return ( <div className={cn( tokens, "group relative flex aspect-square flex-col overflow-hidden rounded-[0.5rem] border border-dashed border-[var(--yc-border)] bg-[color-mix(in_oklab,var(--yc-muted)_30%,transparent)] p-3 text-[var(--yc-fg)]", className, )} > <button type="button" onClick={onOpen} aria-label={t.detailAria(job.prompt)} className="absolute inset-0 z-[1] rounded-[0.5rem] outline-none focus-visible:ring-3 focus-visible:ring-[color-mix(in_oklab,var(--yc-ring)_50%,transparent)] focus-visible:ring-inset" /> <div className="flex items-center gap-1.5 pr-7 text-xs font-medium"> <Icon d={glyph} className={cn("size-3.5", tone)} /> <span className="truncate">{jobStatusLabel(job, t)}</span> </div> <p className="mt-2 line-clamp-3 text-xs text-[var(--yc-muted-fg)]">{held ? t.heldNote : job.status === "canceled" ? "" : job.error}</p> <div className="mt-auto flex items-end gap-2"> {job.sourceSrc ? <img src={job.sourceSrc} alt={t.reference} className="size-9 shrink-0 rounded-[0.4rem] border border-[var(--yc-border)] object-cover" /> : null} <p className="line-clamp-2 min-w-0 text-[11px] text-[color-mix(in_oklab,var(--yc-muted-fg)_80%,transparent)]">{job.prompt}</p> </div> {!held && onRemove ? ( <button type="button" onClick={() => actions.run("delete", onRemove)} disabled={actions.pending === "delete"} aria-label={t.removeAria} title={t.remove} className={cn("absolute top-2 right-2 z-[2] flex size-7 items-center justify-center rounded-full text-[var(--yc-muted-fg)] hover:bg-[var(--yc-muted)] hover:text-[var(--yc-fg)]", ringFocus)} > {actions.pending === "delete" ? <Spinner className="size-3.5" /> : <Icon d={P.x} className="size-3.5" />} </button> ) : null} </div> ); }
似ているブロック
- Pro





