* feat(workspace): shared concept toolbar and dialogs
Add the concept's shared page toolbar (search.toolbar with the search
field, category filter, sort and Filters) and its dialogs in one modal
shell: "Refine this view" (Source / Folder / Media / Tags, Apply filters),
"Import & inspect" with only the real operations (Open inspector, Rescan),
and the "Copy prompt" select-to-copy fallback. The sort lists the
concept's three options first (D14); there is no Save view (D16). Every
dialog returns focus to its trigger on close or Escape.
Refs #249
* fix(workspace): bind shared dialogs to the page and its route
- Drop the invented Refine note; every field is real (D14).
- Ignore a late close event once the shell was reopened or replaced, so
an action that opens the next dialog keeps it open.
- Dialog openers require the page scope; disposing it closes and removes
the shell unless a newer page's dialog is open. Every route change
closes the shared dialog before the next page mounts.
- Clear filters also reports category '' so the page clears the toolbar
category, as the concept does.
- The toolbar requires its scope and falls back to the first sort for an
unknown value; dialog callbacks are validated up front.
Refs #249
* feat(images): concept toolbar, filter row and caption
The Images page now renders the approved mock's heading, shared toolbar,
filter row, section caption and infinite continuation (#249, Task C2).
- Heading: "Your generations, their prompts, and the next idea." with
Import (upload icon) before New prompt (primary).
- Toolbar (shared mountToolbar): search over filenames, linked prompt
text, titles and tags; category (the Library's categories); sort
Recently added / Name A–Z / Highest rated, then Oldest first and
Name Z–A (D14).
- Filter row: Grid/List/Masonry segmented control, Thumbnail size,
the scope chip ("All output folders" or "<source> · <folder>") and
"Group by positive prompt →".
- Caption: "N of M images · K positive prompts" from positive_count; a
plain cursor page keeps the first page's count and an unknown count
hides the "· K positive prompts" part. The date span shows
"<Today|Yesterday|weekday> · <Month D>" of the newest loaded result
under a date sort and is hidden otherwise (D17).
- Continuation: "N of M images · more load as you scroll" with Load
more, the concept's end copy, Retry for a failed page, and the
concept's "K more images loaded. N of M." toast.
- The listing sends category, tags and sort=rating (PR B params).
Old control -> new control:
- "Search filenames" field -> toolbar search "Search workspace"
(placeholder "Search prompts, tags, filenames…"), also matching
prompt text and tags
- Source select -> Filters -> "Refine this view" Source
- Folder select -> Refine Folder (all sources' folders and ancestors)
- Media select -> Refine Media
- (new) Tags -> Refine Tags; Category -> toolbar category select
- Sort select (Newest/Oldest/Filename A–Z/Z–A) -> toolbar sort
(Recently added/Oldest first/Name A–Z/Name Z–A, plus Highest rated)
- Layout buttons -> .segmented Grid/List/Masonry in the filter row
- Thumbnail size field -> label.small + select#image-size
- "Group by positive prompt" link -> button.chip "Group by positive
prompt →" (#/library)
- Refresh -> Import -> "Scan an output folder" -> Rescan (D15)
- "Current gallery" link -> removed; Overview's tool cards link the
legacy gallery (D29)
- "All images" h2 + count -> .section-caption #result-count
- .image-continuation -> .infinite-continuation (Retry kept)
Legacy behavior kept: video items, keyboard grid navigation, scroll and
filter restoration, bounded DOM, continuation retry, source-change
recovery (now disabling the toolbar, Filters and Import). The Filters
and Import dialogs close on route change and browser Back.
The shared toolbar (C1) called .some() on select.options, which is an
HTMLOptionsCollection in a browser (only the unit tests' fake DOM gave
an array); setValue and setCategories now spread it first. The layout
segmented control may wrap at extreme zoom (D31) instead of scrolling
the 390px page sideways.
The retired .image-filters, .image-view-controls, .image-toolbar,
.image-layouts, .image-collection, .image-continuation and duplicated
.image-workspace grid rules are gone from images.css.
* test(workspace): model select.options as a browser collection
The toolbar units' fake DOM returned select.options as an Array, so the
toolbar's .some() call passed there while it threw in every browser
(fixed in 12228e2). options is now an indexed, iterable, frozen
HTMLOptionsCollection-like object without Array methods; against the C1
toolbar three units fail with "sort.options.some is not a function".
The units also assert that an unknown sort falls back to the first
option and that a still-listed category survives a category refresh.
* fix(images): concept Load more focus, empty state and review rulings
Review of #249 C2:
- Load more and Retry focus the first appended image, as the concept
does (app.js loadMoreImages). Focus moves without scrolling so the
visible cards keep their place (bounded-DOM anchor), and only while
focus is still on the pressed control: a viewer or a field the user
moved to keeps it. When a last page adds nothing and the button hides,
focus goes to the last image, never to the page; a failed page focuses
Retry.
- The concept's empty state beside the grid: .empty "No matching
images. Try another search or category."
- D17: the caption date shows only under Newest first (", YYYY" outside
the current year) and is hidden under Oldest first and the name and
rating sorts.
- en-US number grouping in the embedded count too.
- Refine "Folder" defaults to the concept's "All output folders". It is
not narrowed by Source: the concept has no Source field, and the list
holds every source's folders, so any pair can be chosen in one dialog.
- The shared toast moves to toast.mjs; library-editor re-exports it.
- The D32 overlay (extreme zoom) wraps the layout segmented control and
the continuation row instead of pushing them out of the 390px column.
- The legacy gallery checks moved to Overview's "Open existing image
gallery" card (D29).
Mapping additions: grid with no results -> .empty concept copy beside
the grid; Load more press -> focus the first new image (concept).
* feat(images): concept image cards; image opens the viewer
Cards are the concept media card: .media-art > button.image-open with the
image or video, and .media-info with the D10 title (linked title only when
the link is confirmed, else the filename; title attribute = path), the D11
subtitle "W x H · EXT · Seed N" (seed shown as the listing's string) and an
Inspect info button. The byte size and the Preview button are gone.
Activating the image (click, Enter, Space) opens the viewer and focus
returns to it on Escape; Info selects the image into the panel (D19).
Arrow, Home and End navigation, bounded rendering and scroll restoration
are kept.
Columns and gap now come from the concept grid's computed style
(gridMetrics) instead of a production breakpoint table, so the concept
breakpoints apply; a 120px minimum card bounds extreme zoom (D3, D31).
images.css card rules are retired into marked overlay rules. The scope
chip reads "All output folders" when no folder is chosen (D14).
* fix(images): pair-linked cards take the positive's title; concept Info, alt and size
- Pair links title the card, inspector and viewer from the linked positive's
Library title or confirmed first line, never the pair title (the negative
variant's name). The card now equals the concept card, title included.
- Info drops aria-pressed; the card's .selected carries selection, as in the
concept.
- Card images take the card title as alt and the listing's width/height.
- One shared minimum card width for layout and the narrow-card class.
- A debounced search that lands after a sort change no longer reloads page 1.
- 200% zoom test also runs at an 800px viewport and device scale 2.
Refs #249
* feat(images): concept hover zoom
* feat(images): favorite images from the card
* feat(images): concept viewer shell
* fix(images): one favorite request per file across leaving and returning
The pending set and the receiver of each answer now live at module level
beside the saved visit. A press on a returned Images page waits for the
request the earlier page sent, and its success or rollback reaches the
card on screen, or the saved visit when no Images page is mounted.
* fix(images): mark a star busy while its favorite request is pending
The star carries aria-disabled="true" until the answer arrives, also on a
card rendered after returning to Images, so the ignored second press is
announced as unavailable instead of doing nothing silently.
* perf(images): repaint one card on a favorite toggle instead of the collection
stream.updateItem tells onChange which item it patched, and the Images
page then skips the full layout pass (computed style, grid metrics and
layout over every loaded item) because no card changed size or place.
* docs(images): say the lone-star overlay rule is interim until the checkbox PR
* test(images): concept comparison for the Images page
images-concept.spec.mjs compares the production Images page with the
immutable concept on the concept-shaped fixture: heading, toolbar, filter
row, caption, grid, the first six cards, continuation and panel box in
Grid, List and Masonry, at 1600x1100 and 390x844, dark and light, normal
and reduced motion; plus hover zoom, the viewer title, focus restore,
Info selection, search and Load more with its toast. mapImagesConcept
applies only recorded deviations (D3, D8 and D16 follow-up PRs, D9, D10,
D14, D15, D17, D29, D31, D32); removed row items flow again from the
concept's own boxes. A mutation check proves the comparison fails on a
.media-info padding change and on removed Inspect buttons.
Corrections the comparison demonstrated:
- the grid and continuation carry the concept's ids (image-grid,
gallery-continuation);
- bounded rendering reserves the card footer at its fractional height:
offsetHeight rounded a wrapped 67.5px row up, so at 390px every card
was a pixel taller and the grid 6px taller than the concept.
Two mismatches wait for a ruling and are pinned on both sides: the
category order (concept prompt order, production alphabetical) and the
singular count line ("1 positive prompt").
* fix(images): ignore sub-pixel noise when the measured card footer grows
Under page zoom the fractional footer height (rect / scale) can carry float
noise above the stored value, which relaid the grid and scrolled for nothing.
* test(images): map D35-D37 and widen the Images concept comparison
- D35 (singular counts) and D36 (alphabetical categories) are mapped
deviations instead of pinned values; a search for exactly one image
checks both singular nouns, and a one-image Load more checks the toast
and continuation.
- Grid, cards and panel at 1200x900 (2 columns, 275px panel) and
1800x1100 (4 columns); Large and Compact join the layout loop.
- Masonry tops and heights compare unrounded within one layout unit per
card above in the column (D3), not as rounded integers.
- The Save view and sample-tag re-layout is checked against the concept
page with those items removed at runtime.
- The Load more row is compared before the press in both documents (D37).
- Two seedless fixture images (seedless_images on the concept reset)
prove every row reserves the tallest footer (D3).
- D10 paths come from the fixture manifest; the D8 star margin is mapped;
list-row derivations cite D3 and D9.
* fix(images): search never matches a pair's own variant title
Search covers the filename, the linked positive's text and Library title,
and its tags (#249 D12). The pair title names a negative variant, so a
variant name alone no longer admits the positive's images.
* fix(viewer): keep the Media controls group and drop a stale position description
The concept viewer toolbar is again a named group (#249 D34 #8), and
Previous/Next are described by the position line only while a single
item is loaded.
* docs(history): drop the remaining-polish notes the concept viewer and cards closed
The viewer now takes the concept stage and toolbar, and Images cards open
the viewer, select into the panel and favorite. Only the select checkbox
(#249 D8 follow-up) and the tag button (#249 D9) stay outside #209.
* test(images): the singular copy when scrolling loads one image; countCopy in the shared inventory helper
* refactor(images): retire the replaced images.css rules and lint the kept page sheets
The unused .image-facts rules go. The three prompt-block overrides on
concept selectors are marked #249 D22 interim until PR D deletes the
file, and every kept page stylesheet now passes the overlay lint.
* test(images): the extreme-zoom anchor probe reads the fractional footer measurement
Since the concept comparison (#249 C7) the grid measures footers with
getBoundingClientRect, so the probe that hooked offsetHeight never fired.
* test(images): cover the masonry fallback when a finite size underflows its ratio
* docs(images): concept Images page and recorded deviations
TESTING.md documents the Images page controls, the recorded #249
deviations and how the earlier workspace filters moved, and notes that
every kept page stylesheet is linted. The frontend coverage baseline
adds the toast, toolbar and workspace dialog modules.
* fix(images): show that Import → Rescan runs, and how it ended
The old Refresh button disabled itself while /gallery/rescan ran; Import →
Rescan closed its dialog and showed nothing. Now a toast says the rescan
started ("Rescanning output folders…") and how it ended ("Rescan finished.
N files in M output folders.", from the scan's own total and roots, or
"Rescan could not finish. Try again."). A reopened Import dialog shows
Rescan as "Rescanning…" and aria-disabled, and ignores a press on it.
Failing before: the held-rescan browser test saw no toast and no busy
state; the dialog unit test found no "Rescanning…" button.
* fix(images): rewrite the live status only when its text changes
A star press republishes the stream, and the textContent setter replaced
the continuation status, the count and the caption date with the same
text, so a polite role="status" region could announce it again. Text and
the role attribute are now written only when they change.
Failing before: a MutationObserver saw 10 records on those nodes after a
favorite toggle; now none.
* fix(images): Refine's Folder list follows the chosen Source
The workspace subfolder discovery returned only the union of every
source's folders, so "Source: temp" could be paired with a folder that
exists only under output and silently match nothing. In workspace mode
each root now lists its own folders, and "Refine this view" offers only
the chosen Source's folders: changing Source keeps a folder it also has
and otherwise returns Folder to "All output folders", as the old field
row did when it reloaded a Source's folders.
Failing before: the API test found no per-root folders (KeyError), the
dialog unit test and the browser test still offered output-only folders
under the input source.
* fix(images): an unchanged Refine apply keeps the loaded page
"Apply filters" (and "Clear filters" with nothing set) reset the stream,
refetched the first page and dropped the reader's scroll position even
when no filter changed. Like the toolbar's equality guard, an unchanged
refinement now does nothing.
Failing before: the browser test counted one listing fetch after an
unchanged Apply; now none, and the loaded cards stay in place.
* fix(images): one discovery alert when sources and categories both fail
With the server unreachable on load, the sources and the categories
status paragraphs each fired role="alert" back to back. The page now
keeps one alert, written once both first loads settled, naming whatever
failed ("Sources, folders and categories could not be loaded. Rescan
from Import to retry." when both did).
Failing before: getByRole('alert') resolved to two elements.
* fix(images): sort toolbar categories alphabetically on the client
D36 promises alphabetical real categories, which held only while the
server sorted them and a restored category was among its list. The page
now sorts them case-insensitively itself, a restored category included.
Failing before: the toolbar listed a server's [zeta, Alpha, beta] in
that order.
* refactor(db): drop the unused pair title from the link summary query
_link_summary has not read the pair's own title since the card took the
linked positive's Library title (D10), so the query no longer selects
it; the row indexes and the stale comment are updated. All values stay
bound.
Failing before: the summary SQL still selected pp.title.
* test(images): end negative checks on real signals, not fixed sleeps
The "no second request" checks waited a fixed 150 ms or 1000 ms and the
hover probe 450 ms, which can pass vacuously on a slow Firefox or WebKit
run. They now read the fetches the page's code started (the API client
calls fetch in the same task as the press), wait for a timer of the
toolbar's own debounce delay set after the debounced report, and wait
for the hover transition to finish.
Checked by mutation: without the favorite pending guard or the toolbar
equality guard, the rewritten checks fail.
* docs(testing): record the Rescan feedback, Source-bound folders and category sort
The Images contract now names the Rescan toasts and busy state (D15),
the Folder list that follows Source and the no-op unchanged refinement
(D14), and the page-side category sort (D36).
* test(viewer): escape every regex metacharacter in the filename match
* fix(viewer): title a linked card at once instead of waiting for its inspection
On a slow runner the viewer showed only the filename until the inspection
answered, while the concept titles it immediately. The card's linked
title is already loaded, so the header uses it on open.
The favorite test now waits for the first request to settle before the
Space press, which the one-request-per-file guard otherwise ignores.
* fix(images): cap the search at the listing API's 500 characters
A longer paste was sent as is, the API rejected it and the collection
showed "Images could not be loaded". The legacy search capped it.
374 lines
20 KiB
JavaScript
374 lines
20 KiB
JavaScript
/**
|
||
* Native recipe editor dialogs: New prompt, Edit recipe metadata, Create text
|
||
* revision, Add a negative variant, and the pair archive confirmation.
|
||
*
|
||
* Markup, labels, order and native datalists follow the approved concept. All
|
||
* reads, writes, receipts and recovery live in library-editor-state.mjs; this
|
||
* module only renders `controller.state` and forwards user actions.
|
||
*/
|
||
import { createButton } from '../shared/toolkit/core.js';
|
||
import { createLibraryEditorController } from './library-editor-state.mjs';
|
||
|
||
const TITLES = {new: 'New prompt', metadata: 'Edit recipe metadata', revision: 'Create text revision', negative: 'Add a negative variant'};
|
||
const RATINGS = [['5', '5 / 5'], ['4', '4 / 5'], ['3', '3 / 5'], ['2', '2 / 5'], ['1', '1 / 5'], ['0', 'Unrated']];
|
||
const FIELD_IDS = {title: 'recipe-title', positive_text: 'recipe-positive', negative_text: 'recipe-negative', category: 'recipe-category',
|
||
tags: 'recipe-tags', rating: 'recipe-rating', notes: 'recipe-notes'};
|
||
const SUBMITTABLE = new Set(['ready', 'write-error']);
|
||
const NEGATIVE_HELP = 'Leave empty for an explicitly empty negative. The positive stays unchanged.';
|
||
const NO_PAIR = 'Archive needs a selected saved negative variant.';
|
||
const ALREADY_ARCHIVED = 'This negative variant is already archived.';
|
||
const REVIEW = 'Loaded the latest saved values. Review your entries, then save.';
|
||
const REVIEW_ARCHIVE = 'Loaded the latest saved values. Review them, then archive.';
|
||
const REFRESH = ['Reload Library', 'refresh'];
|
||
// The concept has no discard confirmation (its Cancel and × simply close), so the state says it inline:
|
||
// every exit (Reload Library, Cancel, × or Escape) drops the draft.
|
||
const DISCARDS = 'Leaving this dialog discards your entries.';
|
||
// The toast lives in the shell module; re-exported for the pages that already import it from here.
|
||
export { showWorkspaceToast } from './toast.mjs';
|
||
|
||
function el(tag, text, className) {
|
||
const node = document.createElement(tag);
|
||
if (text !== undefined) node.textContent = text;
|
||
if (className) node.className = className;
|
||
return node;
|
||
}
|
||
|
||
/**
|
||
* Inline state copy and its one recovery action; `archive` selects the pair-archive
|
||
* wording. After a restore only New prompt may re-read: every other mode names an
|
||
* owner by its old numeric ID, so it offers only the Library refresh exit, which
|
||
* discards the draft.
|
||
*/
|
||
function statusOf(state, archive, mode = null) {
|
||
const nothing = archive ? 'Nothing was archived.' : 'Nothing was saved.';
|
||
const message = state.error?.message;
|
||
switch (state.phase) {
|
||
case 'initializing': return {text: 'Loading the latest saved values…'};
|
||
case 'initialization-error': return {text: `The latest saved values could not be loaded. ${nothing}`, action: ['Retry', 'retryInitialization']};
|
||
case 'saving': return {text: archive ? 'Archiving… The dialog stays open until the server answers.' : 'Saving… The dialog stays open until the server answers.'};
|
||
case 'write-error': return {text: `${archive ? 'Not archived' : 'Not saved'}: ${message} Your entries are kept.`};
|
||
case 'conflict': return {text: archive ? 'This negative variant changed since it was loaded. Reload it and review it before archiving.'
|
||
: 'This prompt changed since it was loaded. Reload it and review your entries before saving.', action: ['Reload', 'reload']};
|
||
case 'storage-changed': return mode === 'new' ? {text: `Prompt storage was restored since this dialog opened. ${nothing}`, action: ['Reload Library state', 'reload']}
|
||
: {text: `Prompt storage was restored since this dialog opened. ${nothing}${archive ? '' : ` ${DISCARDS}`}`, action: REFRESH};
|
||
case 'unknown-outcome': return {text: archive ? 'Archive could not be confirmed. Retry sends the same archive once.'
|
||
: mode === 'metadata' ? 'Save could not be confirmed. Your entries are kept; Retry reloads the latest saved values for review and sends nothing.'
|
||
: 'Save could not be confirmed. Your entries are kept; Retry sends the same save once.', action: ['Retry', 'retryUnconfirmed']};
|
||
case 'saved-refresh-error':
|
||
// A refresh that found restored storage cannot recover by re-reading; only reloading the Library view can.
|
||
if (state.error?.code === 'storage-changed') {
|
||
return {text: `${archive ? 'Archived' : 'Saved'}; Library refresh failed because prompt storage was restored. Reload the Library to see current data.`, action: REFRESH};
|
||
}
|
||
return {text: archive ? 'Archived; Library refresh failed.' : 'Saved; Library refresh failed.', action: ['Retry refresh', 'retryReconciliation']};
|
||
case 'ready': return message ? {text: message} : state.reviewRequired ? {text: archive ? REVIEW_ARCHIVE : REVIEW} : null;
|
||
default: return null;
|
||
}
|
||
}
|
||
|
||
/** One persistent inline status in the concept's .warning-note style, so live updates are announced. */
|
||
function statusLine() {
|
||
const note = el('p', '', 'warning-note');
|
||
note.id = 'library-editor-status';
|
||
note.setAttribute('role', 'status');
|
||
note.hidden = true;
|
||
return {note, set(text) {
|
||
if (note.textContent !== (text || '')) note.textContent = text || '';
|
||
note.hidden = !text;
|
||
}};
|
||
}
|
||
/** Re-parent only on a real change: moving a focused button would drop its focus. */
|
||
function setChildren(parent, nodes) {
|
||
const current = [...parent.children];
|
||
if (current.length !== nodes.length || current.some((node, index) => node !== nodes[index])) parent.replaceChildren(...nodes);
|
||
}
|
||
|
||
/** Saving or re-reading disables or removes the focused action; focus would drop to the body. */
|
||
const SETTLING = new Set(['saving', 'initializing']);
|
||
const restoredStorage = state => state.phase === 'storage-changed' || (state.phase === 'saved-refresh-error' && state.error?.code === 'storage-changed');
|
||
/**
|
||
* The action that held focus when a write or re-read began gets it back once that
|
||
* settles; when it is gone or disabled (Save after an unconfirmed write), focus moves
|
||
* to the first usable fallback, the recovery action first, and never to the body.
|
||
*/
|
||
function restoreFocus(button, state, fallbacks) {
|
||
if (!button || SETTLING.has(state.phase)) return button;
|
||
if (state.phase !== 'complete' && (!document.activeElement || document.activeElement === document.body)) {
|
||
[button, ...fallbacks].find(node => node?.isConnected && !node.disabled)?.focus();
|
||
}
|
||
return null;
|
||
}
|
||
/** Remember a focused dialog action while the phase settles. */
|
||
function settlingFocus(actions, state, current) {
|
||
return SETTLING.has(state.phase) && actions.contains(document.activeElement) ? document.activeElement : current;
|
||
}
|
||
|
||
function field(label, control, id) {
|
||
const wrapper = el('div', undefined, 'field');
|
||
const caption = el('label', label);
|
||
caption.htmlFor = id;
|
||
control.id = id;
|
||
wrapper.append(caption, control);
|
||
return wrapper;
|
||
}
|
||
function datalist(id, values) {
|
||
const list = el('datalist');
|
||
list.id = id;
|
||
list.append(...values.map(value => Object.assign(document.createElement('option'), {value})));
|
||
return list;
|
||
}
|
||
|
||
/**
|
||
* `onReconciled(result, {outcome, draft})` receives the reconciled result with the
|
||
* controller's outcome and submitted draft. `onRefreshRequired()` is the explicit
|
||
* exit when prompt storage was restored; the dialog closes first.
|
||
*/
|
||
export function createLibraryEditor({api, parentScope, onCommitted = () => {}, onReconciled = () => {},
|
||
onRefreshRequired = () => window.location.reload()}) {
|
||
let session = null, disposed = false;
|
||
const dialog = el('dialog', undefined, 'library-editor');
|
||
dialog.setAttribute('aria-labelledby', 'library-editor-title');
|
||
const header = el('div', undefined, 'dialog-header');
|
||
const title = el('h2');
|
||
title.id = 'library-editor-title';
|
||
const close = createButton('×');
|
||
close.setAttribute('aria-label', 'Close dialog');
|
||
const body = el('div');
|
||
header.append(title, close);
|
||
dialog.append(header, body);
|
||
|
||
const busy = () => session?.controller.state.phase === 'saving';
|
||
close.addEventListener('click', () => finish());
|
||
dialog.addEventListener('cancel', event => {
|
||
event.preventDefault();
|
||
if (!busy()) finish();
|
||
});
|
||
// A browser may still force-close a modal; treat that as a dismissal without claiming rollback.
|
||
dialog.addEventListener('close', () => {if (!dialog.open) finish();});
|
||
|
||
function finish() {
|
||
if (!session) return;
|
||
const {controller, trigger, views} = session;
|
||
session = null;
|
||
views.abort();
|
||
controller.dispose();
|
||
if (dialog.open) dialog.close();
|
||
dialog.remove();
|
||
if (trigger?.isConnected) trigger.focus();
|
||
}
|
||
|
||
function show(heading) {
|
||
title.textContent = heading;
|
||
close.disabled = false;
|
||
if (!dialog.isConnected) document.body.append(dialog);
|
||
if (!dialog.open) dialog.showModal();
|
||
close.focus();
|
||
}
|
||
|
||
/** The one recovery action for a phase, created once per view and reused across renders. */
|
||
function recoveryButton(cache, action, signal) {
|
||
if (!action) return null;
|
||
const [label, method] = action;
|
||
if (!cache.has(label)) {
|
||
const control = createButton(label);
|
||
control.addEventListener('click', () => {
|
||
const {controller} = session;
|
||
if (method === 'refresh') {finish(); onRefreshRequired(); return;}
|
||
if (method === 'reload') controller.reloadOwner({keepDraft: true});
|
||
else controller[method]();
|
||
}, {signal});
|
||
cache.set(label, control);
|
||
}
|
||
return cache.get(label);
|
||
}
|
||
|
||
function controllerFor(mode, positiveId, pairId) {
|
||
const controller = createLibraryEditorController({api, mode, positiveId, pairId, onCommitted,
|
||
onReconciled: result => onReconciled(result, {outcome: controller.state.outcome, draft: controller.state.draft}),
|
||
onChange: state => session?.render(state)});
|
||
return controller;
|
||
}
|
||
|
||
function editorView({mode, positiveId, pairId, draft}) {
|
||
const views = new AbortController();
|
||
const controller = controllerFor(mode, positiveId, pairId);
|
||
const negativeOnly = mode === 'negative';
|
||
const readOnly = mode === 'metadata';
|
||
const form = el('form');
|
||
const controls = {};
|
||
const textarea = (name, required = false) => {
|
||
const node = el('textarea');
|
||
node.required = required;
|
||
node.readOnly = readOnly && (name === 'positive_text' || name === 'negative_text');
|
||
return controls[name] = node;
|
||
};
|
||
const input = (name, required = false) => {
|
||
const node = el('input');
|
||
node.required = required;
|
||
return controls[name] = node;
|
||
};
|
||
if (!negativeOnly) {
|
||
form.append(field('Title', input('title', true), FIELD_IDS.title),
|
||
field('Positive prompt', textarea('positive_text', true), FIELD_IDS.positive_text));
|
||
}
|
||
form.append(field(negativeOnly ? 'Negative prompt' : 'Negative prompt (optional)', textarea('negative_text'), FIELD_IDS.negative_text));
|
||
const categories = datalist('categories', []), tags = datalist('tag-options', []);
|
||
if (!negativeOnly) {
|
||
const columns = el('div', undefined, 'two-col');
|
||
const category = input('category'), tagInput = input('tags');
|
||
category.setAttribute('list', 'categories');
|
||
tagInput.setAttribute('list', 'tag-options');
|
||
columns.append(field('Category', category, FIELD_IDS.category), field('Tags, separated by commas', tagInput, FIELD_IDS.tags));
|
||
const rating = controls.rating = el('select');
|
||
for (const [value, text] of RATINGS) rating.add(new Option(text, value));
|
||
form.append(columns, categories, tags, field('Rating', rating, FIELD_IDS.rating), field('Notes', textarea('notes'), FIELD_IDS.notes));
|
||
} else form.append(el('p', NEGATIVE_HELP, 'small'));
|
||
const line = statusLine(), recovery = new Map();
|
||
const actions = el('div', undefined, 'dialog-actions');
|
||
const revise = createButton('Create text revision'), archive = createButton('Archive…', 'danger');
|
||
const cancel = createButton('Cancel'), save = createButton('Save', 'ca-primary');
|
||
save.type = 'submit';
|
||
form.append(line.note, actions);
|
||
|
||
for (const [name, node] of Object.entries(controls)) {
|
||
node.addEventListener(node.tagName === 'SELECT' ? 'change' : 'input', () => {
|
||
controller.setField(name, name === 'rating' && node.value === '0' ? null : node.value);
|
||
}, {signal: views.signal});
|
||
}
|
||
form.addEventListener('submit', event => {
|
||
event.preventDefault();
|
||
controller.submit();
|
||
}, {signal: views.signal});
|
||
cancel.addEventListener('click', () => finish(), {signal: views.signal});
|
||
revise.addEventListener('click', () => open({mode: 'revision', positiveId, pairId, trigger: session.trigger}), {signal: views.signal});
|
||
archive.addEventListener('click', () => archiveView(), {signal: views.signal});
|
||
if (!negativeOnly) loadVocabulary(tags, views.signal);
|
||
|
||
let categoryKey = null, refocus = null;
|
||
function render(state) {
|
||
for (const [name, node] of Object.entries(controls)) {
|
||
const value = name === 'rating' ? String(state.draft.rating ?? 0) : state.draft[name];
|
||
if (node.value !== value) node.value = value;
|
||
}
|
||
const key = state.categories.join('\n');
|
||
if (key !== categoryKey) {
|
||
categoryKey = key;
|
||
categories.replaceChildren(...datalist('', state.categories).children);
|
||
}
|
||
const saving = state.phase === 'saving';
|
||
refocus = settlingFocus(actions, state, refocus);
|
||
save.disabled = !SUBMITTABLE.has(state.phase);
|
||
cancel.disabled = close.disabled = saving;
|
||
// After a restore the numeric IDs may name another prompt; only the Library reload exit stays.
|
||
revise.disabled = saving || restoredStorage(state);
|
||
const pairProblem = readOnly && !state.pair && pairId === null ? NO_PAIR : state.pair?.archived ? ALREADY_ARCHIVED : null;
|
||
archive.disabled = !SUBMITTABLE.has(state.phase) || !state.pair || state.pair.archived;
|
||
const status = statusOf(state, false, mode);
|
||
line.set(status?.text ?? pairProblem);
|
||
if (!status && pairProblem) archive.setAttribute('aria-describedby', line.note.id);
|
||
else archive.removeAttribute('aria-describedby');
|
||
const retry = recoveryButton(recovery, status?.action, views.signal);
|
||
setChildren(actions, [...(retry ? [retry] : []), ...(readOnly ? [revise, archive] : []), cancel, save]);
|
||
refocus = restoreFocus(refocus, state, [retry, save]);
|
||
if (state.phase === 'complete') finish();
|
||
}
|
||
|
||
body.replaceChildren(form);
|
||
return {controller, views, render, start() {
|
||
if (draft) for (const [name, value] of Object.entries(draft)) controller.setField(name, value);
|
||
render(controller.state);
|
||
controller.initialize();
|
||
}};
|
||
}
|
||
|
||
async function loadVocabulary(list, signal) {
|
||
try {
|
||
const result = await api.get('/prompt_manager/tags', {signal, cache: 'no-store'});
|
||
if (signal.aborted || !Array.isArray(result.tags)) return;
|
||
list.replaceChildren(...datalist('', result.tags.filter(tag => typeof tag === 'string').map(tag => `${tag},`)).children);
|
||
} catch {
|
||
// Tag suggestions are auxiliary vocabulary; the field stays fully usable without them.
|
||
}
|
||
}
|
||
|
||
/** Swap the open Edit dialog to the pair archive confirmation, reusing its controller. */
|
||
function archiveView() {
|
||
const {controller, trigger} = session;
|
||
// An Edit save's failure or validation message is not about the pair; the confirmation starts clean.
|
||
const inherited = controller.state.error;
|
||
session.views.abort();
|
||
const views = new AbortController();
|
||
const block = el('section', undefined, 'prompt-block prompt-negative');
|
||
block.setAttribute('aria-label', 'Negative prompt');
|
||
const blockHeading = el('div', undefined, 'prompt-block-heading');
|
||
blockHeading.append(el('h3', 'Negative prompt'));
|
||
const negative = el('div');
|
||
block.append(blockHeading, negative);
|
||
const links = el('p', undefined, 'small');
|
||
const restore = el('p', 'You can restore it from Show archived in Negative variants.', 'small');
|
||
const line = statusLine(), recovery = new Map();
|
||
let refocus = null;
|
||
const actions = el('div', undefined, 'dialog-actions');
|
||
const reread = createButton('Retry');
|
||
reread.addEventListener('click', () => controller.refreshPair(), {signal: views.signal});
|
||
const cancel = createButton('Cancel'), confirm = createButton('Archive', 'danger');
|
||
cancel.addEventListener('click', () => finish(), {signal: views.signal});
|
||
confirm.addEventListener('click', () => controller.setArchive(true), {signal: views.signal});
|
||
let shownNegative = null;
|
||
|
||
function render(state) {
|
||
const {pair} = state;
|
||
if (pair && pair.negative_text !== shownNegative) {
|
||
shownNegative = pair.negative_text;
|
||
negative.replaceChildren(shownNegative === '' ? el('p', 'Empty negative prompt', 'prompt-empty') : el('pre', shownNegative, 'prompt-text'));
|
||
}
|
||
// Counts come only from the controller's fresh exact-ID pair read.
|
||
const counted = state.pairRead === 'fresh' && Boolean(pair), readFailed = state.pairRead === 'error';
|
||
if (counted) {
|
||
const images = pair.image_count, runs = pair.run_count;
|
||
links.textContent = `${images} image${images === 1 ? '' : 's'} and ${runs} recorded run${runs === 1 ? '' : 's'} stay linked.`;
|
||
}
|
||
const status = state.error && state.error === inherited ? null : statusOf(state, true);
|
||
line.set(status?.text ?? (readFailed ? 'Linked images and recorded runs could not be read. Nothing was archived.'
|
||
: counted ? null : 'Checking linked images and recorded runs…'));
|
||
const retry = recoveryButton(recovery, status?.action, views.signal) ?? (readFailed ? reread : null);
|
||
links.hidden = !counted;
|
||
const saving = state.phase === 'saving';
|
||
refocus = settlingFocus(actions, state, refocus);
|
||
confirm.disabled = !counted || !SUBMITTABLE.has(state.phase);
|
||
cancel.disabled = close.disabled = saving;
|
||
setChildren(actions, [...(retry ? [retry] : []), cancel, confirm]);
|
||
refocus = restoreFocus(refocus, state, [retry, confirm]);
|
||
if (state.phase === 'complete') finish();
|
||
}
|
||
|
||
body.replaceChildren(block, links, restore, line.note, actions);
|
||
session = {controller, trigger, views, render};
|
||
show('Archive negative variant');
|
||
controller.refreshPair();
|
||
render(controller.state);
|
||
}
|
||
|
||
function open({mode, positiveId = null, pairId = null, trigger = null, draft = null}) {
|
||
if (disposed) return;
|
||
const previous = session;
|
||
if (previous) {
|
||
// Swap the same open dialog's content, as the concept does; the old controller stops here.
|
||
previous.views.abort();
|
||
previous.controller.dispose();
|
||
}
|
||
const view = editorView({mode, positiveId, pairId, draft});
|
||
session = {controller: view.controller, trigger: trigger ?? previous?.trigger ?? null, views: view.views, render: view.render};
|
||
show(TITLES[mode]);
|
||
view.start();
|
||
}
|
||
|
||
function dispose() {
|
||
if (disposed) return;
|
||
finish();
|
||
disposed = true;
|
||
}
|
||
if (parentScope.signal.aborted) dispose();
|
||
else parentScope.signal.addEventListener('abort', dispose, {once: true});
|
||
return {open, dispose};
|
||
}
|