* feat(review): add review queue schema with restore validation
Add the Needs review schema group (media_review_metadata,
media_review_items, media_review_decisions) beside the image annotation
group it cites. review_schema_error validates the catalog, columns,
foreign keys, row values and canonical 8 MiB evidence read-only;
migrate_review_state installs it in a SAVEPOINT after the annotation
group, and verify_database_file requires it under require_library_state.
A review group without a valid annotation group is refused. Decisions
null their pair and image navigation through indexes when those are
deleted. Old backups and annotation-era backups restore and gain the
group; browser fixtures clear the new tables on reset.
* feat(review): persist ambiguous sampler evidence from scans and new outputs
The output scan and the live monitor now queue every file the ingestion
resolver finds ambiguous for Needs review. The file is captured, its metadata
is read again from the capture and resolved with the default profile, and only
an ambiguous result is stored, bound to the capture's annotation byte record
and fenced by its storage epoch. Evidence holds one hashed projection per
selectable candidate; none, more than 16 or over 8 MiB is a limited item.
Recording is idempotent per bytes and evidence and never touches a decision.
Scan statuses, counters, outcome rows and legacy SSE events are unchanged; the
job scope gains review_items/review_errors and the log a Needs review line.
The monitor records after its fallback link, best effort.
* feat(review): explicit association decisions with compatible linking
Needs review gains its queue reads and decisions:
- GET /prompt_manager/review/items lists pending items oldest first with
the exact pending total and an HMAC keyset cursor bound to the storage
epoch and the review index revision.
- GET /prompt_manager/review/items/{id} adds the candidates (role texts,
label, selectability), the dependency fingerprint and the digest.
- POST /prompt_manager/review/items/{id}/decision applies a candidate only
for a capture of the item's bytes that the current file still hashes to
and whose evidence is unchanged, through the ingester's compatible-only
rules in the same transaction as the decision row; a conflict writes
nothing. Leave unresolved records the decision and links nothing.
ingest_resolved_pair keeps its contract; its body moves into
_ingest_resolved_pair_in, which runs in the caller's transaction.
Items keep the file's recorded spelling so targets keep their case on
Windows, and a rescan skips the copy and hash of a file whose size and
mtime match the bytes an item already cites.
* fix(review): build the spelling validation test from native paths
On Windows the locator is case-folded and uses backslashes, so the fixed
POSIX pair /out/a.png no longer folded to itself and the new spelling
check refused the good case. The test now spells a mixed-case native path
and folds it with os.path.normcase, and also refuses a locator of another
file.
* fix(review): Apply sees the file under every spelling and rechecks only its choice
Apply now finds the legacy rows of the same physical file however its root
is reached. The roots are real paths while the monitor links under the
directory it watches, so a symlinked or junctioned root, subst or a mapped
drive used to hide the monitor's row and Apply added a second, differently
linked row. Same-name rows are resolved to their physical identity
(normcase(realpath), else samefile); the dependency fingerprint covers all
of them, two rows refuse the choice, one row is enriched under the
ingester's compatible-only rules, and a same-name row the request did not
classify is a changed association.
Apply re-verifies only what the decision depends on: the bytes are still
ambiguous and still offer the chosen candidate. A resolver change that
rewords the reason or reorders candidates leaves pending items applicable.
The resolver version is one constant in prompt_pair_resolver, shared by
ingestion provenance and Needs review.
The transaction's byte check receives the re-hashed digest (or the body's
for Leave unresolved), every Apply refusal branch is tested with zero
writes, and the root listing and realpath calls run on a worker thread.
* fix(review): validate stored review evidence once per startup
Startup used to run the full review validation twice (the early guard and
the install) and the annotation group's row checks inside each, so every
evidence document was parsed and re-encoded twice. The early guard is now
catalog-only (a review group without annotation tables), and the install
validates the group once, trusting the annotation group it has just
validated. The evidence predicate no longer pattern-scans every document in
SQL, because the streamed canonical pass proves it, and the codec is built
once.
Measured on a database with 40,000 items of 4 KiB evidence: startup open
went from 7.7 s to 2.5 s. A test pins one evidence pass per reopen.
Restore and verify_database_file keep the full validation.
* fix(review): keep one capture worker for interactive requests
Needs review recording from the scan and the monitor shared the capture
store's two workers with the Tag dialog and Apply, so a busy scan could
answer a user's preview or decision with "Too many previews are open".
Background captures now never take the last worker or capture slot, and
wait up to two seconds for room before counting the file as not added.
Interactive captures are admitted or refused at once, as before.
* fix(review): refresh the recorded spelling when a file is seen under a new one
A case-only rename on Windows or macOS keeps size and mtime_ns, so the
rescan skipped the file and the item kept the old spelling. Its target was
then formatted from a name the directory no longer lists, the capture
refused it, and the item stayed pending with no way to apply it. The skip
path and a duplicate insert now record the current spelling for every item
at the locator and move the review index revision; item revisions do not
change, so an open decision stays valid. Tested under case-folding
semantics on every platform.
* fix(review): final capture store close and recoverable stale cursors
Closing the capture store at shutdown now runs under the store lock and is
final: a monitor recording or scan batch still in flight gets a capture
error instead of creating a new temp directory and restore subscription
after the cleanup.
A well-formed queue cursor this process cannot verify (opened before a
ComfyUI restart, whose cursor secret is per process) now answers 409
review-conflict with the current total, like any other stale page, instead
of an uncoded 400. Malformed cursors stay 400.
* fix(review): make only the shutdown cleanup final
The previous commit made every close of the capture store final, which
also refused the explicit closes that swap in a fresh store. Only the host's
on_cleanup hook is final now; an observe after it answers a coded capture
error instead of an unhandled 500.
* refactor(admin): move Needs review recording into its own mixin
_record_scanned_review, _record_review_sync, record_review_file and
_log_review_items move unchanged from py/api/admin.py to
py/api/review_recording.py (ReviewRecordingMixin), keeping admin.py from
growing further past the size ceiling. No behaviour change.
* fix(review): record the review fix round and the skip's residual risks in TESTING.md
The Needs review paragraphs now state the rescan skip's residual risks (an
in-place rewrite that keeps size and mtime_ns is never re-queued; a deleted
or moved file leaves its pending item counted), the physical identity rule
for Apply, the candidate-only recheck and shared resolver version, the
spelling refresh, background capture admission, the final shutdown close,
the stale-cursor answer and the measured startup validation cost.
* feat(review): bind queue cursors to the storage epoch only
A decision or a new item (the monitor records one per generation) no
longer makes an open cursor stale: the (created_at, id) keyset stays
ordered when items leave or are appended. A restore still answers
storage-changed and an unverifiable cursor review-conflict.
* feat(review): Needs review page, SAVED VIEWS row and Activity hook
The concept's Metadata review page at #/review: the notice with the
exact pending count, the queue's media cards (shared with Images through
image-card.mjs), and the Resolve the association panel with the sampler
context, the chosen path's prompt blocks, Leave for later and Apply
association. Apply takes a fresh capture; refusals keep the selection
and explain inline; an unanswered decision is resent once. SAVED VIEWS
lists Needs review after Favorites with its count (retires D50), and an
ended scan that recorded review items offers Review metadata in Activity
(D87). Queue items carry the card's media url.
* feat(review): re-read an open Needs review page when its queue changes
An open Needs review page now follows the queue without polling. A new
server-sent event stream, GET /prompt_manager/review/events, sends
"ready" when it opens and "change" after every committed queue change:
an item the scan or the monitor recorded, a spelling refresh, a decision
from any tab, and a restore. database/review_changes.py notifies after
the commit from whichever thread wrote it. The page re-reads its first
page on each event, keeps the open item, its choice and an unanswered
decision, and re-reads the SAVED VIEWS count with it. When the open item
left the queue, the next one opens with a note. A keepalive comment
every 25 s lets the server drop a closed tab; shutdown ends every stream.
Leaving the page mid-decision now releases that decision's capture.
D-NEW-F1 is renumbered D119 in markers and TESTING.md.
* test(review): Needs review page workflows
The review fixture now seeds a real monitor-fallback conflict (the
monitor pipeline links a new output to the most recent prompt, then
queues it), a limited item and a file under no current root, and can add
an output through the monitor or leave one for a metadata scan.
New workflows: Apply links the chosen pair to that file only; a real
association conflict leaves the links unchanged and explains; a limited
item and an unavailable file can only be left unresolved; a tag save
leaves the item pending; keyboard focus, labels and touch targets; an
open page shows items the monitor and a scan add and a decision made in
another tab; leaving the page releases captures, the change stream and
requests. The faked 409 conflict test is replaced by the real one.
* test(review): cover the card Tag button and raise the review floors
The card's Tag on Needs review now has a workflow, and the page's queue
change hook has no unused default. review.mjs and review-state.mjs
floors rise to their measured coverage; no other floor changes.
* feat(review): keep the loaded depth on live re-reads and read once per visit
A queue change re-read only the first 40 items, so the pages Load more had
shown vanished and the page jumped. Each re-read now reads page after page
until it holds as many items as were shown (a restore met after the first
page reads again from the start), so the cards and the scroll position stay.
The stream's ready made every visit read the queue twice. List reads now
answer the queue's version (library_epoch, review_revision) and ready names
the version read after subscribing; the page re-reads on ready only when the
queue it shows is older. The SAVED VIEWS count follows the page's total, so a
change costs no count read. A stream counts as open only once ready is sent.
* test(review): compare Needs review with the approved concept
review-concept.spec.mjs measures the whole Metadata review page as a tree
in the concept and in production, on the review fixture's new
concept-shaped queue (the concept's first three image names and sizes and
its first prompt). mapConceptReview applies only D29, D119, D3, production's
hooks and accessible names and sample data, and the page then matches at
1600x1100 and 390x844 in both themes. The gallery layout follows the
concept at every breakpoint, the SAVED VIEWS rows match with Needs review
after Favorites, the queue's Tag image dialog matches the needs-review
reference, and a dropped notice border or reordered actions fail.
The comparison found one gap: an unavailable file's card lost its media
area. Its empty media button now keeps the concept's 1.33 ratio (D119).
TESTING.md records the comparison, the extended D119 and a summary of the
image-tagging slice (routes, S1, capture limits, the record-changing job,
the no-download rule, the restart note). A ready whose version cannot be
read re-reads the queue (covered by a page test).
* test(review): give the multi-route shell comparison a fitting time budget
The dispatched CI run failed "shell geometry, tokens and controls match the
concept 390x844 light" on WebKit with a 30 s test timeout (no assertion
failed). Each of these tests makes twelve page loads with captures, hovers
and focus checks: 15-19 s on a CI WebKit runner on main, 22-31 s on this
run's loaded shard. With 2 CPUs and 3 workers it fails locally the same way
(6 of 12 timed out); with a 90 s budget, as the other multi-state concept
comparisons have, all 12 pass.
* fix(review): coalesce queue change events and answer queue thumbnails
- The change stream sends the first notice at once and collapses the
notices of the next 0.4 s into one trailing change, so a busy scan costs
an open page one re-read per 0.4 s at most (COALESCE_SECONDS).
- Queue items answer thumbnail_url, the same URL the Images listing builds
(one shared helper, media_thumbnail_url), or null without a thumbnail.
- The "duplicate and refused decision send nothing" test spies on
notify_review_change instead of reading the next event.
* fix(review): keep the live queue right through applies, Load more and lost streams
- A change heard while a decision is in flight is owed and read once the
decision is refused or unanswered (I1).
- Load more has its own read: during a re-read it waits and continues from
the re-read queue; a re-read started during Load more takes the click
over, and a failed re-read leaves Load more clickable (I2, M7).
- A stream the browser gave up on (503, proxy error) reopens after 3 s,
doubling to 30 s, with a quiet "Live updates are paused" line while it is
down (I3, D-NEW-F2).
- A hidden tab closes its stream and a visible one reopens it; the ready
version keeps that to at most one read (I4).
- Apply fences on the detail's epoch and a re-read under another epoch reads
the open item again (M3); leaving during the observe releases its capture
(M4); an unanswered decision that landed finishes as recorded (M5); cards
follow a re-read's url, target and availability and show thumbnails
(M6, M10).
- The unreadable-ready test asserts exactly one re-read (M1); the panel's
long-file-name wrap carries its D119 marker and TESTING.md entry (M8).
* docs(review): number the live-updates-paused deviation D120
* fix(review): refuse monitor recording beside record-changing jobs
System S1 (#289) gives every record change a registry admission class. The
scan already records Needs review items under its own records job. The
monitor's recording lasts one file and is not a job, so it now checks the
records admission: while a records or guarded job or hold runs it records
nothing, logs that the file waits for the next scan, and answers deferred.
The fallback link stands and the next "new" scan reads the ambiguous file
again, because a fallback link is not a resolved one.
JobRegistry.blocker and active iterate a snapshot of the jobs, since the
monitor's worker thread now asks them too.
* test(backup): wait for the restore, not a 5 s timer, in the thread test
test_database_is_usable_from_every_thread_after_restore let its worker
wait 5 s for the restore. On a stalled Windows runner (py3.11, where the
previous restore test also took 25 s instead of 0.3 s) the restore took
longer, the wait timed out, and the worker read the old database before
the restore ran. The worker now waits for the event under a 120 s bound
that only a hung test reaches, reports a timeout as an error, and the
main thread releases it even when the restore raises. With a restore
delayed by 6 s the old test fails and the new one passes.
* fix(activity): drop Cancel job from a job that had ended before Activity opened
Since #289 the Activity list removed an item's actions only when they were
isConnected. On the first render the item is not in the page yet, so a job
that had already ended when Activity opened kept its "Cancel job" (and a
running job's progress was moved after its actions, then back). The list
now asks parentNode instead. The review spec "a scan job with review items
offers Review metadata in Activity" failed on this before the change
(Expected 0 buttons on a finished job, Received 1) and passes after it.
* fix(review): store non-finite evidence as null and count pending items
canonical_evidence now follows main's non-finite policy (#303): NaN and
±Infinity are written as null instead of raising, so a NaN-stamped graph
never turns a review item limited. The System Overview reports the review
queue's pending total in needs_review.pending, read in the same snapshot
as the Library counts.
* fix(review): show the pending count on the System Overview review row
The Overview's review row now reads "N ambiguous image links" with the
concept's line, from needs_review.pending. Its Review metadata action
stays aria-disabled until the Needs review page ships. The system specs
and their concept comparison follow the real count.
* feat(review): open Needs review from the System Overview review row
Review metadata on the Overview's review row now opens #/review, the
concept's go-review, instead of staying aria-disabled.
* fix(system): answer the Overview and Statistics only after every read ended
asyncio.gather answered at the first failed read while its sibling
executor reads were still inside SQLite. In the suite the test teardown
then deleted the database under the running read, and py3.10 on Ubuntu
segfaulted in get_statistics (test_statistics_failure_is_an_error_envelope).
Both routes now wait for all their reads before answering.
* fix(review): queue only ambiguous files that nothing links, and heal the queue
The maintainer's live scan (19,908 files, scope "new") reported 4,677 files
under Needs review, but the queue held 10,232 items: every file the strict
resolver found ambiguous was queued, including the ones the legacy
browser-parser fallback then linked (all sampled "added" rows) and the ones
already linked to a known prompt (135 of 200 sampled "known" rows).
A file is now queued only when its final outcome is ambiguous and unlinked:
the resolver finds it ambiguous, the fallback links nothing and no saved row
links it already. An ambiguous file that a saved row links is reported as
unchanged ("Already linked to its prompt"), not as Needs review.
The queue heals itself. After each batch, the scan removes the pending items
of every listed file (read, or skipped as known) that a saved row now links.
The monitor does the same for each ambiguous output it links, and never
queues one. Only an undecided item is removed (pending, revision 0, no
decision row), so a decision is never deleted or changed and the schema
needs no new state.
The scan job's scope.review_items now counts this scan's files that are in
the pending queue after it, new or already there, so it agrees with the
review group's ambiguous rows and with the queue total. review_added and
review_settled are new, and the log gains "already in Needs review" and
"left Needs review · now linked" lines. A duplicate whose item is decided is
reported as "decided" and is not counted.
* fix(review): announce items that leave the queue, and seed only queueable files
#284 now queues a file only when its final outcome is ambiguous and unlinked,
and it removes the pending items of files that are now linked. That removal
is a queue change, so it calls notify_review_change after its commit, like
recording and decisions: an open Needs review page re-reads its queue, and
its count follows.
The review browser fixture wrote graphs that the scan's fallback links, and
it produced the conflict item through the monitor's fallback link. Neither is
queued any more. Its files now carry ComfyUI's Infinity stamp, which the
legacy parser cannot read, so they stay unlinked with the same two
candidates. The conflict item is queued first and its file is linked to
another prompt afterwards. "monitor" additions go through
record_review_file from a worker thread.
* fix(review): never queue an ambiguous file with nothing to choose
The maintainer's live queue held 39 items whose candidates all read
"unresolved" ("No positive / No negative"). An ambiguous result is now
reviewable only when at least two candidates are resolved with non-blank
positive text. With none the file could not be traced; with exactly one,
the untraced branches may still have made the file, so that text is not
certain either. Both are reported unresolved, never linked and never
queued (also the A1111 two-delimiter case, which has no candidates).
A rescan removes the pending items of such files whose own evidence
offers no choice, with the same safe delete as the linked settle
(pending, revision 0, no decision row). A limited item (over 16 candidates) that holds at least two
candidates is kept. The job scope gains review_untraced and the log
"= N images left Needs review · nothing to choose".
* test(review): seed the limited item from a graph with more candidates than stored
An A1111 block with two negative lines offers no candidate to choose, so
Needs review no longer queues it (#284). The fixture now records a graph of
17 samplers, which the recorder stores limited.
748 lines
44 KiB
JavaScript
748 lines
44 KiB
JavaScript
import { createScope, createButton } from '../shared/toolkit/core.js';
|
||
import { createImageStream, withItem, imageKey, countLine, captionDate, scopeLabel, activeRefinements, initialImagesView } from './images-state.mjs';
|
||
import { createImageCard } from './image-card.mjs';
|
||
import { layoutImages, visibleImages, gridMetrics, stacksCardInfo } from './image-layout.mjs';
|
||
import { mountFileInspector } from './file-inspector.mjs';
|
||
import { createInspectionController } from './inspection-state.mjs';
|
||
import { mountSelectionBar } from './images-selection.mjs';
|
||
import { createPromptSender } from './prompt-sender.mjs';
|
||
import { promptRoles } from './prompt-blocks.mjs';
|
||
import { createWorkspaceIcon } from './icons.mjs';
|
||
import { createMediaViewer } from './media-viewer.mjs';
|
||
import { noun } from './plural.mjs';
|
||
import { pageHeading } from './heading.mjs';
|
||
import { mountToolbar } from './toolbar.mjs';
|
||
import { openImportDialog, openRefineDialog } from './workspace-dialogs.mjs';
|
||
import { openMetadataScan } from './activity-scan.mjs';
|
||
import { showWorkspaceToast } from './toast.mjs';
|
||
import { imagesFilters, imagesViewState } from './saved-views.mjs';
|
||
import { displayPreferences } from './preferences.mjs';
|
||
import { onImageTagsSaved } from './image-tagging.mjs';
|
||
import { followImageTagSaves, openCardTagging } from './images-tagging.mjs';
|
||
import { favoriteBusy, paintStar, receiveFavorites, setFavoriteVisitTarget, toggleFavorite } from './images-favorites.mjs';
|
||
export { onFavoriteChange } from './images-favorites.mjs';
|
||
|
||
/** The concept's panel without an image (app.js updateImages a456–458). */
|
||
function noSelection() {
|
||
const inner = el('div', undefined, 'detail-inner');
|
||
inner.append(el('h2', 'No image selected'), el('p', 'Clear the filters or choose a matching image.', 'small'));
|
||
return inner;
|
||
}
|
||
function el(tag, text, className) {
|
||
const element = document.createElement(tag);
|
||
if (text !== undefined) element.textContent = text;
|
||
if (className) element.className = className;
|
||
return element;
|
||
}
|
||
|
||
/**
|
||
* Live regions re-announce replaced text even when it is the same, and a patched publish (a favorite) repeats the
|
||
* same status: write text and attributes only when they change.
|
||
*/
|
||
function setText(element, text) {
|
||
if (element.textContent !== text) element.textContent = text;
|
||
}
|
||
function setAttr(element, name, value) {
|
||
if (element.getAttribute(name) !== value) element.setAttribute(name, value);
|
||
}
|
||
|
||
function selectOf(id, options, value) {
|
||
const select = el('select');
|
||
select.id = id;
|
||
select.replaceChildren(...options.map(([optionValue, label]) => {
|
||
const node = el('option', label);
|
||
node.value = optionValue;
|
||
return node;
|
||
}));
|
||
select.value = value;
|
||
return select;
|
||
}
|
||
|
||
// The concept's three sorts first, then the production ones it lacks (D14); values are the listing's sorts (B3).
|
||
const IMAGE_SORT_OPTIONS = Object.freeze([['newest', 'Recently added'], ['name', 'Name A–Z'], ['rating', 'Highest rated'],
|
||
['oldest', 'Oldest first'], ['name-desc', 'Name Z–A']]);
|
||
const MEDIA_OPTIONS = Object.freeze([['all', 'All media'], ['image', 'Images'], ['video', 'Videos']]);
|
||
const RETRY_RESCAN = 'Rescan from Import to retry.';
|
||
const RETRY_REFRESH = 'Refresh image collection to retry.';
|
||
/** One alert for whichever of the source discovery and the categories failed, so two failures announce once. */
|
||
function loadFailure(sourcesRetry, categoriesFailed) {
|
||
if (sourcesRetry && categoriesFailed) return `Sources, folders and categories could not be loaded. ${sourcesRetry}`;
|
||
if (sourcesRetry) return `Sources and folders could not be loaded. ${sourcesRetry}`;
|
||
return categoriesFailed ? `Categories could not be loaded. ${RETRY_RESCAN}` : '';
|
||
}
|
||
// Import → Rescan (D15): the concept has no rescan copy, so its toasts follow the workspace pattern. The answer
|
||
// counts every listed file across the output roots it walked.
|
||
const RESCAN_STARTED = 'Rescanning output folders…';
|
||
const RESCAN_FAILED = 'Rescan could not finish. Try again.';
|
||
function rescanFinished(result) {
|
||
const {total, roots} = result ?? {};
|
||
if (![total, roots].every(value => Number.isSafeInteger(value) && value >= 0)) return 'Rescan finished.';
|
||
return `Rescan finished. ${total.toLocaleString('en-US')} ${noun(total, 'file')} in ${roots.toLocaleString('en-US')} output ${noun(roots, 'folder')}.`;
|
||
}
|
||
// The concept card's first `.media-info` reservation and list row (image-layout.mjs); real rows are measured.
|
||
const INITIAL_METRICS = Object.freeze({columns:1, gap:13, footerHeight:54, listHeight:97});
|
||
|
||
let lastVisit = null;
|
||
// The star's answers patch the saved visit while no Images page is mounted (D7).
|
||
setFavoriteVisitTarget((key, favorite) => {
|
||
if (lastVisit?.state) lastVisit = {...lastVisit, state: withItem(lastVisit.state, key, {favorite})};
|
||
});
|
||
|
||
// A tag save made while Images is left (Tags › Auto-tag images) may change what a filtered visit lists: it reloads (M6).
|
||
onImageTagsSaved(() => { if (lastVisit?.filters.tags.length || lastVisit?.filters.q) lastVisit = {...lastVisit, stale: true}; });
|
||
/** The image selected in Images when it was last left (the concept's `state.selectedImage`, for Tags › Auto-tag images). */
|
||
export function selectedImage() {
|
||
const key = lastVisit?.selection;
|
||
return key ? lastVisit.state?.items.find(item => imageKey(item) === key) ?? null : null;
|
||
}
|
||
|
||
/**
|
||
* An embedded collection (the history page's shared gallery and its All images and Repeat run dialogs, D47) has no
|
||
* caption: its page heading or dialog title already names it, and `focusTarget` takes a stranded focus.
|
||
* `savedState` opens a saved view (#249 D16) instead of the last visit; `onSaveView(trigger, state)` is Save view.
|
||
* `favorites` is the Favorites page (#249 D51): only favorites are listed, and it neither restores nor replaces the
|
||
* Images last visit.
|
||
*/
|
||
export function mountImages(main, api, parentScope, {embedded = false, fetchPage, emptyText, focusTarget = null, savedState = null,
|
||
favorites = false, onSaveView = () => {}, activity = null} = {}) {
|
||
const scope = createScope();
|
||
const dispose = () => scope.dispose();
|
||
parentScope.signal.addEventListener('abort', dispose, {once:true});
|
||
scope.cleanup(() => parentScope.signal.removeEventListener('abort', dispose));
|
||
if (parentScope.signal.aborted) { scope.dispose(); return {dispose}; }
|
||
const sender = createPromptSender({scope});
|
||
let detailInspector;
|
||
// System › Appearance: the display defaults this visit starts from (preferences.mjs); null without gallery-settings.js.
|
||
const preferences = displayPreferences();
|
||
const inspection = createInspectionController({api, autoLoad:preferences?.autoLoadMetadata !== false, cache:preferences?.cacheMetadata !== false});
|
||
scope.cleanup(inspection.subscribe(next => detailInspector?.setState(next)));
|
||
scope.cleanup(() => inspection.dispose());
|
||
scope.cleanup(() => detailInspector?.dispose());
|
||
const saved = embedded || !savedState ? null : imagesFilters(savedState);
|
||
const prior = embedded || saved || favorites ? null : lastVisit;
|
||
// A stale visit keeps its filters, layout and size, and lists again instead of restoring (M6).
|
||
const visit = prior?.stale ? null : prior;
|
||
// The layout and size defaults are the Images page's: an embedded gallery (a prompt history's, its dialogs) has no
|
||
// toolbar to change them, so it keeps its fixed Grid/Comfortable. The metadata and card defaults apply everywhere.
|
||
const start = initialImagesView({prior, saved, preferences:embedded ? null : preferences});
|
||
let density = start.density;
|
||
let metrics = {...INITIAL_METRICS};
|
||
let layout = start.layout, selection = visit?.selection || null, frame = 0, loadFrame = 0, restoreFrame = 0, observer;
|
||
let state, geometry = { positions: [], columns: 1, height: 0, maxHeight: 0 }, galleryWidth = 0, optionsRequest, categoryRequest, recovering = false, rescanning = false;
|
||
// Discovered sources (each with its own folders) and every folder, for "Refine this view" and the scope chip.
|
||
let roots = [], folders = [];
|
||
// The open "Refine this view", so a discovery that settles after it opened still lists its sources and folders.
|
||
let refine = null;
|
||
const rendered = new Map();
|
||
const itemIndexes = new Map();
|
||
const filters = { root: 'all', q: '', category: '', tags: [], subfolder: '', media: 'all', sort: 'newest', ...prior?.filters, ...saved,
|
||
favorites: favorites || saved?.favorites === true };
|
||
filters.tags = [...filters.tags];
|
||
if (!IMAGE_SORT_OPTIONS.some(([value]) => value === filters.sort)) filters.sort = 'newest';
|
||
// A saved Source or Folder is only listed once discovery confirms it still exists; until then nothing is fetched.
|
||
let savedScopePending = Boolean(saved) && (filters.root !== 'all' || filters.subfolder !== '');
|
||
// The first discovery settled (found or failed): only then may a pending saved scope be kept or dropped (#249 M3).
|
||
let discoverySettled = false;
|
||
scope.cleanup(() => {
|
||
// A Set category write still in flight may change what the saved collection shows: the return reloads instead.
|
||
// A favorites-only collection or a saved view is not the plain Images collection, so it never becomes the
|
||
// Images return state (#249 D51, and M2 for saved views).
|
||
if (!embedded && !filters.favorites && !saved) lastVisit = state && !bar.writing() ? { filters: {...filters, tags: [...filters.tags]}, state, layout, density, selection, checked: bar.checked(), scrollY: window.scrollY } : null;
|
||
cancelAnimationFrame(restoreFrame);
|
||
});
|
||
main.classList.add('images-main');
|
||
scope.cleanup(() => main.classList.remove('images-main'));
|
||
// The concept's Images heading (app.js renderImages): description, then Import before the shell's New prompt.
|
||
const heading = embedded ? null : pageHeading(main);
|
||
let importButton = null, importDialog = null;
|
||
if (heading) {
|
||
heading.description.textContent = 'Your generations, their prompts, and the next idea.';
|
||
importButton = createButton('');
|
||
importButton.append(createWorkspaceIcon('upload'), el('span', 'Import'));
|
||
heading.actions.prepend(importButton);
|
||
scope.cleanup(() => importButton.remove());
|
||
scope.listen(importButton, 'click', () => {
|
||
importDialog = openImportDialog({scope, trigger:importButton, rescanBusy:rescanning,
|
||
onInspect:() => { window.location.hash = '#/inspect'; }, onRescan:rescan,
|
||
// D55: Scan for metadata reviews the session scan job over every discovered source.
|
||
onMetadataScan:activity ? trigger => openMetadataScan({scope, store:activity, sources:roots.length, trigger}) : null});
|
||
});
|
||
}
|
||
// The shared concept toolbar: search (filename, linked prompt text, title and tags), category and sort (D12–D14).
|
||
const toolbar = embedded ? null : mountToolbar(main, {scope, categories:filters.category ? [filters.category] : [],
|
||
sorts:IMAGE_SORT_OPTIONS, value:{q:filters.q, category:filters.category, sort:filters.sort},
|
||
activeFilters:activeRefinements(filters),
|
||
onChange:value => {
|
||
if (recovering) return;
|
||
const next = {q:value.q.trim(), category:value.category, sort:value.sort};
|
||
// A debounced search report can land after a select change already applied the same values; reloading
|
||
// then would refetch the first page and drop the reader's scroll position.
|
||
if (Object.entries(next).every(([key, item]) => filters[key] === item)) return;
|
||
Object.assign(filters, next);
|
||
reset();
|
||
}, onFilters:openFilters, onSaveView:trigger => {
|
||
const value = toolbar.value();
|
||
onSaveView(trigger, imagesViewState({...filters, q:value.q.trim(), category:value.category, sort:value.sort}));
|
||
}});
|
||
const toolbarControls = toolbar ? [...toolbar.element.querySelectorAll('input, select, button')] : [];
|
||
const optionsStatus = el('p', '', 'options-status muted');
|
||
optionsStatus.hidden = true; optionsStatus.setAttribute('role', 'alert');
|
||
// The failed loads' retry hint (null once sources load) and whether the categories failed.
|
||
let sourcesRetry = null, categoriesFailed = false;
|
||
if (!embedded) main.append(optionsStatus);
|
||
// The concept's filter row: layouts, thumbnail size, the scope chip and Group by positive prompt (D14, D15).
|
||
const filterRow = el('div', undefined, 'filter-row');
|
||
const layouts = el('div', undefined, 'segmented');
|
||
layouts.setAttribute('role', 'group'); layouts.setAttribute('aria-label', 'Image layout');
|
||
for (const mode of ['grid', 'list', 'masonry']) {
|
||
const button = createButton(mode[0].toUpperCase() + mode.slice(1));
|
||
button.prepend(createWorkspaceIcon(mode));
|
||
button.setAttribute('aria-pressed', String(mode === layout));
|
||
scope.listen(button, 'click', () => {
|
||
layout = mode;
|
||
for (const child of layouts.children) child.setAttribute('aria-pressed', String(child === button));
|
||
updateLayout();
|
||
});
|
||
layouts.append(button);
|
||
}
|
||
const sizeLabel = el('label', 'Thumbnail size', 'small');
|
||
sizeLabel.htmlFor = 'image-size';
|
||
const thumbnails = selectOf('image-size', [['comfortable', 'Comfortable'], ['large', 'Large'], ['compact', 'Compact']], density);
|
||
scope.listen(thumbnails, 'change', () => { density = thumbnails.value; updateLayout(); });
|
||
filterRow.append(layouts, sizeLabel, thumbnails);
|
||
const scopeText = document.createTextNode('');
|
||
if (!embedded) {
|
||
const chip = el('span', undefined, 'chip');
|
||
chip.append(createWorkspaceIcon('folder'), scopeText);
|
||
const group = createButton('Group by positive prompt →', 'chip');
|
||
scope.listen(group, 'click', () => { window.location.hash = '#/library'; });
|
||
filterRow.append(chip, group);
|
||
}
|
||
main.append(filterRow);
|
||
const body = el('div', undefined, 'gallery-layout image-workspace');
|
||
const collection = el('section', undefined, 'gallery-body');
|
||
collection.setAttribute('aria-label', 'Images');
|
||
// The concept's caption replaces the old "All images" heading.
|
||
const caption = el('div', undefined, 'section-caption');
|
||
const count = el('span', 'Loading images…');
|
||
count.id = 'result-count';
|
||
const captionDay = el('span');
|
||
captionDay.hidden = true;
|
||
caption.append(count, captionDay);
|
||
const focusFallback = focusTarget || heading?.h1 || main;
|
||
const grid = el('div', undefined, 'image-grid');
|
||
grid.setAttribute('role', 'list'); grid.setAttribute('aria-label', 'Image collection');
|
||
const continuation = el('div', undefined, 'infinite-continuation');
|
||
// The concept's ids (app.js renderImages); the Library-embedded gallery has its own page around it.
|
||
if (!embedded) { grid.id = 'image-grid'; continuation.id = 'gallery-continuation'; }
|
||
const message = el('p', '', 'small');
|
||
const more = createButton('Load more images');
|
||
const retry = createButton('Retry');
|
||
continuation.append(message, more, retry);
|
||
// The concept's empty collection (app.js updateImages), beside the grid because the grid only holds positioned cards.
|
||
// An embedded gallery shows one only when its page names the concept's copy (the history gallery, app.js a620).
|
||
const showsEmpty = !embedded || typeof emptyText === 'string';
|
||
const empty = el('div', embedded ? emptyText : 'No matching images. Try another search or category.', 'empty');
|
||
empty.hidden = true;
|
||
// D47: the history page's shared gallery and dialogs are named by their own heading or title, so they have no caption.
|
||
if (!embedded) collection.append(caption);
|
||
collection.append(grid);
|
||
if (showsEmpty) collection.append(empty);
|
||
collection.append(continuation);
|
||
// After a Load more or Retry press, the index of the first image that batch appends (concept: focus it).
|
||
let focusAfterLoad = null;
|
||
// The concept's side panel (app.js a426, D20); the Library-embedded gallery has its own page around it.
|
||
const details = el('aside', undefined, 'detail-panel');
|
||
if (!embedded) details.id = 'image-inspector';
|
||
details.setAttribute('aria-label', 'Selected image details');
|
||
details.append(noSelection());
|
||
body.append(collection, details);
|
||
// The checked cards and the concept's selection bar (#249 D8), between the filter row and the gallery layout. The
|
||
// selection is kept across appended batches and cleared with the collection; the Library-embedded gallery has none.
|
||
const bar = embedded ? null : mountSelectionBar({scope, api, grid, getItems:() => state.items, focusFallback,
|
||
checked:visit?.checked, onCategorySet:() => { loadCategories(); reset(); }, activity, onTagged:keys => refreshTagged(keys)});
|
||
if (bar) main.append(bar.element);
|
||
main.append(body);
|
||
const mediaViewer = createMediaViewer({api,container:main,parentScope:scope,inspectionController:inspection,sender,
|
||
onSelect:image => {if (selection !== imageKey(image)) inspect(image);else inspection.select(image);},
|
||
onRefresh:refreshInspectionCollection,onClose:scheduleLoad,onRestoreFocus:image => {
|
||
const index = state?.items.findIndex(entry => imageKey(entry) === imageKey(image));
|
||
if (index >= 0) focusImage(index);else focusFallback.focus({preventScroll:true});
|
||
}});
|
||
scope.cleanup(() => mediaViewer.dispose());
|
||
|
||
function releaseVideo(video) {
|
||
video.pause(); video.removeAttribute('src'); video.load();
|
||
}
|
||
function inspect(image) {
|
||
detailInspector?.dispose();
|
||
selection = imageKey(image);
|
||
for (const video of details.querySelectorAll('video')) releaseVideo(video);
|
||
detailInspector = mountFileInspector(details, {sender, parentScope:scope, variant:'panel',
|
||
onTagFilter:embedded ? undefined : filterByTag, onRetry:() => inspection.retry(), onLoad:() => inspection.load(), onRefresh:refreshInspectionCollection});
|
||
detailInspector.setState(inspection.state);
|
||
inspection.select(image);
|
||
for (const [key, card] of rendered) markSelected(card, key === selection);
|
||
}
|
||
/** The concept's `.media-card.selected` (D19); as in the concept, Info carries no pressed state. */
|
||
function markSelected(card, selected) {
|
||
card.classList.toggle('selected', selected);
|
||
}
|
||
function previewImage(image) {
|
||
if (!image) return;
|
||
mediaViewer.open({items:state.items,selectedKey:imageKey(image),trigger:document.activeElement});
|
||
}
|
||
/** The concept media card (image-card.mjs): the image opens the viewer, Info inspects (D7–D11, D19). */
|
||
function cardFor(image) {
|
||
const key = imageKey(image);
|
||
const card = createImageCard(image, {checked:bar ? bar.isChecked(key) : null, favoriteBusy:favoriteBusy(key),
|
||
// D97: "Show image details on cards" off hides the title and file line; Info and Tag stay.
|
||
showInfo:preferences?.showImageInfo !== false});
|
||
markSelected(card, key === selection);
|
||
return card;
|
||
}
|
||
function setFavorite(key, favorite) {
|
||
if (scope.signal.aborted) return;
|
||
stream.updateItem(key, {favorite});
|
||
const button = rendered.get(key)?.querySelector('.star-button');
|
||
if (button) paintStar(button, favorite, favoriteBusy(key));
|
||
}
|
||
// The Images page and every Library-embedded gallery receive favorite answers (#249 D7, PR E).
|
||
receiveFavorites({scope, embedded, setFavorite});
|
||
scope.listen(grid, 'click', event => {
|
||
const card = event.target.closest('article[data-image-key]');
|
||
if (!card) return;
|
||
const image = state.items.find(item => imageKey(item) === card.dataset.imageKey);
|
||
if (!image) return;
|
||
const action = event.target.closest('.image-card-actions button');
|
||
if (event.target.closest('.star-button')) toggleFavorite(api, image);
|
||
else if (event.target.closest('.image-open')) previewImage(image);
|
||
else if (action && !openCardTagging({api, scope, image, action, embedded})) inspect(image);
|
||
});
|
||
|
||
function renderVisible() {
|
||
if (!state || scope.signal.aborted) return;
|
||
const bounds = grid.getBoundingClientRect();
|
||
const scale = bounds.width / Number.parseFloat(getComputedStyle(grid).width) || 1;
|
||
const top = Math.max(0, -bounds.top / scale);
|
||
const viewportHeight = window.innerHeight / scale;
|
||
const active = document.activeElement?.closest('article[data-image-key]')?.dataset.imageKey;
|
||
const focused = active ? itemIndexes.get(active) ?? -1 : -1;
|
||
const indexes = state.items.length <= 120 ? state.items.map((_, index) => index) :
|
||
visibleImages(geometry.positions, top, viewportHeight, focused, geometry.maxHeight);
|
||
const keep = new Set(indexes.map(index => imageKey(state.items[index])));
|
||
for (const [key, card] of rendered) if (!keep.has(key)) {
|
||
for (const video of card.querySelectorAll('video')) releaseVideo(video);
|
||
card.remove(); rendered.delete(key);
|
||
}
|
||
for (const index of indexes) {
|
||
const image = state.items[index], key = imageKey(image);
|
||
let card = rendered.get(key);
|
||
if (!card) { card = cardFor(image); rendered.set(key, card); }
|
||
positionCard(card, index);
|
||
}
|
||
// Keep keyboard order aligned with the collection while preserving existing nodes.
|
||
let previous = null;
|
||
for (const index of indexes) {
|
||
const card = rendered.get(imageKey(state.items[index]));
|
||
if (previous ? previous.nextElementSibling !== card : grid.firstElementChild !== card) grid.insertBefore(card, previous ? previous.nextElementSibling : grid.firstChild);
|
||
previous = card;
|
||
}
|
||
// Natural footer measurements and absolute reservations share unzoomed CSS units. The fractional height, as the
|
||
// concept's own flow lays it out: `offsetHeight` rounds a wrapped 67.5px row up and adds half a pixel per row.
|
||
const footerHeight = Math.max(metrics.footerHeight, ...[...rendered.values()].map(card => card.querySelector('.media-info').getBoundingClientRect().height / scale));
|
||
// A small epsilon: under zoom `rect / scale` carries float noise that must not relayout and scroll for nothing.
|
||
if (footerHeight > metrics.footerHeight + 0.01) {
|
||
const anchor = indexes.find(index => geometry.positions[index].y + geometry.positions[index].height >= top && geometry.positions[index].y <= top + viewportHeight);
|
||
const anchorTop = anchor === undefined ? 0 : geometry.positions[anchor].y;
|
||
metrics = {...metrics, footerHeight, listHeight: Math.max(metrics.listHeight, footerHeight + 2)};
|
||
updateGeometry();
|
||
for (const index of indexes) positionCard(rendered.get(imageKey(state.items[index])), index);
|
||
// A later mounted footer must not move the current visible card.
|
||
const correction = anchor === undefined ? 0 : geometry.positions[anchor].y - anchorTop;
|
||
if (top > 0 && correction) window.scrollBy(0, correction * scale);
|
||
scheduleVisible();
|
||
}
|
||
}
|
||
function positionCard(card, index) {
|
||
const image = state.items[index], position = geometry.positions[index];
|
||
card.dataset.index = index;
|
||
markSelected(card, imageKey(image) === selection);
|
||
card.setAttribute('aria-posinset', String(index + 1)); card.setAttribute('aria-setsize', String(state.total));
|
||
Object.assign(card.style, { left: `${position.x}px`, top: `${position.y}px`, width: `${position.width}px`, height: `${position.height}px` });
|
||
}
|
||
function focusImage(index, actions = false, {scroll = true} = {}) {
|
||
if (index < 0 || index >= state.items.length) return;
|
||
const image = state.items[index], key = imageKey(image);
|
||
let card = rendered.get(key);
|
||
if (!card) {
|
||
card = cardFor(image); rendered.set(key, card); positionCard(card, index);
|
||
grid.insertBefore(card, [...grid.children].find(child => Number(child.dataset.index) > index) || null);
|
||
}
|
||
card.querySelector(actions ? '.image-card-actions button' : '.image-open').focus({ preventScroll: true });
|
||
if (scroll) card.scrollIntoView({ block: 'nearest' });
|
||
cancelAnimationFrame(frame); frame = 0;
|
||
renderVisible();
|
||
}
|
||
scope.listen(grid, 'keydown', event => {
|
||
const card = event.target.closest('article[data-image-key]');
|
||
if (!card) return;
|
||
const index = Number(card.dataset.index);
|
||
const columns = geometry.columns;
|
||
const target = { Home: 0, End: state.items.length - 1, ArrowRight: index + 1,
|
||
ArrowLeft: index - 1, ArrowDown: index + columns, ArrowUp: index - columns }[event.key];
|
||
if (target !== undefined) { event.preventDefault(); focusImage(Math.max(0, Math.min(state.items.length - 1, target))); }
|
||
else if (event.key === 'Tab') {
|
||
const backward = event.shiftKey && event.target.matches('.image-open');
|
||
const forward = !event.shiftKey && event.target.closest('.image-card-actions');
|
||
const adjacent = backward ? index - 1 : index + 1;
|
||
if ((backward || forward) && state.items[adjacent] && !rendered.has(imageKey(state.items[adjacent]))) {
|
||
event.preventDefault(); focusImage(adjacent, backward);
|
||
}
|
||
}
|
||
});
|
||
function scheduleVisible() { if (!frame) frame = requestAnimationFrame(() => { frame = 0; renderVisible(); }); }
|
||
function updateGeometry() {
|
||
geometry = layoutImages(state.items, galleryWidth, layout, metrics);
|
||
// Below the narrowest bounded card (extreme zoom) the info row stacks (the production overlay, #249 D31).
|
||
grid.classList.toggle('narrow-cards', stacksCardInfo(galleryWidth, layout));
|
||
grid.style.height = `${geometry.height}px`;
|
||
grid.style.setProperty('--image-footer-height', `${metrics.footerHeight}px`);
|
||
}
|
||
function updateLayout() {
|
||
if (!state || scope.signal.aborted) return;
|
||
cancelAnimationFrame(frame); frame = 0;
|
||
// The concept's grid classes (app.js updateImages); the concept stylesheet then owns the columns and gap (D3).
|
||
grid.className = ['image-grid', density === 'comfortable' ? '' : density,
|
||
layout === 'list' ? 'list-grid' : layout === 'masonry' ? 'masonry-grid' : ''].filter(Boolean).join(' ');
|
||
const width = Number.parseFloat(getComputedStyle(grid).width);
|
||
const retained = state.items.length && width === galleryWidth && grid.dataset.layout === layout && grid.dataset.density === density ? metrics : null;
|
||
galleryWidth = width;
|
||
metrics = {...INITIAL_METRICS, ...gridMetrics(grid)};
|
||
if (retained) {
|
||
metrics.footerHeight = retained.footerHeight;
|
||
metrics.listHeight = retained.listHeight;
|
||
}
|
||
grid.dataset.layout = layout;
|
||
grid.dataset.density = density;
|
||
updateGeometry();
|
||
renderVisible();
|
||
}
|
||
let resizeFrame = 0, observedWidth;
|
||
const resize = new ResizeObserver(entries => {
|
||
const width = entries[0].contentRect.width;
|
||
if (width === observedWidth) return;
|
||
observedWidth = width;
|
||
if (!resizeFrame) resizeFrame = requestAnimationFrame(() => {
|
||
resizeFrame = 0;
|
||
updateLayout();
|
||
});
|
||
});
|
||
resize.observe(grid);
|
||
scope.listen(window, 'scroll', scheduleVisible);
|
||
scope.listen(window, 'resize', () => {
|
||
if (!resizeFrame) resizeFrame = requestAnimationFrame(() => { resizeFrame = 0; updateLayout(); });
|
||
});
|
||
scope.cleanup(() => { resize.disconnect(); observer?.disconnect(); cancelAnimationFrame(resizeFrame); cancelAnimationFrame(frame); cancelAnimationFrame(loadFrame); });
|
||
function continuationText(next) {
|
||
if (recovering) return 'Images paused until sources and folders are available.';
|
||
if (next.error) return 'Images could not be loaded. Retry or rescan the collection.';
|
||
if (next.loading && !next.loaded) return 'Loading images…';
|
||
if (next.hasMore) return `${next.loaded.toLocaleString('en-US')} of ${next.total.toLocaleString('en-US')} ${noun(next.total, 'image')} · more load as you scroll`;
|
||
if (embedded) return next.loaded ? 'You’re all caught up.' : 'No linked media available for this selection.';
|
||
// The concept's end of the collection (app.js updateImageContinuation).
|
||
return `${next.loaded ? 'You’re all caught up' : 'No matching images'} · ${next.total.toLocaleString('en-US')} ${noun(next.total, 'image')}`;
|
||
}
|
||
function renderState(next, {patch, replaced = false} = {}) {
|
||
const previous = state;
|
||
// A patched item (a favorite) keeps every card's size and place; setFavorite repaints its card.
|
||
const changed = !patch && state?.items !== next.items;
|
||
if (changed) {
|
||
// A refreshed collection (`replaced`) is indexed again from its start; a loaded page only appends.
|
||
if (!next.items.length || replaced) itemIndexes.clear();
|
||
for (let index = replaced ? 0 : state?.items.length || 0; index < next.items.length; index++) itemIndexes.set(imageKey(next.items[index]), index);
|
||
}
|
||
// The selected file left the refreshed result: the panel follows the collection, as after a reload; the
|
||
// selection bar keeps only the checked files still listed (I7).
|
||
if (replaced && selection !== null && !itemIndexes.has(selection)) dropSelection();
|
||
if (replaced) bar?.retain(key => itemIndexes.has(key));
|
||
state = next;
|
||
if (!embedded) {
|
||
setText(count, countLine(next));
|
||
setText(captionDay, captionDate(next.items, filters.sort));
|
||
if (captionDay.hidden !== !captionDay.textContent) captionDay.hidden = !captionDay.textContent;
|
||
}
|
||
if (changed) updateLayout();
|
||
// The concept's Load more toast (app.js loadMoreImages) for every batch appended to a loaded collection.
|
||
if (!embedded && changed && !replaced && previous?.loaded && next.loaded > previous.loaded) {
|
||
const added = next.loaded - previous.loaded;
|
||
showWorkspaceToast(`${added.toLocaleString('en-US')} more ${noun(added, 'image')} loaded. ${next.loaded.toLocaleString('en-US')} of ${next.total.toLocaleString('en-US')}.`);
|
||
}
|
||
setText(message, continuationText(next));
|
||
setAttr(message, 'role', next.error ? 'alert' : 'status');
|
||
retry.hidden = !next.error;
|
||
more.hidden = !next.hasMore || !!next.error;
|
||
more.setAttribute('aria-disabled', String(next.loading || recovering));
|
||
if (showsEmpty) empty.hidden = recovering || next.loading || !!next.error || next.hasMore || next.loaded > 0;
|
||
if (focusAfterLoad !== null && !next.loading) settleLoadFocus(next);
|
||
if (!selection && next.items.length) inspect(next.items[0]);
|
||
scheduleLoad();
|
||
}
|
||
const stream = createImageStream({ api, fetchPage, onChange: renderState, restore: visit ? {filters, state:visit.state} : undefined });
|
||
const refreshTagged = followImageTagSaves({scope, stream, inspection, selection:() => selection, filtered:() => !embedded && !recovering && Boolean(filters.tags.length || filters.q),
|
||
onRefreshing:busy => more.setAttribute('aria-disabled', String(busy || Boolean(state?.loading) || recovering))});
|
||
scope.cleanup(() => {
|
||
stream.dispose();
|
||
for (const video of body.querySelectorAll('video')) releaseVideo(video);
|
||
});
|
||
function pressLoad() {
|
||
// A refresh re-reads the loaded range: Load more waits for it (and focus stays where it is, M3).
|
||
if (recovering || state?.loading || stream.refreshing) return;
|
||
focusAfterLoad = state?.loaded ?? 0;
|
||
stream.loadMore();
|
||
}
|
||
/** The concept focuses the first appended image; focus never stays on a control that just hid. */
|
||
function settleLoadFocus(next) {
|
||
const first = focusAfterLoad;
|
||
focusAfterLoad = null;
|
||
const active = document.activeElement;
|
||
// Only while focus is still on the pressed control: a viewer or another control the user moved to keeps it.
|
||
const stranded = !active || active === document.body || active === more || active === retry;
|
||
if (!stranded) return;
|
||
if (next.error) { retry.focus(); return; }
|
||
// Without scrolling: the visible cards keep their place (bounded-DOM anchor); the next arrow key reveals it.
|
||
if (next.loaded > first) focusImage(first, false, {scroll:false});
|
||
else if (more.hidden) {
|
||
if (next.loaded) focusImage(next.loaded - 1, false, {scroll:false});
|
||
else focusFallback.focus({preventScroll:true});
|
||
}
|
||
}
|
||
scope.listen(more, 'click', pressLoad);
|
||
scope.listen(retry, 'click', pressLoad);
|
||
function maybeLoad() {
|
||
if (!observer || recovering || scope.signal.aborted || !state?.hasMore || state.loading || state.error || main.querySelector('#viewer-dialog[open]')) return;
|
||
const bounds = continuation.getBoundingClientRect();
|
||
if (bounds.top <= window.innerHeight + 250 && bounds.bottom >= 0) stream.loadMore();
|
||
}
|
||
function scheduleLoad() {
|
||
if (!scope.signal.aborted && !loadFrame) loadFrame = requestAnimationFrame(() => { loadFrame = 0; maybeLoad(); });
|
||
}
|
||
if (typeof IntersectionObserver === 'function') {
|
||
observer = new IntersectionObserver(entries => {
|
||
if (entries.some(entry => entry.isIntersecting)) maybeLoad();
|
||
}, { rootMargin: '250px' });
|
||
observer.observe(continuation);
|
||
}
|
||
function updateScope() {
|
||
scopeText.textContent = ` ${scopeLabel(filters, roots)}`;
|
||
toolbar?.setActiveFilters(activeRefinements(filters));
|
||
}
|
||
/** No selected file; `keepPanel` (recovering sources) leaves the panel's details shown. */
|
||
function dropSelection({keepPanel = false} = {}) {
|
||
for (const video of details.querySelectorAll('video')) releaseVideo(video);
|
||
if (!keepPanel) {
|
||
inspection.clear();
|
||
detailInspector?.dispose(); detailInspector = null;
|
||
details.replaceChildren(noSelection());
|
||
}
|
||
selection = null;
|
||
}
|
||
function reset() {
|
||
mediaViewer.stopSlideshow();
|
||
main.querySelector('#viewer-dialog[open]')?.close();
|
||
dropSelection({keepPanel:recovering});
|
||
focusAfterLoad = null;
|
||
// The ruled selection lifetime: a replaced collection may no longer hold the checked files.
|
||
bar?.clear();
|
||
// A toolbar change while discovery is still pending keeps the saved Source and Folder; the settled discovery
|
||
// then lists the view with every current value (#249 M3).
|
||
if (savedScopePending && !discoverySettled) { updateScope(); return; }
|
||
settleSavedScope();
|
||
updateScope();
|
||
stream.reset(filters, {load:!recovering});
|
||
}
|
||
/** A saved view's Source and Folder apply only while the discovered sources still list them (#249 D16). */
|
||
function settleSavedScope() {
|
||
if (!savedScopePending) return;
|
||
savedScopePending = false;
|
||
if (filters.root !== 'all' && !roots.some(root => String(root.index) === filters.root)) filters.root = 'all';
|
||
if (!folderOptions(filters.root).some(([path]) => path === filters.subfolder)) filters.subfolder = '';
|
||
}
|
||
/** A panel tag chip (D21): the Images Tags filter becomes exactly that tag, as "Refine this view" would set it. */
|
||
function filterByTag(tag) {
|
||
if (recovering || !tag.trim() || tag.includes(',')) return;
|
||
if (filters.tags.length === 1 && filters.tags[0] === tag) return;
|
||
filters.tags = [tag];
|
||
reset();
|
||
}
|
||
/** "Refine this view": Source, Folder, Media and Tags, the filters the old field row held (D14). */
|
||
function openFilters(trigger) {
|
||
if (recovering) return;
|
||
refine = openRefineDialog({scope, trigger, fields:[
|
||
{key:'source', options:sourceOptions()},
|
||
{key:'folder', options:folderOptions('all'), optionsFor:folderOptions},
|
||
{key:'media', options:MEDIA_OPTIONS},
|
||
{key:'tags'},
|
||
], values:{source:filters.root, folder:filters.subfolder, media:filters.media, tags:filters.tags.join(', ')},
|
||
onApply:applyRefinement, onClear:cleared => {
|
||
toolbar.setValue({category:cleared.category});
|
||
applyRefinement(cleared);
|
||
}});
|
||
}
|
||
function sourceOptions() {
|
||
return [['all', 'All sources'], ...roots.map(root => [String(root.index), root.label])];
|
||
}
|
||
/** The chosen Source's folders, as the old field row reloaded them; every folder under All sources. */
|
||
function folderOptions(source) {
|
||
const root = source === 'all' ? null : roots.find(item => String(item.index) === source);
|
||
return [['', 'All output folders'], ...(root?.subfolders ?? folders).map(path => [path, path])];
|
||
}
|
||
/** Apply the dialog's values (Clear adds `category`); unchanged filters keep the loaded page, as the toolbar does. */
|
||
function applyRefinement({source, folder, media, tags, category = filters.category}) {
|
||
if (recovering) return;
|
||
const next = {root:source, subfolder:folder, media, category,
|
||
tags:[...new Set(tags.split(',').map(tag => tag.trim()).filter(Boolean))]};
|
||
const same = Object.entries(next).every(([key, value]) => key === 'tags'
|
||
? value.length === filters.tags.length && value.every((tag, index) => tag === filters.tags[index])
|
||
: filters[key] === value);
|
||
if (same) return;
|
||
Object.assign(filters, next);
|
||
reset();
|
||
}
|
||
function setControlsDisabled(disabled) {
|
||
for (const control of [...toolbarControls, more, retry]) control.disabled = disabled;
|
||
if (importButton) importButton.disabled = disabled;
|
||
}
|
||
/**
|
||
* Import → "Scan an output folder" (D15): rescan the output roots, then reload the options and the listing. A toast
|
||
* says it started and how it ended; meanwhile a reopened Import dialog shows Rescan as running.
|
||
*/
|
||
async function rescan() {
|
||
if (rescanning || recovering || scope.signal.aborted) return;
|
||
rescanning = true;
|
||
optionsRequest?.abort(); optionsRequest = null;
|
||
showWorkspaceToast(RESCAN_STARTED);
|
||
try {
|
||
const result = await api.post('/prompt_manager/gallery/rescan', {}, {signal:scope.signal});
|
||
if (scope.signal.aborted) return;
|
||
const [found] = await Promise.all([loadOptions(), loadCategories()]);
|
||
if (scope.signal.aborted) return;
|
||
renderLoadStatus();
|
||
if (found) reset();
|
||
if (!scope.signal.aborted) announceRescan(rescanFinished(result));
|
||
} catch {
|
||
// A failed rescan leaves the collection and any discovery alert as they were.
|
||
if (!scope.signal.aborted) announceRescan(RESCAN_FAILED);
|
||
} finally {
|
||
rescanning = false;
|
||
importDialog?.setRescanBusy(false);
|
||
}
|
||
}
|
||
/**
|
||
* D42: the concept's toast stays fixed at the bottom, so a discovery alert the rescan leaves is scrolled clear of
|
||
* the toast's band (its `scroll-margin-block-end`) only when it is in that band; elsewhere the page stays put.
|
||
*/
|
||
function announceRescan(message) {
|
||
showWorkspaceToast(message);
|
||
if (optionsStatus.hidden) return;
|
||
const {top, bottom} = optionsStatus.getBoundingClientRect();
|
||
const band = parseFloat(getComputedStyle(optionsStatus).scrollMarginBlockEnd) || 0;
|
||
if (bottom > innerHeight - band && top < innerHeight) optionsStatus.scrollIntoView({block:'nearest', inline:'nearest'});
|
||
}
|
||
async function refreshInspectionCollection() {
|
||
if (scope.signal.aborted) return;
|
||
// Numeric roots may now name another source; retire the old stream first.
|
||
recovering = true;
|
||
filters.root = 'all';filters.subfolder = '';
|
||
if (toolbar) filters.q = toolbar.value().q.trim();
|
||
roots = [];folders = [];
|
||
setControlsDisabled(true);
|
||
sourcesRetry = null;
|
||
renderLoadStatus();
|
||
reset();
|
||
const discovery = loadOptions(), request = optionsRequest;
|
||
const found = await discovery;
|
||
if (scope.signal.aborted || request !== optionsRequest) return;
|
||
renderLoadStatus();
|
||
if (!found) return;
|
||
recovering = false;
|
||
setControlsDisabled(false);
|
||
reset();
|
||
}
|
||
function renderLoadStatus() {
|
||
const text = loadFailure(sourcesRetry, categoriesFailed);
|
||
setText(optionsStatus, text);
|
||
optionsStatus.hidden = !text;
|
||
}
|
||
/** Discover the sources and folders; the caller renders the outcome with renderLoadStatus. */
|
||
async function loadOptions() {
|
||
optionsRequest?.abort();
|
||
const request = new AbortController(); optionsRequest = request;
|
||
try {
|
||
// Every source's folders (with ancestors), listed per source too, so the dialog can follow its Source.
|
||
const params = new URLSearchParams({mode:'workspace', include_ancestors:'true'});
|
||
const data = await api.get(`/prompt_manager/gallery/subfolders?${params}`, {signal:request.signal});
|
||
if (scope.signal.aborted || request !== optionsRequest) return false;
|
||
if (!Array.isArray(data?.roots) || !Array.isArray(data.subfolders)) throw new TypeError('Invalid image sources');
|
||
const paths = list => Array.isArray(list) ? list.filter(path => typeof path === 'string' && path) : null;
|
||
roots = data.roots.filter(root => Number.isSafeInteger(root?.index) && typeof root.label === 'string')
|
||
.map(root => ({index:root.index, label:root.label, subfolders:paths(root.subfolders)}));
|
||
folders = paths(data.subfolders);
|
||
refine?.setOptions('source', sourceOptions());
|
||
updateScope();
|
||
sourcesRetry = null;
|
||
return true;
|
||
} catch {
|
||
if (scope.signal.aborted || request !== optionsRequest) return false;
|
||
sourcesRetry = recovering ? RETRY_REFRESH : RETRY_RESCAN;
|
||
return false;
|
||
}
|
||
}
|
||
/** The toolbar's categories are the Library's (the linked positive's category, D13). */
|
||
async function loadCategories() {
|
||
if (!toolbar) return;
|
||
categoryRequest?.abort();
|
||
const request = new AbortController(); categoryRequest = request;
|
||
try {
|
||
const data = await api.get('/prompt_manager/library/options', {signal:request.signal});
|
||
if (scope.signal.aborted || request !== categoryRequest) return;
|
||
if (!Array.isArray(data?.categories)) throw new TypeError('Invalid categories');
|
||
// D36: alphabetical (case-insensitive) whatever order the server sends, a restored category among them.
|
||
const names = new Set([...data.categories.filter(value => typeof value === 'string' && value), filters.category]);
|
||
names.delete('');
|
||
toolbar.setCategories([...names].sort((a, b) => a.localeCompare(b, 'en-US', {sensitivity:'base'}) || (a < b ? -1 : a > b ? 1 : 0)));
|
||
categoriesFailed = false;
|
||
} catch {
|
||
if (scope.signal.aborted || request !== categoryRequest) return;
|
||
categoriesFailed = true;
|
||
}
|
||
}
|
||
scope.cleanup(() => { optionsRequest?.abort(); categoryRequest?.abort(); });
|
||
updateScope();
|
||
// The page's one discovery alert is written once both first loads settled (#249 final review m6).
|
||
if (!embedded) Promise.all([loadOptions(), loadCategories()]).then(() => {
|
||
if (scope.signal.aborted) return;
|
||
discoverySettled = true;
|
||
renderLoadStatus();
|
||
if (savedScopePending) reset();
|
||
});
|
||
if (visit) {
|
||
renderState(stream.state);
|
||
const selected = stream.state.items.find(image => imageKey(image) === selection);
|
||
if (selected) inspect(selected);
|
||
restoreFrame = requestAnimationFrame(() => {
|
||
if (!scope.signal.aborted) window.scrollTo(0, visit.scrollY);
|
||
});
|
||
if (visit.state.loading || visit.state.error) stream.loadMore();
|
||
} else if (savedScopePending) updateScope();
|
||
else reset();
|
||
/** D6: the selected file's prompt pair, only once its inspection loaded with both roles resolved. */
|
||
function selectedPair() {
|
||
const {record, prompts, loading, error, refreshRequired} = inspection.state;
|
||
if (scope.signal.aborted || selection === null || loading || error || refreshRequired || record?.identity?.key !== selection) return null;
|
||
const roles = promptRoles(prompts);
|
||
return Object.hasOwn(roles, 'positive') && Object.hasOwn(roles, 'negative') ? roles : null;
|
||
}
|
||
return {dispose, selectedPair, sender};
|
||
}
|