Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(spreadsheet): add goal seek (#7745)
Wolf Mermelsteinccc91c3bba62
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.mdindex d33622f340..5f483b50fc 100644--- a/apps/web/src/features/block-spreadsheet/README.md+++ b/apps/web/src/features/block-spreadsheet/README.md@@ -11,7 +11,7 @@ spreadsheet, then choose **Import…**.The document title sits above a compact formatting ribbon. **Paste special** offerspaste and values-only paste; **View options** toggles gridlines, the formula bar,and formula display. **Functions** inserts formulas, while **Format and data**-contains sorting, whitespace trimming, fill, and clear actions. **Find and replace**+contains sorting, whitespace trimming, Goal Seek, fill, and clear actions. **Find and replace**is a direct ribbon button. The footer's **Import and export** button also containsExcel and CSV downloads and stays visible beside horizontally scrolling sheet tabs.@@ -320,6 +320,9 @@ compare formula, error, and formatting behavior before replacing it.dialog changes a chart's type, title, legend and data. Edited charts areexported as Macro writes them, without the part Excel saved. Ctrl+Alt+5selects a drawing from the grid and Tab moves between them.+- **Format and data → Goal Seek…** finds the number that makes a formula cell+ reach a typed value, then writes it when confirmed. The search runs on a copy+ of the calculated workbook, so cancel leaves every cell as it was.- Filters, editing named ranges, automatic spill expansion, and dragauto-scroll remain future work.- CSV import writes a validated rectangle at the active cell, appending rows whendiff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsxindex 8ec0865da3..8d43bdf5ea 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx@@ -3,6 +3,7 @@ import ArrowRight from '@phosphor/arrow-right.svg';import CaretRight from '@phosphor/caret-right.svg';import ChartBar from '@phosphor/chart-bar.svg';import Clipboard from '@phosphor/clipboard-text.svg';+import Crosshair from '@phosphor/crosshair.svg';import Download from '@phosphor/download-simple.svg';import Eraser from '@phosphor/eraser.svg';import Eye from '@phosphor/eye.svg';@@ -218,6 +219,14 @@ export function DataFormatMenu(props: SpreadsheetToolbarProps) {<TextAlignLeft class="size-4" />Trim whitespace</Dropdown.Item>+ <Dropdown.Item+ closeOnSelect+ disabled={props.readonly}+ onSelect={() => props.onCommand('goal-seek')}+ >+ <Crosshair class="size-4" />+ Goal Seek…+ </Dropdown.Item></Dropdown.Group><Dropdown.Group><Dropdown.Itemdiff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.test.tsxnew file mode 100644index 0000000000..ede08b0850--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.test.tsx@@ -0,0 +1,101 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import type { ParentProps } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SpreadsheetGoalSeekDialog } from './SpreadsheetGoalSeekDialog';++vi.mock('@ui/components/Tooltip', () => ({+ Tooltip: (props: ParentProps) => props.children,+}));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@components/app/mobile/MobileDrawer', () => ({+ MobileDrawer: () => null,+}));++let animationStyle: HTMLStyleElement;+beforeEach(() => {+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});+ animationStyle = document.createElement('style');+ animationStyle.textContent = '* { animation-name: none !important; }';+ document.head.append(animationStyle);+});+afterEach(() => {+ cleanup();+ animationStyle.remove();+ vi.restoreAllMocks();+});++describe('Goal Seek dialog', () => {+ it('collects the formula, goal, and changing cell, then confirms the solution', () => {+ const onSeek = vi.fn();+ const onApply = vi.fn();+ const onSetCell = vi.fn();+ const onGoal = vi.fn();+ const onChangingCell = vi.fn();+ render(() => (+ <SpreadsheetGoalSeekDialog+ open+ onClose={() => {}}+ setCell="B1"+ onSetCell={onSetCell}+ goal=""+ onGoal={onGoal}+ changingCell="A1"+ onChangingCell={onChangingCell}+ seeking={false}+ solution={undefined}+ message=""+ onSeek={onSeek}+ onApply={onApply}+ onEdit={() => {}}+ />+ ));+ fireEvent.input(screen.getByRole('textbox', { name: 'To value' }), {+ target: { value: '50' },+ });+ expect(onGoal).toHaveBeenCalledWith('50');+ fireEvent.submit(screen.getByRole('dialog').querySelector('form')!);+ expect(onSeek).toHaveBeenCalledOnce();+ expect(onApply).not.toHaveBeenCalled();+ });++ it('writes the found value only after the solution is confirmed', () => {+ const onApply = vi.fn();+ const onEdit = vi.fn();+ render(() => (+ <SpreadsheetGoalSeekDialog+ open+ onClose={() => {}}+ setCell="B1"+ onSetCell={() => {}}+ goal="50"+ onGoal={() => {}}+ changingCell="A1"+ onChangingCell={() => {}}+ seeking={false}+ solution={{+ status: 'found',+ input: '10',+ value: 10,+ result: 50,+ evaluations: 3,+ setSheetId: 'sheet1',+ setAddress: 'B1',+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ }}+ message=""+ onSeek={() => {}}+ onApply={onApply}+ onEdit={onEdit}+ />+ ));+ expect(screen.getByRole('status').textContent).toMatch(+ /A1 becomes 10, and B1 equals 50/+ );+ fireEvent.click(screen.getByRole('button', { name: 'Change cells' }));+ expect(onEdit).toHaveBeenCalledOnce();+ expect(onApply).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'OK' }));+ expect(onApply).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.tsxnew file mode 100644index 0000000000..394db84906--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGoalSeekDialog.tsx@@ -0,0 +1,136 @@+import type { GoalSeekSolution } from '@macro-inc/spreadsheet/goal-seek';+import X from '@phosphor/x.svg';+import { Button } from '@ui/components/Button';+import { Show } from 'solid-js';+import { SpreadsheetDialog as Dialog } from './SpreadsheetDialog';++function formatGoalNumber(value: number) {+ return new Intl.NumberFormat('en-US', {+ maximumSignificantDigits: 12,+ }).format(value);+}++export function SpreadsheetGoalSeekDialog(props: {+ open: boolean;+ onClose: () => void;+ onRestoreFocus?: () => void;+ setCell: string;+ onSetCell: (value: string) => void;+ goal: string;+ onGoal: (value: string) => void;+ changingCell: string;+ onChangingCell: (value: string) => void;+ seeking: boolean;+ solution: GoalSeekSolution | undefined;+ message: string;+ onSeek: () => void;+ onApply: () => void;+ onEdit: () => void;+}) {+ const locked = () => props.seeking || !!props.solution;+ return (+ <Dialog+ onRestoreFocus={props.onRestoreFocus}+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onClose();+ }}+ position="center"+ class="w-108"+ >+ <form+ class="p-5 text-ink"+ onSubmit={(event) => {+ event.preventDefault();+ if (props.solution) props.onApply();+ else if (!props.seeking) props.onSeek();+ }}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <div class="mb-4 flex items-center justify-between">+ <Dialog.Title class="text-sm font-semibold">Goal Seek</Dialog.Title>+ <Button+ type="button"+ label="Close Goal Seek"+ size="icon-sm"+ class="order-last text-ink-muted"+ tabIndex={-1}+ onClick={props.onClose}+ >+ <X class="size-4" />+ </Button>+ </div>+ <Dialog.Description class="mb-4 text-xs text-ink-muted">+ Finds the number in one cell that makes a formula cell reach a value.+ </Dialog.Description>+ <label class="mb-3 block text-xs">+ <span class="mb-1.5 block">Set cell</span>+ <input+ aria-label="Set cell"+ value={props.setCell}+ disabled={locked()}+ onInput={(event) => props.onSetCell(event.currentTarget.value)}+ class="h-9 w-full touch:h-[44px] touch:text-[max(16px,1rem)] rounded-md border border-edge-muted bg-input px-3 text-sm outline-none focus:border-accent disabled:opacity-40"+ />+ </label>+ <label class="mb-3 block text-xs">+ <span class="mb-1.5 block">To value</span>+ <input+ aria-label="To value"+ value={props.goal}+ disabled={locked()}+ onInput={(event) => props.onGoal(event.currentTarget.value)}+ class="h-9 w-full touch:h-[44px] touch:text-[max(16px,1rem)] rounded-md border border-edge-muted bg-input px-3 text-sm outline-none focus:border-accent disabled:opacity-40"+ />+ </label>+ <label class="mb-4 block text-xs">+ <span class="mb-1.5 block">By changing cell</span>+ <input+ aria-label="By changing cell"+ value={props.changingCell}+ disabled={locked()}+ onInput={(event) => props.onChangingCell(event.currentTarget.value)}+ class="h-9 w-full touch:h-[44px] touch:text-[max(16px,1rem)] rounded-md border border-edge-muted bg-input px-3 text-sm outline-none focus:border-accent disabled:opacity-40"+ />+ </label>+ <p role="status" class="min-h-10 py-3 text-xs text-ink-muted">+ <Show when={props.seeking}>Seeking a solution…</Show>+ <Show when={props.solution} keyed>+ {(found) =>+ found.status === 'found'+ ? `Goal Seek found a solution. ${found.changeAddress} becomes ${formatGoalNumber(found.value)}, and ${found.setAddress} equals ${formatGoalNumber(found.result)}.`+ : `Goal Seek could not reach the goal. The closest result is ${formatGoalNumber(found.result)} when ${found.changeAddress} is ${formatGoalNumber(found.value)}.`+ }+ </Show>+ <Show when={props.message}>+ {props.seeking || props.solution+ ? ` ${props.message}`+ : props.message}+ </Show>+ </p>+ <div class="flex flex-wrap justify-end gap-2 border-t border-edge-muted pt-3">+ <Show+ when={props.solution}+ fallback={+ <Button+ type="submit"+ size="sm"+ variant="strong"+ disabled={props.seeking}+ >+ {props.seeking ? 'Seeking…' : 'OK'}+ </Button>+ }+ >+ <Button type="button" size="sm" onClick={props.onEdit}>+ Change cells+ </Button>+ <Button type="submit" size="sm" variant="strong">+ {props.solution?.status === 'found' ? 'OK' : 'Use closest value'}+ </Button>+ </Show>+ </div>+ </form>+ </Dialog>+ );+}diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsxindex 19acf05c63..e4d8e7ee0d 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx@@ -124,6 +124,7 @@ describe('spreadsheet toolbar', () => {['Format and data', 'Sort selected range A → Z', 'sort-asc'],['Format and data', 'Fill down', 'fill-down'],['Format and data', 'Clear formatting', 'clear-formatting'],+ ['Format and data', 'Goal Seek…', 'goal-seek'],])('keeps %s / %s reachable with the keyboard',async (trigger, item, command) => {diff --git a/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts b/apps/web/src/features/block-spreadsheet/core/calculation-protocol.tsindex 896f0cfe4b..dfd4ead66e 100644--- a/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts+++ b/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts@@ -1,4 +1,8 @@import type { CompletionContext } from '@ironcalc/wasm';+import type {+ GoalSeekRequest,+ GoalSeekResult,+} from '@macro-inc/spreadsheet/goal-seek';import type { SheetPivotLayout } from '@macro-inc/spreadsheet/pivot-layout';import type { WorkbookSheetMetadata } from '@macro-inc/spreadsheet/workbook-metadata';import type { AxisChange } from '@macro-inc/spreadsheet/workbook-structure';@@ -57,6 +61,13 @@ export type CalculationRequest =text: string;cursor: number;context?: CalculationContext;+ }+ | {+ id: number;+ type: 'goal-seek';+ request: GoalSeekRequest;+ /** Present when the worker has no loaded workbook to copy. */+ sheets?: CalculationSheet[];};export type CalculationResponse =@@ -74,6 +85,7 @@ export type CalculationResponse =}| { id: number; type: 'copy'; edits: SpreadsheetCellEdits }| { id: number; type: 'complete'; context: CompletionContext }+ | { id: number; type: 'goal-seek'; result: GoalSeekResult }| { id: number; type: 'error'; message: string };export type CalculationOperation =@@ -82,4 +94,5 @@ export type CalculationOperation =| Omit<Extract<CalculationRequest, { type: 'calculate-workbook' }>, 'id'>| Omit<Extract<CalculationRequest, { type: 'update-workbook' }>, 'id'>| Omit<Extract<CalculationRequest, { type: 'copy' }>, 'id'>- | Omit<Extract<CalculationRequest, { type: 'complete' }>, 'id'>;+ | Omit<Extract<CalculationRequest, { type: 'complete' }>, 'id'>+ | Omit<Extract<CalculationRequest, { type: 'goal-seek' }>, 'id'>;diff --git a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts b/apps/web/src/features/block-spreadsheet/core/toolbar-types.tsindex 43017963b7..5310df0752 100644--- a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts+++ b/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts@@ -24,6 +24,7 @@ export type SpreadsheetCommand =| 'sort-asc'| 'sort-desc'| 'trim-whitespace'+ | 'goal-seek'| 'border-all'| 'border-outer'| 'border-none'diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts b/apps/web/src/features/block-spreadsheet/primitives/create-calculation.tsindex 4a46f7e32b..6609c5e225 100644--- a/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts+++ b/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts@@ -1,3 +1,7 @@+import type {+ GoalSeekRequest,+ GoalSeekResult,+} from '@macro-inc/spreadsheet/goal-seek';import { sheetPivotLayouts } from '@macro-inc/spreadsheet/pivot-layout';import type { AxisChange } from '@macro-inc/spreadsheet/workbook-structure';import {@@ -28,6 +32,14 @@ import {CALCULATION_TIMEOUT_MS,createCalculationClient,} from './calculation-client';++const GOAL_SEEK_TIMEOUT_MS = 45_000;+const goalSeekWaiting: GoalSeekResult = {+ status: 'invalid',+ message:+ 'Wait for the sheet to finish calculating, then try Goal Seek again.',+};+import type { SpreadsheetChanges } from './create-spreadsheet-store';function sameInput(@@ -133,6 +145,8 @@ export function createCalculation(: undefined;let generation = 0;const incremental = workbookOptions?.incremental;+ let goalSeek = async (_request: GoalSeekRequest): Promise<GoalSeekResult> =>+ goalSeekWaiting;if (incremental && workbookOptions) {// The worker keeps its own copy of the inputs; send only what changed and// apply only changed results, so large workbooks stay responsive.@@ -316,6 +330,27 @@ export function createCalculation(} else setBusy(false);});};+ goalSeek = async (request) => {+ // Share the calculator worker, which already holds the workbook, and+ // keep recalculation queued until the search finishes.+ if (running || busy()) return goalSeekWaiting;+ running = true;+ setBusy(true);+ try {+ const response = await calculator.run(+ { type: 'goal-seek', request },+ GOAL_SEEK_TIMEOUT_MS+ );+ if (response.type !== 'goal-seek') throw new Error('Goal Seek failed.');+ return response.result;+ } finally {+ running = false;+ if (queued) {+ queued = false;+ run();+ } else setBusy(false);+ }+ };createEffect(on([workbookOptions.workbook, retryCount], ([, retries], previous) => {if (previous && retries !== previous[1]) sent.clear();@@ -323,7 +358,26 @@ export function createCalculation(onCleanup(() => clearTimeout(timer));}));- } else+ } else {+ goalSeek = async (request) => {+ if (busy()) return goalSeekWaiting;+ const sheets = workbookOptions+ ? workbookInputs()+ : [+ {+ id: 'sheet1',+ name: 'Sheet1',+ cells: inputs(),+ rowCount: rowCount(),+ },+ ];+ const response = await copier.run(+ { type: 'goal-seek', request, sheets },+ GOAL_SEEK_TIMEOUT_MS+ );+ if (response.type !== 'goal-seek') throw new Error('Goal Seek failed.');+ return response.result;+ };createEffect(on([sourceInputs, sourceRows, retryCount], () => {const current = ++generation;@@ -362,6 +416,7 @@ export function createCalculation(onCleanup(() => clearTimeout(timer));}));+ }onCleanup(() => {generation++;calculator.dispose();@@ -377,6 +432,7 @@ export function createCalculation(busy,error,retry: () => setRetryCount((count) => count + 1),+ goalSeek,async complete(text: string, cursor: number) {const result = await helper.run({type: 'complete',diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.test.ts b/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.test.tsnew file mode 100644index 0000000000..0dbebf6cc1--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.test.ts@@ -0,0 +1,142 @@+import { createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { SpreadsheetCell } from '../core/spreadsheet-document';+import { createGoalSeek, type GoalSeekSheet } from './create-goal-seek';++const cleanups: Array<() => void> = [];+afterEach(() => {+ for (const dispose of cleanups.splice(0)) dispose();+});++function setup(options?: {+ activeAddress?: string;+ cells?: Record<string, SpreadsheetCell>;+ sheets?: GoalSeekSheet[];+}) {+ return createRoot((dispose) => {+ cleanups.push(dispose);+ const [revision, setRevision] = createSignal(1);+ const cells = options?.cells ?? {+ A1: { value: '2' },+ B1: { value: '=A1*5' },+ };+ const applied: { sheetId: string; address: string; value: string }[] = [];+ const selected: { sheetId: string; address: string }[] = [];+ const seek = vi.fn(async () => ({+ status: 'found' as const,+ input: '10',+ value: 10,+ result: 50,+ evaluations: 4,+ setSheetId: 'sheet1',+ setAddress: 'B1',+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ }));+ const goalSeek = createGoalSeek({+ sheets: () =>+ options?.sheets ?? [+ { id: 'sheet1', name: 'Plan' },+ { id: 'other', name: 'Other' },+ ],+ activeSheetId: () => 'sheet1',+ activeAddress: () => options?.activeAddress ?? 'B1',+ cell: (_sheetId, address) => cells[address],+ canEdit: () => true,+ revision,+ seek,+ apply: (sheetId, address, value) => {+ applied.push({ sheetId, address, value });+ },+ select: (sheetId, address) => {+ selected.push({ sheetId, address });+ },+ });+ return { goalSeek, seek, applied, selected, setRevision };+ });+}++describe('goal seek dialog state', () => {+ it('starts from the active formula and writes the solution', async () => {+ const { goalSeek, seek, applied, selected } = setup();+ goalSeek.show();+ expect(goalSeek.open()).toBe(true);+ expect(goalSeek.setCell()).toBe('B1');+ expect(goalSeek.changingCell()).toBe('');+ goalSeek.setChangingCell('A1');+ goalSeek.setGoal('50');+ await goalSeek.seek();+ expect(seek).toHaveBeenCalledWith({+ setSheetId: 'sheet1',+ setAddress: 'B1',+ goal: 50,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ });+ expect(goalSeek.solution()?.status).toBe('found');+ goalSeek.apply();+ expect(applied).toEqual([+ { sheetId: 'sheet1', address: 'A1', value: '10' },+ ]);+ expect(selected).toEqual([{ sheetId: 'sheet1', address: 'A1' }]);+ expect(goalSeek.open()).toBe(false);+ });++ it('keeps a value cell as the changing cell and accepts a percent goal on another sheet', async () => {+ const { goalSeek, seek } = setup({ activeAddress: 'A1' });+ goalSeek.show();+ expect(goalSeek.setCell()).toBe('');+ expect(goalSeek.changingCell()).toBe('A1');+ goalSeek.setSetCell('Other!B2');+ goalSeek.setGoal('12%');+ await goalSeek.seek();+ expect(seek).toHaveBeenCalledWith({+ setSheetId: 'other',+ setAddress: 'B2',+ goal: 0.12,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ });+ });++ it('discards a solution when the sheet changes during the search', async () => {+ const { goalSeek, setRevision, applied } = setup();+ goalSeek.show();+ goalSeek.setChangingCell('A1');+ goalSeek.setGoal('50');+ const pending = goalSeek.seek();+ setRevision(2);+ await pending;+ expect(goalSeek.solution()).toBeUndefined();+ expect(goalSeek.message()).toMatch(/changed/i);+ goalSeek.apply();+ expect(applied).toEqual([]);+ });++ it('does not write a solution after the sheet changes', async () => {+ const { goalSeek, setRevision, applied } = setup();+ goalSeek.show();+ goalSeek.setChangingCell('A1');+ goalSeek.setGoal('50');+ await goalSeek.seek();+ setRevision(2);+ goalSeek.apply();+ expect(applied).toEqual([]);+ expect(goalSeek.open()).toBe(true);+ expect(goalSeek.message()).toMatch(/changed/i);+ });++ it('explains an address or goal the search cannot use', async () => {+ const { goalSeek, seek } = setup();+ goalSeek.show();+ goalSeek.setGoal('lots');+ goalSeek.setChangingCell('A1');+ await goalSeek.seek();+ expect(seek).not.toHaveBeenCalled();+ expect(goalSeek.message()).toMatch(/value/i);+ goalSeek.setGoal('10');+ goalSeek.setSetCell('not a cell');+ await goalSeek.seek();+ expect(goalSeek.message()).toMatch(/B12/);+ });+});diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.ts b/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.tsnew file mode 100644index 0000000000..6071d9bfc4--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/primitives/create-goal-seek.ts@@ -0,0 +1,190 @@+import {+ type GoalSeekRequest,+ type GoalSeekResult,+ type GoalSeekSolution,+ parseGoalSeekReference,+ parseGoalValue,+} from '@macro-inc/spreadsheet/goal-seek';+import type { Accessor } from 'solid-js';+import { createSignal } from 'solid-js';+import type { SpreadsheetCell } from '../core/spreadsheet-document';++export type GoalSeekSheet = { id: string; name: string };++export function resolveGoalSeekReference(+ text: string,+ sheets: GoalSeekSheet[],+ activeSheetId: string+): { sheetId: string; address: string } | { message: string } {+ const parsed = parseGoalSeekReference(text);+ if (!parsed) return { message: 'Enter a cell such as B12 or Inputs!B12.' };+ if (!parsed.sheet) return { sheetId: activeSheetId, address: parsed.address };+ const sheet = sheets.find(+ (entry) => entry.name.toLowerCase() === parsed.sheet?.toLowerCase()+ );+ if (!sheet) return { message: `There is no sheet named ${parsed.sheet}.` };+ return { sheetId: sheet.id, address: parsed.address };+}++function isFormula(cell: SpreadsheetCell | undefined) {+ return !!cell && cell.format !== 'text' && cell.value.startsWith('=');+}++export function createGoalSeek(source: {+ sheets: Accessor<GoalSeekSheet[]>;+ activeSheetId: Accessor<string>;+ activeAddress: Accessor<string>;+ cell: (sheetId: string, address: string) => SpreadsheetCell | undefined;+ canEdit: Accessor<boolean>;+ revision: Accessor<number>;+ seek: (request: GoalSeekRequest) => Promise<GoalSeekResult>;+ apply: (+ sheetId: string,+ address: string,+ value: string+ ) => string | undefined;+ select: (sheetId: string, address: string) => void;+}) {+ const [open, setOpen] = createSignal(false);+ const [setCell, setSetCell] = createSignal('');+ const [goal, setGoal] = createSignal('');+ const [changingCell, setChangingCell] = createSignal('');+ const [message, setMessage] = createSignal('');+ const [seeking, setSeeking] = createSignal(false);+ const [solution, setSolution] = createSignal<GoalSeekSolution>();+ let operation = 0;+ let solvedRevision = 0;++ function show() {+ if (!source.canEdit()) return;+ const sheetId = source.activeSheetId();+ const address = source.activeAddress();+ const formula = isFormula(source.cell(sheetId, address));+ operation++;+ setSetCell(formula ? address : '');+ setChangingCell(formula ? '' : address);+ setGoal('');+ setMessage('');+ setSolution(undefined);+ setSeeking(false);+ setOpen(true);+ }++ function close() {+ operation++;+ setSeeking(false);+ setOpen(false);+ }++ function request(): GoalSeekRequest | undefined {+ const setTarget = resolveGoalSeekReference(+ setCell(),+ source.sheets(),+ source.activeSheetId()+ );+ if ('message' in setTarget) {+ setMessage(setTarget.message);+ return;+ }+ const goalValue = parseGoalValue(goal());+ if (goalValue === undefined) {+ setMessage('Enter the value the formula should reach.');+ return;+ }+ const changeTarget = resolveGoalSeekReference(+ changingCell(),+ source.sheets(),+ source.activeSheetId()+ );+ if ('message' in changeTarget) {+ setMessage(changeTarget.message);+ return;+ }+ if (+ setTarget.sheetId === changeTarget.sheetId &&+ setTarget.address === changeTarget.address+ ) {+ setMessage('Set cell and the changing cell have to be different cells.');+ return;+ }+ setMessage('');+ return {+ setSheetId: setTarget.sheetId,+ setAddress: setTarget.address,+ goal: goalValue,+ changeSheetId: changeTarget.sheetId,+ changeAddress: changeTarget.address,+ };+ }++ async function seek() {+ const next = request();+ if (!next) return;+ const current = ++operation;+ const revision = source.revision();+ setSolution(undefined);+ setSeeking(true);+ setMessage('');+ try {+ const result = await source.seek(next);+ if (current !== operation) return;+ if (source.revision() !== revision) {+ setMessage('The sheet changed while Goal Seek was running. Try again.');+ return;+ }+ if (result.status === 'invalid') {+ setMessage(result.message);+ return;+ }+ solvedRevision = revision;+ setSolution(result);+ } catch (error) {+ if (current !== operation) return;+ setMessage(error instanceof Error ? error.message : 'Goal Seek failed.');+ } finally {+ if (current === operation) setSeeking(false);+ }+ }++ function apply() {+ const found = solution();+ if (!found) return;+ if (source.revision() !== solvedRevision) {+ setSolution(undefined);+ setMessage('The sheet changed while Goal Seek was running. Try again.');+ return;+ }+ const rejected = source.apply(+ found.changeSheetId,+ found.changeAddress,+ found.input+ );+ if (rejected) {+ setMessage(rejected);+ return;+ }+ source.select(found.changeSheetId, found.changeAddress);+ close();+ }++ return {+ open,+ setCell,+ setSetCell,+ goal,+ setGoal,+ changingCell,+ setChangingCell,+ message,+ seeking,+ solution,+ show,+ close,+ seek,+ apply,+ clearSolution: () => {+ setSolution(undefined);+ setMessage('');+ },+ };+}diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsxindex 0f5781eb25..b51d8caefe 100644--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx@@ -16,6 +16,7 @@ import { ChartDialog } from '../components/ChartDialog';import { SpreadsheetFileMenu } from '../components/SpreadsheetActionMenus';import { SpreadsheetDialog } from '../components/SpreadsheetDialog';import { SpreadsheetFindDialog } from '../components/SpreadsheetDialogs';+import { SpreadsheetGoalSeekDialog } from '../components/SpreadsheetGoalSeekDialog';import {renderedSelectionCell,SpreadsheetGrid,@@ -62,6 +63,7 @@ import { CSV_MAX_BYTES } from '../core/workbook-file-types';import { createCalculation } from '../primitives/create-calculation';import { createCalculationStatus } from '../primitives/create-calculation-status';import { createDrawingActions } from '../primitives/create-drawing-actions';+import { createGoalSeek } from '../primitives/create-goal-seek';import { createGridController } from '../primitives/create-grid-controller';import { createSheetActions } from '../primitives/create-sheet-actions';import type { SpreadsheetStore } from '../primitives/create-spreadsheet-store';@@ -235,6 +237,45 @@ export function SpreadsheetEditor(props: {gridElement?.querySelector(`[data-address="${cellAddress(grid.selection().focus)}"]`)?.scrollIntoView({ block: 'nearest', inline: 'nearest' });+ const goalSeek = createGoalSeek({+ sheets: () =>+ props.store.workbook().map((sheet) => ({+ id: sheet.id,+ name: sheet.name,+ })),+ activeSheetId: props.store.activeSheetId,+ activeAddress: grid.activeAddress,+ cell: (sheetId, address) =>+ props.store.workbook().find((sheet) => sheet.id === sheetId)?.cells[+ address+ ],+ canEdit: editable,+ revision: props.store.revision,+ seek: (request) => calculation.goalSeek(request),+ apply: (sheetId, address, value) => {+ const sheet = props.store+ .workbook()+ .find((entry) => entry.id === sheetId);+ if (!sheet) return 'That sheet is no longer in the workbook.';+ const outcome = validateInput(+ validationAt(sheet.metadata?.validations, address),+ value,+ rangeValues(sheetId),+ definedNames(sheetId)+ );+ if (!outcome.valid && outcome.style === 'stop') return outcome.message;+ props.store.setSheetCells(sheetId, { [address]: { value } });+ },+ select: (sheetId, address) => {+ const position = positionFromAddress(address);+ if (!position) return;+ props.store.setActiveSheet(sheetId);+ queueMicrotask(() => {+ grid.select(position);+ revealSelection();+ });+ },+ });// Comment links drive the imperative grid selection and scroll without moving// keyboard focus out of the comment composer.createEffect(@@ -272,6 +313,7 @@ export function SpreadsheetEditor(props: {}if (actions.findOpen() ||+ goalSeek.open() ||workbookActions.preview() ||workbookActions.sheetDialog())@@ -383,6 +425,17 @@ export function SpreadsheetEditor(props: {.with('fill-right', () => grid.fillDirection('right')).with('select-all', actions.selectAll).with('find', () => actions.setFindOpen(true))+ .with('goal-seek', () => {+ if (calculation.busy() || calculation.error()) {+ actions.setNotice(+ calculation.error()+ ? 'Fix the calculation error before using Goal Seek.'+ : 'Wait for the sheet to finish calculating, then try Goal Seek again.'+ );+ return;+ }+ goalSeek.show();+ }).with('export-csv', exportCsv).with('import', () => importInput.click()).with('export-xlsx', () => {@@ -1157,6 +1210,28 @@ export function SpreadsheetEditor(props: {onConfirm={workbookActions.confirmImport}onClose={workbookActions.closePreview}/>+ <SpreadsheetGoalSeekDialog+ onRestoreFocus={() => {+ focusGrid();+ revealSelection();+ }}+ open={goalSeek.open()}+ onClose={goalSeek.close}+ setCell={goalSeek.setCell()}+ onSetCell={goalSeek.setSetCell}+ goal={goalSeek.goal()}+ onGoal={goalSeek.setGoal}+ changingCell={goalSeek.changingCell()}+ onChangingCell={goalSeek.setChangingCell}+ seeking={goalSeek.seeking()}+ solution={goalSeek.solution()}+ message={goalSeek.message()}+ onSeek={() => {+ void goalSeek.seek();+ }}+ onApply={goalSeek.apply}+ onEdit={goalSeek.clearSolution}+ /><SpreadsheetFindDialogonRestoreFocus={() => {focusGrid();diff --git a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.tsindex e52caf9d9d..972937a843 100644--- a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts+++ b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts@@ -164,6 +164,16 @@ self.onmessage = async (event: MessageEvent<CalculationRequest>) => {operation.context),}))+ .with({ type: 'goal-seek' }, (operation) => ({+ id: operation.id,+ type: 'goal-seek',+ result: operation.sheets+ ? engine.goalSeek(operation.sheets, operation.request)+ : (session?.goalSeek(operation.request) ?? {+ status: 'invalid' as const,+ message: 'Calculate the sheet before using Goal Seek.',+ }),+ })).exhaustive();} catch (error) {response = {diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex c80db1c86d..10c0e94ef5 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -256,7 +256,10 @@ case-sensitive and whole-cell matching. Find next selects each result. Formula rbut replacements preserve the formulas unless **Search within formulas** is checked.**Format and data** sorts the selected rectangle by its active column, keeping eachrow's values, styles, and relative formulas together, or trims whitespace in text-cells. The same menu offers fill down/right, clear formatting, and clear values.+cells. **Goal Seek…** in that menu finds the number to put in one cell so a formula+cell reaches a value you type: set the formula cell, the goal, and the number cell+to change, then confirm to write that number. Cancel leaves the sheet unchanged.+The same menu offers fill down/right, clear formatting, and clear values.Select data without its header when sorting. A concurrent edit cancels a pendingsort; references elsewhere in the sheet are not rewritten to follow sorted rows.diff --git a/packages/spreadsheet/src/calculation.ts b/packages/spreadsheet/src/calculation.tsindex 02e8edd990..6e0b66bb2b 100644--- a/packages/spreadsheet/src/calculation.ts+++ b/packages/spreadsheet/src/calculation.ts@@ -12,6 +12,12 @@ import {type ConditionalAppearance,readConditionalAppearance,} from './conditional-formatting';+import {+ type GoalSeekRequest,+ type GoalSeekResult,+ goalSeekInput,+ solveGoalSeek,+} from './goal-seek';import { displayNumber, numericLiteral } from './number-display';import { type SheetPivotLayout, sheetPivotLayouts } from './pivot-layout';import {@@ -80,6 +86,14 @@ export type SpreadsheetCalculator = {changeAxis: typeof changeWorkbookAxis;/** An incremental calculation for a workbook that is edited repeatedly. */session: () => WorkbookCalculationSession;+ /**+ * Goal Seek on a private copy of `sheets`. The caller's workbook is+ * unchanged; the returned input is what a later edit would write.+ */+ goalSeek: (+ sheets: CalculationSheet[],+ request: GoalSeekRequest+ ) => GoalSeekResult;dispose: () => void;};@@ -1221,9 +1235,151 @@ export type WorkbookCalculationSession = {changes: Record<string, Record<string, SpreadsheetCell | null>>,options?: { includeTypes?: boolean }) => Record<string, Record<string, CalculatedCell | null>>;+ /**+ * Goal Seek on a copy of the loaded model. The loaded workbook and its+ * cached results stay as they were.+ */+ goalSeek: (request: GoalSeekRequest) => GoalSeekResult;dispose: () => void;};+function goalSeekLabel(sheetName: string, address: string) {+ const quote = /[^A-Za-z0-9_]/.test(sheetName);+ const sheet = quote ? `'${sheetName.replaceAll("'", "''")}'` : sheetName;+ return `${sheet}!${address}`;+}++function isFormulaCell(cell: SpreadsheetCell | undefined) {+ return !!cell && cell.format !== 'text' && cell.value.startsWith('=');+}++/** Adjust one numeric cell until a formula cell reaches `request.goal`. */+function goalSeekOnModel(+ model: Model,+ sheets: CalculationSheet[],+ request: GoalSeekRequest+): GoalSeekResult {+ const setSheet = sheets.findIndex((sheet) => sheet.id === request.setSheetId);+ const changeSheet = sheets.findIndex(+ (sheet) => sheet.id === request.changeSheetId+ );+ if (setSheet < 0 || changeSheet < 0)+ return { status: 'invalid', message: 'Choose cells in this workbook.' };+ const setPosition = parseCellAddress(request.setAddress);+ const changePosition = parseCellAddress(request.changeAddress);+ if (!setPosition || !changePosition)+ return { status: 'invalid', message: 'Enter a cell such as B12.' };+ if (!Number.isFinite(request.goal))+ return { status: 'invalid', message: 'Enter a number for the goal.' };+ const setLabel = goalSeekLabel(sheets[setSheet].name, request.setAddress);+ const changeLabel = goalSeekLabel(+ sheets[changeSheet].name,+ request.changeAddress+ );+ if (setSheet === changeSheet && request.setAddress === request.changeAddress)+ return {+ status: 'invalid',+ message: 'Set cell and the changing cell have to be different cells.',+ };+ const setSource = sheets[setSheet].cells[request.setAddress];+ const changeSource = sheets[changeSheet].cells[request.changeAddress];+ if (!isFormulaCell(setSource))+ return {+ status: 'invalid',+ message: `${setLabel} needs a formula. Goal Seek changes another cell until that formula reaches the goal.`,+ };+ if (isFormulaCell(changeSource))+ return {+ status: 'invalid',+ message: `${changeLabel} contains a formula. Choose a cell that holds a number.`,+ };+ if (changeSource?.format === 'text' && changeSource.value !== '')+ return {+ status: 'invalid',+ message: `${changeLabel} is plain text. Choose a cell that holds a number.`,+ };+ if (+ setPosition.row >= sheets[setSheet].rowCount ||+ changePosition.row >= sheets[changeSheet].rowCount+ )+ return { status: 'invalid', message: 'That cell is outside the sheet.' };++ const setRow = setPosition.row + 1;+ const setColumn = setPosition.column + 1;+ const changeRow = changePosition.row + 1;+ const changeColumn = changePosition.column + 1;+ const readSet = () => {+ if (model.getCellType(setSheet, setRow, setColumn) !== 1) return;+ const value = model.getCellNumber(setSheet, setRow, setColumn);+ return value !== undefined && Number.isFinite(value) ? value : undefined;+ };+ if (+ changeSource &&+ changeSource.value !== '' &&+ model.getCellType(changeSheet, changeRow, changeColumn) !== 1+ )+ return {+ status: 'invalid',+ message: `${changeLabel} needs to hold a number.`,+ };+ let guess = 0;+ const current = model.getCellNumber(changeSheet, changeRow, changeColumn);+ if (current !== undefined && Number.isFinite(current)) guess = current;++ const evaluate = (input: number) => {+ model.pauseEvaluation();+ try {+ model.setUserInput(+ changeSheet,+ changeRow,+ changeColumn,+ goalSeekInput(input)+ );+ } catch {+ throw new Error('GOAL_SEEK_CHANGE_FAILED');+ } finally {+ model.resumeEvaluation();+ }+ model.evaluate();+ return readSet();+ };++ let outcome: ReturnType<typeof solveGoalSeek>;+ try {+ outcome = solveGoalSeek({ goal: request.goal, guess, evaluate });+ } catch (error) {+ if (error instanceof Error && error.message === 'GOAL_SEEK_CHANGE_FAILED')+ return {+ status: 'invalid',+ message: `Goal Seek could not change ${changeLabel}. Choose a cell that holds a number.`,+ };+ throw error;+ }+ if (!outcome || outcome.status === 'unchanged') {+ if (outcome?.status === 'unchanged')+ return {+ status: 'invalid',+ message: `Changing ${changeLabel} does not change ${setLabel}.`,+ };+ return {+ status: 'invalid',+ message: `The formula in ${setLabel} does not produce a number Goal Seek can adjust.`,+ };+ }+ const input = goalSeekInput(outcome.input);+ return {+ status: outcome.status,+ input,+ value: Number(input),+ result: outcome.result,+ evaluations: outcome.evaluations,+ setSheetId: request.setSheetId,+ setAddress: request.setAddress,+ changeSheetId: request.changeSheetId,+ changeAddress: request.changeAddress,+ };+}+function createWorkbookCalculationSession(): WorkbookCalculationSession {let workbook: EngineWorkbook | undefined;let results: WorkbookCalculation = {};@@ -1324,6 +1480,26 @@ function createWorkbookCalculationSession(): WorkbookCalculationSession {throw error;}},+ goalSeek(request) {+ if (!workbook)+ return {+ status: 'invalid',+ message: 'Calculate the sheet before using Goal Seek.',+ };+ let clone: Model | undefined;+ try {+ // A copy keeps trial values out of the workbook the editor is showing.+ clone = Model.fromBytes(workbook.model.toBytes(), 'en');+ return goalSeekOnModel(clone, workbook.sheets, request);+ } catch (error) {+ return {+ status: 'invalid',+ message: error instanceof Error ? error.message : 'Goal Seek failed.',+ };+ } finally {+ if (clone) freeModel(clone);+ }+ },dispose,};}@@ -1388,6 +1564,15 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculator]).sheet1;},calculateWorkbook,+ goalSeek(sheets, request) {+ if (disposed) throw new Error('The spreadsheet calculator is disposed.');+ const workbook = buildWorkbook(sheets);+ try {+ return goalSeekOnModel(workbook.model, workbook.sheets, request);+ } finally {+ freeModel(workbook.model);+ }+ },copy(copies, context) {if (disposed) throw new Error('The spreadsheet calculator is disposed.');const model = new Model('Macro copy', 'en', 'UTC', 'en');diff --git a/packages/spreadsheet/src/goal-seek-engine.test.ts b/packages/spreadsheet/src/goal-seek-engine.test.tsnew file mode 100644index 0000000000..73cf49e5a1--- /dev/null+++ b/packages/spreadsheet/src/goal-seek-engine.test.ts@@ -0,0 +1,173 @@+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { initSync } from '@ironcalc/wasm';+import { afterAll, beforeAll, expect, it } from 'vitest';+import {+ type CalculationSheet,+ createInitializedSpreadsheetCalculator,+ type SpreadsheetCalculator,+} from './calculation';+import type { SpreadsheetCell } from './spreadsheet-document';++let calculator: SpreadsheetCalculator;+beforeAll(() => {+ initSync({+ module: readFileSync(+ createRequire(import.meta.url).resolve('@ironcalc/wasm/wasm_bg.wasm')+ ),+ });+ calculator = createInitializedSpreadsheetCalculator();+});+afterAll(() => calculator.dispose());++function cell(+ value: string,+ format?: SpreadsheetCell['format']+): SpreadsheetCell {+ return { value, ...(format && { format }) };+}++function sheet(+ cells: CalculationSheet['cells'],+ id = 'sheet1',+ name = 'Plan'+): CalculationSheet {+ return { id, name, rowCount: 50, cells };+}++it('finds the input that makes a formula reach the goal', () => {+ const found = calculator.goalSeek(+ [sheet({ A1: cell('2'), B1: cell('=A1*5'), C1: cell('=A1+B1') })],+ {+ setSheetId: 'sheet1',+ setAddress: 'B1',+ goal: 50,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ }+ );+ expect(found).toMatchObject({+ status: 'found',+ value: 10,+ result: 50,+ input: '10',+ });+});++it('seeks across sheets and leaves a loaded workbook unchanged', () => {+ const sheets = [+ sheet({ A1: cell('4') }, 'inputs', 'Inputs'),+ sheet({ B1: cell('=Inputs!A1*3') }, 'summary', 'Summary'),+ ];+ const direct = calculator.goalSeek(sheets, {+ setSheetId: 'summary',+ setAddress: 'B1',+ goal: 30,+ changeSheetId: 'inputs',+ changeAddress: 'A1',+ });+ expect(direct).toMatchObject({ status: 'found', value: 10, result: 30 });++ const session = calculator.session();+ try {+ session.load(structuredClone(sheets), { includeTypes: true });+ const found = session.goalSeek({+ setSheetId: 'summary',+ setAddress: 'B1',+ goal: 30,+ changeSheetId: 'inputs',+ changeAddress: 'A1',+ });+ expect(found).toMatchObject({ status: 'found', value: 10, result: 30 });+ const delta = session.update(+ { inputs: { A2: cell('1') } },+ { includeTypes: true }+ );+ expect(delta.inputs?.A1).toBeUndefined();+ expect(delta.summary?.B1).toBeUndefined();+ expect(delta.inputs?.A2.number).toBe(1);+ const fresh = calculator.calculateWorkbook([+ { ...sheets[0], cells: { ...sheets[0].cells, A2: cell('1') } },+ sheets[1],+ ]);+ expect(fresh.inputs.A1.number).toBe(4);+ expect(fresh.summary.B1.number).toBe(12);+ } finally {+ session.dispose();+ }+});++it('rejects a formula changing cell, a constant set cell, and an independent formula', () => {+ const sheets = [+ sheet({+ A1: cell('4'),+ B1: cell('=A1*3'),+ C1: cell('=1+1'),+ D1: cell('=B1'),+ }),+ ];+ expect(+ calculator.goalSeek(sheets, {+ setSheetId: 'sheet1',+ setAddress: 'A1',+ goal: 10,+ changeSheetId: 'sheet1',+ changeAddress: 'B1',+ })+ ).toMatchObject({ status: 'invalid' });+ expect(+ calculator.goalSeek(sheets, {+ setSheetId: 'sheet1',+ setAddress: 'B1',+ goal: 10,+ changeSheetId: 'sheet1',+ changeAddress: 'B1',+ }).status+ ).toBe('invalid');+ expect(+ calculator.goalSeek(sheets, {+ setSheetId: 'sheet1',+ setAddress: 'C1',+ goal: 10,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ })+ ).toMatchObject({+ status: 'invalid',+ message: expect.stringContaining('does not change'),+ });+ const text = calculator.goalSeek(+ [sheet({ A1: cell('hello', 'text'), B1: cell('=A1&"!"') })],+ {+ setSheetId: 'sheet1',+ setAddress: 'B1',+ goal: 1,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ }+ );+ expect(text.status).toBe('invalid');+});++it('solves a payment rate', () => {+ const found = calculator.goalSeek(+ [+ sheet({+ A1: cell('0.05'),+ B1: cell('=PMT(A1/12,360,-200000)'),+ }),+ ],+ {+ setSheetId: 'sheet1',+ setAddress: 'B1',+ goal: 1200,+ changeSheetId: 'sheet1',+ changeAddress: 'A1',+ }+ );+ expect(found.status).toBe('found');+ if (found.status === 'invalid') return;+ expect(found.result).toBeCloseTo(1200, 4);+ expect(found.value).toBeGreaterThan(0.05);+ expect(found.value).toBeLessThan(0.1);+});diff --git a/packages/spreadsheet/src/goal-seek.test.ts b/packages/spreadsheet/src/goal-seek.test.tsnew file mode 100644index 0000000000..2d9a43cdc9--- /dev/null+++ b/packages/spreadsheet/src/goal-seek.test.ts@@ -0,0 +1,80 @@+import { expect, it } from 'vitest';+import {+ goalSeekInput,+ parseGoalSeekReference,+ parseGoalValue,+ solveGoalSeek,+} from './goal-seek';++it('parses cell references and goals', () => {+ expect(parseGoalSeekReference('b12')).toEqual({ address: 'B12' });+ expect(parseGoalSeekReference('$C$3')).toEqual({ address: 'C3' });+ expect(parseGoalSeekReference('Inputs!B12')).toEqual({+ sheet: 'Inputs',+ address: 'B12',+ });+ expect(parseGoalSeekReference("'Q1 ''sheet'''!A1")).toEqual({+ sheet: "Q1 'sheet'",+ address: 'A1',+ });+ expect(parseGoalSeekReference('A1:B2')).toBeUndefined();+ expect(parseGoalSeekReference('not a cell')).toBeUndefined();+ expect(parseGoalValue(' 1,250.5 ')).toBe(1250.5);+ expect(parseGoalValue('$10')).toBe(10);+ expect(parseGoalValue('12%')).toBe(0.12);+ expect(parseGoalValue('1.5e3')).toBe(1500);+ expect(parseGoalValue('goal')).toBeUndefined();+ expect(goalSeekInput(0.1 + 0.2)).toBe('0.3');+ expect(goalSeekInput(-0)).toBe('0');+});++it('solves smooth formulas and reports a goal the formula cannot reach', () => {+ const linear = solveGoalSeek({+ goal: 50,+ guess: 2,+ evaluate: (input) => input * 5,+ });+ expect(linear).toMatchObject({ status: 'found', input: 10, result: 50 });++ const root = solveGoalSeek({+ goal: 2,+ guess: 1,+ evaluate: (input) => input * input,+ });+ expect(root?.status).toBe('found');+ expect(root?.result).toBeCloseTo(2, 6);++ const negative = solveGoalSeek({+ goal: 3,+ guess: 1,+ evaluate: (input) => input + 10,+ });+ expect(negative).toMatchObject({ status: 'found', input: -7, result: 3 });++ const already = solveGoalSeek({+ goal: 10,+ guess: 5,+ evaluate: (input) => input * 2,+ });+ expect(already).toMatchObject({+ status: 'found',+ input: 5,+ result: 10,+ evaluations: 1,+ });++ const unchanged = solveGoalSeek({+ goal: 10,+ guess: 4,+ evaluate: () => 2,+ });+ expect(unchanged?.status).toBe('unchanged');++ const closest = solveGoalSeek({+ goal: 100,+ guess: 0,+ evaluate: (input) => Math.min(40, input),+ });+ expect(closest?.status).toBe('approximate');+ expect(closest?.result).toBe(40);+});diff --git a/packages/spreadsheet/src/goal-seek.ts b/packages/spreadsheet/src/goal-seek.tsnew file mode 100644index 0000000000..fd15201cac--- /dev/null+++ b/packages/spreadsheet/src/goal-seek.ts@@ -0,0 +1,233 @@+import { parseCellAddress } from './spreadsheet-document';++/** A formula cell and the numeric cell Goal Seek is allowed to change. */+export type GoalSeekRequest = {+ setSheetId: string;+ setAddress: string;+ goal: number;+ changeSheetId: string;+ changeAddress: string;+};++export type GoalSeekSolution = {+ status: 'found' | 'approximate';+ /** Literal written into the changing cell. */+ input: string;+ /** The number that literal stores. */+ value: number;+ /** Formula result at that input. */+ result: number;+ evaluations: number;+ setSheetId: string;+ setAddress: string;+ changeSheetId: string;+ changeAddress: string;+};++export type GoalSeekResult =+ | GoalSeekSolution+ | { status: 'invalid'; message: string };++export type GoalSeekSolveStatus = 'found' | 'approximate' | 'unchanged';++export type GoalSeekSolveOutcome = {+ status: GoalSeekSolveStatus;+ input: number;+ result: number;+ evaluations: number;+};++const GOAL_SEEK_REFERENCE =+ /^(?:(?:'((?:[^']|'')+)'|([^'!:\s()]+))!)?\$?([A-Z]{1,3})\$?([1-9]\d{0,6})$/i;++/** `B12`, `$B$12`, `Inputs!B12`, or `'Q1 sheet'!B12`. */+export function parseGoalSeekReference(+ text: string+): { sheet?: string; address: string } | undefined {+ const match = GOAL_SEEK_REFERENCE.exec(text.trim());+ if (!match) return;+ const [, quoted, bare, column, row] = match;+ const address = `${column}${row}`.toUpperCase();+ if (!parseCellAddress(address)) return;+ return { sheet: quoted?.replace(/''/g, "'") ?? bare, address };+}++/** A goal typed as `10`, `1,250.5`, `$10`, or `12%`. */+export function parseGoalValue(text: string): number | undefined {+ const trimmed = text.trim();+ if (!trimmed) return;+ const percent = trimmed.endsWith('%');+ const body = (percent ? trimmed.slice(0, -1) : trimmed)+ .replace(/[$,\s]/g, '')+ .replace(/^\+/, '');+ if (!/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(body)) return;+ const value = Number(body);+ if (!Number.isFinite(value)) return;+ return percent ? value / 100 : value;+}++/** Fifteen significant digits, matching the precision Excel stores. */+export function goalSeekInput(value: number): string {+ if (!Number.isFinite(value)) return '0';+ const precise = Number(value.toPrecision(15));+ if (precise === 0) return '0';+ return String(precise);+}++function reached(result: number, goal: number) {+ const scale = Math.max(1, Math.abs(goal), Math.abs(result));+ return Math.abs(result - goal) <= 1e-7 * scale;+}++/**+ * Find an input that makes `evaluate` return `goal`. Newton steps handle+ * smooth formulas; a sign change switches to bisection. At most 100+ * evaluations, which is Excel's Goal Seek iteration limit.+ */+export function solveGoalSeek(options: {+ goal: number;+ guess: number;+ evaluate: (input: number) => number | undefined;+ maxEvaluations?: number;+}): GoalSeekSolveOutcome | undefined {+ const max = options.maxEvaluations ?? 100;+ const goal = options.goal;+ let evaluations = 0;+ let best: { input: number; result: number; distance: number } | undefined;+ let first: number | undefined;+ let varied = false;++ const sample = (input: number): number | undefined => {+ if (evaluations >= max || !Number.isFinite(input)) return;+ evaluations++;+ const result = options.evaluate(input);+ if (result === undefined || !Number.isFinite(result)) return;+ if (first === undefined) first = result;+ else if (Math.abs(result - first) > 1e-9 * Math.max(1, Math.abs(first)))+ varied = true;+ const distance = Math.abs(result - goal);+ if (!best || distance < best.distance) best = { input, result, distance };+ return result;+ };++ const found = (input: number, result: number): GoalSeekSolveOutcome => {+ // A Newton step can stop a few ulps away from a round input such as 10.+ // Keep a shorter decimal when it still reaches the goal.+ let bestInput = input;+ let bestResult = result;+ const candidates = [Math.round(input)];+ for (const digits of [12, 10, 8, 6, 4, 2]) {+ const rounded = Number(input.toPrecision(digits));+ if (Number.isFinite(rounded)) candidates.push(rounded);+ }+ for (const candidate of candidates) {+ if (!Number.isFinite(candidate) || candidate === bestInput) continue;+ const checked = sample(candidate);+ if (checked === undefined || !reached(checked, goal)) continue;+ if (goalSeekInput(candidate).length < goalSeekInput(bestInput).length) {+ bestInput = candidate;+ bestResult = checked;+ }+ }+ return {+ status: 'found',+ input: bestInput,+ result: bestResult,+ evaluations,+ };+ };++ const finish = (): GoalSeekSolveOutcome | undefined => {+ if (!best) return;+ if (reached(best.result, goal))+ return {+ status: 'found',+ input: best.input,+ result: best.result,+ evaluations,+ };+ return {+ status: varied ? 'approximate' : 'unchanged',+ input: best.input,+ result: best.result,+ evaluations,+ };+ };++ const bisect = (+ leftInput: number,+ leftResult: number,+ rightInput: number,+ rightResult: number+ ) => {+ let left = { input: leftInput, result: leftResult };+ let right = { input: rightInput, result: rightResult };+ while (evaluations < max) {+ const mid = (left.input + right.input) / 2;+ if (mid === left.input || mid === right.input) break;+ const result = sample(mid);+ if (result === undefined) break;+ if (reached(result, goal)) return found(mid, result);+ if ((left.result - goal) * (result - goal) <= 0)+ right = { input: mid, result };+ else left = { input: mid, result };+ }+ return finish();+ };++ const guess = Number.isFinite(options.guess) ? options.guess : 0;+ let current = guess;+ let currentResult = sample(current);+ if (currentResult === undefined) return finish();+ if (reached(currentResult, goal)) return found(current, currentResult);++ // Newton, damped so a steep slope cannot jump to a non-finite input.+ // A sign change between samples is handed to bisection.+ for (let step = 0; step < 24 && evaluations < max - 1; step++) {+ const probe = current + Math.max(Math.abs(current) * 1e-4, 1e-4);+ const probed = sample(probe);+ if (probed === undefined) break;+ if (reached(probed, goal)) return found(probe, probed);+ if ((currentResult - goal) * (probed - goal) < 0)+ return bisect(current, currentResult, probe, probed);+ const slope = (probed - currentResult) / (probe - current);+ if (!Number.isFinite(slope) || slope === 0) break;+ let delta = (currentResult - goal) / slope;+ const limit = Math.max(1, Math.abs(current)) * 10;+ if (Math.abs(delta) > limit) delta = Math.sign(delta) * limit;+ const next = current - delta;+ if (!Number.isFinite(next) || next === current) break;+ const nextResult = sample(next);+ if (nextResult === undefined) break;+ if (reached(nextResult, goal)) return found(next, nextResult);+ if ((currentResult - goal) * (nextResult - goal) < 0)+ return bisect(current, currentResult, next, nextResult);+ if (+ step > 4 &&+ Math.abs(nextResult - goal) >= Math.abs(currentResult - goal)+ )+ break;+ current = next;+ currentResult = nextResult;+ }++ // Expand geometrically around the original guess until the goal is bracketed.+ let anchor = { input: guess, result: currentResult };+ if (best && Math.abs(best.result - goal) < Math.abs(anchor.result - goal))+ anchor = { input: best.input, result: best.result };+ let expansion = Math.max(Math.abs(guess) * 0.5, 0.5);+ for (let step = 0; step < 20 && evaluations < max; step++) {+ expansion *= 2;+ for (const direction of [-1, 1]) {+ const input = guess + direction * expansion;+ const result = sample(input);+ if (result === undefined) continue;+ if (reached(result, goal)) return found(input, result);+ if ((anchor.result - goal) * (result - goal) < 0)+ return bisect(anchor.input, anchor.result, input, result);+ if (Math.abs(result - goal) < Math.abs(anchor.result - goal))+ anchor = { input, result };+ }+ }+ return finish();+}