import { useLayoutEffect, useRef, useState } from 'react' import { ArrowLeft, ChevronRight, Redo2, Undo2, X } from 'lucide-react' import { AlertDialog, Popover } from 'radix-ui' import { api } from '@/api' import { Button } from '@/components/ui/button' import { Switch } from '@/components/ui/controls' import { useClosing } from '@/lib/closing' import { hideLayer, inLayer } from '@/lib/layer' import { cn } from '@/lib/utils' import { useStore } from '@/store' import type { DetailStep, Job, Picture } from '@/types' type Station = 'compose' | 'pick' | 'fix' | 'letter' | 'compare' /** The stations a picture goes through, in their usual order, and the one beside the path. */ const PATH: { id: Station; label: string; hint: string }[] = [ { id: 'compose', label: 'Compose', hint: 'What to make: the request put together from cards' }, { id: 'pick', label: 'Pick', hint: 'Make a sheet and keep the best' }, { id: 'fix', label: 'Fix', hint: 'Anatomy, the text in the picture, any spot' }, { id: 'letter', label: 'Letter', hint: 'Bubbles, captions, sound effects' }, ] const BESIDE = { id: 'compare' as Station, label: 'Compare', hint: 'A sheet with named axes: one seed, one thing changed at a time' } /** The height of the tray with something in work, and with nothing. What is sized by the room * on the page (the whole sheet of Compare) counts with the full one, whatever the tray is at * the moment, so that picking the first picture moves nothing. */ export const TRAY_FULL = 60 export const TRAY_EMPTY = 28 /** The tray under the tools of Fix and Letter, where the picture needs the height more. */ const TRAY_TOOL = 44 export const active = (jobs: Job[]) => jobs.filter((job) => job.state === 'waiting' || job.state === 'running') const JOB_WORDS: Record = { sheet: 'Picture', like: 'Picture', finish: 'Finishing', repaint: 'Repainting', matrix: 'Picture', } /** How far a job has got, in a few words: "Picture 5 of 8". */ export function jobLine(job: Job) { if (job.state === 'waiting') return 'Waiting' return `${JOB_WORDS[job.kind] ?? 'Picture'} ${Math.min(job.done + 1, job.total)} of ${job.total}` } /** The disabled look of a main button: never a dimmed orange one. */ export const DISABLED = 'disabled:bg-secondary disabled:text-muted-foreground disabled:opacity-100' /** The share of the jobs' work that is done, as a thin line along an edge. */ export function ProgressLine({ className }: { className?: string }) { const job = useStore((state) => active(state.jobs)[0]) if (!job) return null const share = Math.round(job.progress * 100) return (
) } /** Close the tab NyxxWorks is in. A tab the script did not open cannot be closed by it: then * the host's own page is opened in it instead, when the host has one. */ async function leave() { // In the layer the tab is the host's: it is never closed, and nothing is loaded into it. if (inLayer) return hideLayer() window.close() await new Promise((done) => window.setTimeout(done, 250)) if (window.closed) return try { // The host's page is the root of the address NyxxWorks is served from. A host started // without a page of its own (the A1111 family with --nowebui) has nothing there. const answer = await fetch('/', { method: 'HEAD' }) if (answer.ok) { window.location.href = '/' return } } catch { // No answer at all: said below. } useStore.setState({ error: '', notice: 'This host has no page of its own to go back to. Close the tab to leave NyxxWorks.' }) } /** Leave NyxxWorks. As a page of its own it asks first while a job runs, and while a tool holds * work that was not kept. As a layer over the host page it only hides: that loses nothing. */ function LeaveButton() { const host = useStore((state) => state.options?.host ?? '') const [asking, setAsking] = useState<{ title: string; body: string; go: string } | null>(null) const press = () => { if (inLayer) return hideLayer() const { jobs, unkept } = useStore.getState() const job = active(jobs)[0] if (job) { const doing = job.state === 'waiting' ? 'A job is waiting its turn.' : `${jobLine(job)} is being ${job.kind === 'finish' ? 'finished' : job.kind === 'repaint' ? 'repainted' : 'made'}.`.replace( /^(Finishing|Repainting)/, 'Picture', ) setAsking({ title: 'A job is still running', body: `${doing} It goes on without this page: the host makes the pictures and keeps them, and they are here when NyxxWorks is opened again.`, go: 'Leave', }) } else if (unkept) { setAsking({ title: unkept, body: 'Leaving now drops them. Keep puts the result into In work.', go: 'Leave without keeping' }) } else void leave() } return ( <> !open && setAsking(null)}> {asking?.title} {asking?.body}
{/* Stay has the focus when the question opens, so Enter and Esc both stay. */}
) } const ICON = 'flex size-[30px] shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 disabled:pointer-events-none disabled:opacity-40' const TAB = 'relative flex h-11 shrink-0 items-center px-2.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60' /** The station on the page: its name in full weight, and a line under it. No accent color. */ const HERE = "font-semibold text-foreground after:absolute after:inset-x-2 after:bottom-0 after:h-0.5 after:bg-foreground after:content-['']" /** The one bar above the work area: the way out, the stations, what is kept of the way of working. */ export function TopBar() { const options = useStore((state) => state.options) const station = useStore((state) => state.station) const picked = useStore((state) => state.tray.length) const fixTool = useStore((state) => state.fixTool) const bar = useStore((state) => state.toolBar) const { goTo, setFixTool } = useStore.getState() const inTool = station === 'fix' || station === 'letter' const tab = (entry: { id: Station; label: string; hint: string }) => { // Fix and Letter work on a picked picture: with none picked there is nothing to open. const open = (entry.id !== 'fix' && entry.id !== 'letter') || picked > 0 return ( ) } const side = (id: 'recipes' | 'stats', label: string, hint: string) => ( ) const tools: { id: 'anatomy' | 'text' | 'repaint'; label: string; hint: string }[] = [ { id: 'anatomy', label: 'Anatomy', hint: 'Fingers, limbs, eyes, teeth: mark the spot and pick the tool' }, { id: 'text', label: 'Text', hint: 'Replace the gibberish text on clothes, signs and equipment' }, { id: 'repaint', label: 'Repaint', hint: 'Any spot: paint over it and say what should be there' }, ] return (
{options && } NyxxWorks {options && ( )} {options && ( {side('recipes', 'Recipes', 'The way of working kept as files: use again, hand to others')} {side('stats', 'Statistics', 'Which cards and settings get picked, and which never do')} {inTool ? ( bar && ( // What every tool has, in the same place: the seed, undo and redo, Keep, and Close last. {bar.seed && seed {bar.seed}} {bar.undo && ( )} {bar.redo && ( )} ) ) : ( {options.model || 'no model loaded'} )} )}
) } /** An error or a notice, floating over the bottom of the work area: it moves nothing. */ export function Message() { const error = useStore((state) => state.error) const notice = useStore((state) => state.notice) const failed = useStore((state) => { const last = state.jobs[state.jobs.length - 1] return last?.state === 'failed' ? last : undefined }) const dismiss = useStore((state) => state.dismiss) const undo = useStore((state) => state.noticeUndo) const [closed, setClosed] = useState('') // the failed job whose message was closed const wrong = error || (failed && failed.id !== closed ? `The last job failed. ${failed.error}` : '') if (!wrong && !notice) return null const close = () => { if (failed) setClosed(failed.id) dismiss() } // The first sentence of an error says what went wrong; the rest explains. const cut = wrong.search(/[.!?](\s|$)/) const first = cut < 0 ? wrong : wrong.slice(0, cut + 1) return (

{wrong ? ( <> {first} {wrong.slice(first.length)} ) : ( notice )}

{!wrong && undo && undo.notice === notice && ( )}
) } const FIELD = 'w-full rounded-md border border-input bg-background px-2 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring/60' /** The size a picture is enlarged to: as the hosts work it out, to whole eights. */ const enlarged = (side: number, scale: number) => Math.max(64, Math.round((side * scale) / 8) * 8) /** How the picked pictures are finished, as one sentence that opens the settings, and the button that does it. */ function Finishing({ waiting }: { waiting: number }) { const upscalers = useStore((state) => state.options?.upscalers ?? []) const detail = useStore((state) => state.options?.detail ?? []) const base = useStore((state) => state.options?.finishBase) const finish = useStore((state) => state.finish) // Two plain values: a selector that makes an object anew each time would never settle. const width = useStore((state) => state.request?.width ?? 0) const height = useStore((state) => state.request?.height ?? 0) const { setFinish, finishPicked } = useStore.getState() const [open, setOpen] = useState(false) const inside = useRef(null) useClosing(open, () => setOpen(false), inside) if (!finish) return null /** A step as it is set now: what was set by hand, else what the host starts it with. */ const stepOf = (name: string): DetailStep => { const start = detail.find((step) => step.name === name) const mine = finish.steps?.[name] ?? {} return { on: mine.on ?? true, confidence: mine.confidence ?? start?.confidence ?? 0.5, strength: mine.strength ?? start?.strength ?? 0.3 } } const setStep = (name: string, change: Partial) => setFinish({ steps: { ...finish.steps, [name]: { ...stepOf(name), ...change } } }) const number = (key: 'scale' | 'denoise', label: string, hint: string, min: number, max: number, step: number) => ( ) const on = detail.filter((step) => stepOf(step.name).on).map((step) => step.name) const sentence = [ `${finish.upscaler || 'the host’s own'} × ${finish.scale}`, `strength ${finish.denoise}`, detail.length ? (finish.detail && on.length ? `details: ${on.join(', ')}` : 'details off') : '', ] .filter(Boolean) .join(' · ') return (
{open && (

Finishing

Applies by itself. Used for every picture you finish.
{upscalers.length > 0 && ( )}
{number('scale', 'How much larger', 'How many times larger the picture gets', 1, 4, 0.25)} {number('denoise', 'Strength', 'How strongly the model goes over the enlarged picture', 0.05, 1, 0.05)}
{width > 0 && height > 0 && (

{width} × {height} becomes {enlarged(width, finish.scale)} × {enlarged(height, finish.scale)}.

)} {detail.length > 0 && ( <>
setFinish({ detail: checked })} />
Step How sure Strength {detail.map((step) => { const now = stepOf(step.name) const field = (key: 'confidence' | 'strength') => ( { const parsed = Number(event.target.value) if (event.target.value !== '' && !Number.isNaN(parsed)) { setStep(step.name, { [key]: Math.min(step.limits[key][1], Math.max(step.limits[key][0], parsed)) }) } }} /> ) return [ , {field('confidence')}, {field('strength')}, ] })}
Done in this order, after enlarging. )} {/* What was not set by hand follows the host's own settings (its hires fix and ADetailer tabs). */}
{Object.keys(base?.pass ?? {}).length > 0 ? 'What is not changed here is taken from the host’s own settings.' : ''}
)}
) } /** What was done to a picture in work last, in the order of the path. */ const STATES = ['draft', 'finished', 'fixed', 'lettered'] as const type TrayState = (typeof STATES)[number] const stateOf = (picture: Picture): TrayState => (picture.final ? picture.last || 'finished' : 'draft') /** A picture in work: a small button that opens it large, as before. What else can be done * with it stands in a small panel above it, which opens when the pointer rests on it or the * keyboard reaches it, so the picture itself is never covered. */ function TrayItem({ picture, small, open, setOpen }: { picture: Picture; small: boolean; open: boolean; setOpen: (id: string | null) => void }) { const { mark, view, openFix, openLetter } = useStore.getState() const inFix = useStore((state) => (state.station === 'fix' || state.station === 'letter') && state.fixing === picture.id) const timer = useRef(null) const shown = picture.final || picture.id const state = stateOf(picture) const seed = String(picture.params.seed ?? '') /** Open or close a moment later: moving from the picture into the panel must not close it. */ const soon = (next: boolean) => { if (timer.current !== null) window.clearTimeout(timer.current) timer.current = window.setTimeout(() => setOpen(next ? picture.id : null), 150) } const now = (next: boolean) => { if (timer.current !== null) window.clearTimeout(timer.current) setOpen(next ? picture.id : null) } const act = (what: () => void) => () => { now(false) what() } return ( !next && now(false)}> {/* Right after the picture in the page, so that Tab goes from the picture into it. */} event.preventDefault()} onCloseAutoFocus={(event) => event.preventDefault()} // The keyboard stands on the picture while the panel is open: that is not a reason to close it. onFocusOutside={(event) => event.preventDefault()} onPointerEnter={() => soon(true)} onPointerLeave={() => soon(false)} onBlur={(event) => { const next = event.relatedTarget as HTMLElement | null if (!next || (!event.currentTarget.contains(next) && !next.closest('[data-tray-panel]'))) now(false) }} className="z-40 flex flex-col gap-2 rounded-lg border bg-card p-2.5 shadow-lg outline-none" >

seed {seed} · {state}

) } const PANEL_BUTTON = 'h-7 shrink-0 rounded-md border border-input px-2.5 text-xs outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60' /** The pictures taken into work: always in view, whatever the station. With nothing in work * it is one line. They stand in groups by what was done to them last, in the order of the * path. How pictures are finished is not shown inside the tools of Fix and Letter, and the * tray is lower there. */ export function Tray() { const tray = useStore((state) => state.tray) const inTool = useStore((state) => state.station === 'fix' || state.station === 'letter') const [open, setOpen] = useState(null) const [cut, setCut] = useState({ left: false, right: false }) const row = useRef(null) const waiting = tray.filter((picture) => !picture.final).length // Where the groups are cut by the edge of their room, the edge fades: there is more that way. const measure = () => { const element = row.current if (!element) return const next = { left: element.scrollLeft > 1, right: element.scrollLeft + element.clientWidth < element.scrollWidth - 1 } setCut((was) => (was.left === next.left && was.right === next.right ? was : next)) } useLayoutEffect(() => { measure() const element = row.current if (!element) return const watch = new ResizeObserver(measure) watch.observe(element) return () => watch.disconnect() }) const groups = STATES.map((state) => ({ state, pictures: tray.filter((picture) => stateOf(picture) === state) })).filter((group) => group.pictures.length) return ( ) }