diff --git a/core/src/form-application.test.ts b/core/src/form-application.test.ts index 02bc80a..6704ecc 100644 --- a/core/src/form-application.test.ts +++ b/core/src/form-application.test.ts @@ -1,10 +1,19 @@ import { describe, expect, it } from 'vitest'; -import { newApplicationFromFormOps } from './form-application'; -import { formUrlKey } from './form-link'; +import { + linkFormAndRecordOps, + newApplicationFromFormOps, +} from './form-application'; +import { formUrlKey, linkFormOps } from './form-link'; import type { FillResult } from './fill/result'; import type { WriteOp } from './repository'; import { emptySnapshot } from './schema'; -import type { Application, Job, Statement, StatusEvent } from './types'; +import type { + Application, + Job, + Snapshot, + Statement, + StatusEvent, +} from './types'; const T = '2026-01-01T00:00:00.000Z'; const URL = 'https://jobs.lever.co/acme/1/apply'; @@ -142,3 +151,61 @@ describe('newApplicationFromFormOps', () => { expect(data.statusEvents).toHaveLength(0); }); }); + +describe('linkFormAndRecordOps', () => { + function snapshotWithApp(): Snapshot { + const data = emptySnapshot(); + data.applications.push({ + id: 'a1', + companyId: 'c1', + status: 'interested', + createdAt: T, + updatedAt: T, + } as Application); + return data; + } + + it('keeps both formUrls and siteType on the last put of the application', () => { + const key = formUrlKey(URL) ?? URL; + const { ops, record } = linkFormAndRecordOps( + snapshotWithApp(), + 'a1', + key, + held('lever'), + makeDeps(), + ); + const apps = stores(ops, 'applications').filter( + (o) => (o as { record: Application }).record.id === 'a1', + ); + expect(apps.length).toBeGreaterThan(1); + const last = (apps[apps.length - 1] as { record: Application }).record; + expect(last.formUrls).toContain(key); + expect(last.siteType).toBe('lever'); + expect(record?.missing).toBe(false); + }); + + it('equals linkFormOps without a held result', () => { + const data = snapshotWithApp(); + const { ops, record } = linkFormAndRecordOps( + data, + 'a1', + 'k', + undefined, + makeDeps(), + ); + expect(ops).toEqual(linkFormOps(data, 'a1', 'k')); + expect(record).toBeUndefined(); + }); + + it('reports a missing application and writes nothing', () => { + const { ops, record } = linkFormAndRecordOps( + emptySnapshot(), + 'gone', + 'k', + held(), + makeDeps(), + ); + expect(ops).toEqual([]); + expect(record?.missing).toBe(true); + }); +}); diff --git a/core/src/form-application.ts b/core/src/form-application.ts index 14eb3d4..28c8c74 100644 --- a/core/src/form-application.ts +++ b/core/src/form-application.ts @@ -1,13 +1,42 @@ import type { FillResult } from './fill/result'; import { fillRecordOps, type FillRecord } from './fill-records'; -import { formUrlKey } from './form-link'; +import { formUrlKey, linkFormOps } from './form-link'; import { createApplicationFromJobOps, saveJobOps, type JobInput, } from './job-ops'; import type { WriteOp } from './repository'; -import type { Deps, Id, Job, Snapshot } from './types'; +import type { Application, Deps, Id, Job, Snapshot } from './types'; + +/** + * Link an application to a form and, with a held fill result, record that fill + * on it, as one op list. Both writes put the whole application, so the record + * step runs on a snapshot that already carries the link; otherwise the later + * put would drop the earlier one's change. + */ +export function linkFormAndRecordOps( + data: Snapshot, + applicationId: Id, + key: string, + held: FillResult | undefined, + deps: Deps, +): { ops: WriteOp[]; record?: FillRecord } { + const ops = linkFormOps(data, applicationId, key); + if (held === undefined) return { ops }; + const replaced = new Map(); + for (const op of ops) { + if (op.kind === 'put' && op.store === 'applications') { + replaced.set(op.record.id, op.record); + } + } + const next: Snapshot = { + ...data, + applications: data.applications.map((a) => replaced.get(a.id) ?? a), + }; + const record = fillRecordOps(next, held, applicationId, deps); + return { ops: [...ops, ...record.ops], record }; +} /** * A job, an application from it and, with a held fill result, the statements diff --git a/shell/ui/FormLink.tsx b/shell/ui/FormLink.tsx new file mode 100644 index 0000000..5291369 --- /dev/null +++ b/shell/ui/FormLink.tsx @@ -0,0 +1,230 @@ +import type { VNode } from 'preact'; +import { useState } from 'preact/hooks'; +import { applicationRows } from '../../core/src/application-list'; +import type { Id, Snapshot } from '../../core/src/types'; +import { Button } from './components/Button'; +import { Field } from './components/Field'; +import { Text } from './components/Text'; + +const MAX_ROWS = 20; + +type Mode = 'idle' | 'choose' | 'new'; + +function nameOf(value: string | undefined, fallback: string): string { + return value !== undefined && value.trim() !== '' ? value : fallback; +} + +/** "Company · Title" with the fallbacks the link line uses. */ +export function displayName( + company: string | undefined, + title: string | undefined, +): string { + return `${nameOf(company, 'Unknown company')} · ${nameOf(title, 'Untitled')}`; +} + +/** The display name of an application in a snapshot. */ +export function applicationLabel(data: Snapshot, id: Id): string { + const row = applicationRows(data).find((r) => r.id === id); + return displayName(row?.companyName, row?.title); +} + +export interface RecordLine { + recorded: number; + alreadyOnForm: number; + name: string; +} + +function recordedText(line: RecordLine): string { + const answers = line.recorded === 1 ? '1 answer' : `${line.recorded} answers`; + const already = + line.alreadyOnForm > 0 + ? ` (${line.alreadyOnForm} ${line.alreadyOnForm === 1 ? 'was' : 'were'} already on the form)` + : ''; + return `Recorded ${answers} on ${line.name}${already}.`; +} + +/** + * Candidate application ids for the picker: active applications, newest + * created first. + */ +export function pickerCandidates(data: Snapshot): Id[] { + return applicationRows(data) + .filter((r) => !r.archived) + .sort((a, b) => + a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0, + ) + .map((r) => r.id); +} + +export function FormLink(props: { + data: Snapshot; + linkedId?: Id; + candidates: Id[]; + initialCompany?: string; + initialTitle?: string; + /** Resolves true when the write succeeded. */ + onLink: (id: Id) => Promise; + onNew: (input: { companyName: string; title: string }) => Promise; + busy: boolean; + error?: string; + /** Called when the mode changes or Cancel is pressed. */ + onClearError?: () => void; + /** A fill is held until an application is linked. */ + heldNotice?: boolean; + notice?: string; + recordLine?: RecordLine; +}): VNode { + const [mode, setMode] = useState('idle'); + const [query, setQuery] = useState(''); + const [company, setCompany] = useState(undefined); + const [title, setTitle] = useState(undefined); + + const changeMode = (next: Mode): void => { + props.onClearError?.(); + setMode(next); + }; + + const rows = applicationRows(props.data); + const byId = new Map(rows.map((r) => [r.id, r] as const)); + const label = (id: Id): string => { + const row = byId.get(id); + return displayName(row?.companyName, row?.title); + }; + + const done = (ok: boolean): void => { + if (ok) setMode('idle'); + }; + + let panel: VNode | null = null; + if (mode === 'choose') { + const needle = query.trim().toLowerCase(); + const matching = props.candidates.filter((id) => { + if (needle === '') return true; + const row = byId.get(id); + return ( + (row?.companyName ?? '').toLowerCase().includes(needle) || + (row?.title ?? '').toLowerCase().includes(needle) + ); + }); + panel = ( + + ); + } else if (mode === 'new') { + const companyValue = company ?? props.initialCompany ?? ''; + const titleValue = title ?? props.initialTitle ?? ''; + panel = ( + + ); + } + + const linked = props.linkedId !== undefined; + return ( + + ); +} diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index e237910..c5f56d1 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -8,7 +8,17 @@ import { saveJobOps, } from '../../core/src/job-ops'; import type { JobInput } from '../../core/src/job-ops'; +import type { FillResult } from '../../core/src/fill/result'; +import { fillRecordOps } from '../../core/src/fill-records'; +import type { FillRecord } from '../../core/src/fill-records'; +import { + linkFormAndRecordOps, + newApplicationFromFormOps, +} from '../../core/src/form-application'; +import { findApplicationsForForm, formUrlKey } from '../../core/src/form-link'; import { profileValues } from '../../core/src/profile'; +import type { WriteOp } from '../../core/src/repository'; +import type { Id, Snapshot } from '../../core/src/types'; import { canonicalizeUrl } from '../../core/src/url'; import { capturePage } from '../capture/inject'; import type { CaptureOutcome } from '../capture/inject'; @@ -17,7 +27,16 @@ import type { FillController } from '../fill/controller'; import { openDashboard } from '../open-dashboard'; import { useAppData } from './app-data'; import { AnyoneHere } from './AnyoneHere'; +import { currentStatus, statusLabel } from '../../core/src/status'; import { FillSection } from './FillSection'; +import { ToldPanel } from './ToldPanel'; +import { + FormLink, + applicationLabel, + displayName, + pickerCandidates, +} from './FormLink'; +import type { RecordLine } from './FormLink'; import { Button } from './components/Button'; import { Fact } from './components/Fact'; import { Field } from './components/Field'; @@ -115,10 +134,48 @@ export function Popup(): VNode { } const controller = controllerRef.current; + const [fillStatus, setFillStatus] = useState(() => controller.state().status); + useEffect(() => { + const unsubscribe = controller.subscribe((s) => setFillStatus(s.status)); + setFillStatus(controller.state().status); + return unsubscribe; + }, [controller]); + + // Set by Choose… and Create and link; see linkedId below. + const [chosenId, setChosenId] = useState(undefined); + const [linking, setLinking] = useState(false); + const [linkError, setLinkError] = useState(undefined); + // A fill result waiting for an application to record it on. + const [held, setHeld] = useState(undefined); + const heldRef = useRef(undefined); + heldRef.current = held; + const [recordLine, setRecordLine] = useState( + undefined, + ); + const [recordNotice, setRecordNotice] = useState( + undefined, + ); + const linkingRef = useRef(false); + const linkedIdRef = useRef(undefined); + useEffect(() => { controller.refresh(); }, [data]); + // A match linked the form without the owner's click: drop the stale held + // fill rather than let a later Choose… record it. The owner's own link + // path records and clears held itself, and is excluded while in flight. + useEffect(() => { + if ( + linkedIdRef.current !== undefined && + heldRef.current !== undefined && + !linkingRef.current + ) { + heldRef.current = undefined; + setHeld(undefined); + } + }); + useEffect(() => { if (started.current) return; started.current = true; @@ -208,6 +265,169 @@ export function Popup(): VNode { const outcomeUrl = outcome.ok ? outcome.capture.url : outcome.url; const linkValue = pasteLink ?? (isHttp(outcomeUrl) ? outcomeUrl.trim() : ''); + const formKey = + outcomeUrl === undefined + ? undefined + : formUrlKey(outcomeUrl, captured?.relCanonical); + // A chosen application that still exists wins; otherwise the first match. + // Task 8 records a fill to linkedId; Task 9 shows a panel for it. + const linkedId: Id | undefined = + chosenId !== undefined && data.applications.some((a) => a.id === chosenId) + ? chosenId + : formKey === undefined + ? undefined + : findApplicationsForForm(data, formKey)[0]; + + linkedIdRef.current = linkedId; + + const MISSING = 'The application is no longer there. Choose another.'; + + // One apply per write, with the held fill result recorded in the same one. + const runLink = ( + build: (d: Snapshot) => { + ops: WriteOp[]; + id: Id; + name: string; + record?: FillRecord; + }, + ): Promise => { + if (linkingRef.current) return Promise.resolve(false); + linkingRef.current = true; + setLinking(true); + setLinkError(undefined); + const got: { + id?: Id; + name: string; + record?: FillRecord; + held?: FillResult; + } = { name: '' }; + return app + .apply((d) => { + // The held result the builder reads, captured in the same sync step. + got.held = heldRef.current; + const built = build(d); + got.id = built.id; + got.name = built.name; + got.record = built.record; + if (built.record?.missing) throw new Error(MISSING); + return built.ops; + }) + .then( + () => { + linkingRef.current = false; + setChosenId(got.id); + setLinking(false); + if (got.record !== undefined) { + // Clear only the result this link recorded; a Fill that finished + // during the write has replaced it and must survive. + if (got.held !== undefined && heldRef.current === got.held) { + setHeld(undefined); + } + setRecordNotice(undefined); + setRecordLine( + got.record.recorded > 0 + ? { + recorded: got.record.recorded, + alreadyOnForm: got.record.alreadyOnForm, + name: got.name, + } + : undefined, + ); + } + return true; + }, + (err: unknown) => { + linkingRef.current = false; + setLinkError(messageOf(err)); + setLinking(false); + return false; + }, + ); + }; + const linkExisting = (id: Id): Promise => + runLink((d) => { + const built = linkFormAndRecordOps( + d, + id, + formKey ?? '', + heldRef.current, + deps, + ); + return { + ops: built.ops, + id, + name: applicationLabel(d, id), + record: built.record, + }; + }); + + const onFilled = (result: FillResult): void => { + setRecordLine(undefined); + setRecordNotice(undefined); + // Read when the fill completes, not at the click (FillSection is fixed). + const id = linkedIdRef.current; + if (id === undefined) { + setHeld(result); + return; + } + const got: { name: string; record?: FillRecord } = { name: '' }; + app + .apply((d) => { + const record = fillRecordOps(d, result, id, deps); + got.record = record; + got.name = applicationLabel(d, id); + return record.ops; + }) + .then( + () => { + const record = got.record; + if (record === undefined) return; + if (record.missing) { + heldRef.current = result; + setHeld(result); + setChosenId(undefined); + setRecordNotice(MISSING); + return; + } + setHeld(undefined); + if (record.recorded > 0) { + setRecordLine({ + recorded: record.recorded, + alreadyOnForm: record.alreadyOnForm, + name: got.name, + }); + } + }, + (err: unknown) => setLinkError(messageOf(err)), + ); + }; + const linkNew = (names: { + companyName: string; + title: string; + }): Promise => + runLink((d) => { + const input: JobInput = { + source: captured + ? captured.source === 'jsonld' + ? 'jsonld' + : 'selection' + : 'paste', + url: isHttp(outcomeUrl) ? outcomeUrl.trim() : undefined, + relCanonical: captured?.relCanonical, + title: names.title, + companyName: names.companyName, + location: captured?.location, + text: captured?.text ?? '', + }; + const built = newApplicationFromFormOps(d, input, deps, heldRef.current); + return { + ops: built.ops, + id: built.applicationId, + name: displayName(names.companyName, names.title), + record: built.record, + }; + }); + let body: VNode; if (captured) { const input: JobInput = { @@ -367,7 +587,37 @@ export function Popup(): VNode { ) : null} - + {fillStatus === 'ready' && formKey !== undefined ? ( + setLinkError(undefined)} + heldNotice={held !== undefined && linkedId === undefined} + notice={recordNotice} + recordLine={recordLine} + /> + ) : null} + + {fillStatus === 'ready' && linkedId !== undefined ? ( + app.apply(build)} + /> + ) : null} + + ) : null} + {markedEvent !== undefined ? ( + + ) : panel.offerApplied ? ( + + ) : null} + {error ? ( + + {error} + + ) : null} + + ); +} diff --git a/shell/ui/theme/popup-layout.css b/shell/ui/theme/popup-layout.css index d60fc68..811a7db 100644 --- a/shell/ui/theme/popup-layout.css +++ b/shell/ui/theme/popup-layout.css @@ -25,6 +25,25 @@ margin: 0.5rem 0; } +.popup-formlink, +.popup-told, +.popup-told-list, +.popup-formlink-panel, +.popup-formlink-list { + display: flex; + flex-direction: column; + gap: var(--space-1); + overflow-wrap: anywhere; +} + +.popup-formlink { + padding: var(--space-1) 0; +} + +.popup-formlink-list { + align-items: flex-start; +} + .popup-fill { display: flex; flex-direction: column;