From 3516c0b6b274bb1357b776f0af4a7d1054ec236c Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 22 Oct 2026 21:25:47 +0000 Subject: [PATCH] feat(assistant): the book design card shows each page before and after The proposal lists its pages in pairs, lets the user leave pages out before applying, and shows what the apply skipped on the receipt. --- client/src/api/bookDesignApi.ts | 21 + .../cards/bookDesign/BookDesignCard.test.tsx | 368 ++++++++++++++++++ .../cards/bookDesign/BookDesignCard.tsx | 202 ++++++++++ .../bookDesign/BookDesignSpreadStrip.tsx | 196 ++++++++++ .../cards/bookDesign/bookDesignLook.ts | 39 ++ .../cards/bookDesign/bookDesignModel.test.ts | 160 ++++++++ .../cards/bookDesign/bookDesignModel.ts | 162 ++++++++ .../cards/bookDesign/bookDesignViews.tsx | 20 + .../cards/bookDesign/useBookDesignDraft.ts | 240 ++++++++++++ .../components/Assistant/cards/cardLooks.ts | 12 + .../components/Assistant/cards/cardViews.ts | 4 + client/src/repo/bookDesignRepo.test.ts | 89 +++++ client/src/repo/bookDesignRepo.ts | 44 +++ shared/src/i18n/ar/assistantBookDesign.ts | 69 ++++ shared/src/i18n/ar/index.ts | 4 + shared/src/i18n/az/assistantBookDesign.ts | 41 ++ shared/src/i18n/az/index.ts | 4 + shared/src/i18n/br/assistantBookDesign.ts | 41 ++ shared/src/i18n/br/index.ts | 4 + shared/src/i18n/ca/assistantBookDesign.ts | 42 ++ shared/src/i18n/ca/index.ts | 4 + shared/src/i18n/cs/assistantBookDesign.ts | 48 +++ shared/src/i18n/cs/index.ts | 4 + shared/src/i18n/de/assistantBookDesign.ts | 43 ++ shared/src/i18n/de/index.ts | 4 + shared/src/i18n/en/assistantBookDesign.ts | 41 ++ shared/src/i18n/en/index.ts | 4 + shared/src/i18n/es/assistantBookDesign.ts | 41 ++ shared/src/i18n/es/index.ts | 4 + shared/src/i18n/et/assistantBookDesign.ts | 41 ++ shared/src/i18n/et/index.ts | 4 + shared/src/i18n/fr/assistantBookDesign.ts | 41 ++ shared/src/i18n/fr/index.ts | 4 + shared/src/i18n/gr/assistantBookDesign.ts | 42 ++ shared/src/i18n/gr/index.ts | 4 + shared/src/i18n/hu/assistantBookDesign.ts | 41 ++ shared/src/i18n/hu/index.ts | 4 + shared/src/i18n/id/assistantBookDesign.ts | 34 ++ shared/src/i18n/id/index.ts | 4 + shared/src/i18n/it/assistantBookDesign.ts | 42 ++ shared/src/i18n/it/index.ts | 4 + shared/src/i18n/ja/assistantBookDesign.ts | 35 ++ shared/src/i18n/ja/index.ts | 4 + shared/src/i18n/ko/assistantBookDesign.ts | 34 ++ shared/src/i18n/ko/index.ts | 4 + shared/src/i18n/nl/assistantBookDesign.ts | 42 ++ shared/src/i18n/nl/index.ts | 4 + shared/src/i18n/pl/assistantBookDesign.ts | 56 +++ shared/src/i18n/pl/index.ts | 4 + shared/src/i18n/ru/assistantBookDesign.ts | 56 +++ shared/src/i18n/ru/index.ts | 4 + shared/src/i18n/sk/assistantBookDesign.ts | 48 +++ shared/src/i18n/sk/index.ts | 4 + shared/src/i18n/sv/assistantBookDesign.ts | 41 ++ shared/src/i18n/sv/index.ts | 4 + shared/src/i18n/th/assistantBookDesign.ts | 34 ++ shared/src/i18n/th/index.ts | 4 + shared/src/i18n/tr/assistantBookDesign.ts | 41 ++ shared/src/i18n/tr/index.ts | 4 + shared/src/i18n/uk/assistantBookDesign.ts | 55 +++ shared/src/i18n/uk/index.ts | 4 + shared/src/i18n/vi/assistantBookDesign.ts | 34 ++ shared/src/i18n/vi/index.ts | 4 + shared/src/i18n/zh-TW/assistantBookDesign.ts | 34 ++ shared/src/i18n/zh-TW/index.ts | 4 + shared/src/i18n/zh/assistantBookDesign.ts | 34 ++ shared/src/i18n/zh/index.ts | 4 + 67 files changed, 2816 insertions(+) create mode 100644 client/src/api/bookDesignApi.ts create mode 100644 client/src/components/Assistant/cards/bookDesign/BookDesignCard.test.tsx create mode 100644 client/src/components/Assistant/cards/bookDesign/BookDesignCard.tsx create mode 100644 client/src/components/Assistant/cards/bookDesign/BookDesignSpreadStrip.tsx create mode 100644 client/src/components/Assistant/cards/bookDesign/bookDesignLook.ts create mode 100644 client/src/components/Assistant/cards/bookDesign/bookDesignModel.test.ts create mode 100644 client/src/components/Assistant/cards/bookDesign/bookDesignModel.ts create mode 100644 client/src/components/Assistant/cards/bookDesign/bookDesignViews.tsx create mode 100644 client/src/components/Assistant/cards/bookDesign/useBookDesignDraft.ts create mode 100644 client/src/repo/bookDesignRepo.test.ts create mode 100644 client/src/repo/bookDesignRepo.ts create mode 100644 shared/src/i18n/ar/assistantBookDesign.ts create mode 100644 shared/src/i18n/az/assistantBookDesign.ts create mode 100644 shared/src/i18n/br/assistantBookDesign.ts create mode 100644 shared/src/i18n/ca/assistantBookDesign.ts create mode 100644 shared/src/i18n/cs/assistantBookDesign.ts create mode 100644 shared/src/i18n/de/assistantBookDesign.ts create mode 100644 shared/src/i18n/en/assistantBookDesign.ts create mode 100644 shared/src/i18n/es/assistantBookDesign.ts create mode 100644 shared/src/i18n/et/assistantBookDesign.ts create mode 100644 shared/src/i18n/fr/assistantBookDesign.ts create mode 100644 shared/src/i18n/gr/assistantBookDesign.ts create mode 100644 shared/src/i18n/hu/assistantBookDesign.ts create mode 100644 shared/src/i18n/id/assistantBookDesign.ts create mode 100644 shared/src/i18n/it/assistantBookDesign.ts create mode 100644 shared/src/i18n/ja/assistantBookDesign.ts create mode 100644 shared/src/i18n/ko/assistantBookDesign.ts create mode 100644 shared/src/i18n/nl/assistantBookDesign.ts create mode 100644 shared/src/i18n/pl/assistantBookDesign.ts create mode 100644 shared/src/i18n/ru/assistantBookDesign.ts create mode 100644 shared/src/i18n/sk/assistantBookDesign.ts create mode 100644 shared/src/i18n/sv/assistantBookDesign.ts create mode 100644 shared/src/i18n/th/assistantBookDesign.ts create mode 100644 shared/src/i18n/tr/assistantBookDesign.ts create mode 100644 shared/src/i18n/uk/assistantBookDesign.ts create mode 100644 shared/src/i18n/vi/assistantBookDesign.ts create mode 100644 shared/src/i18n/zh-TW/assistantBookDesign.ts create mode 100644 shared/src/i18n/zh/assistantBookDesign.ts diff --git a/client/src/api/bookDesignApi.ts b/client/src/api/bookDesignApi.ts new file mode 100644 index 000000000..d338f382b --- /dev/null +++ b/client/src/api/bookDesignApi.ts @@ -0,0 +1,21 @@ +import type { BookDesignSelectionRequest, BookDesignSelectionResponse } from '@trek/shared'; + +import apiClient from './client'; + +/** + * The assistant's whole-book design drafts as the Studio chat's proposal card + * narrows them: the pages of a draft its apply writes. The draft itself is + * read through `assistantApi.bookDesign`, which the Studio also draws a page + * of a draft from. Online only, like the assistant: a draft lives on the + * server for a few hours and nowhere else. + */ +export const bookDesignApi = { + selection: ( + journeyId: number, + designId: string, + body: BookDesignSelectionRequest + ): Promise => + apiClient + .put(`/journeys/${journeyId}/book-designs/${encodeURIComponent(designId)}/selection`, body) + .then((r) => r.data), +}; diff --git a/client/src/components/Assistant/cards/bookDesign/BookDesignCard.test.tsx b/client/src/components/Assistant/cards/bookDesign/BookDesignCard.test.tsx new file mode 100644 index 000000000..48bd02980 --- /dev/null +++ b/client/src/components/Assistant/cards/bookDesign/BookDesignCard.test.tsx @@ -0,0 +1,368 @@ +/** + * FE-BOOKDSN-010 to FE-BOOKDSN-017 + * + * The whole-book design in the Studio's chat: the held apply named by its + * style with its facts, each page it changes drawn beside the page it + * replaces (the book from the Studio, the draft from the server), a page + * taken out of the apply sent after a pause and put back when the server + * refuses, the receipt with the pages it wrote and the ones it left, a draft + * the server forgot, the way to a page, the draft as an answer card, a + * choice still waiting sent as the card goes away, and a book that cannot be + * read; a choice sent at once when the pointer leaves the pages (the way to + * Apply), and an older answer arriving last never taken for what the server + * kept. + */ +import { + type AssistantApplied, + type AssistantChangePreview, + type AssistantMessage, + blankBook, + type BookDesignCard, + type BookDesignDraftResponse, + type BookDocument, + type BookSpread, +} from '@trek/shared'; +import type { ReactNode } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { act, fireEvent, render, screen, waitFor } from '../../../../../tests/helpers/render'; +import { useStudioStore } from '../../../../store/studioStore'; +import AssistantChangeCard from '../../AssistantChangeCard'; +import type { ChangeItem } from '../../assistantParts'; +import { type AssistantView, AssistantViewContext } from '../../assistantViewContext'; +import { CARD_RULES } from '../cardLooks'; +import { BookDesignBlock } from './BookDesignCard'; + +const repo = vi.hoisted(() => ({ draft: vi.fn(), book: vi.fn(), select: vi.fn() })); +vi.mock('../../../../repo/bookDesignRepo', () => ({ bookDesignRepo: repo })); + +const STUDIO = useStudioStore.getState(); + +/** sp-1 the cover, sp-2 the first page, sp-3 a double page, sp-4 the last page, sp-5 the back. */ +function book(): BookDocument { + let seq = 0; + return blankBook({ title: 'Lisbon', newId: (prefix) => `${prefix}-${++seq}` }); +} + +function inner(id: string): BookSpread { + return { id, role: 'inner', background: null, elements: [], parked: [], entryId: null }; +} + +/** The book in the Studio: a second double page (sp-7) after sp-3. */ +function stored(): BookDocument { + const doc = book(); + return { ...doc, spreads: [...doc.spreads.slice(0, 3), inner('sp-7'), ...doc.spreads.slice(3)] }; +} + +/** The designed book: sp-3 laid out again, a new double page sp-9, sp-7 dropped. */ +function designed(): BookDocument { + const doc = book(); + return { ...doc, spreads: [...doc.spreads.slice(0, 3), inner('sp-9'), ...doc.spreads.slice(3)] }; +} + +type Row = [string, number, BookDesignCard['spreads'][number]['action'], number, number]; + +/** The cover kept, sp-3 laid out again (one fault, one warning), sp-9 new (two warnings), sp-7 dropped. */ +const ROWS: Row[] = [ + ['sp-1', 0, 'keep', 0, 0], + ['sp-3', 2, 'replace', 1, 1], + ['sp-9', 3, 'insert', 0, 2], + ['sp-7', 3, 'drop', 0, 0], +]; + +function draft(rows: Row[] = ROWS, doc: BookDocument = designed()): BookDesignDraftResponse { + const plan = rows.map(([spreadId, index, action, severe, warn]) => ({ + spreadId, + index, + action, + beat: 'duo' as const, + chapter: null, + entryId: null, + photoIds: [], + findings: { severe, warn }, + })); + const selection = rows.filter(([, , action]) => action !== 'keep').map(([spreadId]) => spreadId); + return { designId: 'd-1', baseVersion: 4, expiresAt: '2026-10-22T18:00:00.000Z', document: doc, plan, selection }; +} + +function card(over: Partial = {}): BookDesignCard { + const spreads = ROWS.map(([spreadId, index, action, severe, warn]) => ({ + spreadId, + index, + action, + beat: 'duo' as const, + chapter: null, + entryId: null, + photoCount: 0, + severe, + warn, + })); + return { + kind: 'bookDesign', + change: 'proposed', + journeyId: 3, + designId: 'd-1', + baseVersion: 4, + style: 'editorial', + paper: '#faf8f4', + ink: '#1a1a1a', + accent: '#c0392b', + heading: 'playfair', + body: 'garamond', + spreads, + more: 6, + leftOut: 2, + revisionId: null, + skipped: [], + ...over, + }; +} + +function item(state: ChangeItem['state'], held: BookDesignCard): ChangeItem { + const preview: AssistantChangePreview = { + toolCallId: 'w1', + verbKey: 'designBook', + subject: '', + rows: [], + dayId: null, + placeIds: [], + undoable: true, + card: held, + }; + const receipt: AssistantApplied = { toolCallId: 'w1', entity: 'book_page', ids: [], dayId: null, undoUntil: null }; + return { toolCallId: 'w1', preview, applied: state === 'applied' ? receipt : null, state, card: held }; +} + +/** The chat of journey 3's Studio (its key is the negated journey id), unless `view` names another. */ +function inView(ui: ReactNode, view: Partial = {}) { + const value: AssistantView = { tripId: -3, variant: 'window', ...view }; + return render({ui}); +} + +/** The round choice of a page, by the page's name. */ +function choice(page: string, nth = 0): HTMLElement { + return screen.getAllByRole('button', { name: `${page}: use the new design` })[nth] as HTMLElement; +} + +/** The pages of the design, the area a pointer leaves on its way to Apply. */ +function pagesArea(): HTMLElement { + return screen.getByRole('list', { name: 'Pages of the design' }).parentElement as HTMLElement; +} + +beforeEach(() => { + repo.draft.mockResolvedValue(draft()); + repo.book.mockResolvedValue(stored()); + repo.select.mockImplementation((_journeyId: number, _designId: string, ids: string[]) => Promise.resolve(ids)); +}); + +afterEach(() => { + useStudioStore.setState(STUDIO, true); + vi.clearAllMocks(); +}); + +describe('the whole-book design card', () => { + it('FE-BOOKDSN-010: a waiting design names its style and facts, and draws each page beside the one it replaces', async () => { + useStudioStore.setState({ doc: stored(), activeSpread: 0 }); + inView(); + expect(screen.getByText('Editorial design')).toBeInTheDocument(); + expect(screen.getByText('Apply the book design')).toBeInTheDocument(); + expect(screen.getByRole('img', { name: 'Paper, ink and accent colour' })).toBeInTheDocument(); + expect(screen.getByText('Playfair Display and EB Garamond')).toBeInTheDocument(); + expect(screen.getByText('3 pages change')).toBeInTheDocument(); + expect(screen.getByText('2 photos left out')).toBeInTheDocument(); + expect(screen.getByText('4 things to check')).toBeInTheDocument(); + + // The page laid out again shows before and after; the new page and the dropped one stand alone. + expect(await screen.findByText('Before')).toBeInTheDocument(); + expect(screen.getByText('After')).toBeInTheDocument(); + expect(screen.getByText('Double page 1')).toBeInTheDocument(); + expect(screen.getAllByText('Double page 2')).toHaveLength(2); + expect(screen.getByText('New')).toBeInTheDocument(); + expect(screen.getByText('Removed')).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'Show this page' })).toHaveLength(4); + // The page laid out again and the new page each carry two findings; the dropped one none. + expect(screen.getAllByRole('img', { name: '2 things to check' })).toHaveLength(2); + expect(choice('Double page 1')).toHaveAttribute('aria-pressed', 'true'); + // The draft comes from the server, the book from the Studio. + expect(repo.draft).toHaveBeenCalledWith(3, 'd-1'); + expect(repo.book).not.toHaveBeenCalled(); + }); + + it('FE-BOOKDSN-011: a page taken out is shown at once and sent after a pause, the last choice only', async () => { + useStudioStore.setState({ doc: stored() }); + inView(); + await screen.findByText('Before'); + fireEvent.click(choice('Double page 2', 0)); + fireEvent.click(choice('Double page 2', 1)); + expect(choice('Double page 2', 0)).toHaveAttribute('aria-pressed', 'false'); + expect(choice('Double page 2', 1)).toHaveAttribute('aria-pressed', 'false'); + expect(repo.select).not.toHaveBeenCalled(); + await waitFor(() => expect(repo.select).toHaveBeenCalledTimes(1)); + expect(repo.select).toHaveBeenCalledWith(3, 'd-1', ['sp-3']); + + // Put back in: the pages in the plan's order. + fireEvent.click(choice('Double page 2', 1)); + await waitFor(() => expect(repo.select).toHaveBeenCalledTimes(2)); + expect(repo.select).toHaveBeenLastCalledWith(3, 'd-1', ['sp-3', 'sp-7']); + }); + + it('FE-BOOKDSN-012: a refused choice is put back to what the server kept, and says so', async () => { + useStudioStore.setState({ doc: stored() }); + repo.select.mockRejectedValue(new Error('offline')); + inView(); + await screen.findByText('Before'); + fireEvent.click(choice('Double page 1')); + expect(choice('Double page 1')).toHaveAttribute('aria-pressed', 'false'); + expect(await screen.findByText('The choice of pages could not be saved and was put back.')).toBeInTheDocument(); + expect(choice('Double page 1')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('FE-BOOKDSN-013: the receipt draws the pages it wrote as the book holds them, and names the ones it left', async () => { + useStudioStore.setState({ doc: designed() }); + const skipped: BookDesignCard['skipped'] = [ + { spreadId: 'sp-9', reason: 'changed_since' }, + { spreadId: 'sp-7', reason: 'excluded' }, + ]; + inView(); + expect(screen.getByText('1 page changed since, kept as it is')).toBeInTheDocument(); + expect(screen.getByText('1 page not chosen')).toBeInTheDocument(); + expect(screen.queryByText('3 pages change')).toBeNull(); + expect(await screen.findAllByRole('button', { name: 'Show this page' })).toHaveLength(1); + expect(screen.queryByText('Before')).toBeNull(); + expect(screen.queryByRole('button', { name: /use the new design/ })).toBeNull(); + // The draft is gone with the apply: nothing asks for it. + expect(repo.draft).not.toHaveBeenCalled(); + }); + + it('FE-BOOKDSN-014: a draft the server forgot keeps the badges and says so; any other failure says the pages did not load', async () => { + useStudioStore.setState({ doc: stored() }); + repo.draft.mockRejectedValue(Object.assign(new Error('gone'), { response: { status: 410 } })); + const first = inView(); + const gone = await screen.findByText('This draft is gone. Ask for the design again to see its pages.'); + expect(gone).toBeInTheDocument(); + expect(screen.getByText('3 pages change')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Show this page' })).toBeNull(); + first.unmount(); + + repo.draft.mockRejectedValue(new Error('down')); + inView(); + expect(await screen.findByText('The pages could not be loaded.')).toBeInTheDocument(); + }); + + it('FE-BOOKDSN-015: a page opens in the Studio: there its page, elsewhere the Studio on it', async () => { + useStudioStore.setState({ doc: stored(), activeSpread: 0 }); + const onOpen = vi.fn(); + const own = inView(, { onOpen }); + const sheets = await screen.findAllByRole('button', { name: 'Show this page' }); + fireEvent.click(sheets[0] as HTMLElement); + expect(useStudioStore.getState().activeSpread).toBe(2); + expect(onOpen).not.toHaveBeenCalled(); + own.unmount(); + + // A trip's chat: the book is read from the server, and a page opens the Studio on it. + inView(, { tripId: 4, onOpen }); + const away = await screen.findAllByRole('button', { name: 'Show this page' }); + expect(repo.book).toHaveBeenCalledWith(3); + fireEvent.click(away[0] as HTMLElement); + expect(onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/journey/3/studio?page=sp-3' }); + }); + + it('FE-BOOKDSN-017: a choice still waiting is sent when the card goes away; a book that cannot be read leaves the draft alone', async () => { + useStudioStore.setState({ doc: stored() }); + const first = inView(); + await screen.findByText('Before'); + fireEvent.click(choice('Double page 1')); + first.unmount(); + expect(repo.select).toHaveBeenCalledWith(3, 'd-1', ['sp-9', 'sp-7']); + + // A trip's chat whose book read fails: the draft's pages stand alone, the dropped page has nothing to draw. + repo.book.mockRejectedValue(new Error('down')); + inView(, { tripId: 4 }); + expect(await screen.findAllByRole('button', { name: 'Show this page' })).toHaveLength(2); + expect(screen.queryByText('Before')).toBeNull(); + expect(screen.getByText('Double page 1')).toBeInTheDocument(); + }); + + it('FE-BOOKDSN-016: the draft stands as an answer card that gives way to its proposal; a discarded one draws no pages', async () => { + useStudioStore.setState({ doc: stored() }); + const many = Array.from({ length: 14 }, (_, i): Row => [`sp-n${i}`, i + 1, 'insert', 0, 0]); + const doc = book(); + repo.draft.mockResolvedValue(draft(many, { ...doc, spreads: [...doc.spreads, ...many.map(([id]) => inner(id))] })); + const answer = card({ change: 'none' }); + const message = {} as AssistantMessage; + const first = inView(); + expect(screen.getByText('Editorial design')).toBeInTheDocument(); + expect(screen.getByText('10 pages')).toBeInTheDocument(); + expect(await screen.findAllByRole('button', { name: 'Show this page' })).toHaveLength(12); + expect(screen.queryByRole('button', { name: /use the new design/ })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Show all 14 pages' })); + expect(screen.getAllByRole('button', { name: 'Show this page' })).toHaveLength(14); + first.unmount(); + + expect(CARD_RULES.yieldsToChange(answer, card())).toBe(true); + expect(CARD_RULES.yieldsToChange(answer, card({ designId: 'd-2' }))).toBe(false); + + vi.clearAllMocks(); + inView(); + expect(screen.getByText('Editorial design')).toHaveClass('line-through'); + expect(screen.queryByRole('button', { name: 'Show this page' })).toBeNull(); + expect(repo.draft).not.toHaveBeenCalled(); + }); + + it('FE-BOOKDSN-018: a choice goes out as soon as the pointer leaves the pages, and stays faded while the apply runs', async () => { + useStudioStore.setState({ doc: stored() }); + const view = inView(); + await screen.findByText('Before'); + fireEvent.click(choice('Double page 1')); + expect(repo.select).not.toHaveBeenCalled(); + fireEvent.pointerLeave(pagesArea()); + expect(repo.select).toHaveBeenCalledTimes(1); + expect(repo.select).toHaveBeenCalledWith(3, 'd-1', ['sp-9', 'sp-7']); + expect(choice('Double page 1').closest('li')).toHaveClass('opacity-50'); + + // The apply runs: no choice any more, the page taken out still faded, nothing sent twice. + const running = ; + view.rerender( + {running} + ); + expect(screen.queryByRole('button', { name: /use the new design/ })).toBeNull(); + expect(screen.getByText('Double page 1').closest('li')).toHaveClass('opacity-50'); + expect(screen.getAllByText('Double page 2')[0]?.closest('li')).not.toHaveClass('opacity-50'); + expect(repo.select).toHaveBeenCalledTimes(1); + }); + + it('FE-BOOKDSN-019: an older answer arriving last neither shows nor becomes what a refusal puts back', async () => { + useStudioStore.setState({ doc: stored() }); + let release: (ids: string[]) => void = () => undefined; + repo.select + .mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve; + }) + ) + .mockImplementationOnce((_journeyId: number, _designId: string, ids: string[]) => Promise.resolve(ids)) + .mockImplementationOnce(() => Promise.reject(new Error('down'))); + inView(); + await screen.findByText('Before'); + + // sp-7 out (its answer held back), then in again (answered at once). + fireEvent.click(choice('Double page 2', 1)); + fireEvent.pointerLeave(pagesArea()); + fireEvent.click(choice('Double page 2', 1)); + fireEvent.pointerLeave(pagesArea()); + await waitFor(() => expect(repo.select).toHaveBeenCalledTimes(2)); + await act(async () => { + release(['sp-3', 'sp-9']); + await Promise.resolve(); + }); + expect(choice('Double page 2', 1)).toHaveAttribute('aria-pressed', 'true'); + + // A refused choice puts back the newest answer, sp-7 in. + fireEvent.click(choice('Double page 2', 0)); + fireEvent.pointerLeave(pagesArea()); + expect(await screen.findByText('The choice of pages could not be saved and was put back.')).toBeInTheDocument(); + expect(choice('Double page 2', 0)).toHaveAttribute('aria-pressed', 'true'); + expect(choice('Double page 2', 1)).toHaveAttribute('aria-pressed', 'true'); + }); +}); diff --git a/client/src/components/Assistant/cards/bookDesign/BookDesignCard.tsx b/client/src/components/Assistant/cards/bookDesign/BookDesignCard.tsx new file mode 100644 index 000000000..ef08c4555 --- /dev/null +++ b/client/src/components/Assistant/cards/bookDesign/BookDesignCard.tsx @@ -0,0 +1,202 @@ +import type { AssistantMessage, BookDesignCard, TrekCard } from '@trek/shared'; +import { CircleSlash, Files, History, ImageOff, Palette, TriangleAlert, Type } from 'lucide-react'; +import { lazy, Suspense } from 'react'; + +import { useTranslation } from '../../../../i18n'; +import { BOOK_FONTS } from '../../../Studio/bookFonts'; +import type { ChangeItem } from '../../assistantParts'; +import type { CardEntry } from '../cardTypes'; +import { CardFacts, Fact } from '../parts/CardFacts'; +import CardFrame from '../parts/CardFrame'; +import CardHeader from '../parts/CardHeader'; +import { designCounts, skippedCounts, styleLabel } from './bookDesignModel'; + +/** + * The whole-book design in the chat. Its head names the design after its + * style, with the book's colours (paper, ink, accent) as three dots; its + * facts name the two typefaces, how many pages change, the photos left out + * and the findings worth a look; under it the pages, each beside the page it + * replaces (BookDesignSpreadStrip, loaded with the first design card). + * + * `design_book`'s draft stands as an answer card; the held + * `apply_book_design` is a change row whose pages can be taken out one by one + * before the person applies the rest; its receipt shows the pages it wrote + * and names the ones it left as they were. + */ + +interface SlotProps { + card: BookDesignCard; + item: ChangeItem; +} + +const BookDesignSpreadStrip = lazy(() => import('./BookDesignSpreadStrip')); + +/** A change that no longer runs: no pages to draw, its name struck through. */ +const GONE: ReadonlySet = new Set(['failed', 'discarded', 'expired']); +const STRUCK: ReadonlySet = new Set(['discarded', 'expired']); + +const SUBJECT_ROW = 'flex min-w-0 items-center gap-2'; +const SUBJECT = 'block min-w-0 truncate text-body font-semibold leading-tight text-content'; +const SUBJECT_STRUCK = `${SUBJECT} line-through`; +const SWATCHES = 'inline-flex flex-none items-center gap-0.5'; +const SWATCH = 'h-2.5 w-2.5 rounded-full ring-1 ring-inset ring-edge'; +const CARDS = 'flex flex-col gap-2'; +const BODY = 'mt-1'; + +/** The book's colours as three dots: paper, ink and accent. */ +function Swatches({ card }: { card: BookDesignCard }) { + const { t } = useTranslation(); + const colours = [ + { role: 'paper', value: card.paper }, + { role: 'ink', value: card.ink }, + { role: 'accent', value: card.accent }, + ]; + return ( + + {colours.map((colour) => ( + + ))} + + ); +} + +/** The pages an applied design left as they were, by why. */ +function SkippedFacts({ card }: { card: BookDesignCard }) { + const { t } = useTranslation(); + const skipped = skippedCounts(card); + return ( + <> + {skipped.changed_since > 0 && ( + + )} + {skipped.photo_gone > 0 && ( + + )} + {skipped.excluded > 0 && ( + + )} + + ); +} + +/** The design's facts: its typefaces, the pages it changes, photos left out, findings; once applied, what it left. */ +function DesignFacts({ card, applied }: { card: BookDesignCard; applied: boolean }) { + const { t } = useTranslation(); + const counts = designCounts(card); + const faces = { heading: BOOK_FONTS[card.heading].name, body: BOOK_FONTS[card.body].name }; + // One typeface for both is named once. + const typeface = faces.heading === faces.body ? faces.heading : t('assistant.card.bookDesign.faces', faces); + return ( + <> + + {!applied && counts.changes > 0 && ( + + )} + {!applied && card.leftOut > 0 && ( + + )} + {!applied && counts.findings > 0 && ( + + )} + {applied && } + + ); +} + +interface PagesProps { + card: BookDesignCard; + mode: 'draft' | 'applied'; + editable: boolean; +} + +/** The pages of the design under its card or row. */ +function DesignPages({ card, mode, editable }: PagesProps) { + return ( +
+ + + +
+ ); +} + +/** A draft `design_book` made, nothing proposed yet: the design, its facts and its pages. */ +function DesignAnswer({ card }: { card: BookDesignCard }) { + const { t } = useTranslation(); + const counts = designCounts(card); + return ( + + } + /> + + + + + + ); +} + +/** One answer card of the group, drawn when it is a design. */ +function DesignEntry({ card }: { card: TrekCard }) { + return card.kind === 'bookDesign' ? : null; +} + +/** The drafts an answer made, one card each. */ +export function BookDesignBlock({ cards }: { cards: readonly CardEntry[]; message: AssistantMessage }) { + return ( +
+ {cards.map((entry) => ( + + ))} +
+ ); +} + +/** The design as a change row's subject: its style in bold with its colours, struck once it no longer runs. */ +export function BookDesignSubject({ card, item }: SlotProps) { + const { t } = useTranslation(); + const subject = styleLabel(card, t); + return ( + + + {subject} + + + + ); +} + +/** The change row's facts; once applied, the pages it left as they were. */ +export function BookDesignFacts({ card, item }: SlotProps) { + return ; +} + +/** + * The pages under the change row: while it waits, each page beside the one + * it replaces, with the choice of pages until it is decided; once applied, + * the pages as the book holds them now. Nothing for a change that no longer + * runs. + */ +export function BookDesignBody({ card, item }: SlotProps) { + if (GONE.has(item.state)) return null; + const applied = item.state === 'applied'; + const editable = item.state === 'pending' && card.change === 'proposed'; + return ; +} diff --git a/client/src/components/Assistant/cards/bookDesign/BookDesignSpreadStrip.tsx b/client/src/components/Assistant/cards/bookDesign/BookDesignSpreadStrip.tsx new file mode 100644 index 000000000..f7bbff2ea --- /dev/null +++ b/client/src/components/Assistant/cards/bookDesign/BookDesignSpreadStrip.tsx @@ -0,0 +1,196 @@ +import type { BookDesignCard, BookPageSetup, BookSpread } from '@trek/shared'; +import { ArrowRight, Check, TriangleAlert } from 'lucide-react'; +import { type FocusEvent, useState } from 'react'; + +import { useTranslation } from '../../../../i18n'; +import { SpreadThumb } from '../../../Studio/SpreadThumb'; +import { pageLabel } from '../book/bookCardModel'; +import { ChangeMark } from '../parts/CardFacts'; +import type { DesignPair } from './bookDesignModel'; +import { useBookDesignDraft } from './useBookDesignDraft'; + +/** + * The pages of a whole-book design drawn small, a row to scroll through: + * each page the design changes beside the page of the book it replaces (a + * new page alone, marked new; a dropped one alone, marked removed), its + * findings flagged. While the proposal waits, a round choice on each page + * keeps it in the apply or takes it out. Once applied, the pages as the book + * holds them now. Each sheet is the editor's own view under a scale, so the + * card never looks different from the page; pressing one shows that page. + */ + +/** A sheet's height in pixels; its width follows the page. */ +const SHEET_HEIGHT = 48; +/** Pages shown before the rest wait behind "Show all". */ +const FIRST_PAIRS = 12; + +const FOCUS = 'outline-none focus-visible:ring-2 focus-visible:ring-accent'; +const STRIP = 'flex flex-col gap-1.5'; +const ROW = '-mx-1 flex gap-3 overflow-x-auto px-1 pb-1'; +const PAIR = 'flex flex-none flex-col gap-1 transition-opacity'; +const PAIR_OUT = `${PAIR} opacity-50`; +const PAIR_HEAD = 'flex min-w-0 items-center gap-1.5'; +const PAIR_LABEL = 'truncate text-caption text-content-secondary'; +const SHEETS = 'flex items-center gap-1'; +const SHEET_BUTTON = `flex flex-col items-start gap-0.5 rounded-md ${FOCUS}`; +const SHEET = 'relative overflow-hidden rounded-sm ring-1 ring-edge-faint'; +const SHEET_CAPTION = 'text-caption text-content-faint'; +const ARROW = 'flex-none text-content-faint rtl:-scale-x-100'; +const CHOICE = `grid h-4 w-4 flex-none place-items-center rounded-full transition-colors ${FOCUS}`; +const CHOICE_ON = `${CHOICE} bg-accent`; +const CHOICE_OFF = `${CHOICE} border-[1.5px] border-edge bg-surface-card`; +const CHOICE_MARK = 'text-accent-text'; +const MORE = `self-start rounded-sm text-caption font-medium text-accent-on hover:underline ${FOCUS}`; +const NOTE = 'text-caption text-content-muted'; +const NOTE_ERR = 'text-caption text-danger'; +const SKELETON = 'trek-skeleton block h-12 w-48'; +const FLAG_SEVERE = 'flex-none text-danger'; +const FLAG_WARN = 'flex-none text-warning'; + +interface SheetProps { + spread: BookSpread; + page: BookPageSetup; + /** "Before" or "After" under a page drawn beside its other side; nothing under a page alone. */ + caption: string | null; + onShow: () => void; +} + +/** One page drawn small; pressing it shows the page. */ +function Sheet({ spread, page, caption, onShow }: SheetProps) { + const { t } = useTranslation(); + const width = (SHEET_HEIGHT * (spread.role === 'inner' ? page.pageWidth * 2 : page.pageWidth)) / page.pageHeight; + return ( + + ); +} + +type Strip = ReturnType; + +interface PairProps { + pair: DesignPair; + strip: Strip; + editable: boolean; +} + +interface PairRowProps extends PairProps { + /** A proposal's pages: one taken out of the apply is faded, also while the apply runs. */ + choosing: boolean; +} + +/** A page's head: its round choice while it can be taken out, its name, what happens to it, its findings. */ +function PairHead({ pair, strip, editable, label }: PairProps & { label: string }) { + const { t } = useTranslation(); + const included = strip.chosen.has(pair.spreadId); + return ( + + {editable && ( + + )} + {label} + {pair.action === 'insert' && } + {pair.action === 'drop' && } + {pair.findings > 0 && ( + + )} + + ); +} + +/** The page before and after, "Before" and "After" under them when both are drawn. */ +function PairSheets({ pair, strip }: { pair: DesignPair; strip: Strip }) { + const { t } = useTranslation(); + const show = () => strip.show(pair.spreadId); + const both = pair.before !== null && pair.after !== null; + return ( + + {pair.before && strip.beforePage && ( + + )} + {both && + ); +} + +/** One page of the design: its head, and the page before and after; faded once taken out of the apply. */ +function Pair({ pair, strip, editable, choosing }: PairRowProps) { + const { t } = useTranslation(); + const label = pair.page ? pageLabel(pair.page, t) : t('assistant.card.book.spreadAny'); + return ( +
  • + + +
  • + ); +} + +interface StripProps { + card: BookDesignCard; + /** `draft` while the design waits, `applied` for its receipt. */ + mode: 'draft' | 'applied'; + /** The pages can be taken out of the apply (a proposal still waiting). */ + editable: boolean; +} + +export default function BookDesignSpreadStrip({ card, mode, editable }: StripProps) { + const { t } = useTranslation(); + const strip = useBookDesignDraft(card, mode, editable); + const [all, setAll] = useState(false); + // The choice goes out as soon as the pointer or the focus leaves the pages, so an Apply right after it applies it. + const leave = (event: FocusEvent) => { + if (!event.currentTarget.contains(event.relatedTarget)) strip.flush(); + }; + if (strip.status === 'loading') return