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
chore(sheets): add date support to spreadsheets (#7078)
Wolf Mermelstein379ab4747363
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.mdindex de20b30218..a91a6851a0 100644--- a/apps/web/src/features/block-spreadsheet/README.md+++ b/apps/web/src/features/block-spreadsheet/README.md@@ -252,6 +252,10 @@ and compare formula, error, and formatting behavior before updating the pin.All cell styles persist, sync independently, copy/fill, and undo. Number formatsinclude general, number, USD currency, percent, scientific, date, time, and plaintext, with adjustable decimal places. Date/time displays are deterministic UTC.+ Cells without an explicit format honor the date/time formats IronCalc infers for+ typed dates, `DATE()`-style results and arithmetic on date cells (formula results+ only from the year 2000 on, so day counts stay numbers). A cell holding one+ `<m-date-mention>` pill calculates as that local calendar date.Plain text treats formula-looking input literally. Wrapped rows grow to 160px at100% zoom; larger content remains available in the formula bar/editor.- Internal copying preserves formatting and translates relative/mixed referencesdiff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsxindex 1d62a66017..077a6663fc 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx@@ -1237,7 +1237,7 @@ export function SpreadsheetGrid(props: {cell()?.value.startsWith('=') &&cell()?.format !== 'text') &&- /<m-(?:user|document)-mention>|https?:\/\/|www\.|[^\s@]+@[^\s@]+\.[^\s@]+/i.test(+ /<m-(?:user|document|date)-mention>|https?:\/\/|www\.|[^\s@]+@[^\s@]+\.[^\s@]+/i.test(cell()?.value ?? '');return (diff --git a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts b/apps/web/src/features/block-spreadsheet/core/calculation.test.tsindex a714856786..3ad5465287 100644--- a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/calculation.test.ts@@ -195,6 +195,42 @@ describe('spreadsheet calculation with IronCalc', () => {expect(result.A8.display).toBe('0.00');});+ it('shows typed dates and date arithmetic as dates without an explicit format', () => {+ const result = calculator.calculate({+ A1: { value: '9/28/2026' },+ A2: { value: '2026-09-28' },+ A3: { value: '=A1+7' },+ A4: { value: '=DATE(2026,1,1)' },+ A5: { value: '=A3-A1' },+ A6: { value: '=A1+7', format: 'number' },+ A7: { value: '5/1/1985' },+ A8: { value: '=DATE(1985,5,1)' },+ A9: { value: '=A1+1' },+ A10: { value: '=A9+1' },+ A11: { value: '46293' },+ A12: { value: 'Sep 28, 2026' },+ A13: { value: '=YEAR(A1)' },+ A14: { value: '=A1+7', numberFormat: '0.0' },+ });+ expect(result.A1).toEqual({ display: '9/28/2026', number: 46293 });+ expect(result.A2).toEqual({ display: '9/28/2026', number: 46293 });+ expect(result.A3).toEqual({ display: '10/5/2026', number: 46300 });+ expect(result.A4).toEqual({ display: '1/1/2026', number: 46023 });+ // The engine formats a difference of dates as a date; a day count is not.+ expect(result.A5).toEqual({ display: '7', number: 7 });+ expect(result.A6.display).toBe('46,300.00');+ expect(result.A7).toEqual({ display: '5/1/1985', number: 31168 });+ // Formula results before 2000 stay serial numbers; day counts are common there.+ expect(result.A8).toEqual({ display: '31168', number: 31168 });+ // Chained formulas are entered in grid order, so each inherits the format.+ expect(result.A9).toEqual({ display: '9/29/2026', number: 46294 });+ expect(result.A10).toEqual({ display: '9/30/2026', number: 46295 });+ expect(result.A11).toEqual({ display: '46293', number: 46293 });+ expect(result.A12).toEqual({ display: 'Sep 28, 2026' });+ expect(result.A13).toEqual({ display: '2026', number: 2026 });+ expect(result.A14.display).toBe('46300.0');+ });+it('keeps text-formatted values literal during calculation and copying', () => {const result = calculator.calculate({A1: { value: '=SUM(B1:B2)', format: 'text' },diff --git a/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts b/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.tsindex a5b16c0c6c..36c0bc4227 100644--- a/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts@@ -3,6 +3,7 @@ import { createRequire } from 'node:module';import { initSync } from '@ironcalc/wasm';import { createInitializedSpreadsheetCalculator } from '@macro-inc/spreadsheet/calculation';import {+ cellDateMention,cellMentionQuery,cellPlainText,cellTextParts,@@ -97,4 +98,72 @@ describe('spreadsheet mention source', () => {engine.dispose();}});+ it('reads the docs date mention encoding and rejects unparseable dates', () => {+ const due = encodeCellMention({+ type: 'date',+ date: '2026-09-28T04:00:00.000Z',+ displayFormat: 'Tomorrow',+ });+ expect(cellTextParts(due)[0].mention).toEqual({+ type: 'date',+ date: '2026-09-28T04:00:00.000Z',+ displayFormat: 'Tomorrow',+ });+ expect(cellPlainText(`Due ${due}!`)).toBe('Due Tomorrow!');+ expect(+ cellPlainText(+ '<m-date-mention>{"date":"2026-09-28T04:00:00.000Z","displayFormat":"","mentionUuid":"m1"}</m-date-mention>'+ )+ ).toBe('Sep 28, 2026');+ for (const text of [+ '<m-date-mention>{"date":"someday","displayFormat":"Someday"}</m-date-mention>',+ '<m-date-mention>{"displayFormat":"Tomorrow"}</m-date-mention>',+ ])+ expect(cellPlainText(text)).toBe(text);+ expect(cellMentionQuery(`${due} @tom`, due.length + 5)?.query).toBe('tom');+ });+ it('identifies cells holding a single date pill', () => {+ const due = encodeCellMention({+ type: 'date',+ date: '2026-09-28T04:00:00.000Z',+ displayFormat: 'Tomorrow',+ });+ expect(cellDateMention(due)?.date).toBe('2026-09-28T04:00:00.000Z');+ expect(cellDateMention(` ${due} \n`)?.displayFormat).toBe('Tomorrow');+ expect(cellDateMention(`Due ${due}`)).toBeUndefined();+ expect(cellDateMention(`${due}${due}`)).toBeUndefined();+ expect(cellDateMention(`${person} ${due}`)).toBeUndefined();+ expect(cellDateMention('9/28/2026')).toBeUndefined();+ });+ it('calculates a lone date pill as that calendar date in the local time zone', () => {+ const engine = createInitializedSpreadsheetCalculator();+ try {+ const local = new Date(2026, 8, 28, 9, 30);+ const due = encodeCellMention({+ type: 'date',+ date: local.toISOString(),+ displayFormat: 'Tomorrow',+ });+ const values = engine.calculate({+ A1: { value: `${due} ` },+ A2: { value: '=A1+7' },+ A3: { value: `Due ${due}` },+ A4: { value: '=A3' },+ A5: { value: due, format: 'number' },+ A6: { value: due, format: 'text' },+ A7: { value: '=A1-DATE(2026,9,20)' },+ });+ // The pill's time of day is dropped so date arithmetic stays whole days.+ expect(values.A1).toEqual({ display: '9/28/2026', number: 46293 });+ expect(values.A2).toEqual({ display: '10/5/2026', number: 46300 });+ expect(values.A3).toEqual({ display: 'Due Tomorrow' });+ expect(values.A4).toEqual({ display: 'Due Tomorrow' });+ expect(values.A5).toEqual({ display: '46,293.00', number: 46293 });+ expect(values.A6).toEqual({ display: 'Tomorrow' });+ // A day count is not a date, even though the engine formats it as one.+ expect(values.A7).toEqual({ display: '8', number: 8 });+ } finally {+ engine.dispose();+ }+ });});diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.tsindex fd555079a3..c632d1f5a5 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.test.ts@@ -70,6 +70,32 @@ describe('Excel workbook files', () => {ExcelJS.ValueType.String);});+ it('exports a lone date pill as a dated number instead of its label', async () => {+ const sheet = simpleSheet();+ const due = encodeCellMention({+ type: 'date',+ date: new Date(2026, 8, 28).toISOString(),+ displayFormat: 'Tomorrow',+ });+ sheet.cells = {+ A1: { value: `${due} ` },+ A2: { value: `Due ${due}` },+ A3: { value: due, format: 'number' },+ };+ sheet.values = calculator.calculate(sheet.cells);+ const result = await encodeXlsx({ sheets: [sheet] });+ expect(result.warnings.join(' ')).toContain('mention');+ const workbook = new ExcelJS.Workbook();+ await workbook.xlsx.load(result.bytes.slice().buffer);+ const exported = workbook.worksheets[0];+ expect(exported.getCell('A1').value).toEqual(+ new Date(Date.UTC(2026, 8, 28))+ );+ expect(exported.getCell('A1').numFmt).toBe('m/d/yyyy');+ expect(exported.getCell('A2').value).toBe('Due Tomorrow');+ expect(exported.getCell('A3').value).toBe(46293);+ expect(exported.getCell('A3').numFmt).toBe('#,##0.00');+ });it('round trips real XLSX with multiple sheets, formula caches, values, styles and widths', async () => {const sheets: WorkbookFileSheet[] = [{diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.tsindex deecb505bc..0c96e06490 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-codec.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-codec.ts@@ -1,4 +1,7 @@-import { cellPlainText } from '@macro-inc/spreadsheet/cell-mentions';+import {+ cellDateMention,+ cellPlainText,+} from '@macro-inc/spreadsheet/cell-mentions';import {parseWorkbookMetadata,type WorkbookSheetMetadata,@@ -511,10 +514,23 @@ export async function decodeXlsx(bytes: Uint8Array): Promise<WorkbookFileData> {warnings: [...warnings],};}+/** A cell holding one date pill exports as the calculated date serial. */+function exportedDateMention(+ cell: SpreadsheetCell,+ calculated?: CalculatedCell+) {+ return cell.format !== 'text' &&+ calculated?.number !== undefined &&+ cellDateMention(cell.value)+ ? calculated.number+ : undefined;+}function exportValue(cell: SpreadsheetCell,calculated?: CalculatedCell): CellValue {+ const dateSerial = exportedDateMention(cell, calculated);+ if (dateSerial !== undefined) return dateSerial;if (cellPlainText(cell.value) !== cell.value)return cellPlainText(cell.value);if (cell.format === 'text') return cell.value;@@ -647,12 +663,18 @@ export async function encodeXlsx(`Cell ${source.name}!${address} exceeds 10,000 characters.`);const target = sheet.getCell(address);- target.value = exportValue(cell, source.values?.[address]);- if (cellPlainText(cell.value) !== cell.value)+ const calculated = source.values?.[address];+ target.value = exportValue(cell, calculated);+ const exportsDate = exportedDateMention(cell, calculated) !== undefined;+ if (!exportsDate && cellPlainText(cell.value) !== cell.value)warnings.add('Macro mentions are exported as their display text; interactive pills remain in Macro.');- target.style = writeXlsxStyle(cell);+ target.style = writeXlsxStyle(+ exportsDate && (!cell.format || cell.format === 'general')+ ? { ...cell, format: 'date' }+ : cell+ );}for (const [column, pixels] of Object.entries(source.columnWidths)) {const index = Number(column);diff --git a/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.test.ts b/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.test.tsindex 6c08db16a4..68a1163d23 100644--- a/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.test.ts+++ b/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.test.ts@@ -32,3 +32,20 @@ it('edits mention tokens atomically and maps selection offsets to the canonicalexpect(root.textContent).toBe('**literal** <script>unsafe</script>');root.remove();});+it('labels date pills relative to today while keeping the stored instant', () => {+ const root = document.createElement('div');+ document.body.append(root);+ const tomorrow = new Date();+ tomorrow.setHours(0, 0, 0, 0);+ tomorrow.setDate(tomorrow.getDate() + 1);+ const token = encodeCellMention({+ type: 'date',+ date: tomorrow.toISOString(),+ displayFormat: 'Next week',+ });+ writeCellText(root, `Due ${token}`);+ expect(root.textContent).toBe('Due Tomorrow');+ expect(root.querySelector('span')?.contentEditable).toBe('false');+ expect(readCellText(root)).toBe(`Due ${token}`);+ root.remove();+});diff --git a/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.ts b/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.tsindex f2d09d9d1e..228925e226 100644--- a/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.ts+++ b/apps/web/src/features/block-spreadsheet/primitives/cell-mention-dom.ts@@ -1,8 +1,17 @@+import { formatRelativeDay } from '@core/util/dateParser';import {+ type CellMention,cellMentionLabel,cellTextParts,} from '@macro-inc/spreadsheet/cell-mentions';+/** Match the grid, where date chips relabel themselves as days pass. */+function pillLabel(mention: CellMention) {+ return mention.type === 'date'+ ? formatRelativeDay(new Date(mention.date))+ : cellMentionLabel(mention);+}+export function readCellText(node: Node): string {if (node instanceof HTMLElement && node.dataset.cellMention)return node.dataset.cellMention;@@ -19,7 +28,7 @@ export function writeCellText(root: HTMLElement, value: string) {pill.dataset.cellMention = part.text;pill.className ='inline-block max-w-full align-bottom truncate rounded border border-edge-muted bg-accent/8 px-1 text-accent';- pill.textContent = cellMentionLabel(part.mention);+ pill.textContent = pillLabel(part.mention);return pill;}));diff --git a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsx b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsxnew file mode 100644index 0000000000..3668a07ee7--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsx@@ -0,0 +1,47 @@+import { encodeCellMention } from '@macro-inc/spreadsheet/cell-mentions';+import { cleanup, render, screen } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';++vi.mock(+ '@core/component/LexicalMarkdown/component/decorator/DocumentMention',+ () => ({ DocumentMention: () => 'document mention' })+);+vi.mock(+ '@core/component/LexicalMarkdown/component/decorator/UserMention',+ () => ({ UserMention: () => 'user mention' })+);+vi.mock(+ '@core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu',+ () => ({ MentionsMenu: () => null })+);+vi.mock(+ '@core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils',+ () => ({ getBlockNameFromEntity: () => 'md' })+);+vi.mock(+ '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin',+ () => ({ parseMacroAppUrl: () => ({ isValid: false }) })+);+vi.mock('./spreadsheet-cell-links', () => ({+ SpreadsheetCellLinks: (props: { value: string }) => props.value,+}));++import { spreadsheetMentions } from './spreadsheet-mentions';++afterEach(cleanup);++it('renders a date pill as a relative chip with the full date as its tooltip', () => {+ const tomorrow = new Date();+ tomorrow.setHours(9, 30, 0, 0);+ tomorrow.setDate(tomorrow.getDate() + 1);+ const due = encodeCellMention({+ type: 'date',+ date: tomorrow.toISOString(),+ displayFormat: 'Next week',+ });+ render(() => spreadsheetMentions.renderText(`Due ${due}`));+ const chip = screen.getByTitle(/9:30 AM$/);+ expect(chip.textContent).toBe('Tomorrow');+ expect(chip.getAttribute('data-date')).toBe(tomorrow.toISOString());+ expect(document.body.textContent).toBe('Due Tomorrow');+});diff --git a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsxindex 7a6ba90ea1..3069413a38 100644--- a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx+++ b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.tsx@@ -4,10 +4,13 @@ import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/Menimport { getBlockNameFromEntity } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils';import { parseMacroAppUrl } from '@core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin';import type { MentionItem } from '@core/component/LexicalMarkdown/utils/mentionsUtils';+import { formatRelativeDay, formatTooltipDate } from '@core/util/dateParser';import {+ type CellDateMention,cellTextParts,encodeCellMention,} from '@macro-inc/spreadsheet/cell-mentions';+import ClockIcon from '@phosphor/clock.svg';import { For, Suspense } from 'solid-js';import { CellMentionEditor } from './components/CellMentionEditor';import type { SpreadsheetMentions } from './context/spreadsheet-mentions';@@ -49,6 +52,29 @@ function fromItem(item: MentionItem): string | undefined {documentName: item.data.name ?? '',blockName: getBlockNameFromEntity(item),});+ if (item.kind === 'date')+ return encodeCellMention({+ type: 'date',+ date: item.data.date.toISOString(),+ displayFormat: item.data.displayText,+ });+}+/** Same chip as docs, without the picker: edit the cell to change the date. */+function CellDateChip(props: CellDateMention) {+ const date = () => new Date(props.date);+ return (+ <span+ data-spreadsheet-mention+ data-date={props.date}+ class="inline-block max-w-full align-bottom truncate rounded-md bg-accent/8 p-0.5 text-accent"+ title={formatTooltipDate(date())}+ >+ <span class="relative top-[0.125em] mx-0.5 inline-flex size-[1em]">+ <ClockIcon class="size-full" />+ </span>+ {formatRelativeDay(date())}+ </span>+ );}function CellMentions(props: { value: string }) {return (@@ -56,6 +82,7 @@ function CellMentions(props: { value: string }) {{(part) => {const mention = part.mention;if (!mention) return <SpreadsheetCellLinks value={part.text} />;+ if (mention.type === 'date') return <CellDateChip {...mention} />;return (<spandata-spreadsheet-mention@@ -93,7 +120,7 @@ export const spreadsheetMentions: SpreadsheetMentions = {<MentionsMenumenu={menu}anchor={anchor}- sources={['users', 'documents', 'channels', 'emails']}+ sources={['users', 'documents', 'channels', 'emails', 'dates']}showOpenTabs={false}onPick={(item) => {const value = fromItem(item);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsxindex f827bb7014..b8a559e643 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DateMention.tsx@@ -1,9 +1,8 @@import { DatePicker } from '@core/component/DatePicker';-import { formatRelativeDay } from '@core/util/dateParser';+import { formatRelativeDay, formatTooltipDate } from '@core/util/dateParser';import type { DateMentionDecoratorProps } from '@macro-inc/lexical-core';import { $isDateMentionNode } from '@macro-inc/lexical-core';import ClockIcon from '@phosphor/clock.svg';-import { differenceInCalendarDays } from 'date-fns';import {$getNodeByKey,COMMAND_PRIORITY_NORMAL,@@ -18,22 +17,6 @@ import { MentionTooltip } from './MentionTooltip';false && floatWithElement;-function formatTooltipDate(date: Date): string {- const diff = Math.abs(differenceInCalendarDays(date, new Date()));- const options: Intl.DateTimeFormatOptions = {- weekday: 'long',- month: 'long',- day: 'numeric',- year: 'numeric',- };- if (diff <= 5) {- options.hour = 'numeric';- options.minute = '2-digit';- options.hour12 = true;- }- return date.toLocaleDateString('en-US', options);-}-export function DateMention(props: DateMentionDecoratorProps) {const lexicalWrapper = useContext(LexicalWrapperContext);const editor = lexicalWrapper?.editor;diff --git a/apps/web/src/lib/core/util/dateParser.ts b/apps/web/src/lib/core/util/dateParser.tsindex 1684e71142..1fafaab12b 100644--- a/apps/web/src/lib/core/util/dateParser.ts+++ b/apps/web/src/lib/core/util/dateParser.ts@@ -337,6 +337,26 @@ export function formatRelativeDay(date: Date): string {}}+/**+ * Full date for a mention tooltip, with the time of day for dates near now.+ * (Moved from the DateMention decorator so spreadsheet chips can share it.)+ */+export function formatTooltipDate(date: Date): string {+ const diff = Math.abs(differenceInCalendarDays(date, new Date()));+ const options: Intl.DateTimeFormatOptions = {+ weekday: 'long',+ month: 'long',+ day: 'numeric',+ year: 'numeric',+ };+ if (diff <= 5) {+ options.hour = 'numeric';+ options.minute = '2-digit';+ options.hour12 = true;+ }+ return date.toLocaleDateString('en-US', options);+}+function _getDateSuggestions(input: string): ParsedDate[] {const suggestions: ParsedDate[] = [];const normalized = input.toLowerCase().trim();diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex fa34117dac..eea4883d09 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -1405,6 +1405,8 @@ export interface SpreadsheetCellInput {* Raw text or formula, at most 10,000 characters. Macro links render as mention pills.* For named pills, use the same inline tags as docs: <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Person"}</m-user-mention>* or <m-document-mention>{"documentId":"UUID","documentName":"Budget","blockName":"spreadsheet"}</m-document-mention>.+ * A date chip is <m-date-mention>{"date":"2026-09-28T00:00:00.000Z","displayFormat":"Sep 28"}</m-date-mention>; a cell holding only that chip calculates as the date.+ * Plain dates such as 9/28/2026 or =DATE(2026,9,28) display as dates without a number format.* Tags can be mixed with ordinary text. Use IDs from search/read results; do not invent them. Other Markdown is literal.*/value: string;diff --git a/crates/documents/src/domain/spreadsheet/models.rs b/crates/documents/src/domain/spreadsheet/models.rsindex 7f5863efa8..3c7a3174d3 100644--- a/crates/documents/src/domain/spreadsheet/models.rs+++ b/crates/documents/src/domain/spreadsheet/models.rs@@ -194,6 +194,8 @@ pub struct SpreadsheetCellInput {/// Raw text or formula, at most 10,000 characters. Macro links render as mention pills./// For named pills, use the same inline tags as docs: <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]","displayName":"Person"}</m-user-mention>/// or <m-document-mention>{"documentId":"UUID","documentName":"Budget","blockName":"spreadsheet"}</m-document-mention>.+ /// A date chip is <m-date-mention>{"date":"2026-09-28T00:00:00.000Z","displayFormat":"Sep 28"}</m-date-mention>; a cell holding only that chip calculates as the date.+ /// Plain dates such as 9/28/2026 or =DATE(2026,9,28) display as dates without a number format./// Tags can be mixed with ordinary text. Use IDs from search/read results; do not invent them. Other Markdown is literal.pub value: String,}diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex b900091be5..d811461cea 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -130,7 +130,7 @@ collaborative rows and columns have stable identities. Adding blank rows at thebottom remains available. Hidden cells are skipped by keyboard navigation.Cells support Macro mentions without Markdown formatting. Type `@` in a cell or-the formula bar to search people, documents, channels and email, then choose an+the formula bar to search people, documents, channels, email and dates, then choose anitem with the pointer or keyboard. Pasting a Macro app link renders a documentpill, preserving navigation parameters. Formulas still use the formula editor;`@` inside a formula or email address does not start mention search. Other Markdown@@ -138,8 +138,16 @@ is literal text. Mentions remain attached through copy/fill, undo and collaboratExcel/CSV export uses their display text. Plain URLs and email addresses are clickable;web links use the same hover preview as channel messages. Click the surrounding cellor use the formula bar to edit link text. AI `set_cells` accepts Macro URLs or the-same `<m-user-mention>` / `<m-document-mention>` encoding as docs. Formula references-to mention cells use literal labels, never execute a label as a formula.+same `<m-user-mention>` / `<m-document-mention>` / `<m-date-mention>` encoding as docs.+Formula references to mention cells use literal labels, never execute a label as a formula.++Dates: `@tomorrow`, `@next friday` or `@sep 28` offer a **Dates** bucket and insert+the same clock chip as docs; hover it for the full date, and edit the cell to change+it. A cell holding only a date chip is a date value: `=A1+7` produces a date, and+Excel export writes a dated number rather than the label. Typed dates such as+`9/28/2026` or `2026-09-28`, `=DATE(...)`, and arithmetic on date cells display as+dates without choosing the Date number format. A difference of two dates stays a+plain day count, and an explicit number format from the toolbar always wins.CSV imports a file up to 1 MB into the selection, adding rows if needed within the1,000 × 26 limit. Existing cells in that rectanglediff --git a/packages/spreadsheet/src/calculation.ts b/packages/spreadsheet/src/calculation.tsindex 3a4569c58c..0370a809cd 100644--- a/packages/spreadsheet/src/calculation.ts+++ b/packages/spreadsheet/src/calculation.ts@@ -1,6 +1,6 @@import { type CompletionContext, getTokens, Model } from '@ironcalc/wasm';import { format as formatExcelNumber } from 'ssf';-import { cellPlainText } from './cell-mentions';+import { cellDateMention, cellPlainText } from './cell-mentions';import {formatCellAddress,parseCellAddress,@@ -85,9 +85,74 @@ const timeFormatter = new Intl.DateTimeFormat('en-US', {second: '2-digit',});const DAY_MILLISECONDS = 86_400_000;+const SERIAL_EPOCH = Date.UTC(1899, 11, 30);+/** 1 January 2000 as an Excel serial number. */+const MIN_FORMULA_DATE_SERIAL = 36_526;// IronCalc treats this exact extent as a column style, without materializing// a style cell for every empty row. The editable grid is still bounded to 1,000.const ENGINE_COLUMN_HEIGHT = 1_048_576;+const numericLiteral = /^\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?\s*$/i;++/**+ * Excel serial for the mention's local calendar day. Presets such as+ * "Tomorrow" carry an end-of-day time, so the time of day is dropped to keep+ * date differences whole.+ */+function dateMentionSerial(iso: string): number {+ const date = new Date(iso);+ return (+ (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) -+ SERIAL_EPOCH) /+ DAY_MILLISECONDS+ );+}++/**+ * IronCalc assigns date and time number formats to typed dates and to formulas+ * that operate on them, as Excel does. Honor those for cells without an+ * explicit Macro format; other inferred formats stay general.+ */+function inferredFormat(numberFormat: string): 'date' | 'time' | undefined {+ const tokens = numberFormat.replace(/"[^"]*"|\\.|\[[^\]]*\]/g, '');+ if (/[dy]/i.test(tokens)) return 'date';+ if (/[hs]/i.test(tokens)) return 'time';+}++/**+ * Whether the engine's own number format may decide how a general cell shows.+ * Plain numeric literals never become dates; dates and formulas may.+ */+function canInferFormat(+ cell: SpreadsheetCell,+ value: string,+ isDate: boolean+): boolean {+ return (+ (!cell.format || cell.format === 'general') &&+ !cell.numberFormat &&+ (isDate || !numericLiteral.test(value))+ );+}++/**+ * IronCalc infers a formula's date format from the cells it references when+ * the formula is entered, so plain values go first and formulas follow in+ * grid order, which chained schedules usually read in.+ */+function entryOrder(cells: SpreadsheetCells): string[] {+ const isFormula = (address: string) =>+ cells[address].value.startsWith('=') && cells[address].format !== 'text';+ const addresses = Object.keys(cells).sort((a, b) => {+ const first = parseCellAddress(a);+ const second = parseCellAddress(b);+ if (!first || !second) return first ? -1 : second ? 1 : 0;+ return first.row - second.row || first.column - second.column;+ });+ return [+ ...addresses.filter((address) => !isFormula(address)),+ ...addresses.filter(isFormula),+ ];+}function displayNumber(number: number, cell?: SpreadsheetCell): string {const format = cell?.format ?? 'general';@@ -236,15 +301,28 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculator}}}+ const inferableBySheet: string[][] = [];for (const [sheetIndex, { id, cells, rowCount }] of bounded.entries()) {const unsupported: Record<string, string> = {};unsupportedBySheet[id] = unsupported;- for (const address of Object.keys(cells).sort()) {+ const inferable: string[] = [];+ inferableBySheet.push(inferable);+ for (const address of entryOrder(cells)) {const position = parseCellAddress(address);const cell = cells[address];- const value = cellPlainText(cell.value);- const literal = cell.format === 'text' || value !== cell.value;+ const dateMention =+ cell.format === 'text' ? undefined : cellDateMention(cell.value);+ const value = dateMention+ ? String(dateMentionSerial(dateMention.date))+ : cellPlainText(cell.value);+ const literal =+ !dateMention && (cell.format === 'text' || value !== cell.value);if (!position || position.row >= rowCount || value === '') continue;+ if (+ !literal &&+ canInferFormat(cell, value, dateMention !== undefined)+ )+ inferable.push(address);const fn = literal ? undefined : unsupportedFunction(value);if (fn) {unsupported[address] =@@ -311,10 +389,38 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculatorposition.column + 1,input);+ // A date pill is a date value: formulas referencing it inherit the format.+ if (dateMention)+ model.updateRangeStyle(+ {+ sheet: sheetIndex,+ row: position.row + 1,+ column: position.column + 1,+ width: 1,+ height: 1,+ },+ 'num_fmt',+ 'm/d/yyyy'+ );+ }+ }+ model.resumeEvaluation();+ model.evaluate();+ const inferredBySheet = inferableBySheet.map((inferable, sheetIndex) => {+ const inferred: Record<string, 'date' | 'time'> = {};+ for (const address of inferable) {+ const position = parseCellAddress(address)!;+ const row = position.row + 1;+ const column = position.column + 1;+ if (model.getCellType(sheetIndex, row, column) !== 1) continue;+ const format = inferredFormat(+ model.getCellStyle(sheetIndex, row, column).style.num_fmt+ );+ if (format) inferred[address] = format;}// The WASM binding exposes numeric values through its formatter. Read- // sufficient significant digits in a fixed locale, before display- // formatting, so sums and percentages do not use rounded UI strings.+ // sufficient significant digits in a fixed locale, after inspecting the+ // engine's own formats, so sums and percentages do not use rounded UI strings.model.updateRangeStyle({sheet: sheetIndex,@@ -326,11 +432,11 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculator'num_fmt','0.###############E+00');- }- model.resumeEvaluation();- model.evaluate();+ return inferred;+ });for (const [sheetIndex, { id, cells, rowCount }] of bounded.entries()) {const unsupported = unsupportedBySheet[id];+ const inferred = inferredBySheet[sheetIndex];const results: SpreadsheetCalculation = {};// Include array spill results, which have no persisted source cell.for (let row = 0; row < rowCount; row++) {@@ -369,7 +475,20 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculatorconst number = Number(display);const customFormat = cells[address]?.numberFormat;- let formatted = displayNumber(number, cells[address]);+ const engineFormat = inferred[address];+ // IronCalc also formats a difference of two dates as a date, so+ // formula results only count as dates from 2000 onwards; a day+ // count or a negative number stays a plain number.+ const dateLike =+ engineFormat !== 'date' ||+ !cells[address].value.startsWith('=') ||+ number >= MIN_FORMULA_DATE_SERIAL;+ let formatted = displayNumber(+ number,+ engineFormat && dateLike+ ? { ...cells[address], format: engineFormat }+ : cells[address]+ );let warning: string | undefined;if (customFormat) {try {diff --git a/packages/spreadsheet/src/cell-mentions.ts b/packages/spreadsheet/src/cell-mentions.tsindex efa94c6659..c0ad875a43 100644--- a/packages/spreadsheet/src/cell-mentions.ts+++ b/packages/spreadsheet/src/cell-mentions.ts@@ -7,8 +7,20 @@ export type CellMention =documentName: string;blockName: string;blockParams?: Record<string, string>;- };+ }+ | CellDateMention;+/** `date` is the ISO instant docs store; `displayFormat` is the label chosen at insertion. */+export type CellDateMention = {+ type: 'date';+ date: string;+ displayFormat: string;+};export type CellTextPart = { text: string; mention?: CellMention };+const dateLabelFormatter = new Intl.DateTimeFormat('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+});const blocks = new Set(['csv','write',@@ -81,6 +93,19 @@ function mentionData(type: string, encoded: string): CellMention | undefined {...(params ? { blockParams: params } : {}),};}+ if (+ type === 'date' &&+ text('date') &&+ data.date.length <= 64 &&+ Number.isFinite(Date.parse(data.date)) &&+ typeof data.displayFormat === 'string' &&+ data.displayFormat.length <= 2048+ )+ return {+ type: 'date',+ date: data.date,+ displayFormat: data.displayFormat,+ };} catch {/* Malformed tags remain literal text. */}@@ -91,7 +116,7 @@ export function cellTextParts(value: string): CellTextPart[] {const parts: CellTextPart[] = [];let end = 0;for (const match of value.matchAll(- /<m-(user|document)-mention>(.*?)<\/m-\1-mention>/gs+ /<m-(user|document|date)-mention>(.*?)<\/m-\1-mention>/gs)) {const mention = mentionData(match[1], match[2]);if (!mention) continue;@@ -103,9 +128,24 @@ export function cellTextParts(value: string): CellTextPart[] {return parts.length ? parts : [{ text: value }];}export function cellMentionLabel(mention: CellMention): string {- return mention.type === 'user'- ? `@${mention.displayName || mention.email}`- : mention.documentName || 'Linked item';+ if (mention.type === 'user')+ return `@${mention.displayName || mention.email}`;+ if (mention.type === 'date')+ return (+ mention.displayFormat || dateLabelFormatter.format(new Date(mention.date))+ );+ return mention.documentName || 'Linked item';+}+/** A cell holding exactly one date pill, ignoring surrounding whitespace. */+export function cellDateMention(value: string): CellDateMention | undefined {+ let found: CellDateMention | undefined;+ for (const part of cellTextParts(value)) {+ if (part.mention?.type === 'date') {+ if (found) return;+ found = part.mention;+ } else if (part.mention || part.text.trim()) return;+ }+ return found;}export function cellPlainText(value: string): string {return cellTextParts(value)