Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions frontend/src/app/AppShell.creationNote.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { creationNoteStorageKey } from '../hooks/useRememberedVisible'
import { entryFixture, findingFixture } from '../test/fixtures'
import { draftFixture, entryFixture, findingFixture } from '../test/fixtures'
import { cleanupControllerTest, getTauriMock, setupControllerTest, useAppController } from './useAppController.testHarness'

const { AppShell } = await import('./AppShell')
Expand All @@ -13,7 +13,8 @@ beforeEach(() => {
setupControllerTest()
window.localStorage.removeItem(creationNoteStorageKey)
HTMLElement.prototype.scrollIntoView = vi.fn()
tauri.listFindings.mockResolvedValue([findingFixture({ title: 'Saved finding' })])
tauri.listFindings.mockResolvedValue([findingFixture({ id: 'finding-saved', title: 'Saved finding', body: '<p>Card payment fails at checkout.</p>' })])
tauri.listDrafts.mockResolvedValue([draftFixture({ id: 'draft-saved', title: 'Checkout test cases', body: '<p>Pay with an expired card.</p>' })])
tauri.readNoteSource.mockResolvedValue({ entry: entryFixture({ body: '<h2>Checkout</h2><ul><li><p>Pay with a saved card.</p></li></ul>' }), revision: 0 })
})
afterEach(cleanupControllerTest)
Expand Down Expand Up @@ -71,3 +72,28 @@ it('says so in the panel when the Session has no Note, and the draft still saves
fireEvent.change(screen.getByRole('textbox', { name: 'Finding title' }), { target: { value: 'Written without a Note' } })
expect(screen.getByRole('button', { name: 'Save finding' })).toBeEnabled()
})

it('shows a saved test case or Finding beside the draft in place of the Note, chosen per draft', async () => {
render(<Subject />)
await createFinding()
const choice = within(await screen.findByRole('complementary', { name: 'Note' })).getByRole('combobox', { name: 'Show beside the draft' })
// The draft's own kind is listed first.
expect(within(choice).getAllByRole('group').map(group => group.getAttribute('label'))).toEqual(['Findings', 'Test cases'])

fireEvent.change(choice, { target: { value: 'testware:draft-saved' } })
const testCase = await screen.findByRole('complementary', { name: 'Checkout test cases' })
await waitFor(() => expect(testCase).toHaveTextContent('Pay with an expired card.'))
expect(within(testCase).getByRole('textbox', { name: 'Checkout test cases content' })).toHaveAttribute('aria-readonly', 'true')
expect(testCase).not.toHaveTextContent('Pay with a saved card.')

// Closed, the panel is brought back by what it shows.
fireEvent.click(within(testCase).getByRole('button', { name: 'Close test case' }))
fireEvent.click(within(screen.getByRole('article', { name: 'New finding' })).getByRole('button', { name: 'Show test case' }))
fireEvent.change(within(await screen.findByRole('complementary', { name: 'Checkout test cases' })).getByRole('combobox'), { target: { value: 'finding:finding-saved' } })
await waitFor(() => expect(screen.getByRole('complementary', { name: 'Saved finding' })).toHaveTextContent('Card payment fails at checkout.'))

// A new draft starts with the Note again.
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
await createFinding()
expect(await screen.findByRole('complementary', { name: 'Note' })).toHaveTextContent('Pay with a saved card.')
})
17 changes: 15 additions & 2 deletions frontend/src/app/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ActionButton } from '../components/ActionButton'
import { CreationWorkspace } from '../views/CreationTools'
import { CreationNotePanel } from '../views/CreationNotePanel'
import { referenceLabel, useCreationReference } from './creationReference'
import { useCreationNoteVisible } from '../hooks/useCreationNoteVisible'
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { catalogSelectorEnabled } from '../settings/catalog'
Expand Down Expand Up @@ -54,8 +55,20 @@ export function AppShell(c: AppController) {
&& c.activeView === (c.creationIntent.kind === 'finding' ? 'findings' : 'testware') ? c.creationIntent : null
const contentRef = useRef<HTMLDivElement>(null)
const [noteVisible, toggleNote] = useCreationNoteVisible(shownDraft?.id ?? null, contentRef)
const [reference, setReference] = useCreationReference(shownDraft?.id ?? null)
const referenceRecords = { testware: c.testwareDrafts, finding: c.findings }
const askAiVisible = c.askAi.visible && !shownDraft
const composer = c.creationIntent && !creationResultReady ? <CreationWorkspace c={c} onShowNote={noteVisible ? undefined : toggleNote} /> : null
const composer = c.creationIntent && !creationResultReady ? <CreationWorkspace c={c}
showPanel={noteVisible ? undefined : { label: referenceLabel(reference, referenceRecords), onShow: toggleNote }} /> : null

// The panel lists both kinds of saved record, and each kind loads with its own tab, so load the other one here.
const { loadDraftsForSession, loadFindingsForSession } = c
const referenceSessionId = shownDraft && noteVisible ? shownDraft.sessionId : null
useEffect(() => {
if (!referenceSessionId) return
void loadDraftsForSession(referenceSessionId).catch(() => undefined)
void loadFindingsForSession(referenceSessionId).catch(() => undefined)
}, [referenceSessionId, loadDraftsForSession, loadFindingsForSession])

const { loadDraftLibrary, loadFindingLibrary, sessionLibraryComplete } = c
// Startup loads only recent Sessions; the palette searches every Session without changing the sidebar.
Expand Down Expand Up @@ -273,7 +286,7 @@ export function AppShell(c: AppController) {
/>
) : null}
</div>
{shownDraft && noteVisible ? <CreationNotePanel intent={shownDraft} noteReadOnly={c.noteReadOnly} onReadNote={() => void c.creation.reviewSource()} onClose={toggleNote} /> : null}
{shownDraft && noteVisible ? <CreationNotePanel intent={shownDraft} records={referenceRecords} reference={reference} onReferenceChange={setReference} noteReadOnly={c.noteReadOnly} onReadNote={() => void c.creation.reviewSource()} onClose={toggleNote} /> : null}
<AppChat c={c} recordVisible={askAiVisible} modelSelectionControl={modelSelectionControl} onConfigureAi={() => runCommand('ai.configure')} />
</div>
</section>
Expand Down
33 changes: 33 additions & 0 deletions frontend/src/app/creationReference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useState } from 'react'
import type { StoredRichBody } from '../editor/editorDocument'
import type { CreationKind } from '../tauri'

/** A saved test case or Finding that can show beside a new draft in place of the Note. */
export type ReferenceRecord = StoredRichBody & { id: string; title: string }
export type ReferenceRecords = Record<CreationKind, ReadonlyArray<ReferenceRecord>>
/** What shows beside the draft: the Note, or a saved record of either kind. */
export type CreationReference = { kind: 'note' } | { kind: CreationKind; id: string }

export const noteReference: CreationReference = { kind: 'note' }
export const kindLabels: Record<CreationKind, { group: string; one: string }> = {
testware: { group: 'Test cases', one: 'test case' },
finding: { group: 'Findings', one: 'Finding' },
}
export const referenceValue = (reference: CreationReference) => reference.kind === 'note' ? 'note' : `${reference.kind}:${reference.id}`

/** What shows beside each draft, kept per draft: a new draft starts with the Note. */
export function useCreationReference(draftId: string | null): [CreationReference, (reference: CreationReference) => void] {
const [chosen, setChosen] = useState<{ draftId: string; reference: CreationReference } | null>(null)
const reference = chosen && chosen.draftId === draftId ? chosen.reference : noteReference
return [reference, (next) => { if (draftId) setChosen({ draftId, reference: next }) }]
}

/** The saved record a reference names, or null for the Note or a record that is gone. */
export function referencedRecord(reference: CreationReference, records: ReferenceRecords) {
return reference.kind === 'note' ? null : records[reference.kind].find(record => record.id === reference.id) ?? null
}

/** Names what the panel shows: the Note, or the kind of record it shows. */
export function referenceLabel(reference: CreationReference, records: ReferenceRecords): string {
return reference.kind !== 'note' && referencedRecord(reference, records) ? kindLabels[reference.kind].one : 'Note'
}
5 changes: 2 additions & 3 deletions frontend/src/hooks/useCreationNoteVisible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useLayoutEffect, useState, type RefObject } from 'react'
import { creationNoteStorageKey, useRememberedVisible } from './useRememberedVisible'

export const creationNotePanelId = 'creation-note'
export const showNoteLabel = 'Show Note'

/** The workspace width at or below which a side panel covers the document area: the container query in ask-ai.css. */
const narrowWorkspace = 850
Expand All @@ -21,7 +20,7 @@ function useNarrowWorkspace(workspace: RefObject<HTMLElement | null>): boolean {
}

/**
* Whether the Note shows beside the open draft. In a wide workspace the choice is remembered. In a narrow one
* Whether the panel beside the open draft (the Note, or a saved record) shows. In a wide workspace the choice is remembered. In a narrow one
* the Note would cover the draft, so it is closed until opened for this draft, and that choice is not kept.
*/
export function useCreationNoteVisible(draftId: string | null, workspace: RefObject<HTMLElement | null>): [boolean, () => void] {
Expand All @@ -34,7 +33,7 @@ export function useCreationNoteVisible(draftId: string | null, workspace: RefObj
if (narrow) setChosen({ draftId, visible: !visible })
else { setChosen(null); remember(!visible) }
// Focus follows the Note: into the panel when it opens, back to the button that brings it back when it closes.
requestAnimationFrame(() => document.querySelector<HTMLElement>(visible ? `[aria-label="${showNoteLabel}"]` : `#${creationNotePanelId} button`)?.focus())
requestAnimationFrame(() => document.querySelector<HTMLElement>(visible ? '.creation-note-toggle' : `#${creationNotePanelId} :is(select, button)`)?.focus())
}
return [visible, toggle]
}
20 changes: 19 additions & 1 deletion frontend/src/styles/collections.css
Original file line number Diff line number Diff line change
Expand Up @@ -1078,7 +1078,25 @@
.creation-composer > .record-title-row:has(> .creation-note-toggle) { grid-template-columns: minmax(0, 1fr) auto auto; }
.creation-composer > .record-title-row > .creation-note-toggle { grid-column: 3; grid-row: 1; margin-block: calc((23px * 1.2 - var(--control-lg)) / 2); }

/* The Note beside a new draft (CreationNotePanel, a side-panel): read-only, scrolling on its own. */
/* The panel beside a new draft (CreationNotePanel, a side-panel): the Note or a saved record, read-only, scrolling on its own. */
/* The choice of what shows reads as the panel's heading: quiet until pointed at. The panel's colour behind it, for WebKitGTK. */
.creation-reference-select {
flex: 1;
min-width: 0;
height: var(--control-lg);
margin-left: calc(-1 * var(--space-2));
padding-left: var(--space-2);
color: var(--text-primary);
font-family: var(--font-display);
font-size: var(--font-size-lg);
font-weight: 650;
text-overflow: ellipsis;
background-color: var(--surface-panel);
border: 1px solid transparent;
border-radius: var(--radius-md);
}
.creation-reference-select:hover { border-color: var(--border-default); }

.creation-note-body {
display: grid;
flex: 1;
Expand Down
71 changes: 53 additions & 18 deletions frontend/src/views/CreationNotePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,72 @@ import { FileText, PanelRightClose, PanelRightOpen } from 'lucide-react'
import { ActionButton } from '../components/ActionButton'
import { StatePanel } from '../components/Common'
import { RichTextEditor } from '../editor/RichTextEditor'
import { richEditorDocumentFromHtml } from '../editor/editorDocument'
import { richEditorDocumentFromHtml, richEditorDocumentFromStoredBody, withoutRepeatedTitleHeading } from '../editor/editorDocument'
import { htmlHasContent } from '../editor/editorHtml'
import { creationNotePanelId, showNoteLabel } from '../hooks/useCreationNoteVisible'
import { creationNotePanelId } from '../hooks/useCreationNoteVisible'
import type { CreationIntent } from '../app/creationIntent'
import type { CreationKind } from '../tauri'
import { kindLabels, noteReference, referencedRecord, referenceLabel, referenceValue, type CreationReference, type ReferenceRecord, type ReferenceRecords } from '../app/creationReference'

export function ShowNoteButton({ onShow }: { onShow: () => void }) {
return <ActionButton variant="quiet" iconOnly icon={PanelRightOpen} className="creation-note-toggle" aria-label={showNoteLabel}
tooltip={showNoteLabel} tooltipAlign="end" aria-expanded={false} aria-controls={creationNotePanelId} onClick={onShow} />
export function ShowNoteButton({ label, onShow }: { label: string; onShow: () => void }) {
const tooltip = `Show ${label}`
return <ActionButton variant="quiet" iconOnly icon={PanelRightOpen} className="creation-note-toggle" aria-label={tooltip}
tooltip={tooltip} tooltipAlign="end" aria-expanded={false} aria-controls={creationNotePanelId} onClick={onShow} />
}

/** The Session's Note, read-only on the right of a new draft: the source Generate uses. */
export function CreationNotePanel({ intent, noteReadOnly, onReadNote, onClose }: {
/**
* Read-only on the right of a new draft: the Session's Note, the source Generate uses, or a saved test case or
* Finding of this Session to write from. Records of the draft's own kind are listed first.
*/
export function CreationNotePanel({ intent, records, reference, onReferenceChange, noteReadOnly, onReadNote, onClose }: {
intent: CreationIntent
records: ReferenceRecords
reference: CreationReference
onReferenceChange: (reference: CreationReference) => void
noteReadOnly: boolean
onReadNote: () => void
onClose: () => void
}) {
const body = intent.source?.entry.body
const written = body !== undefined && htmlHasContent(body)
const note = useMemo(() => body === undefined ? null : richEditorDocumentFromHtml(body), [body])
return <aside id={creationNotePanelId} className="side-panel" aria-label="Note">
// A record deleted while it is shown leaves the Note in its place.
const record = referencedRecord(reference, records)
const shown = record ? reference : noteReference
const label = referenceLabel(shown, records)
const kinds: CreationKind[] = intent.kind === 'finding' ? ['finding', 'testware'] : ['testware', 'finding']
return <aside id={creationNotePanelId} className="side-panel" aria-label={record?.title ?? 'Note'}>
<header className="side-panel-header">
<h2>Note</h2>
<ActionButton variant="quiet" iconOnly icon={PanelRightClose} aria-label="Close Note" tooltip="Close Note" tooltipAlign="end" onClick={onClose} />
<select className="creation-reference-select" aria-label="Show beside the draft" value={referenceValue(shown)} onChange={event => {
const [kind, id] = event.target.value.split(/:(.*)/s)
onReferenceChange(kind === 'testware' || kind === 'finding' ? { kind, id } : noteReference)
}}>
<option value="note">Note</option>
{kinds.filter(kind => records[kind].length > 0).map(kind => <optgroup key={kind} label={kindLabels[kind].group}>
{records[kind].map(item => <option key={item.id} value={referenceValue({ kind, id: item.id })}>{item.title.trim() || 'Untitled'}</option>)}
</optgroup>)}
</select>
<ActionButton variant="quiet" iconOnly icon={PanelRightClose} aria-label={`Close ${label}`} tooltip={`Close ${label}`} tooltipAlign="end" onClick={onClose} />
</header>
<div className="creation-note-body">
{noteReadOnly ? <p className="inline-message advisory" role="status">Recover the Session Note before generating from it. Ordinary writing remains available.</p> : null}
{note && written ? <RichTextEditor value={note} readOnly ariaLabel="Note content" />
: intent.sourceNoteId && !note ? <StatePanel icon={FileText} title="The Note is not shown yet" description="Read the latest saved Note to see it here."
action={{ label: 'Read Note', onClick: onReadNote }} />
: <StatePanel icon={FileText} title="This Session has no Note yet" description="You can still write and save this draft." />}
{record ? <ReferenceRecordBody record={record} /> : <NoteBody intent={intent} noteReadOnly={noteReadOnly} onReadNote={onReadNote} />}
</div>
</aside>
}

function ReferenceRecordBody({ record }: { record: ReferenceRecord }) {
const { body, bodyJson, title } = record
const document = useMemo(() => withoutRepeatedTitleHeading(richEditorDocumentFromStoredBody({ body, bodyJson }), title), [body, bodyJson, title])
// The choice above names the record, so its body shows without the title.
return <RichTextEditor key={record.id} value={document} readOnly ariaLabel={`${title.trim() || 'Untitled'} content`} />
}

function NoteBody({ intent, noteReadOnly, onReadNote }: { intent: CreationIntent; noteReadOnly: boolean; onReadNote: () => void }) {
const body = intent.source?.entry.body
const written = body !== undefined && htmlHasContent(body)
const note = useMemo(() => body === undefined ? null : richEditorDocumentFromHtml(body), [body])
return <>
{noteReadOnly ? <p className="inline-message advisory" role="status">Recover the Session Note before generating from it. Ordinary writing remains available.</p> : null}
{note && written ? <RichTextEditor value={note} readOnly ariaLabel="Note content" />
: intent.sourceNoteId && !note ? <StatePanel icon={FileText} title="The Note is not shown yet" description="Read the latest saved Note to see it here."
action={{ label: 'Read Note', onClick: onReadNote }} />
: <StatePanel icon={FileText} title="This Session has no Note yet" description="You can still write and save this draft." />}
</>
}
11 changes: 7 additions & 4 deletions frontend/src/views/CreationTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,22 @@ import type { AppController } from '../app/useAppController'

const creationModes = [{ value: 'write', label: 'Write', icon: PenLine }, { value: 'generate', label: 'Generate', icon: Sparkles }] satisfies ReadonlyArray<SegmentedOption<CreationMode>>

export function CreationWorkspace({ c, onShowNote }: { c: AppController; onShowNote?: () => void }) {
/** `showPanel` brings back the closed panel beside the draft, named for what it shows. */
export type ShowPanel = { label: string; onShow: () => void }

export function CreationWorkspace({ c, showPanel }: { c: AppController; showPanel?: ShowPanel }) {
const intent = c.creationIntent
if (!intent) return null
return <CreationDraft key={intent.id} intent={intent} c={c} onShowNote={onShowNote} />
return <CreationDraft key={intent.id} intent={intent} c={c} showPanel={showPanel} />
}

/** A new draft: written by hand, or, when AI is ready, generated from the Note shown beside it. */
function CreationDraft({ intent, c, onShowNote }: { intent: CreationIntent; c: AppController; onShowNote?: () => void }) {
function CreationDraft({ intent, c, showPanel }: { intent: CreationIntent; c: AppController; showPanel?: ShowPanel }) {
const generation = useCreationGenerate(intent, c)
const aiActive = creationAiActive(c)
const mode = shownCreationMode(intent, aiActive)
return <CreationComposer intent={intent} actions={c.creation} copyState={c.copyState} onCopy={c.copy}
headerAction={onShowNote ? <ShowNoteButton onShow={onShowNote} /> : undefined}
headerAction={showPanel ? <ShowNoteButton label={showPanel.label} onShow={showPanel.onShow} /> : undefined}
modeSwitch={aiActive ? <Segmented label="How to create" options={creationModes} value={mode}
disabled={intent.phase.state !== 'editing' || generation.busy}
onChange={(next) => {
Expand Down
Loading