Merge remote-tracking branch 'origin/main' into feat/444-library-folder-or

# Conflicts:
#	TESTING.md
This commit is contained in:
Vito Sansevero
2026-10-28 19:17:22 -07:00
43 changed files with 3388 additions and 155 deletions
+2 -1
View File
@@ -78,7 +78,8 @@ export function parseCollections(data) {
}
/** The sidebar's order while a re-read is pending: an approximation of the server's name key, then id. */
const nameKey = name => name.normalize('NFC').toLowerCase().normalize('NFC');
export const collectionNameKey = name => name.normalize('NFC').toLowerCase().normalize('NFC');
const nameKey = collectionNameKey;
const ordered = list => [...list].sort((a, b) => {
const left = nameKey(a.name), right = nameKey(b.name);
return left < right ? -1 : left > right ? 1 : a.id - b.id;
+18 -1
View File
@@ -8,6 +8,7 @@ import { showWorkspaceToast } from './toast.mjs';
import { openCopyFallback } from './workspace-dialogs.mjs';
import { displayPreferences } from './preferences.mjs';
import { fallBackToOriginal, thumbnailSource } from './thumbnail-support.mjs';
import { openCollectionsDialog } from './inspector-collections.mjs';
const RAW_KEYS = ['prompt', 'workflow', 'parameters', 'comfyassets_prompt_pairs'];
const RAW_LIMIT = 'Raw metadata exceeds the response limit. Download the original file to inspect it externally.';
@@ -220,7 +221,12 @@ function prefixedChip(prefix, text) {
/** D124: the inspector's line while "Load metadata on selection" is off. */
export const DEFERRED_TEXT = 'Metadata loads when you ask for it.';
export function mountFileInspector(container, {api, sender, parentScope, variant, inline = false, promptContext = '', onTagFilter, onRetry, onRefresh, onLoad, onInteraction = () => {}, copyFallback = openCopyFallback}) {
/**
* #331 D139: with the client store `collections`, a listed file's footer ends with "Collections…", which opens its
* collections checklist; `onCollectionsChanged({added, removed})` hears the confirmed changes.
*/
export function mountFileInspector(container, {api, sender, parentScope, variant, inline = false, promptContext = '', onTagFilter, onRetry, onRefresh, onLoad, onInteraction = () => {}, copyFallback = openCopyFallback,
collections = null, onCollectionsChanged = null}) {
if (parentScope.signal.aborted) return {setState() {}, dispose() {}};
const scope = childScope(parentScope);
let contentScope;
@@ -317,6 +323,17 @@ export function mountFileInspector(container, {api, sender, parentScope, variant
});
footer.append(history);
}
const member = collections ? revealTarget(record.identity) : null;
if (member) {
const button = createButton('');
button.dataset.collections = '';
button.append(createWorkspaceIcon('folder'), ' Collections…');
// A re-render replaces the button: closing focuses the current one, else the inspector's heading.
const fallback = () => container.querySelector('button[data-collections]') ?? container.querySelector('h2');
contentScope.listen(button, 'click', () => openCollectionsDialog({scope, collections, target:member, trigger:button,
onChanged:onCollectionsChanged, focusFallback:fallback}));
footer.append(button);
}
if (!full && footer.childNodes.length) container.append(footer);
}
/**
+76
View File
@@ -0,0 +1,76 @@
/**
* The Images selection bar's collection actions (#331 D138, design §7.2–7.4):
*
* - **Add to collection** (the concept's `bulk-collection` simpleInput, app.js a1392–1398): "Add selected images to
* collection", "Collection name", Add, with the existing names offered as suggestions. A name that matches a
* collection ignoring case adds to it; a new name creates it. The selection stays and the listing is not reloaded
* (an add never changes it).
* - **Remove from collection** (beyond the concept, only while a collection filter is active): no confirmation; the
* listing then reloads through `onChanged`, keeping the checked files still listed.
*
* The routes take at most 500 explicit files. "All N matching" (#392, D135) is accepted only when every match is
* loaded and checked and there are at most 500 of them; otherwise the action toasts "Select at most 500 images." and
* sends nothing (ruling for #331 PR 3: the collection routes have no filter body).
*/
import { bulkTargets } from './images-tagging-bulk.mjs';
import { ADD_DIALOG_ACTION, ADD_DIALOG_LABEL, ADD_DIALOG_TITLE, ADD_FAILED_TOAST, FILES_NOT_FOUND_TOAST, MAX_COLLECTION_NAME_LENGTH,
REMOVE_FAILED_TOAST, TOO_MANY_TOAST, addedMessage, isCollectionGone, normalizeCollectionName, removedMessage,
writeFailure } from './collections.mjs';
import { openInputDialog } from './workspace-dialogs.mjs';
import { showWorkspaceToast } from './toast.mjs';
/**
* The files an action sends for the checked `images` (listing order): `{targets}`, or `{refusal}` with the toast.
* With `allMatching`, `total` is the listing's match count; only a fully loaded match is sent.
*/
export function collectionTargets(images, { allMatching = false, total = images.length } = {}) {
if (allMatching && total !== images.length) return { refusal: TOO_MANY_TOAST };
const targets = bulkTargets(images);
if (!targets) return { refusal: TOO_MANY_TOAST };
return targets.length ? { targets } : { refusal: FILES_NOT_FOUND_TOAST };
}
/**
* Add to collection over `images` (the checked files, taken now). `collections` is the client store; `openInput` is
* the dialog seam. A stale source (409) calls `onSourceChanged()` after its toast, so the page reloads the listing.
*/
export function openAddToCollection({ scope, collections, images, trigger = null, allMatching = false, total = images.length,
notify = showWorkspaceToast, openInput = openInputDialog, onSourceChanged = null }) {
const { targets, refusal } = collectionTargets(images, { allMatching, total });
if (refusal) { notify(refusal); return; }
openInput({ scope, trigger, title: ADD_DIALOG_TITLE, label: ADD_DIALOG_LABEL, action: ADD_DIALOG_ACTION,
maxLength: MAX_COLLECTION_NAME_LENGTH, suggestions: collections.collections.map(item => item.name),
onApply: async text => {
const name = normalizeCollectionName(text);
if (name === null) { notify(ADD_FAILED_TOAST); return; }
try {
const result = await collections.add({ name }, targets);
if (!scope.signal.aborted) notify(addedMessage(result));
} catch (error) {
if (scope.signal.aborted) return;
notify(writeFailure(error, ADD_FAILED_TOAST));
if (error?.code === 'source-changed') onSourceChanged?.();
}
} });
}
/**
* Remove the checked `images` from the open collection `collectionId`. Resolves once the toast is shown; a confirmed
* remove, or a collection found deleted meanwhile, calls `onChanged()` so the page lists it again.
*/
export async function removeFromCollection({ scope, collections, collectionId, images, allMatching = false, total = images.length,
notify = showWorkspaceToast, onChanged = null, onSourceChanged = null }) {
const { targets, refusal } = collectionTargets(images, { allMatching, total });
if (refusal) { notify(refusal); return; }
try {
const result = await collections.remove(collectionId, targets);
if (scope.signal.aborted) return;
notify(removedMessage(result.collection.name, result.removed));
onChanged?.();
} catch (error) {
if (scope.signal.aborted) return;
notify(writeFailure(error, REMOVE_FAILED_TOAST));
if (isCollectionGone(error)) onChanged?.();
else if (error?.code === 'source-changed') onSourceChanged?.();
}
}
+38 -2
View File
@@ -8,6 +8,7 @@ import { closeWorkspaceDialog, openContentDialog, openInputDialog } from './work
import { TOO_MANY, bulkTargets, openAddTags, openAutoTag } from './images-tagging-bulk.mjs';
import { showWorkspaceToast } from './toast.mjs';
import { applyKeys, createLongPress, matchingLabel, matchingOffer, offersAllMatching, rangeKeys } from './images-multiselect.mjs';
import { openAddToCollection, removeFromCollection } from './images-collections.mjs';
const CHECKBOX = '.image-overlays input[type="checkbox"]';
const CHECKBOX_LABEL = '.image-overlays > label';
@@ -42,9 +43,14 @@ function el(tag, text, className) {
* `clear` serve the grid's keys (images.mjs). `getListing()` gives `{total, hasMore, positiveCount}` and
* `getFilter()` the listing filter: once every loaded image is checked and more match, the bar offers "Select all N
* matching", whose actions send that filter to the server.
*
* Collections (#331 D138, design §7): with the client store `collections`, Add to collection follows Set category;
* while a collection filter is active (`collection`, its id) Remove from collection follows it, and a confirmed remove
* calls `onCollectionsChanged()` to reload the listing. A stale source on either calls `onSourceChanged()`.
*/
export function mountSelectionBar({ scope, api, grid, getItems, focusFallback, onCategorySet, activity = null, onTagged,
getListing, getFilter, getCategories, checked: initial = Object.freeze(new Set()) }) {
getListing, getFilter, getCategories, checked: initial = Object.freeze(new Set()), collections = null,
collection = null, onCollectionsChanged = null, onSourceChanged = null }) {
let checked = initial;
let exporting = false, categorizing = false;
// D135: the range anchor, "all N matching" mode, touch selection mode and a pending Shift+click on a checkbox.
@@ -75,7 +81,19 @@ export function mountSelectionBar({ scope, api, grid, getItems, focusFallback, o
...matchingTarget() }));
bulk.append(addTags, autoTag);
}
bulk.append(setCategory, exportMetadata, clearButton);
bulk.append(setCategory);
if (collections) {
const addToCollection = createButton('Add to collection');
scope.listen(addToCollection, 'click', () => openAddToCollection({ scope, collections, images: checkedImages(),
trigger: addToCollection, ...collectionSelection(), onSourceChanged }));
bulk.append(addToCollection);
}
if (collections && collection) {
const removeButton = createButton('Remove from collection');
scope.listen(removeButton, 'click', () => removeChecked(removeButton));
bulk.append(removeButton);
}
bulk.append(exportMetadata, clearButton);
/** The count updates in place: the same bar and `strong`, its text written only when it changes. */
function render() {
@@ -143,6 +161,24 @@ export function mountSelectionBar({ scope, api, grid, getItems, focusFallback, o
function matchingTarget() {
return allMatching ? { filter: getFilter(), count: getListing().total } : {};
}
/** The collection actions' view of "all N matching" (#331 ruling): the loaded images and the match count. */
function collectionSelection() {
return { allMatching, total: allMatching ? getListing().total : checked.size };
}
/** Remove from collection: one write at a time; the selection stays (a reload keeps what is still listed). */
let removing = false;
async function removeChecked(button) {
if (removing) return;
removing = true;
const release = busy(button);
try {
await removeFromCollection({ scope, collections, collectionId: Number(collection), images: checkedImages(),
...collectionSelection(), onChanged: onCollectionsChanged, onSourceChanged });
} finally {
removing = false;
release();
}
}
/** Toggle one image on its own; it becomes the anchor. */
function toggle(key, on = !isChecked(key)) {
settleMatching();
+30 -4
View File
@@ -116,10 +116,12 @@ export function selectedImage() {
* Images last visit. `collection` (an id) is a collection page (#331 D137): only its members are listed, favorites is
* off, and it neither restores nor replaces the last visit either. A listing that answers `collection-not-found` calls
* `onCollectionMissing()` when given (the shell shows its deleted-collection page); otherwise (a saved view on a
* deleted collection, D140) the page lists nothing and says so.
* deleted collection, D140) the page lists nothing and says so. `collections` (the shell's client store) adds the
* selection bar's Add to collection, and Remove from collection while a collection is open (D138).
*/
export function mountImages(main, api, parentScope, {embedded = false, fetchPage, emptyText, focusTarget = null, savedState = null,
favorites = false, collection: collectionId = null, onCollectionMissing = null, onSaveView = () => {}, activity = null} = {}) {
favorites = false, collection: collectionId = null, onCollectionMissing = null, onSaveView = () => {}, activity = null,
collections = null} = {}) {
const scope = createScope();
const dispose = () => scope.dispose();
parentScope.signal.addEventListener('abort', dispose, {once:true});
@@ -302,10 +304,20 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
getFilter:() => {
const filter = listingFilter(filters), scope = state?.items[0]?.root_scope;
return filter.root !== undefined && typeof scope === 'string' ? {...filter, root_scope:scope} : filter;
}});
},
// #331 D138: Add to collection, and Remove from collection on an open collection, which then lists it again.
collections, collection:filters.collection || null, onCollectionsChanged:collectionChanged,
onSourceChanged:refreshInspectionCollection});
if (bar) main.append(bar.element);
main.append(body);
// #331 D139: a change the inspector or the viewer confirmed that touches the open collection lists it again; the
// viewer reports only once it closes.
const inspectorCollections = embedded ? null : collections;
const collectionsChangedBy = ({added, removed}) => {
if (filters.collection && [...added, ...removed].includes(Number(filters.collection))) collectionChanged();
};
const mediaViewer = createMediaViewer({api,container:main,parentScope:scope,inspectionController:inspection,sender,
collections:inspectorCollections,onCollectionsChanged:collectionsChangedBy,
onSelect:image => {if (selection !== imageKey(image)) inspect(image);else inspection.select(image);},
onRefresh:refreshInspectionCollection,onClose:scheduleLoad,onMediaError:image => recovery.recover(image),onRestoreFocus:image => {
const index = state?.items.findIndex(entry => imageKey(entry) === imageKey(image));
@@ -322,7 +334,8 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
selectedImage = 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});
onTagFilter:embedded ? undefined : filterByTag, onRetry:() => inspection.retry(), onLoad:() => inspection.load(), onRefresh:refreshInspectionCollection,
collections:inspectorCollections, onCollectionsChanged:collectionsChangedBy});
detailInspector.setState(inspection.state);
inspection.select(image);
for (const [key, card] of rendered) markSelected(card, key === selection);
@@ -734,6 +747,19 @@ export function mountImages(main, api, parentScope, {embedded = false, fetchPage
const band = parseFloat(getComputedStyle(optionsStatus).scrollMarginBlockEnd) || 0;
if (bottom > innerHeight - band && top < innerHeight) optionsStatus.scrollIntoView({block:'nearest', inline:'nearest'});
}
/**
* A confirmed collection change that may change this listing (a remove from the open collection): the loaded range
* is read again in place, keeping the scroll and the checked files still listed. A failed re-read lists the page
* again from its start, whose failure shows the usual Retry (or the deleted-collection page).
*/
async function collectionChanged() {
if (scope.signal.aborted || !filters.collection || recovering) return;
try {
await stream.refresh();
} catch {
if (!scope.signal.aborted) reset();
}
}
async function refreshInspectionCollection() {
if (scope.signal.aborted) return;
recovery.reset();
+1 -1
View File
@@ -410,7 +410,7 @@ function mountWorkspace() {
if (route.id === 'images' || route.id === 'favorites' || route.id === 'collection') {
mountNewPromptAction(main, api, view);
images = mountImages(main, api, view, {savedState:saved?.state, favorites:route.id === 'favorites',
collection, onCollectionMissing, onSaveView:saveView('images', view), activity});
collection, onCollectionMissing, onSaveView:saveView('images', view), activity, collections});
return;
}
if (route.id === 'library') {
+189
View File
@@ -0,0 +1,189 @@
/**
* The shared inspector's "Collections…" dialog (#331 D139, design §8), beyond the concept: one listed file's
* collections as a checklist in the sidebar's order, a New collection field, then Cancel and Save.
*
* - The file's membership is read when the dialog opens ("Loading collections…"); a failed read says "Collections
* could not be loaded." with Retry, and Save waits for a read that worked.
* - Each row is the concept's checkbox row (`label.tag-suggestion`, app.js a1128). With no collection the list says
* "No collections yet. Name one below."
* - Save sends one request per change, in order: the new name, each newly checked collection, each unchecked one.
* Nothing changed sends nothing and closes. All sent: the dialog closes with "Collections updated.". A failure keeps
* it open with "The collections could not be updated. Try again." and the membership read again; the changes that
* went through still reach `onChanged({added, removed})` (collection ids), as a full success does, but only once the
* dialog closes: a page that lists the file again (a collection page) would otherwise remove the dialog before its
* failure is read. Save waits for the membership read again.
* - A New collection name equal to a listed collection ignoring case is that collection's checkbox, checked. A name
* that cannot be a collection name is refused on the field; nothing is sent and the checkbox edits stay.
* - Focus starts on the field and moves to the first checkbox once they are listed; closing returns it to the
* trigger, or to `focusFallback()` when an inspector re-render removed the trigger.
*/
import { createButton } from '../shared/toolkit/core.js';
import { closeWorkspaceDialog, field, openContentDialog } from './workspace-dialogs.mjs';
import { showWorkspaceToast } from './toast.mjs';
import { COLLECTIONS_UPDATED_TOAST, MAX_COLLECTION_NAME_LENGTH, MEMBERSHIP_FAILED_TEXT, MEMBERSHIP_LOADING_TEXT,
NO_COLLECTIONS_TEXT, UPDATE_FAILED_TEXT, collectionNameKey, normalizeCollectionName } from './collections.mjs';
export const COLLECTIONS_DIALOG_TITLE = 'Collections';
export const NEW_COLLECTION_LABEL = 'New collection';
function el(tag, text, className) {
const node = document.createElement(tag);
if (text !== undefined) node.textContent = text;
if (className) node.className = className;
return node;
}
/**
* Open the dialog for `target` (`{root_index, root_scope, path}`) with the client store `collections`. `openDialog`
* and `closeDialog` are the dialog seams; `notify` the toast.
*/
export function openCollectionsDialog({ scope, collections, target, trigger = null, notify = showWorkspaceToast, onChanged = null,
focusFallback = null, openDialog = openContentDialog, closeDialog = closeWorkspaceDialog }) {
const local = new AbortController();
const active = () => !scope.signal.aborted && !local.signal.aborted;
let member = null, saving = false, listed = false;
// The confirmed changes, reported once when the dialog closes (review M2).
const changes = { added: [], removed: [] };
const status = el('p', '', 'small');
const retry = createButton('Retry');
const list = el('div');
list.setAttribute('role', 'group');
list.setAttribute('aria-label', COLLECTIONS_DIALOG_TITLE);
const input = el('input');
input.value = '';
input.maxLength = MAX_COLLECTION_NAME_LENGTH;
input.autocomplete = 'off';
input.addEventListener('input', () => input.setCustomValidity?.(''));
const problem = el('p', '', 'small');
problem.setAttribute('role', 'alert');
problem.hidden = true;
const actions = el('div', undefined, 'dialog-actions');
const cancel = createButton('Cancel');
const save = createButton('Save', 'ca-primary');
actions.append(cancel, save);
const blocked = () => member === null || saving;
const paintSave = () => {
if (blocked()) save.setAttribute('aria-disabled', 'true');
else save.removeAttribute('aria-disabled');
};
retry.addEventListener('click', () => load());
cancel.addEventListener('click', () => { if (!saving) closeDialog(); });
save.addEventListener('click', () => { if (!blocked()) submit(); });
/** One checkbox row per collection, checked where the file is a member. */
function renderList() {
list.replaceChildren();
if (!collections.collections.length) {
list.append(el('p', NO_COLLECTIONS_TEXT, 'small'));
return;
}
for (const item of collections.collections) {
const row = el('label', undefined, 'tag-suggestion');
const box = el('input');
Object.assign(box, { type: 'checkbox', id: `collection-choice-${item.id}`, checked: member.has(item.id) });
box.dataset.collectionId = String(item.id);
row.htmlFor = box.id;
row.append(box, el('span', item.name));
list.append(row);
}
}
function showStatus(text, failed) {
status.textContent = text;
status.setAttribute('role', failed ? 'alert' : 'status');
status.hidden = !text;
retry.hidden = !failed;
}
/** Save waits while the membership is read (again). */
function loading() {
member = null;
paintSave();
list.replaceChildren();
showStatus(MEMBERSHIP_LOADING_TEXT, false);
}
async function load() {
loading();
try {
const ids = await collections.membership(target);
if (!active()) return;
member = new Set(ids);
showStatus('', false);
renderList();
// The first listing takes focus from the untouched field to the first checkbox (review L6).
if (!listed && !input.value) firstBox().focus();
listed = true;
} catch {
if (!active()) return;
showStatus(MEMBERSHIP_FAILED_TEXT, true);
}
paintSave();
}
const boxesOf = () => [...list.children].map(row => row.children?.[0]).filter(box => box?.dataset?.collectionId);
const firstBox = () => boxesOf()[0] ?? input;
/**
* The requests Save sends, in order; null when the new name cannot be a collection name. A name equal to a listed
* collection's ignoring case is that collection's checkbox, checked (review L4).
*/
function plan() {
const typed = input.value.trim();
const name = typed ? normalizeCollectionName(typed) : '';
if (name === null) return null;
const named = name ? collections.collections.find(item => collectionNameKey(item.name) === collectionNameKey(name)) : null;
const steps = name && !named ? [{ add: { name } }] : [];
const boxes = boxesOf().map(box => ({ id: Number(box.dataset.collectionId), checked: box.checked }))
.map(box => (box.id === named?.id ? { ...box, checked: true } : box));
for (const box of boxes) if (box.checked && !member.has(box.id)) steps.push({ add: { collectionId: box.id } });
for (const box of boxes) if (!box.checked && member.has(box.id)) steps.push({ remove: box.id });
return steps;
}
async function submit() {
problem.textContent = '';
problem.hidden = true;
const steps = plan();
if (steps === null) {
// Review L5: refused on the field; nothing is sent and the checkbox edits stay.
input.setCustomValidity?.(UPDATE_FAILED_TEXT);
input.reportValidity?.();
input.focus();
return;
}
if (steps.length === 0) { closeDialog(); return; }
saving = true;
paintSave();
let failed = false;
for (const step of steps) {
try {
if (step.add) changes.added.push((await collections.add(step.add, [target])).collection.id);
else changes.removed.push((await collections.remove(step.remove, [target])).collection.id);
} catch {
failed = true;
break;
}
if (!active()) return;
if (step.add?.name) input.value = '';
}
if (!active()) return;
saving = false;
if (!failed) {
closeDialog();
notify(COLLECTIONS_UPDATED_TOAST);
return;
}
problem.textContent = UPDATE_FAILED_TEXT;
problem.hidden = false;
// Review M1: Save waits from here until the membership is read again. A collection deleted meanwhile is
// re-read by the store; the list then shows what the server holds.
loading();
await collections.settled();
if (active()) await load();
}
function closed() {
local.abort();
if (changes.added.length || changes.removed.length) onChanged?.({ added: [...changes.added], removed: [...changes.removed] });
// The shell focuses a trigger still on the page; one an inspector re-render replaced falls back (review L6).
if (trigger && !trigger.isConnected) focusFallback?.()?.focus();
}
showStatus('', false);
openDialog({ scope, title: COLLECTIONS_DIALOG_TITLE, trigger, canClose: () => !saving, onClose: closed, focusTarget: input,
nodes: [status, retry, list, field(NEW_COLLECTION_LABEL, input, 'collection-new'), problem, actions] });
load();
}
+124 -24
View File
@@ -2,19 +2,23 @@ import { createButton } from '../shared/toolkit/core.js';
import { selectionLabel, toggleSelection } from './images-state.mjs';
import { applyKeys, rangeKeys } from './images-multiselect.mjs';
import { CATEGORY_DIALOG, CATEGORY_FAILED, CATEGORY_MAX_LENGTH, setOutcome } from './images-category.mjs';
import { NO_TAGS, parseBulkTags } from './images-tagging-bulk.mjs';
import { openInputDialog } from './workspace-dialogs.mjs';
import { countOf } from './plural.mjs';
import { showWorkspaceToast } from './toast.mjs';
/**
* The Prompt library's selection and its one bulk action, "Set category" (#437, D148, beyond the concept): the
* legacy admin page's "Set Category" in the workspace. Built from the concept's Images parts only: each card's
* `.image-overlays` checkbox and the `.bulkbar` row ("N selected", the action, Clear). The selection is a set of
* The Prompt library's selection and its bulk actions (D148, D151, beyond the concept): "Add tags" (#442, D151) and "Set
* category" (#437), the legacy admin page's bulk Add Tags and Set Category in the workspace. Built from the concept's
* Images parts only: each card's `.image-overlays` checkbox and the `.bulkbar` row ("N selected", the actions in the
* Images bar's order, Clear). The selection is a set of
* prompt ids over the shelf's loaded items, so windowed-out cards keep their state; Shift+click on a checkbox applies
* the anchor's range (the Images helpers, D135). The dialog, the range helpers, the count and the toast text are the
* Images bar's own; one bar core shared with images-selection.mjs is a follow-up (D148).
*
* Apply posts `{prompt_ids, category, expected_epoch}` to `POST /prompt_manager/bulk/category`: the epoch the shelf
* was read under, so a restored storage answers 409 `storage-changed` and nothing is written.
* Apply posts `{prompt_ids, category|tags, expected_epoch}` to `POST /prompt_manager/bulk/category` or `/bulk/tags`:
* the epoch the shelf was read under, so a restored storage answers 409 `storage-changed` and nothing is written.
* Add tags writes prompt tags only, never image tags or auto-tags.
*/
export const CATEGORY_URL = '/prompt_manager/bulk/category';
export const PROMPT_CATEGORY_DIALOG = Object.freeze({ ...CATEGORY_DIALOG, title: 'Categorize selected prompts' });
@@ -26,6 +30,17 @@ export const UNCONFIRMED = 'The category change could not be confirmed. The Libr
export const NONE_FOUND = 'None of the selected prompts could be found. The Library was reloaded.';
export const CONTROL_CHARACTERS = 'A category cannot contain control characters.';
export { CATEGORY_FAILED };
export const TAGS_URL = '/prompt_manager/bulk/tags';
export const TAG_OPTIONS_URL = '/prompt_manager/tags';
export const PROMPT_TAGS_DIALOG = Object.freeze({ title: 'Tag selected prompts', label: 'Tags, separated by commas', action: 'Apply' });
// What the editor's save accepts for one prompt (`validate_tags`): the route refuses more.
export const MAX_PROMPT_TAGS = 20;
export const MAX_TAG_LENGTH = 50;
export const TAG_PROBLEMS = Object.freeze({ none: NO_TAGS, many: 'Enter at most 20 tags.',
long: 'A tag can have at most 50 characters.', control: 'A tag cannot contain control characters.' });
export const TAGS_FAILED = 'Tags could not be added. Try again.';
export const TAGS_STORAGE_CHANGED = 'Prompt storage was restored since this page loaded. No tags were added.';
export const TAGS_UNCONFIRMED = 'Adding the tags could not be confirmed. The Library was reloaded.';
// Answers that may follow a committed write (the Library editor's unknown outcome): no status, or a gateway's.
const UNCONFIRMED_STATUSES = new Set([502, 503, 504]);
@@ -43,16 +58,56 @@ function el(tag, text, className) {
* What a settled write means for the page: `toast` to show, whether the write may have `committed` (the page then
* invalidates its cached Library views) and whether the shelf must `reload` (which clears the selection).
*/
export function writeOutcome(result, failure) {
export function writeOutcome(result, failure, kind = 'category') {
const copy = WRITES[kind];
if (failure === null && result?.success) {
const found = (Number(result.updated) || 0) + (Number(result.unchanged) || 0);
const found = ['updated', 'unchanged', 'over_limit'].reduce((sum, key) => sum + (Number(result[key]) || 0), 0);
if (!found) return { toast: NONE_FOUND, committed: false, reload: true };
return { toast: setOutcome(result, result.category, 'prompt'), committed: true, reload: true };
return { toast: copy.success(result), committed: (Number(result.updated) || 0) > 0, reload: true };
}
if (failure?.code === 'storage-changed') return { toast: STORAGE_CHANGED, committed: false, reload: true };
if (failure?.code === 'storage-changed') return { toast: copy.storage, committed: false, reload: true };
const status = failure?.status;
if (!Number.isInteger(status) || UNCONFIRMED_STATUSES.has(status)) return { toast: UNCONFIRMED, committed: true, reload: true };
return { toast: CATEGORY_FAILED, committed: false, reload: false };
if (!Number.isInteger(status) || UNCONFIRMED_STATUSES.has(status)) return { toast: copy.unconfirmed, committed: true, reload: true };
return { toast: copy.failed, committed: false, reload: false };
}
/** The Add tags toast (#442): what was added, then what already had them, was skipped or could not be found. */
export function tagsOutcome(result) {
const updated = Number(result?.updated) || 0, unchanged = Number(result?.unchanged) || 0;
const skipped = Number(result?.over_limit) || 0, missing = Number(result?.not_found) || 0;
const names = Array.isArray(result?.tags) ? result.tags.join(', ') : '';
const parts = [];
if (updated) parts.push(`Added “${names}” to ${countOf(updated, 'prompt')}.`);
if (unchanged) parts.push(`${countOf(unchanged, 'prompt')} already had ${updated ? 'them' : `“${names}”`}.`);
if (skipped) parts.push(`${countOf(skipped, 'prompt')} would pass ${MAX_PROMPT_TAGS} tags and ${skipped === 1 ? 'was' : 'were'} skipped.`);
if (missing) parts.push(`${missing.toLocaleString('en-US')} could not be found.`);
return parts.join(' ');
}
const WRITES = Object.freeze({
category: { success: result => setOutcome(result, result.category, 'prompt'), storage: STORAGE_CHANGED,
unconfirmed: UNCONFIRMED, failed: CATEGORY_FAILED },
tags: { success: tagsOutcome, storage: TAGS_STORAGE_CHANGED, unconfirmed: TAGS_UNCONFIRMED, failed: TAGS_FAILED },
});
/**
* "Select all N loaded" (#444 ruling, D151; the legacy page's select-all checkbox): offered while some loaded prompts
* are unchecked and no more are loaded than an action accepts. It sits where D135's "Select all N matching" sits on
* Images, but that offer appears once every loaded image is checked; this one reaches only the loaded prompts.
*/
export function offersLoaded(selected, keys) {
return selected.size > 0 && keys.length <= MAX_CATEGORY_PROMPTS && keys.some(key => !selected.has(key));
}
export const loadedOffer = count => `Select all ${count.toLocaleString('en-US')} loaded`;
/** The Add tags field's check before Apply: the parsed names, as `validate_tags` would judge them. */
export function tagsProblem(text) {
const tags = parseBulkTags(text);
if (!tags.length) return TAG_PROBLEMS.none;
if (tags.length > MAX_PROMPT_TAGS) return TAG_PROBLEMS.many;
if (tags.some(tag => tag.length > MAX_TAG_LENGTH)) return TAG_PROBLEMS.long;
if (tags.some(tag => /[\x00-\x1f]/.test(tag))) return TAG_PROBLEMS.control;
return null;
}
/** The field's check before Apply: what `validate_category` refuses beyond the length the field already limits. */
@@ -63,7 +118,7 @@ export function categoryProblem(value) {
/**
* Mount the selection on the shelf `grid`. `getItems()` is the shelf's loaded items in order, `getEpoch()` the
* storage epoch they were read under, `getCategories()` the Library's category list (the field's suggestions).
* `onCommitted(receipt)` runs after a write that may have changed prompts, even once the page is gone (the page
* `onCommitted(kind, receipt)` (`category` or `tags`) runs after a write that may have changed prompts, even once the page is gone (the page
* invalidates its cached Library views); `onReload()` then reloads the mounted shelf (which calls `clear`). Focus moves
* to `focusFallback` when it was on the bar the reload hides.
*/
@@ -73,9 +128,19 @@ export function mountLibrarySelection({ scope, api, grid, getItems, getEpoch, ge
const element = el('div');
element.id = 'library-bulkbar';
const bulk = el('div', undefined, 'bulkbar'), count = el('strong');
const addTags = createButton('Add tags');
const setCategory = createButton('Set category');
const clearButton = createButton('Clear');
bulk.append(count, setCategory, clearButton);
const selectLoaded = createButton('');
const actions = [addTags, setCategory, selectLoaded];
bulk.append(count, addTags, setCategory, clearButton);
scope.listen(selectLoaded, 'click', () => {
if (writing) return;
selectAll();
// The pressed offer left the bar: focus moves to its first action, as after D135's offer.
addTags.focus({ preventScroll: true });
});
scope.listen(addTags, 'click', () => openTags());
scope.listen(setCategory, 'click', () => openCategory());
scope.listen(clearButton, 'click', () => { clear(); focusFallback.focus({ preventScroll: true }); });
// Escape in the bar clears the selection; the bar hides, so focus moves to the page heading as after Clear.
@@ -91,6 +156,12 @@ export function mountLibrarySelection({ scope, api, grid, getItems, getEpoch, ge
if (!checked.size) { bulk.remove(); return; }
const label = selectionLabel(checked.size);
if (count.textContent !== label) count.textContent = label;
const keys = ids();
if (offersLoaded(checked, keys)) {
const offer = loadedOffer(keys.length);
if (selectLoaded.textContent !== offer) selectLoaded.textContent = offer;
if (count.nextElementSibling !== selectLoaded) count.after(selectLoaded);
} else selectLoaded.remove();
if (bulk.parentNode !== element) element.append(bulk);
}
function paint() {
@@ -104,6 +175,10 @@ export function mountLibrarySelection({ scope, api, grid, getItems, getEpoch, ge
anchor = null;
if (checked.size) update(Object.freeze(new Set()));
}
/** Every loaded prompt, windowed-out cards included; the anchor stays. */
function selectAll() {
update(applyKeys(checked, ids(), true));
}
// The checkbox toggles natively; a Shift+click applies the anchor's range with the box's new state.
scope.listen(grid, 'click', event => {
const box = event.target.closest('.image-overlays > label');
@@ -134,32 +209,53 @@ export function mountLibrarySelection({ scope, api, grid, getItems, getEpoch, ge
return overlays;
}
function openCategory() {
if (writing) return;
/** The selected loaded prompts and the shelf epoch, or null after a toast says why nothing can be sent. */
function target(failed) {
if (writing) return null;
const loaded = new Set(ids()), selected = [...checked].filter(id => loaded.has(id));
if (selected.length > MAX_CATEGORY_PROMPTS) { showWorkspaceToast(TOO_MANY_PROMPTS); return; }
if (selected.length > MAX_CATEGORY_PROMPTS) { showWorkspaceToast(TOO_MANY_PROMPTS); return null; }
const epoch = getEpoch();
if (!selected.length || typeof epoch !== 'string') { showWorkspaceToast(CATEGORY_FAILED); return; }
if (!selected.length || typeof epoch !== 'string') { showWorkspaceToast(failed); return null; }
return { prompt_ids: selected, expected_epoch: epoch };
}
function openCategory() {
const chosen = target(CATEGORY_FAILED);
if (!chosen) return;
openInputDialog({ scope, trigger: setCategory, title: PROMPT_CATEGORY_DIALOG.title, label: PROMPT_CATEGORY_DIALOG.label,
action: PROMPT_CATEGORY_DIALOG.action, maxLength: CATEGORY_MAX_LENGTH, suggestions: getCategories(),
validate: categoryProblem, onApply: category => write({ prompt_ids: selected, category, expected_epoch: epoch }) });
validate: categoryProblem, onApply: category => write(CATEGORY_URL, { ...chosen, category }, 'category') });
}
/** Add tags (#442): the tag vocabulary as suggestions, the editor's list; a failed read opens without them. */
async function openTags() {
const chosen = target(TAGS_FAILED);
if (!chosen) return;
let suggestions = null;
try {
const result = await api.get(TAG_OPTIONS_URL, { signal: scope.signal, cache: 'no-store' });
if (Array.isArray(result?.tags)) suggestions = result.tags.filter(tag => typeof tag === 'string');
} catch {
// Suggestions are auxiliary; the field works without them.
}
if (scope.signal.aborted) return;
openInputDialog({ scope, trigger: addTags, ...PROMPT_TAGS_DIALOG, suggestions, validate: tagsProblem,
onApply: text => write(TAGS_URL, { ...chosen, tags: parseBulkTags(text) }, 'tags') });
}
/** The write carries no page signal: once sent it completes even if the page is left. A failure keeps the selection. */
async function write(body) {
async function write(url, body, kind) {
writing = true;
setCategory.setAttribute('aria-disabled', 'true');
for (const button of actions) button.setAttribute('aria-disabled', 'true');
let result = null, failure = null;
try {
result = await api.post(CATEGORY_URL, body);
result = await api.post(url, body);
} catch (error) {
failure = error;
} finally {
writing = false;
setCategory.removeAttribute('aria-disabled');
for (const button of actions) button.removeAttribute('aria-disabled');
}
const outcome = writeOutcome(result, failure);
const outcome = writeOutcome(result, failure, kind);
// A left page still invalidates what it cached, so a return never shows the old categories.
if (outcome.committed) onCommitted(result?.success ? result : { phase: 'unconfirmed' });
if (outcome.committed) onCommitted(kind, result?.success ? result : { phase: 'unconfirmed' });
if (scope.signal.aborted) return;
const focused = element.contains(document.activeElement);
showWorkspaceToast(outcome.toast);
@@ -173,7 +269,11 @@ export function mountLibrarySelection({ scope, api, grid, getItems, getEpoch, ge
element,
overlayFor,
isChecked: id => checked.has(id),
hasSelection: () => checked.size > 0,
clear,
selectAll,
/** A loaded batch: the count and the offer follow it. */
listingChanged: () => { if (checked.size) render(); },
/** Whether a Set category write is still in flight. */
writing: () => writing,
};
+8 -2
View File
@@ -189,7 +189,7 @@ export function mountLibrary(main,api,parentScope,{positiveId,savedState=null,on
let categoryNames=[];
const selection=mountLibrarySelection({scope,api,grid,getItems:()=>state?.items ?? [],getEpoch:()=>state?.epoch ?? null,
getCategories:()=>categoryNames,focusFallback:{focus:()=>focusHeading(main)},
onCommitted:receipt=>invalidateLibraryAfterWrite({kind:'bulk-category',receipt}),onReload:()=>{loadCategories();reset();}});
onCommitted:(kind,receipt)=>invalidateLibraryAfterWrite({kind:`bulk-${kind}`,receipt}),onReload:()=>{loadCategories();reset();}});
const message=el('p','','library-status');message.setAttribute('role','status');
const continuation=el('div',undefined,'library-continuation');
const more=createButton('Load more prompts');const retry=createButton('Retry prompt library');retry.hidden=true;
@@ -375,6 +375,9 @@ export function mountLibrary(main,api,parentScope,{positiveId,savedState=null,on
scope.listen(grid,'keydown',event=>{
const card=event.target.closest('article[data-prompt-id]');if(!card) return;
const index=Number(card.dataset.index);
// D151 (#444 ruling): Ctrl/Cmd+A selects every loaded prompt and Escape clears, as on Images (focus stays).
if((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase()==='a') {event.preventDefault();selection.selectAll();return;}
if(event.key==='Escape' && selection.hasSelection()) {event.preventDefault();selection.clear();return;}
if(event.target.matches('[data-history]') && ['Home','End','ArrowLeft','ArrowRight'].includes(event.key)) {event.preventDefault();focusCard(event.key==='Home'?0:event.key==='End'?state.items.length-1:index+(event.key==='ArrowLeft'?-1:1),false,true);}
else if(event.key==='Tab') {
const controls=card.querySelectorAll(CARD_CONTROLS);const next=index+(event.shiftKey?-1:1);
@@ -383,7 +386,8 @@ export function mountLibrary(main,api,parentScope,{positiveId,savedState=null,on
}
});
function render(next) {
if(items!==next.items) {
const batch=items!==next.items;
if(batch) {
pendingAnchor ||= captureAnchor();items=next.items;indexesById=new Map(items.map((item,index)=>[item.id,index]));dirty=true;
if(!items.length) {
anchor=null;pendingAnchor=null;heights.clear();layout={rows:[],height:0};
@@ -392,6 +396,8 @@ export function mountLibrary(main,api,parentScope,{positiveId,savedState=null,on
} else if(retainedAnchor) {pendingAnchor=retainedAnchor;retainedAnchor=null;}
}
state=next;
// A loaded batch: the selection bar's count and Select all N loaded follow it (D151).
if(batch) selection.listingChanged();
if(next.variantTotal!==null) {
const count=`${countOf(next.total,'positive prompt')} · ${countOf(next.variantTotal,'negative variant')}`;
if(captionCount.textContent!==count) captionCount.textContent=count;caption.hidden=false;
+13 -3
View File
@@ -19,7 +19,12 @@ function element(tag, className, text) {
return node;
}
export function createMediaViewer({api,container,parentScope,inspectionController,sender,onSelect,onRefresh,onRestoreFocus,onClose,onMediaError,adapter = rootedFileAdapter}) {
/**
* #331 D139: with the client store `collections`, the viewer's inspector offers "Collections…"; the changes it confirms
* reach `onCollectionsChanged({added, removed})` once the viewer closes, so the viewer keeps its place while open.
*/
export function createMediaViewer({api,container,parentScope,inspectionController,sender,onSelect,onRefresh,onRestoreFocus,onClose,onMediaError,adapter = rootedFileAdapter,
collections = null,onCollectionsChanged = null}) {
const scope = createScope();
let active = null, retryVersion = 0;
const dispose = () => scope.dispose();
@@ -36,7 +41,7 @@ export function createMediaViewer({api,container,parentScope,inspectionControlle
active?.close(false);
const {items,selectedKey,trigger = document.activeElement} = options;
let mounted = false, initial, entry, currentKey, viewer = null, withoutViewer = false, mediaScope = null, closed = false;
let originalDownload = null, inspectionState = inspectionController.state;
let originalDownload = null, inspectionState = inspectionController.state, collectionChanges = null;
const session = createViewerSession({adapter,items,initialKey:selectedKey,onChange:(state,selected) => {
if (!mounted) { initial = [state,selected]; return; }
update(state,selected);
@@ -99,7 +104,11 @@ export function createMediaViewer({api,container,parentScope,inspectionControlle
const localSender = {open(roles,trigger) {session.stop();sender.open(roles,trigger);}};
const inspector = mountFileInspector(details,{api,sender:localSender,parentScope:local,variant:'full',onInteraction:() => session.stop(),onRetry:() => inspectionController.retry(),
onLoad:() => inspectionController.load?.(),
onRefresh:onRefresh ? () => { closeViewer();onRefresh(); } : undefined});
onRefresh:onRefresh ? () => { closeViewer();onRefresh(); } : undefined,collections,
onCollectionsChanged:({added,removed}) => {
collectionChanges ??= {added:[],removed:[]};
collectionChanges.added.push(...added);collectionChanges.removed.push(...removed);
}});
function closeViewer(restore = true) {
if (closed) return;
closed = true;active = null;local.dispose();
@@ -108,6 +117,7 @@ export function createMediaViewer({api,container,parentScope,inspectionControlle
else onRestoreFocus?.(entry);
}
if (!scope.signal.aborted) onClose?.();
if (collectionChanges && !scope.signal.aborted) onCollectionsChanged?.(collectionChanges);
}
active = {close:closeViewer,stop:() => session.stop()};
local.cleanup(() => {
+5 -4
View File
@@ -340,8 +340,9 @@ export const INPUT_SUGGESTIONS_ID = 'workspace-input-suggestions';
* reports `fallback` when one is given (Save view's "Saved view", a1339). A positive `maxLength` limits the field.
* `validate(value)` may refuse a value with a message: the dialog then stays open with the typed text and the field
* reports the message (its native validity) until it is edited. `suggestions` (text list) offers values in a
* `<datalist>` under the field; `secondary` (`{label, onClick}`) adds a button between Cancel and the action that
* closes the dialog and runs `onClick` (#332).
* `<datalist>` under the field (Set category's categories, #332; Add to collection's names, #331 D138); the field
* still takes any text. `secondary` (`{label, onClick}`) adds a button between Cancel and the action that closes the
* dialog and runs `onClick` (#332).
*/
export function openInputDialog({ scope, title, label, action, value = '', maxLength, fallback, onApply, trigger = null,
validate = null, suggestions = null, secondary = null }) {
@@ -408,13 +409,13 @@ export function openInputDialog({ scope, title, label, action, value = '', maxLe
* another dialog replaces its body, so the page can dispose what it mounted there. While `canClose()` answers false,
* × and Escape leave the dialog open (the page, a route change or a replacing dialog still close it).
*/
export function openContentDialog({ scope, title, nodes, onClose = null, trigger = null, canClose = null }) {
export function openContentDialog({ scope, title, nodes, onClose = null, trigger = null, canClose = null, focusTarget = null }) {
requireScope(scope);
if (typeof title !== 'string' || !title) throw new TypeError('The dialog needs a title');
if (!Array.isArray(nodes) || nodes.some(node => !node || typeof node !== 'object')) throw new TypeError('The dialog needs its nodes');
if (onClose !== null && typeof onClose !== 'function') throw new TypeError('The dialog onClose must be a function');
if (canClose !== null && typeof canClose !== 'function') throw new TypeError('The dialog canClose must be a function');
show(title, nodes, { scope, trigger, onClose, canClose });
show(title, nodes, { scope, trigger, onClose, canClose, focusTarget });
}
export const SCAN_REVIEW_SENTENCE = 'Enrich positive / negative associations, reuse canonical text and report unchanged files. ' +