File size: 34,269 Bytes
e94c49d | 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | 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<Job['kind'], string> = {
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 (
<div role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={share} className={cn('pointer-events-none absolute inset-x-0 h-0.5', className)}>
<div className="h-full bg-primary transition-[width] duration-300" style={{ width: `${share}%` }} />
</div>
)
}
/** 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 (
<>
<button
type="button"
aria-label={`Leave NyxxWorks, back to the ${host || 'host'} page`}
title={inLayer ? 'Hide NyxxWorks' : 'Leave NyxxWorks'}
data-keeps-panels={inLayer || undefined}
onClick={press}
className="flex h-7 shrink-0 items-center gap-1 rounded-md border border-input px-2 text-xs text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
>
<ArrowLeft className="size-3.5" aria-hidden />
{host}
</button>
<AlertDialog.Root open={asking !== null} onOpenChange={(open) => !open && setAsking(null)}>
<AlertDialog.Portal>
<AlertDialog.Overlay className="fixed inset-0 z-50 bg-background/70" />
<AlertDialog.Content className="fixed left-1/2 top-1/2 z-50 w-[420px] max-w-[calc(100vw-32px)] -translate-x-1/2 -translate-y-1/2 rounded-lg border bg-card p-4 shadow-lg outline-none">
<AlertDialog.Title className="text-sm font-semibold">{asking?.title}</AlertDialog.Title>
<AlertDialog.Description className="mt-2 text-[13px] leading-snug text-muted-foreground">{asking?.body}</AlertDialog.Description>
<div className="mt-4 flex justify-end gap-2">
<AlertDialog.Action asChild>
<Button variant="outline" onClick={() => void leave()}>
{asking?.go}
</Button>
</AlertDialog.Action>
{/* Stay has the focus when the question opens, so Enter and Esc both stay. */}
<AlertDialog.Cancel asChild>
<Button variant="secondary" autoFocus>
Stay
</Button>
</AlertDialog.Cancel>
</div>
</AlertDialog.Content>
</AlertDialog.Portal>
</AlertDialog.Root>
</>
)
}
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 (
<button
key={entry.id}
type="button"
disabled={!open}
aria-current={entry.id === station ? 'page' : undefined}
title={open ? entry.hint : `${entry.hint}. Pick a picture first.`}
onClick={() => goTo(entry.id)}
className={cn(TAB, entry.id === station ? HERE : 'text-muted-foreground', open && entry.id !== station && 'hover:text-foreground', !open && 'cursor-not-allowed opacity-45')}
>
{entry.label}
</button>
)
}
const side = (id: 'recipes' | 'stats', label: string, hint: string) => (
<button
type="button"
aria-current={station === id ? 'page' : undefined}
title={hint}
onClick={() => goTo(station === id ? 'pick' : id)}
className={cn(TAB, 'text-[13px]', station === id ? HERE : 'text-muted-foreground hover:text-foreground')}
>
{label}
</button>
)
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 (
<header className="flex h-11 shrink-0 items-center border-b bg-card px-3">
{options && <LeaveButton />}
<span className="ml-3 mr-2 shrink-0 text-sm font-semibold tracking-tight">NyxxWorks</span>
{options && (
<nav aria-label="Stations" className="flex shrink-0 items-center">
{PATH.map((entry, index) => [
index > 0 && <ChevronRight key={`${entry.id}-then`} aria-hidden className="size-3.5 shrink-0 text-input" />,
tab(entry),
// The tools of Fix stand right after it, as a part of it.
entry.id === 'fix' && station === 'fix' && (
<div
key="tools"
role="group"
aria-label="Tool of the Fix station"
className="mx-1 flex h-7 shrink-0 overflow-hidden rounded-[6px] border border-input text-xs"
>
{tools.map((tool) => (
<button
key={tool.id}
type="button"
aria-pressed={fixTool === tool.id}
title={tool.hint}
onClick={() => setFixTool(tool.id)}
className={cn(
'px-2.5 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60',
fixTool === tool.id ? 'bg-secondary font-semibold text-foreground' : 'text-muted-foreground hover:text-foreground',
)}
>
{tool.label}
</button>
))}
</div>
),
])}
<span aria-hidden className="mx-2 h-5 w-px shrink-0 bg-border" />
{tab(BESIDE)}
</nav>
)}
{options && (
<span className="ml-auto flex min-w-0 items-center pl-3">
{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.
<span className="ml-2 flex min-w-0 items-center gap-1.5">
{bar.seed && <span className="min-w-0 truncate text-xs tabular-nums text-muted-foreground">seed {bar.seed}</span>}
{bar.undo && (
<button type="button" aria-label="Undo" title={bar.undoHint ?? 'Undo (Ctrl+Z)'} disabled={!bar.canUndo} onClick={bar.undo} className={ICON}>
<Undo2 className="size-4" aria-hidden />
</button>
)}
{bar.redo && (
<button type="button" aria-label="Redo" title={bar.redoHint ?? 'Redo'} disabled={!bar.canRedo} onClick={bar.redo} className={ICON}>
<Redo2 className="size-4" aria-hidden />
</button>
)}
<Button className={cn('h-[30px] shrink-0', DISABLED)} disabled={!bar.canKeep} onClick={bar.keep} title={bar.keepHint ?? 'Keep the result: it takes the place of this picture in the tray'}>
Keep
</Button>
<Button variant="outline" className="h-[30px] shrink-0" onClick={bar.close} title="Back to Pick (Esc)">
Close
</Button>
</span>
)
) : (
<span className="ml-2 min-w-0 truncate text-xs text-muted-foreground" title="The checkpoint the host has loaded">
{options.model || 'no model loaded'}
</span>
)}
</span>
)}
</header>
)
}
/** 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 (
<div
role={wrong ? 'alert' : 'status'}
className={cn(
'absolute bottom-2 left-1/2 z-30 flex max-w-[min(720px,calc(100%-32px))] -translate-x-1/2 items-start gap-3 rounded-md border bg-card py-2 pl-3 pr-2 text-[13px] leading-snug shadow-lg',
wrong ? 'border-destructive' : 'border-input',
)}
>
<p className="min-w-0">
{wrong ? (
<>
<span className="font-semibold text-destructive">{first}</span>
{wrong.slice(first.length)}
</>
) : (
notice
)}
</p>
{!wrong && undo && undo.notice === notice && (
<button
type="button"
onClick={undo.run}
className="-my-0.5 h-6 shrink-0 rounded border border-input px-2 text-xs outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60"
>
Undo
</button>
)}
<button
type="button"
aria-label="Close the message"
onClick={close}
className="flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
>
<X className="size-3.5" aria-hidden />
</button>
</div>
)
}
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<HTMLDivElement>(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<DetailStep>) => setFinish({ steps: { ...finish.steps, [name]: { ...stepOf(name), ...change } } })
const number = (key: 'scale' | 'denoise', label: string, hint: string, min: number, max: number, step: number) => (
<label className="flex min-w-0 flex-1 flex-col gap-1 text-xs text-muted-foreground" title={hint}>
{label}
<input
type="number"
className={cn(FIELD, 'h-8 tabular-nums text-foreground')}
min={min}
max={max}
step={step}
value={finish[key]}
onChange={(event) => {
const parsed = Number(event.target.value)
if (event.target.value !== '' && !Number.isNaN(parsed)) setFinish({ [key]: Math.min(max, Math.max(min, parsed)) })
}}
/>
</label>
)
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 (
<div ref={inside} className="flex min-w-0 shrink items-center gap-2">
<button
type="button"
aria-expanded={open}
aria-label={`How pictures are finished: ${sentence}`}
title="How the picked pictures are finished. Press to change it."
onClick={() => setOpen(!open)}
className={cn(
'h-8 min-w-0 truncate rounded-md border border-input px-2.5 text-xs text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60',
open && 'bg-accent text-foreground',
)}
>
{sentence}
</button>
<Button
className={cn('shrink-0', DISABLED)}
disabled={!waiting}
onClick={() => void finishPicked()}
title="Enlarge the picked pictures and go over them with the model"
>
Finish {waiting || ''}
</Button>
{open && (
<div
role="dialog"
aria-label="Finishing"
className="scroll-thin absolute bottom-full right-4 z-30 mb-[9px] flex max-h-[calc(100vh-100px)] w-[400px] max-w-[calc(100vw-32px)] flex-col gap-3 overflow-y-auto rounded-lg border bg-card p-4 shadow-lg"
>
<div className="flex items-baseline justify-between gap-3">
<h2 className="text-sm font-semibold">Finishing</h2>
<span className="text-right text-xs text-muted-foreground">Applies by itself. Used for every picture you finish.</span>
</div>
{upscalers.length > 0 && (
<label className="flex flex-col gap-1 text-xs text-muted-foreground" title="What enlarges the picture before the model goes over it">
Enlarge with
<select className={cn(FIELD, 'h-8 text-foreground')} value={finish.upscaler} onChange={(event) => setFinish({ upscaler: event.target.value })}>
{upscalers.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
</label>
)}
<div className="flex gap-3">
{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)}
</div>
{width > 0 && height > 0 && (
<p className="text-xs tabular-nums text-muted-foreground">
{width} × {height} becomes {enlarged(width, finish.scale)} × {enlarged(height, finish.scale)}.
</p>
)}
{detail.length > 0 && (
<>
<hr className="border-border" />
<div className="flex items-center justify-between gap-3">
<label htmlFor="finish-details" className="min-w-0 text-[13px]">
<span className="font-medium">Details</span>
<span className="ml-2 text-xs text-muted-foreground">repair parts, face and hands after enlarging</span>
</label>
<Switch id="finish-details" checked={finish.detail} onCheckedChange={(checked) => setFinish({ detail: checked })} />
</div>
<div className="grid grid-cols-[1fr_5rem_5rem] items-center gap-x-2 gap-y-1.5 text-[13px]">
<span className="text-xs text-muted-foreground">Step</span>
<span className="text-xs text-muted-foreground" title="How sure the detector must be that it has found the thing, 0 to 1">
How sure
</span>
<span className="text-xs text-muted-foreground" title="How strongly a found place is repainted, 0 to 1">
Strength
</span>
{detail.map((step) => {
const now = stepOf(step.name)
const field = (key: 'confidence' | 'strength') => (
<input
type="number"
aria-label={`${step.name}: ${key === 'confidence' ? 'how sure' : 'strength'}`}
className={cn(FIELD, 'h-[30px] tabular-nums disabled:opacity-50')}
min={step.limits[key][0]}
max={step.limits[key][1]}
step={0.05}
disabled={!now.on || !finish.detail}
value={now[key]}
onChange={(event) => {
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 [
<label key={`${step.name}-on`} className="flex min-w-0 items-center gap-2" title={step.model}>
<input type="checkbox" checked={now.on} disabled={!finish.detail} onChange={(event) => setStep(step.name, { on: event.target.checked })} />
<span className="truncate">{step.name}</span>
</label>,
<span key={`${step.name}-confidence`}>{field('confidence')}</span>,
<span key={`${step.name}-strength`}>{field('strength')}</span>,
]
})}
</div>
<span className="text-xs text-muted-foreground">Done in this order, after enlarging.</span>
</>
)}
{/* What was not set by hand follows the host's own settings (its hires fix and ADetailer tabs). */}
<div className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">
{Object.keys(base?.pass ?? {}).length > 0 ? 'What is not changed here is taken from the host’s own settings.' : ''}
</span>
<Button
variant="outline"
size="sm"
disabled={!(finish.own?.length || Object.keys(finish.steps ?? {}).length)}
onClick={() => setFinish({ upscaler: base?.upscaler ?? finish.upscaler, scale: base?.scale ?? finish.scale, denoise: base?.denoise ?? finish.denoise, steps: {}, own: [] })}
>
As at first
</Button>
</div>
</div>
)}
</div>
)
}
/** 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<number | null>(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 (
<Popover.Root open={open} onOpenChange={(next) => !next && now(false)}>
<Popover.Anchor asChild>
<button
type="button"
aria-label={`Seed ${seed}, ${state}`}
aria-haspopup="dialog"
aria-expanded={open}
// A finished picture opens beside the draft it came from.
onClick={() => view({ ids: [shown], index: 0, beside: picture.final ? picture.id : null })}
onPointerEnter={() => soon(true)}
onPointerLeave={() => soon(false)}
onFocus={(event) => event.currentTarget.matches(':focus-visible') && now(true)}
onBlur={(event) => {
// Tab into the panel keeps it open; anywhere else closes it.
if (!(event.relatedTarget as HTMLElement | null)?.closest('[data-tray-panel]')) now(false)
}}
className={cn(
'block shrink-0 overflow-hidden rounded outline-none focus-visible:ring-2 focus-visible:ring-foreground',
small ? 'h-9 w-7' : 'h-[46px] w-9',
// The picture the tool on the page is open for.
inFix && 'ring-2 ring-foreground',
)}
>
<img src={api.imageUrl(shown, 'thumb')} alt="" className="h-full w-full object-cover" />
</button>
</Popover.Anchor>
{/* Right after the picture in the page, so that Tab goes from the picture into it. */}
<Popover.Content
data-tray-panel
side="top"
sideOffset={8}
align="center"
collisionPadding={8}
onOpenAutoFocus={(event) => 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"
>
<p className="text-xs tabular-nums text-muted-foreground">
seed {seed} · {state}
</p>
<div className="flex gap-1.5">
<button type="button" onClick={act(() => openFix(picture.id))} title="Send to Fix" className={PANEL_BUTTON}>
Fix
</button>
<button type="button" onClick={act(() => openLetter(picture.id))} title="Send to Letter" className={PANEL_BUTTON}>
Letter
</button>
<button type="button" onClick={act(() => void mark(picture.id, { picked: false }))} className={PANEL_BUTTON}>
Take out of work
</button>
</div>
</Popover.Content>
</Popover.Root>
)
}
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<string | null>(null)
const [cut, setCut] = useState({ left: false, right: false })
const row = useRef<HTMLDivElement>(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 (
<footer
className="relative flex shrink-0 items-center gap-3 border-t bg-card px-4"
style={{ height: tray.length ? (inTool ? TRAY_TOOL : TRAY_FULL) : TRAY_EMPTY }}
>
<span className="shrink-0 text-xs text-muted-foreground">
In work
<span className="ml-1 tabular-nums text-foreground">{tray.length}</span>
</span>
{tray.length === 0 ? (
<span className="truncate text-xs text-muted-foreground">Pick pictures on a sheet: they stay here, also after a restart.</span>
) : (
<>
<div className="relative min-w-[120px] flex-1 self-stretch">
<div
ref={row}
onScroll={measure}
// The wheel moves the groups sideways: the tray has no room for a scrollbar. A
// panel that is open closes, since its picture moves away from under the pointer.
// (Not on every scroll: the keyboard reaching a picture scrolls it into view.)
onWheel={(event) => {
if (!row.current || !event.deltaY) return
row.current.scrollLeft += event.deltaY
setOpen(null)
}}
className={cn('flex h-full items-center overflow-x-auto px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden', inTool ? 'gap-2.5' : 'gap-3.5')}
>
{groups.map((group, index) => [
index > 0 && <span key={`${group.state}-line`} aria-hidden className={cn('w-px shrink-0 bg-border', inTool ? 'h-[22px]' : 'h-7')} />,
<div key={group.state} role="group" aria-label={group.state} className={cn('flex shrink-0 items-center', inTool ? 'gap-2.5' : 'gap-3.5')}>
<span className="shrink-0 text-xs text-muted-foreground">{group.state}</span>
<div className="flex shrink-0 gap-1.5">
{group.pictures.map((picture) => (
<TrayItem key={picture.id} picture={picture} small={inTool} open={open === picture.id} setOpen={setOpen} />
))}
</div>
</div>,
])}
</div>
{cut.left && <span aria-hidden className="pointer-events-none absolute inset-y-0 left-0 w-6 bg-gradient-to-r from-card to-transparent" />}
{cut.right && <span aria-hidden className="pointer-events-none absolute inset-y-0 right-0 w-6 bg-gradient-to-l from-card to-transparent" />}
</div>
{!inTool && <Finishing waiting={waiting} />}
</>
)}
</footer>
)
}
|