* feat(views): saved-views store and API
Add a saved_views table (page images|library, trimmed 1-100 character
name, whitelisted JSON state of at most 4 KB, position, timestamps)
installed through the same validated-savepoint migration as image
favorites. It is optional in old backups and required in a migrated
restore stage; restore rejects a tampered definition, extra indexes and
any row that would fail write validation.
Routes under /prompt_manager/saved-views: GET lists views by position,
POST {page,name,state} returns 201 {success, view}, PATCH /{id} {name}
renames and DELETE /{id} removes, both 404 for an unknown id. The state
must hold exactly the page's toolbar and Refine-this-view keys (Images:
q, category, sort, source, folder, media, tags; Library: q, category,
sort, tags) with their types and sort/media values; anything else is a
400.
Refs #249
* feat(views): Save view, the SAVED VIEWS sidebar and opening a view
The shared toolbar gains the concept's Save view between sort and Filters
on Images and the Prompt library. It opens the concept's simpleInput
("Save this view", "View name", default "Search: <q>" or "My workspace
view", Cancel / Save); an empty name is "Saved view". A save posts the
page's full whitelisted state (toolbar value plus Refine filters) and
toasts "Saved view added to the sidebar.".
The shell adds the concept's SAVED VIEWS label and nav#saved-nav, loaded
with the shell and re-read after every save. Rows use the concept's
links() markup (search icon, name, no count) and link #/saved/<id>.
Opening one mounts its page with the saved state through the page's own
filters, so the toolbar and "Filters · N" (D44) show it; the h1,
breadcrumb and title are the view's name. A removed Source or Folder is
dropped to its default after discovery, so no listing read is rejected;
an unknown id re-reads the list once, then opens Images; a failed list
read offers Retry.
D16 is retired: images-concept and library-concept no longer map Save
view out. New deviations: D49 (no PROPOSED badge) and D50 (no Needs
review row); shell-concept maps Favorites out until Task 3 and compares
a saved row against the concept's. Browser fixtures now wipe
saved_views.
* feat(views): Edit rename/delete and the Favorites saved view
- Favorites is the first SAVED VIEWS row (star icon, name, real count).
The count is the Favorites listing's own limit=1 total, follows the
nav-count rules and is re-read after every confirmed star or unstar.
- #/favorites opens Images filtered to favorites. The workspace listing
takes favorites=1: each selected root's favorites are read through the
image_favorites primary key and matched against the cached scan with the
toggle's case folding; a failed read is an error, never an unfiltered
page. The cursor scope includes the flag.
- Saved Images state gains a required favorites boolean, so Save view on
Favorites reopens the favorites.
- An open saved view's heading leads with Edit: "Edit saved view" with
View name, Delete... (danger), Cancel and Save. Delete... confirms in the
same dialog (never window.confirm). Toasts "Saved view renamed." and
"Saved view deleted."; a delete returns to the view's plain page.
- shell-concept no longer maps Favorites out (Needs review stays, D50).
Recorded as D51 in TESTING.md.
* fix(views): open stale saved views safely and finish the review fixes
Startup and restore now check only the saved_views structure (table,
columns, types, sizes, a JSON object state) and never the value rules,
so a row saved under older rules no longer stops the database from
opening. Reads normalize each view: missing keys take their defaults,
unknown keys are dropped, invalid values default and the name is made
displayable. POST and PATCH still validate strictly.
Only request validation (SavedViewInvalid) maps to 400; database and
internal errors are a logged generic 500. A saved view no longer
replaces the plain Images or Library return state, a toolbar change
while sources load keeps a saved Source and Folder, a state over 4 KB
is refused in the browser with its own toast, the delete confirmation
skips its failure toast after the page is gone, the Edit dialog reuses
the shared field helper, and quick star toggles coalesce into one
Favorites count read.
* test(views): cover leaving a pending saved view and add its coverage floor
A saved view left while the list or a rename is still pending leaves
the next page alone; the shell drops two unreachable heading guards.
workspace/saved-views.mjs gets its frontend coverage baseline entry;
no existing floor changes.
* fix(views): a corrupt saved-view state no longer blocks startup
At startup a saved_views row whose state is not a JSON object is
logged as a warning by id only and left in place. The listing and
rename skip it, so its #/saved/<id> link behaves like a missing view.
Restore stays strict and still rejects a backup holding such a row.
125 lines
6.3 KiB
JavaScript
125 lines
6.3 KiB
JavaScript
export const routes = [
|
||
{ id: 'images', label: 'Images', href: '/prompt_manager/gallery',
|
||
description: 'Browse your images, inspect their metadata and review generated tags.', action: 'Open existing image gallery' },
|
||
{ id: 'library', label: 'Prompt library', href: '/prompt_manager/admin',
|
||
description: 'Find, edit and organize the prompts already in your library.', action: 'Open existing prompt library' },
|
||
// Native screen; `title` is the concept's breadcrumb/title, the href stays for Overview's card.
|
||
{ id: 'tags', label: 'Tags & categories', title: 'Tags', href: '/prompt_manager/admin#/tags',
|
||
description: 'Explore your vocabulary and find the prompts associated with each tag.', action: 'Open existing tag manager' },
|
||
{ id: 'inspect', label: 'Inspect a file', href: '/prompt_manager/gallery.html',
|
||
description: 'Inspect generation metadata from an image or video file.', action: 'Open existing metadata inspector' },
|
||
{ id: 'overview', label: 'Overview' },
|
||
// SAVED VIEWS' first row (#249 D51): Images filtered to favorites. No href, so Overview lists no card for it.
|
||
{ id: 'favorites', label: 'Favorites' },
|
||
{ id: 'system', label: 'System', href: '/prompt_manager/admin',
|
||
description: 'Open the current dashboard, then choose Settings or Maintenance for configuration, scans, backups and diagnostics.', action: 'Open existing administration' },
|
||
];
|
||
|
||
const NATIVE_ROUTES = new Set(['images', 'library', 'tags', 'overview', 'saved', 'favorites']);
|
||
|
||
/** A saved view (#249 D16): the shell resolves its id to the view's page, name and state. */
|
||
const SAVED_ROUTE = Object.freeze({ id: 'saved', label: 'Saved view' });
|
||
|
||
/** Breadcrumb and document title: the concept names a few pages differently from their nav label. */
|
||
export function routeTitle(route) {
|
||
return route.title || route.label;
|
||
}
|
||
|
||
/** Routes the workspace does not render yet show the generic legacy handoff panel. */
|
||
export function isHandoff(route) {
|
||
return !NATIVE_ROUTES.has(route.id);
|
||
}
|
||
|
||
export function resolveRoute(hash) {
|
||
const saved = /^#\/saved\/([1-9]\d*)$/.exec(hash);
|
||
if (saved && Number.isSafeInteger(Number(saved[1]))) return {...SAVED_ROUTE, savedId:Number(saved[1]), hash};
|
||
const match = /^#\/library\/([1-9]\d*)$/.exec(hash);
|
||
if (match && Number.isSafeInteger(Number(match[1]))) {
|
||
return {...routes.find(route => route.id === 'library'), positiveId:Number(match[1]), hash};
|
||
}
|
||
return routes.find(route => hash === `#/${route.id}`) || routes[0];
|
||
}
|
||
|
||
export function summarizeStats(stats) {
|
||
return [['Prompts', 'total_prompts'], ['Images', 'total_images'], ['Tags', 'total_tags']]
|
||
.map(([label, key]) => {
|
||
const count = stats?.[key];
|
||
if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid library statistics');
|
||
return [label, count];
|
||
});
|
||
}
|
||
|
||
// The sidebar's real counts (D27): one bounded `limit=1` read each, whose `total` is the count. Favorites (D51) is the
|
||
// Favorites page's own listing, so its count is what that page lists.
|
||
const NAV_COUNT_SOURCES = Object.freeze([
|
||
['images', '/prompt_manager/images/output?mode=workspace&limit=1'],
|
||
['favorites', '/prompt_manager/images/output?mode=workspace&favorites=1&limit=1'],
|
||
['library', '/prompt_manager/library?limit=1'],
|
||
['tags', '/prompt_manager/vocabulary/tags?limit=1'],
|
||
]);
|
||
|
||
/** Route id -> count for the sidebar links; null when a page is missing or its total is not a count. */
|
||
export function summarizeNavCounts(pages = {}) {
|
||
return new Map(NAV_COUNT_SOURCES.map(([id]) => {
|
||
const total = pages?.[id]?.total;
|
||
return [id, Number.isSafeInteger(total) && total >= 0 ? total : null];
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* Read the counts; a failed read yields null for its route only. `onCount(id, count)` runs as each read settles, so a
|
||
* slow listing (the Images output scan) never holds back the cheap Library and Tags counts.
|
||
*/
|
||
/** The sidebar routes that carry a count (WORKSPACE, plus SAVED VIEWS' Favorites). */
|
||
export const NAV_COUNT_ROUTES = Object.freeze(NAV_COUNT_SOURCES.map(([id]) => id));
|
||
|
||
/** The counts a confirmed Library or vocabulary write can change; the Images listing cannot. */
|
||
export const LIBRARY_WRITE_COUNTS = Object.freeze(['library', 'tags']);
|
||
|
||
/** The count a confirmed favorite change can change. */
|
||
export const FAVORITE_WRITE_COUNTS = Object.freeze(['favorites']);
|
||
// Trailing delay that coalesces quick star toggles into one Favorites count read (#249 M1).
|
||
export const FAVORITE_COUNT_DELAY_MS = 300;
|
||
|
||
/** Read the given sidebar counts (all by default), reporting each as its own read settles. */
|
||
export async function loadNavCounts(api, signal, onCount = () => {}, ids = NAV_COUNT_ROUTES) {
|
||
const pages = {};
|
||
await Promise.all(NAV_COUNT_SOURCES.filter(([id]) => ids.includes(id)).map(async ([id, url]) => {
|
||
try { pages[id] = await api.get(url, { signal }); } catch { pages[id] = undefined; }
|
||
onCount(id, summarizeNavCounts(pages).get(id));
|
||
}));
|
||
return new Map([...summarizeNavCounts(pages)].filter(([id]) => ids.includes(id)));
|
||
}
|
||
|
||
/** Fired on the window to render the current route again, where setting the same hash fires no `hashchange`. */
|
||
const ROUTE_REFRESH_EVENT = 'prompt-manager:route-refresh';
|
||
|
||
/** The concept's `go()` (app.js 292–297): a link to the route already shown re-renders it instead of doing nothing. */
|
||
export function navigateTo(hash, win = window) {
|
||
if (win.location.hash === hash) win.dispatchEvent(new Event(ROUTE_REFRESH_EVENT));
|
||
else win.location.hash = hash;
|
||
}
|
||
|
||
export function mountRouter(win, onRoute) {
|
||
let current;
|
||
const refresh = () => {
|
||
current = undefined;
|
||
update();
|
||
};
|
||
const update = () => {
|
||
const route = resolveRoute(win.location.hash);
|
||
const hash = route.hash || `#/${route.id}`;
|
||
if (win.location.hash !== hash) win.history.replaceState(win.history.state, '', hash);
|
||
if (current?.id === route.id && current?.positiveId === route.positiveId && current?.savedId === route.savedId) return;
|
||
current = route;
|
||
onRoute(route);
|
||
};
|
||
win.addEventListener('hashchange', update);
|
||
win.addEventListener(ROUTE_REFRESH_EVENT, refresh);
|
||
update();
|
||
return () => {
|
||
win.removeEventListener('hashchange', update);
|
||
win.removeEventListener(ROUTE_REFRESH_EVENT, refresh);
|
||
};
|
||
}
|