* feat(saved-views): keep a collection in a saved view Images saved views gain a collection key (#331 D140): empty or a collection id of 1 to 9 digits. Writes refuse favorites together with a collection; older rows read an empty collection, and a stored row with both opens the collection, as the listing does for a URL with both. Part of #331 * feat(collections): store collections in the library database * feat(collections): add, remove and rename collections and keep members through duplicate cleanup * feat(collections): add collection routes and the Images collection filter * feat(images): store images' own categories in the library database (#332) One new table, image_categories, and its category index, created empty by a forward-only migration that reads and writes only its own objects. Startup checks the structure; restore also checks the values. The store sets, clears and reads own categories by file key (the deepest output source holding the file and the path below it), and copies a removed duplicate's category to a kept copy that has none. * feat(images): duplicate cleanup keeps images' own categories (#332) The kept copy's own category wins; a kept copy without one receives the removed copy's, keyed by the deepest output source holding each file. The removed copy's row is never deleted, so a give-back or a failed delete loses nothing. The job log reports how many were kept. * feat(images): set, remove and list images' own categories (#332) PUT /prompt_manager/images/category sets the own category of up to 500 listed files, DELETE removes it (listed or not), and GET /prompt_manager/images/categories lists the values whose file is listed. Targets are the Images listing identity of an output source, checked by media_target (shared with Collections). The routes never touch prompts, recipes or links; POST /prompt_manager/bulk/category is unchanged. * fix(images): key symlinked output folders and keep key work off the event loop (#332) Review fixes: a source matches by its configured spelling too, so a detected output folder that is a symlink keys its files (routes and duplicate cleanup). File keys are computed in the executor. A path no source holds is a plain 403, a lone surrogate a 400. The install repairs a table that lacks its category index instead of refusing to open. * fix(collections): address review findings * feat(images): set or remove a category on all N matching images (#332) The category routes also accept the Images listing filter of "Select all N matching" (#392) instead of explicit items, resolved now and capped at 500 images like an explicit selection. * feat(collections): browse a collection from the sidebar The sidebar gains the concept's COLLECTIONS group (D136): one row per collection with its folder icon, name and listed-member count, without the PROPOSED badge; the label shows once a collection exists. A row opens #/collection/<id>, the Images page filtered to that collection (D137): the collection's name as h1, Collection as breadcrumb and title, Edit to rename or delete it through the saved views' Edit dialog with collection nouns, and a note counting members the sources do not list now. An unknown or deleted collection shows a page that says so with a link to Images. A saved view on a deleted collection lists nothing and says so (MC6, D140). The list is read again after a restore and the counts 300 ms after a change. Part of #331 * test(collections): compare the COLLECTIONS group with the concept The concept hides COLLECTIONS at 950 px and below, which would leave a phone no way to open a collection; production shows the rows there in the wrapped layout of every other sidebar nav (D136). The shell comparison now compares the group instead of filtering it out: the concept fixture seeds Landscapes (12) and Experiments (8), the rows compare by name order, and at phone width the nav compares against the concept's own sidebar-nav layout. The collection rows are checked at 1600x1100 and 390x844 in both themes. Part of #331 * test(vendor): count the #332 host case in the execution matrix image-attribution.spec.mjs gains the image category route case, so the execution config lists 92 tests (3 attribution cases per project). * test(browser): install the slideshow clock before wrapping setTimeout The slideshow fixture wrapped window.setTimeout before page.clock.install(), so the viewer's timer ran on real time and clock.runFor() did not drive it; a late WebKit timer failed 'slideshow exposes exact state labels' on CI. * feat(collections): add and remove from the selection bar Add to collection follows Set category in the Images selection bar and opens the concept's simpleInput ("Add selected images to collection", "Collection name", Add) with the existing names as a datalist. Remove from collection follows it while a collection filter is active and reloads the listing in place, keeping the checked files still listed. Every outcome uses the design's strings (section 7.4). The routes take at most 500 explicit files, so an "all N matching" selection is sent only when every match is loaded, checked and at most 500; otherwise the action toasts "Select at most 500 images." (D138, #331). * fix(collections): address review findings - A list read superseded by a newer one (the 300 ms count read, a restore) no longer shows "could not be loaded": the collection and saved-view pages wait for the list to settle. - A listing that finds the open collection gone shows the deleted page once the list no longer holds it; when the list read fails or still holds it, the page keeps the listing's error and Retry instead of staying blank, and each failed read is reported again. - The missing-members note follows every list read and goes away at zero. - A rename that settles after its Edit dialog closed leaves any dialog opened since alone. - The deleted-collection, list-failed and saved-view failure pages focus their title after a route change, as every page does. Part of #331 * feat(collections): add and remove from the inspector and the viewer The shared inspector's footer ends with Collections… (folder icon) after Prompt history for a listed file, in the Images side panel and the viewer. Its dialog reads the file's membership, lists every collection as the concept's checkbox rows, takes an optional new name, and Save sends one request per change (new name, added, removed). A failure keeps the dialog with the membership read again. On a collection page a change to the open collection reloads the listing at once from the side panel and only when the viewer closes from the viewer. The inspector concept comparison draws the button into the concept after Prompt history (D139, #331). * test(collections): compare the collection page and dialog with the concept images-concept compares Add to collection in place in the selection bar (only Remove links… stays omitted) and the collection page's heading, toolbar and filter row against the concept's #collection-landscapes, with D137's Edit drawn into the concept. collections-concept compares the Add to collection dialog with the concept's simpleInput (D138: "Add", an empty field, the datalist of names), in both themes at 1600 and 390 px, with a mutation check. TESTING.md gains the Collections contract (database, keys, missing members, duplicate move, restore, routes, rules, limits, the PR 1 rulings and the all-matching ruling), D136-D140, and amends D28 and D8; docs/application-redesign.md gets the delivery-status line. The coverage baseline adds the two new modules; optional collection callbacks are null rather than no-op defaults so they do not count as uncovered functions. * test(coverage): keep main's floors for files this PR does not touch coverage:update raised nine floors of untouched files from one run; metadata-autocomplete.js branches then measured 84.84 against 85. * fix(collections): address review findings - M1: after a failed Save the Collections dialog shows the membership loading and keeps Save disabled until the re-read lands, so a stale plan cannot be sent. - M2: the changes a Save made reach the page only when the dialog closes, so a collection page's reload cannot remove the dialog before its failure is read. - L4: a New collection name equal to a listed collection ignoring case is that collection's checkbox, checked; never an add then a remove. - L5: a name that cannot be a collection name is refused on the field; nothing is sent, the checkbox edits stay, no re-read. - L6: focus starts on the field and moves to the first checkbox once listed; closing after a re-render replaced the trigger focuses the inspector's current Collections… button or its heading (openContentDialog takes an optional focusTarget). - L3, L7: TESTING.md D138/D139 describe the stale-source and deleted collection outcomes and the above; the viewer spec asserts no listing request while it is open, and a browser test covers M2. * test(legacy): record the image category routes in the legacy contract snapshot (#332) #332 adds PUT/DELETE /prompt_manager/images/category and GET /prompt_manager/images/categories; the legacy pages' routes are unchanged. * test(duplicates): a removed copy with a collection and a category moves both (#331, #332) * test(collections): map the Add to collection suggestions to the shared dialog's datalist (#331) After the merge with #332 PR 3 the input dialog places its datalist after the field with the id workspace-input-suggestions; the concept mapping follows.
382 lines
20 KiB
JavaScript
382 lines
20 KiB
JavaScript
import { createButton } from '../shared/toolkit/core.js';
|
|
import { imageKey, toggleSelection, selectionLabel } from './images-state.mjs';
|
|
import { inspectPath, toInspectionRecord } from './inspection-state.mjs';
|
|
import { BUNDLE_FILENAME, metadataBundle, collectImagesMetadata, exportOutcome } from './images-export.mjs';
|
|
import { CATEGORY_DIALOG, CATEGORY_MAX_LENGTH, CATEGORY_URL, MAX_CATEGORY_IMAGES, REMOVE_DIALOG, USE_PROMPT_CATEGORY,
|
|
NONE_FOUND, clearOutcome, failureMessage, removeQuestion, setOutcome } from './images-category.mjs';
|
|
import { closeWorkspaceDialog, openContentDialog, openInputDialog } from './workspace-dialogs.mjs';
|
|
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';
|
|
const CARD = 'article[data-image-key]';
|
|
// D135: Export metadata reads every image's inspection in the browser, so it waits for loaded images.
|
|
export const EXPORT_LOADED_ONLY = 'Export metadata reads each image in the browser, so it works on loaded images only.';
|
|
|
|
function el(tag, text, className) {
|
|
const element = document.createElement(tag);
|
|
if (text !== undefined) element.textContent = text;
|
|
if (className) element.className = className;
|
|
return element;
|
|
}
|
|
|
|
/**
|
|
* The Images page's checked cards and the concept's selection bar (#249 D8; app.js renderImages, updateBulk and the
|
|
* bulk handlers). `element` is the `#bulkbar` the page places between its filter row and gallery layout: empty while
|
|
* nothing is checked, else "N selected" and the real actions in the concept's order. The page renders each card's
|
|
* checkbox from `isChecked`; this module follows the boxes through the grid's `change` events.
|
|
*
|
|
* - `getItems()` is the listing in its order; `checked` restores a saved visit's selection.
|
|
* - `onCategorySet()` reloads the categories and the listing after a successful Set category or Use prompt category
|
|
* (the reload clears the selection through `clear`); focus then moves to `focusFallback` if it was on the hidden
|
|
* action. `getCategories()` gives the toolbar's categories, the field's suggestions.
|
|
* - `retain(kept)` drops the checked files a refreshed listing no longer holds (a tag save under a filter, I7).
|
|
* - With the Activity store `activity`, Add tags and Auto-tag selected (D85) follow the count, as the concept's Add tags
|
|
* leads its actions; `onTagged(keys)` re-reads the files a finished tagging job tagged. The selection stays.
|
|
*
|
|
* File-manager selection (#392, D135, beyond the concept's checkbox): the anchor is the last image toggled on its own;
|
|
* Shift+click (a checkbox or anywhere on a card) applies the anchor's range, Ctrl/Cmd+click toggles a card without
|
|
* opening it, a touch long-press starts touch selection mode in which taps toggle. `selectAll`, `extend` and
|
|
* `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()), 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.
|
|
let anchor = null, allMatching = false, touchMode = false, lastPointer = 'mouse', shiftBox = null;
|
|
const element = el('div');
|
|
element.id = 'bulkbar';
|
|
const bulk = el('div', undefined, 'bulkbar'), count = el('strong');
|
|
const selectMatching = createButton('');
|
|
scope.listen(selectMatching, 'click', () => {
|
|
allMatching = true;
|
|
render();
|
|
focusAfterOffer();
|
|
});
|
|
const setCategory = createButton('Set category');
|
|
scope.listen(setCategory, 'click', () => openCategory(setCategory));
|
|
const exportMetadata = createButton('Export metadata');
|
|
scope.listen(exportMetadata, 'click', () => { if (!allMatching) exportChecked(exportMetadata); });
|
|
const clearButton = createButton('Clear');
|
|
// Clear hides the bar it sits in, so focus moves to the page heading instead of falling to the page.
|
|
scope.listen(clearButton, 'click', () => { clear(); focusFallback.focus({ preventScroll: true }); });
|
|
bulk.append(count);
|
|
if (activity) {
|
|
const addTags = createButton('Add tags');
|
|
scope.listen(addTags, 'click', () => openAddTags({ scope, store: activity, images: checkedImages(), trigger: addTags, onTagged,
|
|
...matchingTarget() }));
|
|
const autoTag = createButton('Auto-tag selected'); // D85
|
|
scope.listen(autoTag, 'click', () => openAutoTag({ api, scope, store: activity, images: checkedImages(), trigger: autoTag, onTagged,
|
|
...matchingTarget() }));
|
|
bulk.append(addTags, autoTag);
|
|
}
|
|
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() {
|
|
if (!checked.size && !allMatching) { touchMode = false; bulk.remove(); return; }
|
|
const listing = getListing();
|
|
const label = allMatching ? matchingLabel(listing.total) : selectionLabel(checked.size);
|
|
if (count.textContent !== label) count.textContent = label;
|
|
// "Select all N matching" (D135) follows the count while every loaded image is checked and more match.
|
|
if (!allMatching && offersAllMatching(checked, loadedKeys(), listing)) {
|
|
const offer = matchingOffer(listing.total);
|
|
if (selectMatching.textContent !== offer) selectMatching.textContent = offer;
|
|
if (count.nextElementSibling !== selectMatching) count.after(selectMatching);
|
|
} else selectMatching.remove();
|
|
if (allMatching) {
|
|
exportMetadata.setAttribute('aria-disabled', 'true');
|
|
exportMetadata.title = EXPORT_LOADED_ONLY;
|
|
} else if (exportMetadata.title) {
|
|
exportMetadata.removeAttribute('title');
|
|
if (!exporting) exportMetadata.removeAttribute('aria-disabled');
|
|
}
|
|
if (bulk.parentNode !== element) element.append(bulk);
|
|
}
|
|
/** Every rendered checkbox shows the selection (cards mounted later read `isChecked`). */
|
|
function paint() {
|
|
for (const box of grid.querySelectorAll(CHECKBOX)) {
|
|
const on = isChecked(box.closest(CARD).dataset.imageKey);
|
|
if (box.checked !== on) box.checked = on;
|
|
}
|
|
}
|
|
function update(next) {
|
|
checked = next;
|
|
paint();
|
|
render();
|
|
}
|
|
/** Leaving "all N matching": the loaded images become the explicit selection the next change applies to. */
|
|
function settleMatching() {
|
|
if (!allMatching) return;
|
|
allMatching = false;
|
|
checked = Object.freeze(new Set(loadedKeys()));
|
|
}
|
|
function clear() {
|
|
anchor = null; touchMode = false;
|
|
if (!checked.size && !allMatching) return;
|
|
allMatching = false;
|
|
update(Object.freeze(new Set()));
|
|
}
|
|
/** Keep only the checked files `kept(key)` still lists (a refreshed result), so the count is what the actions apply to. */
|
|
function retain(kept) {
|
|
if (allMatching) { render(); return; }
|
|
const next = [...checked].filter(kept);
|
|
if (next.length === checked.size) return;
|
|
checked = Object.freeze(new Set(next));
|
|
render();
|
|
}
|
|
function loadedKeys() {
|
|
return getItems().map(imageKey);
|
|
}
|
|
function isChecked(key) {
|
|
return allMatching || checked.has(key);
|
|
}
|
|
function checkedImages() {
|
|
return allMatching ? getItems() : getItems().filter(image => checked.has(imageKey(image)));
|
|
}
|
|
/** The actions' images for "all N matching": the listing filter and its total, which the server resolves. */
|
|
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();
|
|
anchor = key;
|
|
update(toggleSelection(checked, key, on));
|
|
}
|
|
/** The anchor's range to `key` takes `on`; without an anchor `key` is toggled on and becomes it. */
|
|
function range(key, on = true) {
|
|
settleMatching();
|
|
const keys = rangeKeys(loadedKeys(), anchor, key);
|
|
if (anchor === null || keys.length === 1) anchor = key;
|
|
update(applyKeys(checked, keys, on));
|
|
}
|
|
/** Shift+arrow keys: the range from the anchor (`from`, the card focus left, when there is none) to `to`. */
|
|
function extend(from, to) {
|
|
if (anchor === null || !loadedKeys().includes(anchor)) anchor = from;
|
|
range(to, true);
|
|
}
|
|
function selectAll() {
|
|
if (allMatching) return;
|
|
update(applyKeys(checked, loadedKeys(), true));
|
|
}
|
|
function focusAfterOffer() {
|
|
// The pressed offer left the bar: focus moves to the count's first action instead of the page.
|
|
(bulk.querySelector('button:not([aria-disabled="true"])') ?? focusFallback).focus({ preventScroll: true });
|
|
}
|
|
// Every card carries its image key; its only form control is the checkbox, so a toggle never opens or inspects.
|
|
scope.listen(grid, 'change', event => {
|
|
const box = event.target;
|
|
if (!box.matches(CHECKBOX)) return;
|
|
const key = box.closest(CARD).dataset.imageKey;
|
|
if (shiftBox === key) range(key, box.checked);
|
|
else toggle(key, box.checked);
|
|
shiftBox = null;
|
|
});
|
|
// D135: modified clicks select instead of opening, inspecting or starring. Captured, so the page's own click
|
|
// handler (images.mjs) never sees them; a plain click keeps its meaning.
|
|
grid.addEventListener('click', event => {
|
|
const card = event.target.closest(CARD);
|
|
if (!card) return;
|
|
const key = card.dataset.imageKey;
|
|
if (longPress.consumeClick()) { swallow(event); return; }
|
|
if (event.target.closest(CHECKBOX_LABEL)) {
|
|
// The box toggles natively; its change event applies the range.
|
|
if (event.shiftKey) shiftBox = key;
|
|
return;
|
|
}
|
|
// A keyboard click (Enter, Space: `detail` 0) keeps its plain meaning in touch selection mode.
|
|
const tapped = touchMode && lastPointer !== 'mouse' && event.detail !== 0;
|
|
if (event.shiftKey) { swallow(event); range(key, true); }
|
|
else if (event.ctrlKey || event.metaKey || tapped) { swallow(event); toggle(key); }
|
|
}, { capture: true, signal: scope.signal });
|
|
function swallow(event) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
}
|
|
// A touch long-press selects the card and starts touch selection mode (D135).
|
|
const longPress = createLongPress({ onLongPress: key => {
|
|
touchMode = true;
|
|
anchor = key;
|
|
if (!isChecked(key)) toggle(key, true);
|
|
} });
|
|
scope.cleanup(() => longPress.cancel());
|
|
scope.listen(grid, 'pointerdown', event => {
|
|
lastPointer = event.pointerType || 'mouse';
|
|
shiftBox = null;
|
|
const card = event.target.closest(CARD);
|
|
if (lastPointer === 'mouse' || !card || !event.isPrimary) { longPress.cancel(); return; }
|
|
longPress.down(event.clientX, event.clientY, card.dataset.imageKey);
|
|
});
|
|
scope.listen(grid, 'pointermove', event => longPress.move(event.clientX, event.clientY));
|
|
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) scope.listen(grid, type, () => longPress.up());
|
|
// A long-press's context menu (Android) would cover the selection it just started.
|
|
scope.listen(grid, 'contextmenu', event => {
|
|
if (lastPointer !== 'mouse' && (touchMode || longPress.pending())) event.preventDefault();
|
|
});
|
|
// Escape in the bar clears the selection; the bar hides, so focus moves to the page heading as after Clear.
|
|
scope.listen(element, 'keydown', event => {
|
|
if (event.key !== 'Escape' || (!checked.size && !allMatching)) return;
|
|
event.preventDefault();
|
|
clear();
|
|
focusFallback.focus({ preventScroll: true });
|
|
});
|
|
|
|
/** Busy until it settles: `aria-disabled` now, released in a `finally` so a throw cannot leave it stuck. */
|
|
function busy(button) {
|
|
button.setAttribute('aria-disabled', 'true');
|
|
return () => button.removeAttribute('aria-disabled');
|
|
}
|
|
/**
|
|
* Export metadata: the checked images' inspector envelopes in listing order, as one JSON download. A second press
|
|
* while it runs is ignored and the selection is kept. Leaving the page aborts the reads: no download, no toast.
|
|
*/
|
|
async function exportChecked(button) {
|
|
if (exporting) return;
|
|
exporting = true;
|
|
const release = busy(button);
|
|
try {
|
|
const { envelopes, failed } = await collectImagesMetadata(checkedImages(),
|
|
async image => toInspectionRecord(await api.get(inspectPath(image), { signal: scope.signal }), image));
|
|
if (scope.signal.aborted) return;
|
|
if (envelopes.length) downloadJson(BUNDLE_FILENAME, metadataBundle(envelopes, new Date().toISOString()));
|
|
showWorkspaceToast(exportOutcome(envelopes.length, envelopes.length + failed));
|
|
} finally {
|
|
exporting = false;
|
|
release();
|
|
}
|
|
}
|
|
/** A Blob, an anchor and a deferred revoke, as the concept's exportSample does. */
|
|
function downloadJson(filename, value) {
|
|
const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' }));
|
|
let timer, released = false;
|
|
const release = () => { if (released) return; released = true; clearTimeout(timer); URL.revokeObjectURL(url); };
|
|
scope.cleanup(release);
|
|
const anchor = el('a'); anchor.href = url; anchor.download = filename;
|
|
element.append(anchor); anchor.click(); anchor.remove();
|
|
timer = setTimeout(release, 1000);
|
|
}
|
|
/**
|
|
* Set category (app.js bulk-category → simpleInput, #332 D140): Apply sets each selected image's own category, linked
|
|
* or not; "Use prompt category" removes it after a confirmation that states the count. Up to 500 images (DC2): an
|
|
* explicit selection or "all N matching" (the listing filter, resolved by the server); more opens nothing.
|
|
*/
|
|
function openCategory(button) {
|
|
if (categorizing) return;
|
|
const count = allMatching ? getListing().total : checked.size;
|
|
const targets = allMatching ? {filter: getFilter()} : {items: bulkTargets(checkedImages())};
|
|
if (count > MAX_CATEGORY_IMAGES) { showWorkspaceToast(TOO_MANY); return; }
|
|
// Checked files the listing no longer holds (a refresh dropped them): nothing to send.
|
|
if (!allMatching && !targets.items?.length) { showWorkspaceToast(NONE_FOUND); return; }
|
|
openInputDialog({ scope, trigger: button, title: CATEGORY_DIALOG.title, label: CATEGORY_DIALOG.label,
|
|
action: CATEGORY_DIALOG.action, maxLength: CATEGORY_MAX_LENGTH, suggestions: getCategories(),
|
|
secondary: { label: USE_PROMPT_CATEGORY, onClick: () => confirmRemove(button, targets, count) },
|
|
onApply: category => writeCategory(button, () => api.put(CATEGORY_URL, {...targets, category}),
|
|
result => setOutcome(result, category)) });
|
|
}
|
|
/** "Use prompt category": nothing is sent until Remove; Cancel leaves every category as it was. */
|
|
function confirmRemove(button, targets, count) {
|
|
const text = el('p', removeQuestion(count));
|
|
const actions = el('div', undefined, 'dialog-actions');
|
|
const cancel = createButton('Cancel'), remove = createButton(REMOVE_DIALOG.action, 'danger');
|
|
actions.append(cancel, remove);
|
|
cancel.addEventListener('click', () => closeWorkspaceDialog());
|
|
remove.addEventListener('click', () => {
|
|
closeWorkspaceDialog();
|
|
writeCategory(button, () => api.del(CATEGORY_URL, {body: targets}), clearOutcome);
|
|
});
|
|
openContentDialog({ scope, trigger: button, title: REMOVE_DIALOG.title, nodes: [text, actions] });
|
|
cancel.focus();
|
|
}
|
|
/**
|
|
* The write carries no page signal: once sent it finishes even if the page is left (`writing` then tells the page
|
|
* not to save a visit that predates it). A failure keeps the selection, except a changed source, which reloads the
|
|
* listing as a success does (`onCategorySet`).
|
|
*/
|
|
async function writeCategory(button, send, outcome) {
|
|
categorizing = true;
|
|
const release = busy(button);
|
|
let result = null, failure = null;
|
|
try {
|
|
result = await send();
|
|
} catch (error) {
|
|
failure = error;
|
|
} finally {
|
|
categorizing = false;
|
|
release();
|
|
}
|
|
if (scope.signal.aborted) return;
|
|
const focused = document.activeElement === button;
|
|
if (failure !== null || !result) {
|
|
showWorkspaceToast(failureMessage(failure));
|
|
// A changed source reloads the listing (clearing the selection); any other failure keeps it.
|
|
if (failure?.code !== 'source-changed') return;
|
|
onCategorySet();
|
|
if (focused) focusFallback.focus({ preventScroll: true });
|
|
return;
|
|
}
|
|
showWorkspaceToast(outcome(result));
|
|
onCategorySet();
|
|
// The reload hides the bar with the focused action in it, as Clear does: focus moves to the page heading.
|
|
if (focused) focusFallback.focus({ preventScroll: true });
|
|
}
|
|
|
|
render();
|
|
return {
|
|
element,
|
|
isChecked,
|
|
// A saved visit keeps "all N matching" as its loaded images; the offer then shows again.
|
|
checked: () => (allMatching ? Object.freeze(new Set(loadedKeys())) : checked),
|
|
hasSelection: () => allMatching || checked.size > 0,
|
|
clear,
|
|
retain,
|
|
selectAll,
|
|
extend,
|
|
/** A loaded batch or a refreshed total: the count and the offer follow it. */
|
|
listingChanged: () => { if (checked.size || allMatching) render(); },
|
|
/** Whether a Set category write is still in flight. */
|
|
writing: () => categorizing,
|
|
};
|
|
}
|