fix(studio): the assistant column draws the page the server applied, and reads the user's role

A page preview draws the spread the server applied with the journey's photos,
texts and figures instead of applying the operations again without them. The
Studio's welcome, privacy banner and header fit a journey chat: a viewer is
told they can only look, the banner speaks of the book, and the trip notes
button stays in the trip chat. Escape closes the header menu before it stops a
reply, a single page renders at the full long edge, the status says a model
reads pages only while its provider has not refused an image, and pointing at
a page in a design card outlines it in the Studio.
This commit is contained in:
Maurice
2026-10-23 01:45:16 +00:00
parent 72c61f242e
commit 9e40092507
85 changed files with 857 additions and 144 deletions
@@ -1,22 +1,25 @@
/**
* FE-STUDIO-ASTPANEL-001 to FE-STUDIO-ASTPANEL-003
* FE-STUDIO-ASTPANEL-001 to FE-STUDIO-ASTPANEL-009
*
* The assistant's column in TREK Studio (journey-studio.md 3.4, 4.5): the
* journey's chat with its own question; the notice that images of a page
* leave only once the user agreed, for the connection on screen, and that
* "Not now" keeps it text for the visit; every key inside the column belongs
* to the chat, so Studio neither closes nor edits the page's selection, and
* Escape stops a running answer first.
* leave only once the user agreed, for the connection on screen, that "Not
* now" keeps it text for the visit, and that a model reading no images is
* never asked; every key inside the column belongs to the chat, so Studio
* neither closes nor edits the page's selection, and Escape stops a running
* answer first, while Escape in the header's menu only closes the menu; the
* journey's chat offers no trip notes, and its privacy banner speaks of the
* journey; the bar's switch and the column it opens.
*/
import type { AiStatusResponse } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
import { aiConnectionsRepo } from '../../repo/aiConnectionsRepo';
import { assistantRepo } from '../../repo/assistantRepo';
import { assistantChatKey } from '../../store/assistantChatKey';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import StudioAssistantPanel from './StudioAssistantPanel';
import StudioAssistantPanel, { StudioAssistantColumn, StudioAssistantToggle } from './StudioAssistantPanel';
import type { StudioAssistant } from './useStudioAssistant';
const JOURNEY = 12;
@@ -32,13 +35,24 @@ const STATUS: AiStatusResponse = {
instance: { kind: 'anthropic', model: 'claude', host: 'api.anthropic.com' },
quota: null,
privacyAcked: true,
studioImages: true,
studioImagesAcked: false,
retention: { mode: 'days', days: 90 },
openrouterOAuth: false,
};
function assistant(): StudioAssistant {
return { chatKey: KEY, available: true, open: true, toggle: vi.fn(), jobs: [], drawn: vi.fn() };
function assistant(over: Partial<StudioAssistant> = {}): StudioAssistant {
return { chatKey: KEY, available: true, open: true, toggle: vi.fn(), jobs: [], drawn: vi.fn(), ...over };
}
/** A chat whose answer is still being written, with the store's cancel spied on. */
function running() {
const cancel = vi.fn();
useAssistantStore.setState({
cancel,
byTrip: { [KEY]: { ...chatOf(useAssistantStore.getState(), KEY), isRunning: true } },
});
return cancel;
}
beforeEach(() => {
@@ -83,11 +97,7 @@ describe('StudioAssistantPanel', () => {
});
it('FE-STUDIO-ASTPANEL-003: keys in the column stay there, Escape stops a running answer first', () => {
const cancel = vi.fn();
useAssistantStore.setState({
cancel,
byTrip: { [KEY]: { ...chatOf(useAssistantStore.getState(), KEY), isRunning: true } },
});
const cancel = running();
const studioKeys = vi.fn();
window.addEventListener('keydown', studioKeys);
const panel = assistant();
@@ -105,4 +115,94 @@ describe('StudioAssistantPanel', () => {
expect(panel.toggle).not.toHaveBeenCalled();
window.removeEventListener('keydown', studioKeys);
});
it("FE-STUDIO-ASTPANEL-004: Escape in the header's menu closes the menu, not the answer or Studio", async () => {
const cancel = running();
const studioKeys = vi.fn();
window.addEventListener('keydown', studioKeys);
const panel = assistant();
render(<StudioAssistantPanel assistant={panel} title="Lisbon" />);
fireEvent.click(screen.getByRole('button', { name: 'More options' }));
const item = within(await screen.findByRole('menu')).getAllByRole('button')[0] as HTMLElement;
// The menu's own keys stay out of the Studio and leave the answer alone.
fireEvent.keyDown(item, { key: 'ArrowDown' });
fireEvent.keyDown(item, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('menu')).toBeNull());
expect(cancel).not.toHaveBeenCalled();
expect(studioKeys).not.toHaveBeenCalled();
expect(panel.toggle).not.toHaveBeenCalled();
window.removeEventListener('keydown', studioKeys);
});
it('FE-STUDIO-ASTPANEL-005: the journey chat offers no trip notes, which only a trip turn reads', async () => {
render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
expect(await screen.findByText('What should the book look like?')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Recent chats' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Trip notes' })).toBeNull();
});
it('FE-STUDIO-ASTPANEL-006: on the admin connection the privacy banner speaks of the journey', async () => {
useAssistantStore.setState({ status: { ...STATUS, privacyAcked: false } });
render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
expect(
await screen.findByText('Your messages and the journey data the assistant reads go to Anthropic.')
).toBeInTheDocument();
expect(screen.queryByText(/trip data/)).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'What gets shared?' }));
expect(
screen.getByText('Not your password or your other journeys. A picture of a page goes only once you allow it.')
).toBeInTheDocument();
expect(screen.getByText(/what the assistant reads of this journey/)).toBeInTheDocument();
expect(screen.queryByText('Not your password, your files or your other trips.')).toBeNull();
});
it('FE-STUDIO-ASTPANEL-007: a connection whose model reads no images is never asked to show pages', async () => {
useAssistantStore.setState({
status: {
...STATUS,
effective: { source: 'instance', kind: 'custom', model: 'llama3', host: 'ollama.lan', paidBy: 'instance' },
studioImages: false,
},
});
render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
expect(await screen.findByText('What should the book look like?')).toBeInTheDocument();
expect(screen.queryByRole('note')).toBeNull();
expect(screen.queryByRole('button', { name: 'Show it pages' })).toBeNull();
});
it('FE-STUDIO-ASTPANEL-008: the bar switch shows where the assistant runs, tells its state and toggles', () => {
const { unmount } = render(<StudioAssistantToggle assistant={assistant({ available: false })} />);
expect(screen.queryByRole('button', { name: 'Assistant' })).toBeNull();
unmount();
const closed = assistant({ open: false });
const second = render(<StudioAssistantToggle assistant={closed} />);
const toggle = screen.getByRole('button', { name: 'Assistant' });
expect(toggle).toHaveAttribute('aria-pressed', 'false');
expect(toggle).toHaveAttribute('title', 'Design the book together with the assistant');
expect(toggle).not.toHaveClass('is-on');
fireEvent.click(toggle);
expect(closed.toggle).toHaveBeenCalledTimes(1);
second.unmount();
render(<StudioAssistantToggle assistant={assistant()} />);
expect(screen.getByRole('button', { name: 'Assistant' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'Assistant' })).toHaveClass('is-on');
});
it('FE-STUDIO-ASTPANEL-009: the column mounts only while it is open, named after the journey or as one', async () => {
const { unmount } = render(<StudioAssistantColumn assistant={assistant({ open: false })} title="Lisbon" />);
expect(screen.queryByRole('complementary', { name: 'Book assistant' })).toBeNull();
unmount();
render(<StudioAssistantColumn assistant={assistant()} />);
expect(screen.getByRole('complementary', { name: 'Book assistant' })).toBeInTheDocument();
expect(await screen.findByText('What should the book look like?')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Journey' })).toBeInTheDocument();
});
});
@@ -1,6 +1,6 @@
import '../../styles/studio-assistant.css';
import { ImageIcon } from 'lucide-react';
import { ImageIcon, MessageSquare } from 'lucide-react';
import { type HTMLAttributes, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
@@ -23,7 +23,8 @@ import type { StudioAssistant, StudioRenderJob } from './useStudioAssistant';
*
* Studio closes on Escape and edits the selection on Delete, copy and paste.
* Inside the column every key belongs to the chat, so it stops here, and
* Escape stops a running answer first.
* Escape stops a running answer first. A key from the header's menu, which
* sits in a portal, is not the chat's to act on.
*/
/** The column is not a window: its head moves nothing. */
@@ -32,17 +33,20 @@ const NO_DRAG: HTMLAttributes<HTMLElement> = { style: { cursor: 'default' } };
/**
* Images of a page leave only once the user agreed, per connection. Until
* then the Studio's assistant reads the pages as text. "Not now" hides the
* notice for this visit; the next one asks again.
* notice for this visit; the next one asks again. A model that reads no
* images (a custom server, OpenRouter, an OpenAI text-only model) is never
* asked: its pages always go as text.
*/
function StudioImagesNotice() {
const { t } = useTranslation();
const toast = useToast();
const effective = useAssistantStore((s) => s.status?.effective ?? null);
const reads = useAssistantStore((s) => s.status?.studioImages === true);
const acked = useAssistantStore((s) => s.status?.studioImagesAcked === true);
const ackStudioImages = useAssistantStore((s) => s.ackStudioImages);
const [later, setLater] = useState(false);
if (!effective || acked || later) return null;
if (!effective || !reads || acked || later) return null;
const provider = providerLabel(effective.kind, effective.host);
const allow = async () => {
@@ -146,9 +150,12 @@ export default function StudioAssistantPanel({ assistant, title }: { assistant:
// Every key pressed in the column is the chat's: the editor's own keys
// (Delete, Backspace, copy, paste, undo, Escape) listen on the window and
// would otherwise act on the page's selection from a focused chat button.
// Keys from a portal (the header's menu) bubble here through React too;
// they stop here as well, but they are not the chat's to act on.
const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
const inside = e.currentTarget.contains(e.target as Node);
e.stopPropagation();
if (e.key === 'Escape' && isRunning && !e.defaultPrevented) stop();
if (inside && e.key === 'Escape' && isRunning && !e.defaultPrevented) stop();
};
return (
@@ -171,3 +178,28 @@ export default function StudioAssistantPanel({ assistant, title }: { assistant:
</aside>
);
}
/** The Studio bar's switch for the column; only where the assistant can run for this user. */
export function StudioAssistantToggle({ assistant }: { assistant: StudioAssistant }) {
const { t } = useTranslation();
if (!assistant.available) return null;
return (
<button
type="button"
className={`st-tool ${assistant.open ? 'is-on' : ''}`}
onClick={assistant.toggle}
aria-pressed={assistant.open}
title={t('journey.studio.assistant.toggleHint')}
>
<MessageSquare size={14} />
<span className="st-tool-label">{t('journey.studio.assistant.toggle')}</span>
</button>
);
}
/** The chat column at the end of the Studio's body, while it is open, named after the journey. */
export function StudioAssistantColumn({ assistant, title }: { assistant: StudioAssistant; title?: string }) {
const { t } = useTranslation();
if (!assistant.open) return null;
return <StudioAssistantPanel assistant={assistant} title={title || t('journey.title')} />;
}
@@ -168,6 +168,8 @@ function PagesPanel({
}: { page: BookPageSetup; pxPerMm: number; bookView: boolean; t: (k: string) => string }) {
const doc = useStudioStore(s => s.doc)
const active = useStudioStore(s => s.activeSpread)
// The page a chat card points at, outlined here (journey-studio.md 4.2).
const hinted = useStudioStore(s => s.hintSpread)
const setActive = useStudioStore(s => s.setActiveSpread)
const addSpread = useStudioStore(s => s.addSpread)
const insertSpread = useStudioStore(s => s.insertSpread)
@@ -194,7 +196,7 @@ function PagesPanel({
return (
<div className="st-thumb-row" key={sp.id}>
<button type="button"
className={`st-thumb ${i === active ? 'is-active' : ''}`}
className={`st-thumb ${i === active ? 'is-active' : ''} ${sp.id === hinted ? 'is-hinted' : ''}`}
onClick={() => setActive(i)}
>
<SpreadThumb
@@ -4,7 +4,7 @@
* The page image the Studio sends the assistant (journey-studio.md 3.1, 3.4):
* a sheet's size in CSS pixels, the filter that leaves out pictures from
* other servers and hidden photos before anything is rasterised, the photos
* the upload declares read off what is kept, and the JPEG at most 1280 pixels
* the upload declares read off what is kept, and the JPEG at 1280 pixels
* on its long edge. modern-screenshot is faked; a real browser draws the page
* in the Playwright flows.
*/
@@ -102,13 +102,13 @@ describe('pageSnapshot', () => {
expect(filter?.(picture('/api/photos/7/thumbnail'))).toBe(true);
});
it('FE-STUDIO-SNAP-005: an image too large for the server is not sent, a small sheet is not enlarged', async () => {
it('FE-STUDIO-SNAP-005: an image too large for the server is not sent, a small sheet is drawn to the long edge', async () => {
vi.mocked(domToBlob).mockResolvedValueOnce(new Blob([new Uint8Array(ASSISTANT_PAGE_IMAGE.maxBytes + 1)]));
expect(await snapshotSpread(sheet(), { width: 1600, height: 800 }, HIDDEN)).toBeNull();
vi.mocked(domToBlob).mockResolvedValueOnce(new Blob(['jpeg'], { type: 'image/jpeg' }));
const small = await snapshotSpread(sheet(), { width: 400, height: 300 }, HIDDEN);
expect(small).toMatchObject({ width: 400, height: 300 });
expect(blobCalls()[1]?.[1]).toMatchObject({ scale: 1 });
expect(small).toMatchObject({ width: 1280, height: 960 });
expect(blobCalls()[1]?.[1]).toMatchObject({ width: 400, height: 300, scale: 3.2 });
});
});
+8 -5
View File
@@ -113,10 +113,12 @@ async function picturesLoaded(root: Element, hidden: ReadonlySet<number>): Promi
}
/**
* The sheet under `root` as a JPEG, its long edge at most
* `ASSISTANT_PAGE_IMAGE.longEdge` pixels. `size` is the sheet's own size in
* CSS pixels (`sheetSizePx`). Null when the image comes out larger than the
* server takes, so the turn goes on with the page's description.
* The sheet under `root` as a JPEG, its long edge at
* `ASSISTANT_PAGE_IMAGE.longEdge` pixels (journey-studio.md 3.2: a double
* spread 1280 x 640, a single page 1280 on its long edge). `size` is the
* sheet's own size in CSS pixels (`sheetSizePx`). Null when the image comes
* out larger than the server takes, so the turn goes on with the page's
* description.
*/
export async function snapshotSpread(
root: HTMLElement,
@@ -124,7 +126,8 @@ export async function snapshotSpread(
hiddenPhotoIds: ReadonlySet<number>
): Promise<PageSnapshot | null> {
await picturesLoaded(root, hiddenPhotoIds);
const scale = Math.min(1, ASSISTANT_PAGE_IMAGE.longEdge / Math.max(size.width, size.height));
// A single page is drawn up to the long edge too: a larger scale renders the page sharper, it stretches no pixels.
const scale = ASSISTANT_PAGE_IMAGE.longEdge / Math.max(size.width, size.height);
const { domToBlob } = await import('modern-screenshot');
const image = await domToBlob(root, {
width: size.width,
@@ -5,8 +5,8 @@
* hosts the journey's chat while the column shows; it draws the page a turn
* asks for off screen, with other members' photos as empty frames, and sends
* it at the version the turn named; a page of a design draft comes from the
* draft; a preview runs on an unsaved copy; each question carries the page on
* screen; `?page=` shows a page. The snapshot
* draft; a preview draws the page the server applied, nothing saved; each
* question carries the page on screen; `?page=` shows a page. The snapshot
* and the repo are faked: a real browser draws the page in the Playwright flows.
*/
import {
@@ -198,20 +198,25 @@ describe('useStudioAssistant', () => {
expect(background).toMatch(/#abcdef|171, 205, 239/i);
});
it('FE-STUDIO-AST-004:a preview runs its ops on an unsaved copy, nothing is drawn when they fail', () => {
it('FE-STUDIO-AST-004: a preview draws the page the server applied, the stored book untouched', () => {
const doc = book();
const deadline = { signal: new AbortController().signal, release: vi.fn() };
const stored = doc.spreads[2];
if (!stored) throw new Error('no inner spread');
const job = renderJobOf(doc, { ...REQUEST, ops: [{ op: 'background', color: '#123456' }] }, deadline);
const job = renderJobOf(doc, { ...REQUEST, spread: { ...stored, background: '#123456' } }, deadline);
expect(job?.spread.background).toBe('#123456');
expect(job?.page).toBe(doc.page);
expect(job?.folios.length).toBeGreaterThan(0);
expect([...(job?.hidden ?? [])]).toEqual([31]);
expect(doc.spreads[2]?.background).toBeNull();
// Without a proposal the page is drawn as the book holds it; a page the book lacks is not drawn.
expect(renderJobOf(doc, REQUEST, deadline)?.spread).toBe(stored);
expect(renderJobOf(doc, { ...REQUEST, spreadId: 'sp-99' }, deadline)).toBeNull();
// An element the page does not hold refuses the whole edit.
const missing: AssistantPageRender = { ...REQUEST, ops: [{ op: 'remove', elementIds: ['nope'], park: true }] };
expect(renderJobOf(doc, missing, deadline)).toBeNull();
// A page sent for another spread is never drawn in this one's place.
const other: AssistantPageRender = { ...REQUEST, spread: { ...stored, id: 'sp-4', background: '#654321' } };
expect(renderJobOf(doc, other, deadline)?.spread).toBe(stored);
});
it('FE-STUDIO-AST-005: each question carries the page on screen and the elements selected on it', () => {
@@ -1,6 +1,5 @@
import {
ASSISTANT_PAGE_IMAGE,
applyBookOps,
bookElementIdSchema,
bookSpreadIdSchema,
type AssistantPageRender,
@@ -27,7 +26,8 @@ import { sheetSizePx, snapshotSpread } from './pageSnapshot';
* - Each question carries the page on screen and the elements selected on it.
* - A page a turn asks to look at is drawn here, by the editor's own
* SpreadView off screen, and uploaded as an image (3.1): a page of the
* book, or of a design draft the assistant has not applied yet.
* book, of a design draft the assistant has not applied yet, or a
* proposal's page as the server applied it.
* - `?page=<spread id>`, which a page card opens, shows that page.
*/
@@ -83,29 +83,27 @@ function withDeadline(signal: AbortSignal): { signal: AbortSignal; release: () =
}
/**
* The page a request asks for, from the book at the version it names: with
* the request's ops applied to an unsaved copy (a preview). Null when the
* page is gone or the ops do not apply, so nothing is drawn.
* The page a request asks for, from the book at the version it names. A
* preview carries the proposal's page as the server applied it, with the
* journey's photos, words and figures this tab does not hold: that page is
* drawn in place of the stored one, nothing saved. A proposal changes only
* its own page, so the page setup and the folios stay the book's. Null when
* the page is gone, so nothing is drawn.
*/
export function renderJobOf(
doc: BookDocument,
request: AssistantPageRender,
deadline: { signal: AbortSignal; release: () => void }
): StudioRenderJob | null {
let next = doc;
if (request.ops) {
const made = applyBookOps(doc, { spreadId: request.spreadId, ops: request.ops });
if (made.ok === false) return null;
next = made.doc;
}
const index = next.spreads.findIndex((s) => s.id === request.spreadId);
const spread = next.spreads[index];
if (!spread) return null;
const index = doc.spreads.findIndex((s) => s.id === request.spreadId);
const stored = doc.spreads[index];
if (!stored) return null;
const spread = request.spread?.id === stored.id ? request.spread : stored;
return {
request,
spread,
page: next.page,
folios: foliosOf(next.spreads, index, next.page.pageNumbers.startAt),
page: doc.page,
folios: foliosOf(doc.spreads, index, doc.page.pageNumbers.startAt),
hidden: new Set(request.hiddenPhotoIds),
...deadline,
};
@@ -0,0 +1,139 @@
/**
* FE-STUDIO-HINT-001 to FE-STUDIO-HINT-003
*
* Pointing at a page drawn in a chat card outlines the same page in the
* Studio's page rail (journey-studio.md 4.2): by pointer or by focus, gone
* again on leaving, on blur and when the card goes away while it points; a
* page the open book does not hold outlines nothing, and opening a book
* clears it. A book change's card points this way from its thumbnails.
*/
import { blankBook, type BookPageCard } from '@trek/shared';
import { afterEach, describe, expect, it } from 'vitest';
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
import { useStudioStore } from '../../store/studioStore';
import type { ChangeItem } from '../Assistant/assistantParts';
import { AssistantViewContext } from '../Assistant/assistantViewContext';
import BookPageThumbs from '../Assistant/cards/book/BookPageThumbs';
import { type JourneySource, StudioSidebar } from './StudioSidebar';
import type { StudioUploader } from './studioUpload';
import { useStudioPageHint } from './useStudioPageHint';
const STUDIO = useStudioStore.getState();
const SOURCE: JourneySource = { entries: [], photos: [], photoEntries: {} };
const NO_UPLOAD: StudioUploader = async () => ({ photoIds: [], failed: 0, skippedVideos: 0 });
/** A blank book with readable ids: sp-1 the cover, sp-2 the first page, sp-3 its double page, sp-4 and sp-5. */
function book() {
let seq = 0;
return blankBook({ title: 'Lisbon', newId: (prefix) => `${prefix}-${++seq}` });
}
/** The page rail of the open book. */
function renderRail() {
const doc = useStudioStore.getState().doc;
if (!doc) throw new Error('no book open');
return render(
<StudioSidebar
page={doc.page}
pxPerMm={96 / 25.4}
bookView={false}
source={SOURCE}
stats={null}
path={[]}
t={(k: string) => k}
locale="en-US"
canEdit
onUpload={NO_UPLOAD}
onToggleStop={async () => true}
/>
);
}
/** The rail's thumbnails, in the book's order, by whether each is outlined. */
function outlined(): boolean[] {
return [...document.querySelectorAll('.st-thumb')].map((thumb) => thumb.classList.contains('is-hinted'));
}
/** A page drawn in a card, as the card thumbnails draw one: a button that points at it. */
function CardPage({ spreadId }: { spreadId: string }) {
const hint = useStudioPageHint(spreadId);
return (
<button type="button" {...hint}>
{`card page ${spreadId}`}
</button>
);
}
afterEach(() => {
useStudioStore.setState(STUDIO, true);
});
describe('useStudioPageHint', () => {
it('FE-STUDIO-HINT-001: pointing at a card page outlines that page in the rail, leaving takes it off', () => {
act(() => useStudioStore.getState().load(book()));
renderRail();
render(<CardPage spreadId="sp-3" />);
const page = screen.getByRole('button', { name: 'card page sp-3' });
expect(outlined()).toEqual([false, false, false, false, false]);
fireEvent.pointerEnter(page);
expect(useStudioStore.getState().hintSpread).toBe('sp-3');
expect(outlined()).toEqual([false, false, true, false, false]);
fireEvent.pointerLeave(page);
expect(outlined()).toEqual([false, false, false, false, false]);
// The keyboard points the same way.
fireEvent.focus(page);
expect(useStudioStore.getState().hintSpread).toBe('sp-3');
fireEvent.blur(page);
expect(useStudioStore.getState().hintSpread).toBeNull();
});
it('FE-STUDIO-HINT-002: a page the book lacks outlines nothing; a card gone or a book opened clears it', () => {
act(() => useStudioStore.getState().load(book()));
render(<CardPage spreadId="sp-new" />);
fireEvent.pointerEnter(screen.getByRole('button', { name: 'card page sp-new' }));
expect(useStudioStore.getState().hintSpread).toBeNull();
const card = render(<CardPage spreadId="sp-4" />);
fireEvent.pointerEnter(screen.getByRole('button', { name: 'card page sp-4' }));
expect(useStudioStore.getState().hintSpread).toBe('sp-4');
card.unmount();
expect(useStudioStore.getState().hintSpread).toBeNull();
// A card going away that points at no page leaves another card's outline alone.
const other = render(<CardPage spreadId="sp-2" />);
act(() => useStudioStore.getState().setHintSpread('sp-5'));
other.unmount();
expect(useStudioStore.getState().hintSpread).toBe('sp-5');
act(() => useStudioStore.getState().load(book()));
expect(useStudioStore.getState().hintSpread).toBeNull();
});
it("FE-STUDIO-HINT-003: a book change's thumbnail points at its page in the Studio's rail", () => {
act(() => useStudioStore.getState().load(book()));
renderRail();
const card = {
kind: 'bookPage',
journeyId: 3,
change: 'changed',
pages: [{ spreadId: 'sp-3', index: 2, role: 'inner', number: 1, photos: 0 }],
ops: [],
cover: null,
} as unknown as BookPageCard;
const item = { state: 'applied' } as ChangeItem;
render(
<AssistantViewContext.Provider value={{ tripId: -3, variant: 'window' }}>
<BookPageThumbs card={card} item={item} />
</AssistantViewContext.Provider>
);
const thumb = screen.getByRole('button', { name: 'Show this page' });
fireEvent.pointerEnter(thumb);
expect(outlined()).toEqual([false, false, true, false, false]);
fireEvent.pointerLeave(thumb);
expect(outlined()).toEqual([false, false, false, false, false]);
});
});
@@ -0,0 +1,36 @@
import { useCallback, useEffect } from 'react';
import { useStudioStore } from '../../store/studioStore';
/** What a page drawn in a chat card spreads on its button so the Studio's page rail outlines that page. */
interface StudioPageHint {
onPointerEnter: () => void;
onPointerLeave: () => void;
onFocus: () => void;
onBlur: () => void;
}
/**
* Pointing at a page drawn in a chat card, with the pointer or the keyboard's
* focus, outlines the same page in the Studio's page rail (journey-studio.md
* 4.2); leaving it, or the card going away while it points, takes the outline
* off again. A page the open book does not hold (a new page of a design,
* another book) outlines nothing.
*/
export function useStudioPageHint(spreadId: string): StudioPageHint {
const setHint = useStudioStore((s) => s.setHintSpread);
const point = useCallback(() => {
const held = useStudioStore.getState().doc?.spreads.some((spread) => spread.id === spreadId) ?? false;
setHint(held ? spreadId : null);
}, [spreadId, setHint]);
const leave = useCallback(() => {
if (useStudioStore.getState().hintSpread === spreadId) setHint(null);
}, [spreadId, setHint]);
// A card that re-renders or leaves the thread while pointed at takes its outline with it.
useEffect(() => leave, [leave]);
return { onPointerEnter: point, onPointerLeave: leave, onFocus: point, onBlur: leave };
}