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(sheets): color-code referenced cells while editing a formula (#7683)
teod54443f7e2b6
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.browser.e2e.tsindex 6a17d7f5ae..6ad7b8cf36 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.browser.e2e.ts+++ b/apps/web/src/features/block-spreadsheet/browser-test/spreadsheet.browser.e2e.ts@@ -52,6 +52,47 @@ test('completes formulas and inserts a pointer-selected range without losing theawait expect(page.locator('[data-address="C2"]')).toHaveText('30');});+test('color-codes the referenced ranges and their formula text while editing', async ({+ page,+}) => {+ await page.locator('[data-address="C2"]').dblclick();+ const input = page.getByRole('textbox', { name: 'Edit C2' });+ await input.fill('=B2+SUM(B2:B3)*$b$2');+ const highlights = page.locator('[data-formula-highlight]');+ await expect(highlights).toHaveCount(3);+ const colors = await highlights.evaluateAll((elements) =>+ elements.map((element) => getComputedStyle(element).borderTopColor)+ );+ expect(colors[0]).toBe(colors[2]);+ expect(colors[1]).not.toBe(colors[0]);+ const cell = await page.locator('[data-address="B2"]').boundingBox();+ const box = await highlights.first().boundingBox();+ expect(Math.abs((box?.x ?? 0) - (cell?.x ?? 0))).toBeLessThan(2);+ expect(Math.abs((box?.y ?? 0) - (cell?.y ?? 0))).toBeLessThan(2);++ const formulaBar = page.getByRole('textbox', { name: 'Formula bar' });+ for (const editor of [input, formulaBar]) {+ const mirror = editor.locator(+ 'xpath=following-sibling::*[@data-formula-mirror]'+ );+ await expect(mirror).toHaveText('=B2+SUM(B2:B3)*$b$2');+ const coloredText = await mirror+ .locator('span span')+ .evaluateAll((spans) =>+ spans+ .filter((span) => (span as HTMLElement).style.color)+ .map((span) => [span.textContent, getComputedStyle(span).color])+ );+ expect(coloredText.map(([text]) => text)).toEqual(['B2', 'B2:B3', '$b$2']);+ expect(coloredText.map(([, color]) => color)).toEqual(colors);+ expect(await mirror.boundingBox()).toEqual(await editor.boundingBox());+ }++ await input.press('Enter');+ await expect(highlights).toHaveCount(0);+ await expect(page.locator('[data-formula-mirror]')).toHaveCount(0);+});+test('keeps function insertion, find, and paste menu focus usable from the ribbon', async ({page,}) => {diff --git a/apps/web/src/features/block-spreadsheet/components/FormulaInput.test.tsx b/apps/web/src/features/block-spreadsheet/components/FormulaInput.test.tsxindex 9b285ecdff..af0d7e36ac 100644--- a/apps/web/src/features/block-spreadsheet/components/FormulaInput.test.tsx+++ b/apps/web/src/features/block-spreadsheet/components/FormulaInput.test.tsx@@ -131,3 +131,31 @@ it('commits on blur after starting a formula without a mention adapter', () => {input.blur();expect(blur).toHaveBeenCalledOnce();});++it('colors reference text while the textarea keeps the caret', () => {+ const view = render(() => (+ <FormulaInput+ label="Formula"+ value="=A1+B2"+ class=""+ references={[+ { start: 1, end: 3, color: 'var(--color-blue)' },+ { start: 4, end: 6, color: 'var(--color-red)' },+ ]}+ onInput={vi.fn()}+ onKeyDown={vi.fn()}+ onBlur={vi.fn()}+ />+ ));+ const input = view.getByRole('textbox', { name: 'Formula' });+ expect(input.style.color).toBe('transparent');+ const mirror = view.container.querySelector('[data-formula-mirror]')!;+ expect(mirror.textContent).toBe('=A1+B2');+ const colored = [...mirror.querySelectorAll<HTMLSpanElement>('span span')]+ .filter((span) => span.style.color)+ .map((span) => [span.textContent, span.style.color]);+ expect(colored).toEqual([+ ['A1', 'var(--color-blue)'],+ ['B2', 'var(--color-red)'],+ ]);+});diff --git a/apps/web/src/features/block-spreadsheet/components/FormulaInput.tsx b/apps/web/src/features/block-spreadsheet/components/FormulaInput.tsxindex 6638093ac0..35cd095eb7 100644--- a/apps/web/src/features/block-spreadsheet/components/FormulaInput.tsx+++ b/apps/web/src/features/block-spreadsheet/components/FormulaInput.tsx@@ -24,7 +24,10 @@ import {formulaFunctions,functionSummary,} from '../core/formula-completion';-import type { FormulaTextSelection } from '../core/formula-reference';+import type {+ FormulaReferenceSpan,+ FormulaTextSelection,+} from '../core/formula-reference';import {type CompleteFormula,createFormulaAssistance,@@ -42,6 +45,8 @@ export type FormulaInputProps = {placeholder?: string;complete?: CompleteFormula;selectionRequest?: FormulaTextSelection;+ /** Spans of `value` to draw in their reference's color. */+ references?: FormulaReferenceSpan[];pickingReference?: boolean;onSelectionChange?: (start: number, end: number) => void;onFocus?: () => void;@@ -176,6 +181,11 @@ function FormulaTextarea(props: FormulaInputProps) {maxLength={10_000}placeholder={props.placeholder}class={`${props.class} touch:text-[max(16px,1rem)]`}+ style={+ props.references?.length+ ? { color: 'transparent', 'caret-color': 'var(--color-ink)' }+ : undefined+ }value={props.value}onFocus={() => {props.onFocus?.();@@ -209,6 +219,15 @@ function FormulaTextarea(props: FormulaInputProps) {props.onBlur();}}/>+ <Show when={props.references?.length ? props.references : undefined}>+ {(references) => (+ <ReferenceMirror+ input={input}+ value={props.value}+ references={references()}+ />+ )}+ </Show><Show when={popupVisible()}><Portal><FormulaPopup@@ -306,6 +325,93 @@ function FormulaTextarea(props: FormulaInputProps) {);}+/**+ * Draws the textarea's text over it, with references in their colors. A+ * textarea cannot style part of its text, so it keeps the caret and selection+ * while its own text is transparent.+ */+function ReferenceMirror(props: {+ input: HTMLTextAreaElement;+ value: string;+ references: FormulaReferenceSpan[];+}) {+ let mirror!: HTMLDivElement;+ let text!: HTMLSpanElement;+ const segments = () => {+ const parts: { text: string; color?: string }[] = [];+ let at = 0;+ for (const reference of props.references) {+ if (reference.start < at || reference.end > props.value.length) continue;+ parts.push({ text: props.value.slice(at, reference.start) });+ parts.push({+ text: props.value.slice(reference.start, reference.end),+ color: reference.color,+ });+ at = reference.end;+ }+ parts.push({ text: props.value.slice(at) });+ return parts;+ };+ const sync = () => {+ const { input } = props;+ const style = getComputedStyle(input);+ Object.assign(mirror.style, {+ left: `${input.offsetLeft}px`,+ top: `${input.offsetTop}px`,+ width: `${input.offsetWidth}px`,+ height: `${input.offsetHeight}px`,+ fontFamily: style.fontFamily,+ fontSize: style.fontSize,+ fontWeight: style.fontWeight,+ fontStyle: style.fontStyle,+ letterSpacing: style.letterSpacing,+ lineHeight: style.lineHeight,+ textAlign: style.textAlign,+ paddingTop: style.paddingTop,+ paddingRight: style.paddingRight,+ paddingBottom: style.paddingBottom,+ paddingLeft: style.paddingLeft,+ borderTopWidth: style.borderTopWidth,+ borderRightWidth: style.borderRightWidth,+ borderBottomWidth: style.borderBottomWidth,+ borderLeftWidth: style.borderLeftWidth,+ });+ text.style.transform = `translate(${-input.scrollLeft}px, ${-input.scrollTop}px)`;+ };+ onMount(() => {+ sync();+ props.input.addEventListener('scroll', sync);+ const observer =+ typeof ResizeObserver === 'undefined'+ ? undefined+ : new ResizeObserver(sync);+ observer?.observe(props.input);+ onCleanup(() => {+ props.input.removeEventListener('scroll', sync);+ observer?.disconnect();+ });+ });+ createEffect(on(() => props.value, sync, { defer: true }));+ return (+ <div+ ref={mirror}+ aria-hidden="true"+ data-formula-mirror+ class="pointer-events-none absolute box-border overflow-hidden whitespace-pre border-solid border-transparent text-ink"+ >+ <span ref={text} class="block">+ <For each={segments()}>+ {(segment) => (+ <span style={segment.color ? { color: segment.color } : undefined}>+ {segment.text}+ </span>+ )}+ </For>+ </span>+ </div>+ );+}+function FormulaPopup(props: {anchor: HTMLElement;interactive: boolean;diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsxindex 2387f7f79c..5ac1c1b5b9 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx@@ -27,7 +27,11 @@ import type { SpreadsheetCommentsCapability } from '../context/spreadsheet-commeimport type { SpreadsheetMentions } from '../context/spreadsheet-mentions';import { SPREADSHEET_CLIPBOARD_TYPE } from '../core/cell-copy';import type { ChartData } from '../core/chart-data';-import type { FormulaTextSelection } from '../core/formula-reference';+import type {+ FormulaReferenceSpan,+ FormulaTextSelection,+ ReferenceHighlight,+} from '../core/formula-reference';import {type CellPosition,type CellSelection,@@ -213,6 +217,10 @@ export function SpreadsheetGrid(props: {formulaEditing?: boolean;editorSelection?: FormulaTextSelection;referenceSelection?: CellSelection;+ /** The colored ranges of the references in the formula being edited. */+ referenceHighlights?: ReferenceHighlight[];+ /** Colored spans of the formula draft's reference text. */+ draftReferences?: FormulaReferenceSpan[];pickingReference?: boolean;onTextSelection?: (start: number, end: number) => void;onReferenceStart?: (position: CellPosition) => boolean;@@ -1772,6 +1780,7 @@ export function SpreadsheetGrid(props: {complete={props.complete}readonly={props.readonly}selectionRequest={props.editorSelection}+ references={props.draftReferences}pickingReference={props.pickingReference ||(isTouchDevice() && !!props.referenceSelection)@@ -2001,6 +2010,20 @@ export function SpreadsheetGrid(props: {</Show></div></Show>+ <For each={props.referenceHighlights}>+ {(highlight) => (+ <div+ aria-hidden="true"+ data-formula-highlight+ class="pointer-events-none absolute z-[3] border-2"+ style={{+ ...rangeStyle(highlight.bounds),+ 'border-color': highlight.color,+ background: `color-mix(in srgb, ${highlight.color} 10%, transparent)`,+ }}+ />+ )}+ </For><Show when={props.referenceSelection}>{(range) => (<divdiff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.tsxindex d590d0b1c5..e1a94758da 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.tsx@@ -17,7 +17,10 @@ import X from '@phosphor/x.svg';import { Button, type ButtonProps } from '@ui/components/Button';import { Show } from 'solid-js';import type { SpreadsheetMentions } from '../context/spreadsheet-mentions';-import type { FormulaTextSelection } from '../core/formula-reference';+import type {+ FormulaReferenceSpan,+ FormulaTextSelection,+} from '../core/formula-reference';import type { SpreadsheetToolbarProps } from '../core/toolbar-types';import type { CompleteFormula } from '../primitives/create-formula-assistance';import { createTouchPress } from '../primitives/create-touch-press';@@ -301,6 +304,7 @@ export function FormulaBar(props: {editing?: boolean;complete: CompleteFormula;selectionRequest?: FormulaTextSelection;+ references?: FormulaReferenceSpan[];pickingReference?: boolean;onSelectionChange?: (start: number, end: number) => void;onNavigate: (address: string) => void;@@ -357,6 +361,7 @@ export function FormulaBar(props: {label="Formula bar"complete={props.complete}selectionRequest={props.selectionRequest}+ references={props.references}pickingReference={props.pickingReference}onSelectionChange={props.onSelectionChange}placeholder={diff --git a/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts b/apps/web/src/features/block-spreadsheet/core/formula-reference.test.tsindex 6481c5e7fe..bc29bb38aa 100644--- a/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts@@ -1,8 +1,11 @@import { describe, expect, it } from 'vitest';import {+ FORMULA_REFERENCE_COLORS,formulaRangeReference,formulaReferenceSlot,+ formulaReferences,} from './formula-reference';+import { SPREADSHEET_MAX_ROWS } from './spreadsheet-document';describe('formula reference slots', () => {it.each(['=', '=SUM(', '=A1+', '=IF(A1>0, ', '=SUM(B1:B4,'])(@@ -90,3 +93,61 @@ it('quotes cross-sheet ranges and replaces a complete sheet-qualified operand',formulaReferenceSlot('="Sheet2!A1"', { start: 8, end: 8 })).toBeUndefined();});++describe('formula references', () => {+ const spans = (text: string) =>+ formulaReferences(text).map((reference) =>+ text.slice(reference.start, reference.end)+ );++ it('finds cells, ranges, and whole rows or columns with their bounds', () => {+ const text = '=SUM($B4:c$8)+A1*COUNT(D:D)+SUM(2:3)';+ expect(spans(text)).toEqual(['$B4:c$8', 'A1', 'D:D', '2:3']);+ expect(formulaReferences(text).map((value) => value.bounds)).toEqual([+ { top: 3, bottom: 7, left: 1, right: 2 },+ { top: 0, bottom: 0, left: 0, right: 0 },+ { top: 0, bottom: SPREADSHEET_MAX_ROWS - 1, left: 3, right: 3 },+ expect.objectContaining({ top: 1, bottom: 2, left: 0 }),+ ]);+ });++ it('colors each distinct reference in order and reuses a repeated one', () => {+ const colors = formulaReferences('=A1+B2+$A$1+C3').map(+ (value) => value.color+ );+ expect(colors).toEqual([+ FORMULA_REFERENCE_COLORS[0],+ FORMULA_REFERENCE_COLORS[1],+ FORMULA_REFERENCE_COLORS[0],+ FORMULA_REFERENCE_COLORS[2],+ ]);+ });++ it('reads sheet names, quoted or not', () => {+ const references = formulaReferences(+ "='Owner''s budget'!A1:B4+Sheet2!C3+C3"+ );+ expect(references.map((value) => value.sheetName)).toEqual([+ "Owner's budget",+ 'Sheet2',+ undefined,+ ]);+ expect(references[1].color).not.toBe(references[2].color);+ });++ it.each([+ 'A1',+ '="A1"&B2',+ '=LOG10(2)',+ '=ATAN2(1,2)',+ "='My A1 sheet'!",+ '=A1A',+ '=XFE1',+ ])('ignores text that only looks like a reference: %s', (text) => {+ expect(spans(text).filter((span) => span !== 'B2')).toEqual([]);+ });++ it('keeps references outside strings that contain apostrophes', () => {+ expect(spans(`="it's"&A2`)).toEqual(['A2']);+ });+});diff --git a/apps/web/src/features/block-spreadsheet/core/formula-reference.ts b/apps/web/src/features/block-spreadsheet/core/formula-reference.tsindex a3e8ce3bbc..7ebc7645f4 100644--- a/apps/web/src/features/block-spreadsheet/core/formula-reference.ts+++ b/apps/web/src/features/block-spreadsheet/core/formula-reference.ts@@ -1,11 +1,133 @@import {type CellSelection,cellAddress,+ positionFromAddress,selectionBounds,} from './grid-selection';+import {+ SPREADSHEET_MAX_COLUMNS,+ SPREADSHEET_MAX_ROWS,+} from './spreadsheet-document';export type FormulaTextSelection = { start: number; end: number };+export const FORMULA_REFERENCE_COLORS = [+ 'var(--color-blue)',+ 'var(--color-red)',+ 'var(--color-purple)',+ 'var(--color-green)',+ 'var(--color-orange)',+ 'var(--color-pink)',+ 'var(--color-teal)',+];++type RangeBounds = { top: number; bottom: number; left: number; right: number };++export type FormulaReferenceSpan = {+ start: number;+ end: number;+ color: string;+};++export type ReferenceHighlight = { bounds: RangeBounds; color: string };++export type FormulaReference = FormulaReferenceSpan & {+ /** The sheet named by the reference; absent means the formula's own sheet. */+ sheetName?: string;+ bounds: RangeBounds;+};++const CELL = String.raw`\$?[A-Z]{1,3}\$?[1-9]\d*`;+const COLUMN = String.raw`\$?[A-Z]{1,3}`;+const ROW = String.raw`\$?[1-9]\d*`;+const REFERENCE = new RegExp(+ String.raw`(?:('(?:[^']|'')+'|[A-Z_][\w.]*)!)?(${CELL}(?::${CELL})?|${COLUMN}:${COLUMN}|${ROW}:${ROW})`,+ 'gi'+);++function referenceBounds(range: string) {+ const [first, last = first] = range.replaceAll('$', '').split(':');+ if (/^\d+$/.test(first)) {+ const top = positionFromAddress(`A${first}`)?.row;+ const bottom = positionFromAddress(`A${last}`)?.row;+ if (top === undefined || bottom === undefined) return;+ return {+ top: Math.min(top, bottom),+ bottom: Math.max(top, bottom),+ left: 0,+ right: SPREADSHEET_MAX_COLUMNS - 1,+ };+ }+ if (/^[A-Z]+$/i.test(first)) {+ const left = positionFromAddress(`${first}1`)?.column;+ const right = positionFromAddress(`${last}1`)?.column;+ if (left === undefined || right === undefined) return;+ return {+ top: 0,+ bottom: SPREADSHEET_MAX_ROWS - 1,+ left: Math.min(left, right),+ right: Math.max(left, right),+ };+ }+ const anchor = positionFromAddress(first);+ const focus = positionFromAddress(last);+ return anchor && focus ? selectionBounds({ anchor, focus }) : undefined;+}++/** String literals and quoted sheet names, from opening to closing quote. */+function quotedRanges(text: string) {+ const quoted: { from: number; to: number }[] = [];+ let quote: { char: string; from: number } | undefined;+ for (let index = 1; index < text.length; index++) {+ const char = text[index];+ if (quote?.char === char) {+ if (text[index + 1] === char) index++;+ else {+ quoted.push({ from: quote.from, to: index });+ quote = undefined;+ }+ } else if (!quote && (char === '"' || char === "'"))+ quote = { char, from: index };+ }+ if (quote) quoted.push({ from: quote.from, to: text.length });+ return quoted;+}++/**+ * The cell and range references in a formula, each colored like Excel: the+ * same reference written twice shares a color.+ */+export function formulaReferences(text: string): FormulaReference[] {+ if (!text.startsWith('=')) return [];+ const quoted = quotedRanges(text);+ const colors = new Map<string, string>();+ const references: FormulaReference[] = [];+ for (const match of text.matchAll(REFERENCE)) {+ const from = match.index;+ const to = from + match[0].length;+ if (quoted.some((range) => from > range.from && from <= range.to)) continue;+ if (+ /[\w.$!:]/.test(text[from - 1] ?? '') ||+ /[\w.!(:$]/.test(text[to] ?? '')+ )+ continue;+ const bounds = referenceBounds(match[2]);+ if (!bounds) continue;+ const sheetName = match[1]?.startsWith("'")+ ? match[1].slice(1, -1).replaceAll("''", "'")+ : match[1];+ const key = `${sheetName?.toUpperCase() ?? ''}!${match[2].replaceAll('$', '').toUpperCase()}`;+ let color = colors.get(key);+ if (!color) {+ color =+ FORMULA_REFERENCE_COLORS[colors.size % FORMULA_REFERENCE_COLORS.length];+ colors.set(key, color);+ }+ references.push({ start: from, end: to, sheetName, bounds, color });+ }+ return references;+}+/** Find an operand slot without treating strings or function names as references. */export function formulaReferenceSlot(text: string,diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.tsindex a97d5e7022..a44edb47a6 100644--- a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts+++ b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts@@ -778,3 +778,48 @@ it('moves from the active cell after whole-row or whole-column selections, not tkey('ArrowRight');expect(grid.activeAddress()).toBe('B5');});++it('highlights the draft references that fall on the sheet being shown', () => {+ const view = createRoot((dispose) => {+ cleanups.push(dispose);+ const [sheetId, setSheetId] = createSignal('sheet1');+ const grid = createGridController({+ cells: () => ({}),+ sheetId,+ sheets: () => [+ { id: 'sheet1', name: 'Sheet1' },+ { id: 'sheet2', name: "Owner's budget" },+ ],+ setActiveSheet: setSheetId,+ setSheetCells: vi.fn(),+ canEdit: () => true,+ rowCount: () => 20,+ columnCount: () => 5,+ setCells: vi.fn(),+ undo: vi.fn(),+ redo: vi.fn(),+ });+ return { grid, setSheetId };+ });+ const { grid } = view;+ expect(grid.referenceHighlights()).toEqual([]);++ grid.beginEdit('cell', "=SUM(A1:B2)+'Owner''s budget'!C3+D:D+$a$1:b2");+ const [first, other, column, repeat] = grid.draftReferences();+ expect(repeat.color).toBe(first.color);+ expect(other.color).not.toBe(first.color);+ expect(grid.referenceHighlights()).toEqual([+ { color: first.color, bounds: { top: 0, bottom: 1, left: 0, right: 1 } },+ { color: column.color, bounds: { top: 0, bottom: 19, left: 3, right: 3 } },+ { color: first.color, bounds: { top: 0, bottom: 1, left: 0, right: 1 } },+ ]);++ grid.switchSheet('sheet2');+ expect(grid.referenceHighlights()).toEqual([+ { color: other.color, bounds: { top: 2, bottom: 2, left: 2, right: 2 } },+ ]);++ grid.cancel();+ expect(grid.draftReferences()).toEqual([]);+ expect(grid.referenceHighlights()).toEqual([]);+});diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.tsindex 648ef57b7b..7643eaa0e5 100644--- a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts+++ b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts@@ -2,6 +2,7 @@ import {type Accessor,batch,createEffect,+ createMemo,createSignal,on,onCleanup,@@ -18,6 +19,7 @@ import {type FormulaTextSelection,formulaRangeReference,formulaReferenceSlot,+ formulaReferences,} from '../core/formula-reference';import {type CellPosition,@@ -146,6 +148,37 @@ export function createGridController(source: GridSource) {const editingAddress = () => editTarget?.address ?? activeAddress();const canPickReference = () =>!!editing() && !!formulaReferenceSlot(draft(), textSelection);+ const draftReferences = createMemo(() =>+ editing() ? formulaReferences(draft()) : []+ );+ /** The draft's references that fall on the sheet being shown. */+ const referenceHighlights = createMemo(() => {+ const sheets = source.sheets?.() ?? [];+ const shown = source.sheetId?.();+ const shownName = sheets+ .find((sheet) => sheet.id === shown)+ ?.name.toUpperCase();+ const ownSheet = editTarget?.sheetId ?? shown;+ return draftReferences().flatMap((reference) => {+ const onShownSheet = reference.sheetName+ ? reference.sheetName.toUpperCase() === shownName+ : ownSheet === shown;+ const { top, left } = reference.bounds;+ if (!onShownSheet || top >= rowCount() || left >= columnCount())+ return [];+ return [+ {+ color: reference.color,+ bounds: {+ top,+ left,+ bottom: Math.min(reference.bounds.bottom, rowCount() - 1),+ right: Math.min(reference.bounds.right, columnCount() - 1),+ },+ },+ ];+ });+ });// Remote deletion and local tab changes invalidate drafts and async fills.// An explicit reference-picking tab switch keeps the origin draft. Remote@@ -706,6 +739,8 @@ export function createGridController(source: GridSource) {? referenceSelection(): undefined,pickingReference,+ draftReferences,+ referenceHighlights,beginReference,updateReference,endReference,diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsxindex dde08d0ffe..0f5781eb25 100644--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx@@ -746,6 +746,7 @@ export function SpreadsheetEditor(props: {editing={!!grid.editing()}complete={calculation.complete}selectionRequest={grid.editorSelection()}+ references={grid.draftReferences()}pickingReference={grid.pickingReference() ||(isTouchDevice() && !!grid.referenceSelection())@@ -867,6 +868,8 @@ export function SpreadsheetEditor(props: {}editorSelection={grid.editorSelection()}referenceSelection={grid.referenceSelection()}+ referenceHighlights={grid.referenceHighlights()}+ draftReferences={grid.draftReferences()}pickingReference={grid.pickingReference()}onTextSelection={grid.setTextSelection}onReferenceStart={grid.beginReference}diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 3b2fbff535..2f6d66730c 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -176,6 +176,11 @@ click its tab while the formula is awaiting a reference, then click or drag thesource cells. The draft stays in the formula bar; Enter commits it to the originalsheet and cell. Names with spaces are quoted automatically. Escape cancels andreturns to the original sheet.+While a formula is being edited, each cell or range it refers to, including whole+columns or rows such as `D:D`, is outlined in its own color on the grid, and the+reference text in both editors uses the same color. A repeated reference keeps+its color. Only references to the sheet being shown are outlined; the colors+disappear when the edit is committed or cancelled.On touch screens, tap a cell while editing a formula, then drag **Move referencestart** or **Move reference end** to extend its reference. Tapping a suggestion oradjusting a reference should keep the input focused and the software keyboard open.