* 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. * feat(vocabulary): count and rename image categories (#332) Tags & categories lists every category value with image_count, the stored image_categories rows holding it. Values only images hold follow every prompt-backed value (first_pid at SQLite's INTEGER maximum), so keyset cursors cross the boundary. /library/options keeps its own query and never lists image-only values. Manage category counts image rows (impact.images), treats an image-held target as existing, renames image rows in the same transaction, allows renaming an image-only value, and hashes the sorted image rowids into the impact token so a change between preview and apply is refused with vocabulary-conflict. Every image-category statement reads idx_image_categories_category. * feat(images): the category filter matches each image's effective category (#332) An image's own category wins; without one it inherits its link's: the recipe's category when set, else the positive prompt's (MC4, one rule with the inspector chip). Ambiguous and unlinked images inherit nothing, so an unlinked image with its own category is now listed. The link read no longer filters by category in SQL; the page filter, select all N matching and saved views compare the effective value. A failed own-category read answers the existing listing-failed 500. * 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. * feat(inspector): show an image's own category in the inspector and History (#332) The inspector's library facts gain category_scope "image": an image's own category overrides the inherited one for any link status (linked, ambiguous, none). Images reads it for output sources only; History reads it once per inspection inside its snapshot, keyed by the same file key from the symlink-resolved output folder. A failed read hides the chip rather than show a possibly wrong value. The chip's hidden prefix names the origin ("Image category: "); the visible origin text comes in PR 3. * perf(images): keep the category filter's link read narrow; record D141, D142, D145 (#332) Under a category the link read keeps only links whose raw recipe or positive category is the value (Python still decides the inherited one), the links of images whose own category is the value are read by path, and plain reads skip the inherited-category work. The own-category map is keyed by normalized path. TESTING.md records D141, D142 and D145 and amends D13, D36 and D39; the filter budget seeds 2,000 own categories. * 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. * fix(images): Windows path keys for own categories; plan check for the category read (#332) Review fixes: on Windows the own-category map keys each file with normalize_image_path (abspath drops trailing dots and spaces), and the plan test also covers the category's narrowing clause. * feat(images): Set category sets each image's own category; the chip names its origin (#332) The selection bar's Set category writes the selected images' own category (linked or not, up to 500, or all N matching up to 500), with the toolbar categories as suggestions; Use prompt category removes it after a confirmation that states the count. It never writes a prompt (#259's prompt action is retired from Images; the Library editor and the legacy admin Set Category still change prompt categories). The toolbar lists the listed images' own categories beside the prompt and recipe ones. The inspector chip shows its origin: "· this image", "· prompt" or "· recipe". Tags & categories counts images and opens Images for a category only images use. * test(images): compare the category chip's visible origin against the concept (#332) D146: the inspector comparison measures each chip's span.chip-source and lays the concept's own chip out with the recorded rule and origin added at runtime (withChipSource), in the side panel and the viewer's details. The D39 recipe case asserts the visible " · prompt"; the mutation check removes the origin. * test(images): compare Set category and the category options against the concept (#332) With one image's own category set through the real route, the toolbar's #category-filter options are compared with D141 mapped (the image category sorted in with the Library's, D36), and the Set category dialog against the concept's simpleInput laid out as recorded at runtime: D140 (empty field, datalist#workspace-input-suggestions of the toolbar's categories, Use prompt category between Cancel and Apply) and D8 (Apply). Unmapped, the dialog differs only in those parts. * test(history): compare the History media inspector's category chip against the concept (#332) D145: with an own category set on the baseline's newest output, the Recorded run viewer's chip is compared with the concept viewer's category chip laid out with the D146 origin and the own category at runtime; D21 maps its hidden "Image category: " prefix. Unmapped, the two differ only in the text, the prefix, the width and span.chip-source. * test(images): Set category sets each image's own category in page workflows (#332) Replace the #259 prompt-category tests with CUJ 1, 2, 3, 8 and 10, the suggestions datalist, the 500-image limit, the source-changed path, D142 and coded refusals; Images never posts /prompt_manager/bulk/category. * test(inspector): the category chip names its origin in the panel, viewer and History (#332) CUJ 4 and 5: "· this image", "· prompt" and "· recipe" chips, an unlinked file's own category, and History's current-file inspector. * test(vocabulary): category rename covers image categories; image-only rows browse Images (#332) CUJ 6 and 7 with own categories set through the API on two output files. * test(vocabulary): compare image-category rows and the Manage category preview against the concept (#332) The vocabulary fixture seeds own image categories on request (image_categories: Landscapes on two images, Portraits on one image only). mapVocabularyConcept maps D143 ("N positive prompts · M images", image-only rows before Manage category), a model checked against the concept page with those rows added at runtime, and mapVocabularyDialog takes the preview sentence, so the Manage category preview is compared with D9 and D144's images. The default fixture and mapping are unchanged. * test(vocabulary): park the pointer before measuring the category rows (#332) Firefox kept the pointer where the concept's Review was pressed, over the production Portraits row's Browse, so that button was measured hovered. * docs(testing): record D140, D143, D144 and D146 and the image category UI (#332) D140 (Set category writes images' own categories), D146 (the chip's visible origin) beside D141, D142 and D145; D143 and D144 in the vocabulary section. D8, D21 (the D20/D21 side panel) and D39 amended; the D8, the "all N matching" and the Native vocabulary UI paragraphs name the Prompt library editor and the legacy admin "Set Category" for prompt categories; the #332 section lists the interface and its comparisons. * 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). * fix(images): focus after a changed source; Browse is a fresh Images visit (#332) Review fixes: a 409 source-changed reload moves focus to the heading as a success does; a selection the listing no longer holds says none could be found instead of sending nothing; a Tags & categories Browse opens a plain Images visit filtered by the category (remembered and with the Appearance defaults) rather than a saved-view visit. * 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. * refactor(images): take the selection bar's categories from its one caller (#332) The getCategories default was never used (images.mjs always passes the toolbar's categories) and left images-selection.mjs function coverage at 97.05 (floor 98).
255 lines
12 KiB
JavaScript
255 lines
12 KiB
JavaScript
/**
|
||
* Native Tags & categories screen (concept renderTags, app.js:719-729).
|
||
*
|
||
* Composition, labels and order follow the approved concept: Auto-tag images
|
||
* opens the Tag image dialog for the image selected in Images (aria-disabled
|
||
* without one, D115) and the Images cells count the files carrying each tag
|
||
* (#249 C2). The recorded deviation left is bounded lists with Load more. Rows
|
||
* are real vocabulary pages from vocabulary-state.mjs; Browse hands the exact
|
||
* constraint to the existing Library filters.
|
||
*/
|
||
import { createButton } from '../shared/toolkit/core.js';
|
||
import { browseFilters, categoryBrowseTarget, categoryRowText, createVocabularyCommand, createVocabularyStream } from './vocabulary-state.mjs';
|
||
import { browseLibrary, invalidateLibraryAfterWrite } from './library.mjs';
|
||
import { createVocabularyDialog } from './vocabulary-dialog.mjs';
|
||
import { pageHeading } from './heading.mjs';
|
||
import { browseImages, selectedImage } from './images.mjs';
|
||
import { onImageTagsSaved, openImageTagging } from './image-tagging.mjs';
|
||
import { showWorkspaceToast } from './toast.mjs';
|
||
|
||
/** D115: why Auto-tag images (and System › Auto-tagging's Preview tagging review) only explains without a selection. */
|
||
export const NO_SELECTION = 'Select an image in Images first.';
|
||
|
||
const COPY = {
|
||
tags: {empty: 'No tags yet.', error: 'Tags could not be loaded. Nothing was changed.', more: 'Load more tags'},
|
||
categories: {empty: 'No categories yet.', error: 'Categories could not be loaded. Nothing was changed.', more: 'Load more categories'},
|
||
};
|
||
// Append the next page this far before the end of a list comes into view.
|
||
const LOAD_MARGIN = 250;
|
||
|
||
function el(tag, text, className) {
|
||
const node = document.createElement(tag);
|
||
if (text !== undefined) node.textContent = text;
|
||
if (className) node.className = className;
|
||
return node;
|
||
}
|
||
|
||
/** The concept's `.operation` row: h3 title, p description, one row action. */
|
||
function operation(title, description, label) {
|
||
const row = el('div', undefined, 'operation');
|
||
const copy = el('div');
|
||
copy.append(el('h3', title), el('p', description));
|
||
const actions = el('div', undefined, 'row-actions');
|
||
const button = createButton(label);
|
||
actions.append(button);
|
||
row.append(copy, actions);
|
||
return {row, button};
|
||
}
|
||
|
||
function tagRow(tag) {
|
||
const row = el('tr');
|
||
// The files carrying the tag (absent from an older server, which counts none).
|
||
const images = el('td', String(tag.image_count ?? 0));
|
||
const cell = el('td');
|
||
const actions = el('div', undefined, 'row-actions');
|
||
const browse = createButton('Browse');
|
||
browse.dataset.action = 'browse';
|
||
const rename = createButton('Rename / merge');
|
||
rename.dataset.action = 'rename';
|
||
actions.append(browse, rename);
|
||
cell.append(actions);
|
||
row.append(el('td', tag.name), el('td', String(tag.prompt_count)), images, cell);
|
||
return row;
|
||
}
|
||
|
||
function categoryRow(category) {
|
||
const {row, button} = operation(category.value, categoryRowText(category), 'Browse');
|
||
button.dataset.action = 'browse';
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* One bounded list: rows append as pages arrive, the end of the list loads the
|
||
* next page each time it scrolls into view, and `Load more` stays available while
|
||
* more remain. Only a new intersection appends: when scroll anchoring keeps the end
|
||
* in view (stacked layout below 700px), pages do not chain on their own. Before any row arrives (loading, failed) the list shows no rows, so a
|
||
* failed read never looks like zero counts.
|
||
*/
|
||
function mountList(scope, api, kind, {content, rowsHost, renderRow, after}) {
|
||
const copy = COPY[kind];
|
||
const empty = el('p', copy.empty, 'empty');
|
||
const continuation = el('div', undefined, 'vocabulary-continuation');
|
||
const status = el('p', '', 'vocabulary-status');
|
||
status.setAttribute('role', 'status');
|
||
const alert = el('p', copy.error, 'vocabulary-error');
|
||
alert.setAttribute('role', 'alert');
|
||
const retry = createButton('Retry');
|
||
const more = createButton(copy.more);
|
||
continuation.append(status, alert, retry, more);
|
||
after.after(empty, continuation);
|
||
const items = new WeakMap();
|
||
const listeners = new Set();
|
||
let rendered = 0, first = null;
|
||
|
||
function maybeLoad() {
|
||
const {state} = stream;
|
||
if (scope.signal.aborted || !state.hasMore || state.loading || state.error || state.resetRequired) return;
|
||
const bounds = continuation.getBoundingClientRect();
|
||
if (bounds.top <= window.innerHeight + LOAD_MARGIN && bounds.bottom >= -LOAD_MARGIN) stream.loadMore();
|
||
}
|
||
function render(state) {
|
||
// A reset starts again from page one; otherwise pages only append.
|
||
if (state.items.length < rendered || (rendered && state.items[0] !== first)) {
|
||
rowsHost.replaceChildren();
|
||
rendered = 0;
|
||
}
|
||
const appended = [];
|
||
for (const item of state.items.slice(rendered)) {
|
||
const row = renderRow(item);
|
||
items.set(row, item);
|
||
appended.push(row);
|
||
}
|
||
rowsHost.append(...appended);
|
||
rendered = state.items.length;
|
||
first = state.items[0] ?? null;
|
||
const failed = Boolean(state.error);
|
||
content.hidden = !rendered;
|
||
empty.hidden = Boolean(rendered || state.loading || failed || state.hasMore);
|
||
status.textContent = state.loading ? 'Loading…' : '';
|
||
status.hidden = !state.loading;
|
||
alert.hidden = !failed;
|
||
retry.hidden = !failed;
|
||
const hideMore = !state.hasMore || failed || !rendered;
|
||
// Keyboard users keep a focus target: Retry after a failed read, else the first new (or first) row.
|
||
if (hideMore && document.activeElement === more) {
|
||
(failed ? retry : appended[0]?.querySelector('button') ?? rowsHost.querySelector('button'))?.focus();
|
||
}
|
||
more.hidden = hideMore;
|
||
more.setAttribute('aria-disabled', String(state.loading));
|
||
continuation.hidden = !(state.loading || failed || state.hasMore);
|
||
for (const listener of listeners) listener(state);
|
||
}
|
||
const stream = createVocabularyStream({api, kind, onChange: render});
|
||
scope.listen(more, 'click', () => stream.loadMore());
|
||
scope.listen(retry, 'click', () => (stream.state.resetRequired ? stream.reset() : stream.loadMore()));
|
||
let observer = null;
|
||
if (typeof IntersectionObserver === 'function') {
|
||
observer = new IntersectionObserver(entries => {
|
||
if (entries.some(entry => entry.isIntersecting)) maybeLoad();
|
||
}, {rootMargin: `${LOAD_MARGIN}px`});
|
||
observer.observe(continuation);
|
||
}
|
||
scope.cleanup(() => {
|
||
stream.dispose();
|
||
observer?.disconnect();
|
||
});
|
||
render(stream.state);
|
||
/** The rendered row whose item matches, if it is loaded. */
|
||
function rowFor(match) {
|
||
return [...rowsHost.children].find(row => {const item = items.get(row); return item !== undefined && match(item);}) ?? null;
|
||
}
|
||
/** Follow this list's state (a dialog reading further pages); returns the unsubscribe. */
|
||
function subscribe(listener) {
|
||
listeners.add(listener);
|
||
return () => listeners.delete(listener);
|
||
}
|
||
return {stream, itemOf: row => items.get(row), rowFor, subscribe};
|
||
}
|
||
|
||
/** Mount the screen into `main` below the shell's heading; `scope` owns every request, listener and observer. */
|
||
export function mountVocabulary(main, api, scope) {
|
||
main.classList.add('vocabulary-main');
|
||
scope.cleanup(() => main.classList.remove('vocabulary-main'));
|
||
const { description, actions } = pageHeading(main);
|
||
description.textContent = 'Organize once. Reuse everywhere.';
|
||
const create = createButton('+ Create tag');
|
||
const autoTag = createButton('Auto-tag images', 'ca-primary');
|
||
actions.append(create, autoTag);
|
||
// The concept's `tag-review` for `state.selectedImage` (app.js a1511); D115: none selected, so it only explains.
|
||
const selected = selectedImage();
|
||
if (!selected) autoTag.setAttribute('aria-disabled', 'true');
|
||
scope.listen(autoTag, 'click', () => {
|
||
if (!selected) { showWorkspaceToast(NO_SELECTION); return; }
|
||
openImageTagging({api, scope, image: selected, source: 'tags', trigger: autoTag});
|
||
});
|
||
|
||
const grid = el('div', undefined, 'two-col');
|
||
const tagSurface = el('section', undefined, 'surface');
|
||
const wrap = el('div', undefined, 'table-wrap');
|
||
const table = el('table');
|
||
const head = el('thead');
|
||
const headRow = el('tr');
|
||
for (const label of ['Tag', 'Prompts', 'Images', 'Actions']) {
|
||
const cell = el('th', label);
|
||
cell.scope = 'col';
|
||
headRow.append(cell);
|
||
}
|
||
head.append(headRow);
|
||
const body = el('tbody');
|
||
table.append(el('caption', 'Reusable tags'), head, body);
|
||
wrap.append(table);
|
||
tagSurface.append(el('h2', 'Tag vocabulary'),
|
||
el('p', 'Category/tag autocomplete uses this same vocabulary across nodes and dialogs.'), wrap);
|
||
|
||
const categorySurface = el('section', undefined, 'surface');
|
||
const categoryRows = el('div', undefined, 'vocabulary-categories');
|
||
const manage = operation('Manage category', 'Rename or consolidate a category with a preview of affected recipes.', 'Review');
|
||
categorySurface.append(el('h2', 'Categories'),
|
||
el('p', 'Categories provide a broad home. Tags describe content; proposed collections group projects without changing either.'),
|
||
categoryRows, manage.row);
|
||
grid.append(tagSurface, categorySurface);
|
||
main.append(grid);
|
||
|
||
const tags = mountList(scope, api, 'tags', {content: wrap, rowsHost: body, renderRow: tagRow, after: wrap});
|
||
const categories = mountList(scope, api, 'categories', {content: categoryRows, rowsHost: categoryRows, renderRow: categoryRow, after: categoryRows});
|
||
scope.listen(body, 'click', event => {
|
||
const button = event.target.closest('button[data-action="browse"]');
|
||
const tag = button && tags.itemOf(button.closest('tr'));
|
||
if (tag) browseLibrary(browseFilters('tags', tag.name));
|
||
});
|
||
scope.listen(categoryRows, 'click', event => {
|
||
const button = event.target.closest('button[data-action="browse"]');
|
||
const category = button && categories.itemOf(button.closest('.operation'));
|
||
if (!category) return;
|
||
// MC10: a category only images hold opens Images filtered by it; the Library would be empty.
|
||
if (categoryBrowseTarget(category) === 'images') browseImages({category: category.value});
|
||
else browseLibrary(browseFilters('categories', category.value));
|
||
});
|
||
|
||
let settled = Promise.resolve();
|
||
/** Re-read both lists from page one: after any command, rows can move between pages. */
|
||
function reload() {
|
||
settled = Promise.all([tags.stream.reset(), categories.stream.reset()]).then(() => undefined);
|
||
return settled;
|
||
}
|
||
/** A guarded command for one dialog; any outcome that may have changed storage re-reads the lists and the Library shelf. */
|
||
function createCommand(onChange) {
|
||
return createVocabularyCommand({api, onChange, onInvalidate: event => {
|
||
invalidateLibraryAfterWrite({kind: 'vocabulary', receipt: event.receipt || {phase: event.phase}});
|
||
reload();
|
||
}});
|
||
}
|
||
const h1 = main.querySelector('h1');
|
||
const actionOf = (row, action) => row?.querySelector(`button[data-action="${action}"]`) ?? null;
|
||
const dialog = createVocabularyDialog({api, scope, createCommand,
|
||
epoch: () => tags.stream.state.epoch ?? categories.stream.state.epoch,
|
||
categories: {stream: categories.stream, subscribe: categories.subscribe},
|
||
reload,
|
||
// Rows are replaced on every reset, so a result's row exists only once the re-read has landed.
|
||
settled: () => settled,
|
||
heading: () => h1,
|
||
tagAction: id => actionOf(tags.rowFor(item => item.id === id), 'rename'),
|
||
categoryAction: value => actionOf(categories.rowFor(item => item.value === value), 'browse')});
|
||
scope.listen(create, 'click', () => dialog.createTag(create));
|
||
scope.listen(manage.button, 'click', () => dialog.manageCategories(manage.button));
|
||
scope.listen(body, 'click', event => {
|
||
const button = event.target.closest('button[data-action="rename"]');
|
||
const tag = button && tags.itemOf(button.closest('tr'));
|
||
if (tag) dialog.renameTag(tag, button);
|
||
});
|
||
// A saved image tag set changes the Images counts.
|
||
scope.cleanup(onImageTagsSaved(() => { if (!scope.signal.aborted) reload(); }));
|
||
reload();
|
||
return {autoTag, create, manage: manage.button, tags: tags.stream, categories: categories.stream, reload, createCommand, dialog};
|
||
}
|