mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(studio): change a book page by page over MCP, and pick its photos from the gallery
This commit is contained in:
@@ -10,6 +10,7 @@ import {
|
||||
bookSpreadSchema,
|
||||
bookTextElementSchema,
|
||||
} from './book.schema';
|
||||
import { PHOTO_PICK } from './photo-pick';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -233,14 +234,26 @@ export const createBookArgs = {
|
||||
title: z.string().max(MAX_BOOK_TITLE).optional(),
|
||||
preset: bookPageSetupSchema.shape.preset.unwrap().optional(),
|
||||
};
|
||||
export const restoreBookPageArgs = {
|
||||
spread: bookSpreadSchema,
|
||||
/** Where it goes back when it is gone; a page still in the book is replaced where it is. */
|
||||
/**
|
||||
* A page as it was before a write, for the assistant's undo: `index` is where
|
||||
* it goes back when it is gone, a page still in the book is replaced where it is.
|
||||
*/
|
||||
export const bookPreviousSpreadSchema = z.object({
|
||||
index: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(MAX_SPREADS - 1),
|
||||
spread: bookSpreadSchema,
|
||||
});
|
||||
export type BookPreviousSpread = z.infer<typeof bookPreviousSpreadSchema>;
|
||||
|
||||
/**
|
||||
* The pages a write answered under `previous_spreads`, put back in one call
|
||||
* (several deleted pages are one undo), lowest index first.
|
||||
*/
|
||||
export const restoreBookPageArgs = {
|
||||
pages: z.array(bookPreviousSpreadSchema).min(1).max(BOOK_OP_LIMITS.pagesPerCall),
|
||||
expectedVersion: z.number().int().nonnegative(),
|
||||
};
|
||||
export const describeBookPageArgs = { spreadId: bookSpreadIdSchema };
|
||||
@@ -252,7 +265,7 @@ export const suggestBookPhotosArgs = {
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.optional(),
|
||||
purpose: z.enum(['page', 'cover']).optional(),
|
||||
limit: z.number().int().min(1).max(60).optional(),
|
||||
limit: z.number().int().min(1).max(PHOTO_PICK.maxLimit).optional(),
|
||||
};
|
||||
|
||||
export const editBookPageRequestSchema = z.strictObject(editBookPageArgs);
|
||||
@@ -357,18 +370,19 @@ export const bookPageDescriptionSchema = z.object({
|
||||
});
|
||||
export type BookPageDescription = z.infer<typeof bookPageDescriptionSchema>;
|
||||
|
||||
/** A page as it was before a write, for the assistant's undo. */
|
||||
export const bookPreviousSpreadSchema = z.object({
|
||||
index: z.number().int().nonnegative(),
|
||||
spread: bookSpreadSchema,
|
||||
});
|
||||
|
||||
/** What a book write answers. `previous_spreads` only when the call asked with `returnPrevious`. */
|
||||
/**
|
||||
* What a book write answers. `dropped` names the elements whose content left
|
||||
* the page (a layout, a hard remove). `previous_spreads` only when the call
|
||||
* asked with `returnPrevious`; `from_index` only from a move, where the page
|
||||
* stood before it, so a move can be taken back.
|
||||
*/
|
||||
export const bookWriteResultSchema = z.object({
|
||||
version: z.number().int().nonnegative(),
|
||||
spread_ids: z.array(z.string()),
|
||||
pages: z.array(bookSpreadSummarySchema),
|
||||
findings: z.array(bookFindingSchema).max(BOOK_OP_LIMITS.findings),
|
||||
dropped: z.array(z.string()).max(MAX_SPREAD_ELEMENTS * 2),
|
||||
previous_spreads: z.array(bookPreviousSpreadSchema).optional(),
|
||||
from_index: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
export type BookWriteResult = z.infer<typeof bookWriteResultSchema>;
|
||||
|
||||
@@ -126,6 +126,11 @@ describe('add, move and delete', () => {
|
||||
expect(ids(doc)).toEqual(['sp-cover', 'sp-first', 'sp-in2', 'sp-in3', 'sp-in1', 'sp-last', 'sp-back']);
|
||||
});
|
||||
|
||||
it('BOOKPG-023: answers the very same document for a move to where the page already is', () => {
|
||||
const before = book(3);
|
||||
expect(ok(moveBookPage(before, { spreadId: 'sp-in2', toIndex: 3 }))).toBe(before);
|
||||
});
|
||||
|
||||
it('BOOKPG-009: refuses to move a fixed page or to move a spread outside the covers', () => {
|
||||
for (const id of ['sp-cover', 'sp-first', 'sp-last', 'sp-back']) {
|
||||
expect(refused(moveBookPage(book(2), { spreadId: id, toIndex: 2 }))).toBe('protected_spread');
|
||||
@@ -155,7 +160,7 @@ describe('restore', () => {
|
||||
it('BOOKPG-012: puts a page back in its place when the book still has it', () => {
|
||||
const before = book(2);
|
||||
const changed = { ...(before.spreads[2] as BookSpread), background: '#112233' };
|
||||
const doc = ok(restoreBookPage(before, { spread: changed, index: 5, expectedVersion: 3 }));
|
||||
const doc = ok(restoreBookPage(before, { pages: [{ spread: changed, index: 5 }], expectedVersion: 3 }));
|
||||
expect(ids(doc)).toEqual(ids(before));
|
||||
expect(doc.spreads[2]?.background).toBe('#112233');
|
||||
});
|
||||
@@ -164,30 +169,95 @@ describe('restore', () => {
|
||||
const before = book(2);
|
||||
const gone = before.spreads[3] as BookSpread;
|
||||
const without = ok(deleteBookPages(before, { spreadIds: [gone.id] }));
|
||||
expect(ids(ok(restoreBookPage(without, { spread: gone, index: 3, expectedVersion: 1 })))).toEqual(ids(before));
|
||||
const clamped = ok(restoreBookPage(without, { spread: gone, index: 0, expectedVersion: 1 }));
|
||||
const back = ok(restoreBookPage(without, { pages: [{ spread: gone, index: 3 }], expectedVersion: 1 }));
|
||||
expect(ids(back)).toEqual(ids(before));
|
||||
const clamped = ok(restoreBookPage(without, { pages: [{ spread: gone, index: 0 }], expectedVersion: 1 }));
|
||||
expect(clamped.spreads[2]?.id).toBe(gone.id);
|
||||
});
|
||||
|
||||
it('BOOKPG-014: refuses a page that is not a page', () => {
|
||||
expect(
|
||||
refused(restoreBookPage(book(1), { spread: { id: 'x', role: 'middle' }, index: 2, expectedVersion: 1 })),
|
||||
).toBe('invalid_op');
|
||||
const notAPage = { pages: [{ spread: { id: 'x', role: 'middle' }, index: 2 }], expectedVersion: 1 };
|
||||
expect(refused(restoreBookPage(book(1), notAPage))).toBe('invalid_op');
|
||||
expect(refused(restoreBookPage(book(1), { pages: [], expectedVersion: 1 }))).toBe('invalid_op');
|
||||
});
|
||||
|
||||
it('BOOKPG-019: never makes a second cover, and never turns a page into another kind', () => {
|
||||
const doc = book(1);
|
||||
const asCover = { ...(doc.spreads[2] as BookSpread), role: 'cover' as const };
|
||||
expect(refused(restoreBookPage(doc, { spread: asCover, index: 2, expectedVersion: 1 }))).toBe('invalid_op');
|
||||
expect(refused(restoreBookPage(doc, { pages: [{ spread: asCover, index: 2 }], expectedVersion: 1 }))).toBe(
|
||||
'invalid_op',
|
||||
);
|
||||
for (const role of ['cover', 'first', 'last', 'back'] as const) {
|
||||
const extra = { ...blankSpread(role), id: `sp-extra-${role}` };
|
||||
expect(refused(restoreBookPage(doc, { spread: extra, index: 2, expectedVersion: 1 }))).toBe('protected_spread');
|
||||
expect(refused(restoreBookPage(doc, { pages: [{ spread: extra, index: 2 }], expectedVersion: 1 }))).toBe(
|
||||
'protected_spread',
|
||||
);
|
||||
}
|
||||
const lost = { ...doc, spreads: doc.spreads.filter((s) => s.role !== 'back') };
|
||||
const back = doc.spreads[doc.spreads.length - 1] as BookSpread;
|
||||
const restored = ok(restoreBookPage(lost, { spread: back, index: lost.spreads.length, expectedVersion: 1 }));
|
||||
const restored = ok(
|
||||
restoreBookPage(lost, { pages: [{ spread: back, index: lost.spreads.length }], expectedVersion: 1 }),
|
||||
);
|
||||
expect(ids(restored)).toEqual(ids(doc));
|
||||
});
|
||||
|
||||
it('BOOKPG-024: puts several deleted pages back in one call, lowest index first whatever order they come in', () => {
|
||||
const before = book(4);
|
||||
const without = ok(deleteBookPages(before, { spreadIds: ['sp-in1', 'sp-in3', 'sp-in4'] }));
|
||||
const previous = before.spreads.flatMap((spread, index) =>
|
||||
['sp-in1', 'sp-in3', 'sp-in4'].includes(spread.id) ? [{ index, spread }] : [],
|
||||
);
|
||||
const result = restoreBookPage(without, { pages: [...previous].reverse(), expectedVersion: 2 });
|
||||
expect(ids(ok(result))).toEqual(ids(before));
|
||||
expect(result.ok && result.spreadIds).toEqual(['sp-in1', 'sp-in3', 'sp-in4']);
|
||||
});
|
||||
|
||||
it('BOOKPG-025: refuses a photo that is neither in the gallery nor in the book, and takes one the book holds', () => {
|
||||
const base = book(2);
|
||||
const frame = (id: string, photoId: number) =>
|
||||
bookPhotoElementSchema.parse({ id, kind: 'photo', frame: { x: 10, y: 10, w: 80, h: 80 }, photoId });
|
||||
const withPhoto = {
|
||||
...base,
|
||||
spreads: base.spreads.map((s) => (s.id === 'sp-in1' ? { ...s, elements: [frame('p-kept', 7)] } : s)),
|
||||
};
|
||||
const page = withPhoto.spreads[3] as BookSpread;
|
||||
const photos = [{ photoId: 1 }];
|
||||
const stray = { ...page, elements: [frame('p-stray', 99)] };
|
||||
const args = (spread: BookSpread) => ({ pages: [{ spread, index: 3 }], expectedVersion: 1 });
|
||||
expect(refused(restoreBookPage(withPhoto, args(stray), { photos }))).toBe('photo_not_in_gallery');
|
||||
const fromBook = { ...page, elements: [frame('p-again', 7)] };
|
||||
expect(ok(restoreBookPage(withPhoto, args(fromBook), { photos })).spreads[3]?.elements[0]?.id).toBe('p-again');
|
||||
const fromGallery = { ...page, elements: [frame('p-new', 1)] };
|
||||
expect(ok(restoreBookPage(withPhoto, args(fromGallery), { photos })).spreads[3]?.elements[0]?.id).toBe('p-new');
|
||||
// Without a gallery in the context the engine cannot tell, and leaves it to the caller.
|
||||
expect(ok(restoreBookPage(withPhoto, args(stray))).spreads[3]?.elements[0]?.id).toBe('p-stray');
|
||||
});
|
||||
|
||||
it('BOOKPG-026: keeps a locked element as it is on a page put back in place, and adds no locked one', () => {
|
||||
const base = book(1);
|
||||
const lockedText = bookTextElementSchema.parse({
|
||||
id: 't-lock',
|
||||
kind: 'text',
|
||||
frame: { x: 20, y: 20, w: 100, h: 20 },
|
||||
text: 'Kept',
|
||||
locked: true,
|
||||
});
|
||||
const doc = {
|
||||
...base,
|
||||
spreads: base.spreads.map((s) => (s.id === 'sp-in1' ? { ...s, elements: [lockedText] } : s)),
|
||||
};
|
||||
const page = doc.spreads[2] as BookSpread;
|
||||
const args = (spread: BookSpread) => ({ pages: [{ spread, index: 2 }], expectedVersion: 1 });
|
||||
// The same element with its keys in another order is the same element.
|
||||
const backwards = Object.fromEntries(Object.entries(lockedText).reverse()) as BookTextElement;
|
||||
const reordered = { ...page, background: '#223344', elements: [backwards] };
|
||||
expect(ok(restoreBookPage(doc, args(reordered))).spreads[2]?.background).toBe('#223344');
|
||||
const changed = { ...page, elements: [{ ...lockedText, text: 'Changed' }] };
|
||||
expect(refused(restoreBookPage(doc, args(changed)))).toBe('locked');
|
||||
expect(refused(restoreBookPage(doc, args({ ...page, elements: [] })))).toBe('locked');
|
||||
const newLock = { ...lockedText, id: 't-new' };
|
||||
expect(refused(restoreBookPage(doc, args({ ...page, elements: [lockedText, newLock] })))).toBe('locked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the cover', () => {
|
||||
|
||||
@@ -91,6 +91,8 @@ export function moveBookPage(doc: BookDocument, args: unknown): BookEditResult {
|
||||
if (toIndex < first || toIndex >= limit) {
|
||||
throw failOp('index_out_of_range', `inner pages sit at index ${first} to ${limit - 1}`, null);
|
||||
}
|
||||
// A page already there: the very same document back, so a caller can tell nothing changed.
|
||||
if (toIndex === from) return { ok: true, doc, spreadIds: [spreadId], created: [], dropped: [] };
|
||||
const spreads = doc.spreads.filter((_, i) => i !== from);
|
||||
spreads.splice(toIndex, 0, doc.spreads[from] as BookSpread);
|
||||
return { ok: true, doc: { ...doc, spreads }, spreadIds: [spreadId], created: [], dropped: [] };
|
||||
@@ -121,46 +123,112 @@ export function deleteBookPages(doc: BookDocument, args: unknown): BookEditResul
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a page back as it was, for the assistant's undo: in its place when the
|
||||
* book still has a page with its id, else inserted at `index`, kept inside the
|
||||
* covers when it is an inner spread. The version check is the server's.
|
||||
* Put pages back as they were, for the assistant's undo: each in its place
|
||||
* when the book still has a page with its id, else inserted at its `index`,
|
||||
* kept inside the covers when it is an inner spread. The version check is the
|
||||
* server's. Several pages deleted at once go back lowest index first, so each
|
||||
* index means what it meant before the delete.
|
||||
*
|
||||
* Never a second cover: a page still in the book is only replaced by one of
|
||||
* the same role, and a cover, first, last or back page comes back only into a
|
||||
* book that has lost its own. Several pages deleted at once go back lowest
|
||||
* index first, so each index means what it meant before the delete.
|
||||
* book that has lost its own. A restore is no way around the rules of an
|
||||
* edit: with a gallery in the context, a photo must be in it or already in the
|
||||
* book, and a page still in the book keeps every locked element exactly as it
|
||||
* is, adding none. An honest undo always passes both, since the change it
|
||||
* takes back could touch neither and anything saved since fails the version.
|
||||
*/
|
||||
export function restoreBookPage(doc: BookDocument, args: unknown): BookEditResult {
|
||||
export function restoreBookPage(doc: BookDocument, args: unknown, ctx: BookOpsContext = {}): BookEditResult {
|
||||
const parsed = restoreBookPageRequestSchema.safeParse(args);
|
||||
if (!parsed.success) return { ok: false, error: invalidOp(parsed.error, null) };
|
||||
const { spread, index } = parsed.data;
|
||||
const pages = [...parsed.data.pages].sort((a, b) => a.index - b.index);
|
||||
return caught(() => {
|
||||
const at = doc.spreads.findIndex((s) => s.id === spread.id);
|
||||
if (at >= 0) {
|
||||
const current = doc.spreads[at] as BookSpread;
|
||||
if (current.role !== spread.role) {
|
||||
throw failOp(
|
||||
'invalid_op',
|
||||
`${spread.id} is the ${current.role} page now and cannot become the ${spread.role}`,
|
||||
null,
|
||||
);
|
||||
}
|
||||
const spreads = doc.spreads.slice();
|
||||
spreads[at] = spread;
|
||||
return { ok: true, doc: { ...doc, spreads }, spreadIds: [spread.id], created: [], dropped: [] };
|
||||
let cur = doc;
|
||||
for (const { spread, index } of pages) {
|
||||
restorablePhotos(spread, cur, ctx);
|
||||
cur = putBack(cur, spread, index);
|
||||
}
|
||||
if (spread.role !== 'inner' && doc.spreads.some((s) => s.role === spread.role)) {
|
||||
throw failOp('protected_spread', `the book already has its ${spread.role} page`, null);
|
||||
}
|
||||
if (doc.spreads.length >= MAX_SPREADS)
|
||||
throw failOp('too_many_spreads', `a book holds at most ${MAX_SPREADS} pages`, null);
|
||||
const { first, limit } = innerSpreadBounds(doc.spreads);
|
||||
const to = spread.role === 'inner' ? Math.min(Math.max(index, first), limit) : Math.min(index, doc.spreads.length);
|
||||
const spreads = [...doc.spreads.slice(0, to), spread, ...doc.spreads.slice(to)];
|
||||
return { ok: true, doc: { ...doc, spreads }, spreadIds: [spread.id], created: [], dropped: [] };
|
||||
const restored = [...new Set(pages.map((p) => p.spread.id))];
|
||||
return { ok: true, doc: cur, spreadIds: restored, created: [], dropped: [] };
|
||||
});
|
||||
}
|
||||
|
||||
/** One page back into the book: replaced where it is, or inserted at `index`. */
|
||||
function putBack(doc: BookDocument, spread: BookSpread, index: number): BookDocument {
|
||||
const at = doc.spreads.findIndex((s) => s.id === spread.id);
|
||||
if (at >= 0) {
|
||||
const current = doc.spreads[at] as BookSpread;
|
||||
if (current.role !== spread.role) {
|
||||
throw failOp(
|
||||
'invalid_op',
|
||||
`${spread.id} is the ${current.role} page now and cannot become the ${spread.role}`,
|
||||
null,
|
||||
);
|
||||
}
|
||||
sameLocks(current, spread);
|
||||
const spreads = doc.spreads.slice();
|
||||
spreads[at] = spread;
|
||||
return { ...doc, spreads };
|
||||
}
|
||||
if (spread.role !== 'inner' && doc.spreads.some((s) => s.role === spread.role)) {
|
||||
throw failOp('protected_spread', `the book already has its ${spread.role} page`, null);
|
||||
}
|
||||
if (doc.spreads.length >= MAX_SPREADS) {
|
||||
throw failOp('too_many_spreads', `a book holds at most ${MAX_SPREADS} pages`, null);
|
||||
}
|
||||
const { first, limit } = innerSpreadBounds(doc.spreads);
|
||||
const to = spread.role === 'inner' ? Math.min(Math.max(index, first), limit) : Math.min(index, doc.spreads.length);
|
||||
return { ...doc, spreads: [...doc.spreads.slice(0, to), spread, ...doc.spreads.slice(to)] };
|
||||
}
|
||||
|
||||
/** The photos a page shows: its photo frames, placed or parked, and the pictures on its map markers. */
|
||||
function photoIdsOf(spread: BookSpread): number[] {
|
||||
return [...spread.elements, ...spread.parked].flatMap((e) => {
|
||||
if (e.kind === 'photo') return e.photoId == null ? [] : [e.photoId];
|
||||
if (e.kind === 'map') return e.points.flatMap((p) => (p.photoId == null ? [] : [p.photoId]));
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
/** With a gallery known, every photo of a page coming back is in it or somewhere in the book already. */
|
||||
function restorablePhotos(spread: BookSpread, doc: BookDocument, ctx: BookOpsContext): void {
|
||||
if (!ctx.photos) return;
|
||||
const known = new Set([...ctx.photos.map((p) => p.photoId), ...doc.spreads.flatMap(photoIdsOf)]);
|
||||
const stray = photoIdsOf(spread).find((id) => !known.has(id));
|
||||
if (stray !== undefined) {
|
||||
throw failOp('photo_not_in_gallery', `photo ${stray} is neither in this journey's gallery nor in the book`, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Key order aside, the same value: a parsed and a stored element list their fields in different orders. */
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||
if (value && typeof value === 'object') {
|
||||
const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined);
|
||||
entries.sort(([a], [b]) => a.localeCompare(b));
|
||||
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
|
||||
}
|
||||
return JSON.stringify(value) ?? 'null';
|
||||
}
|
||||
|
||||
/** A page replaced in place keeps each of its locked elements as it is and gains no new one. */
|
||||
function sameLocks(current: BookSpread, spread: BookSpread): void {
|
||||
const lockedOf = (s: BookSpread) =>
|
||||
new Map([...s.elements, ...s.parked].filter((e) => e.locked).map((e) => [e.id, e] as const));
|
||||
const before = lockedOf(current);
|
||||
const after = new Map([...spread.elements, ...spread.parked].map((e) => [e.id, e] as const));
|
||||
for (const [id, el] of before) {
|
||||
const back = after.get(id);
|
||||
if (!back || canonical(back) !== canonical(el)) {
|
||||
throw failOp('locked', `${id} is locked and stays as it is`, null, id);
|
||||
}
|
||||
}
|
||||
for (const [id] of lockedOf(spread)) {
|
||||
if (!before.has(id)) {
|
||||
throw failOp('locked', `${id} is not locked on the page now and cannot come back locked`, null, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isBoundTo = (el: BookElement, source: 'journey.title' | 'journey.subtitle') =>
|
||||
el.kind === 'text' && el.binding?.source === source;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user