Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(sheets): parse typed partial dates and add date format presets (#8133)

teo070e6a21a1c2
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index a3b0d133dd..b43ff31599 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -315,10 +315,26 @@ compare formula, error, and formatting behavior before replacing it.
show in parentheses and zero as a dash. It exports as Excel's built-in accounting
format, and imported dollar formats with a repeated fill (`*`) open as accounting.
Date/time displays are deterministic UTC.
+ **Number format → Date formats** offers date presets (`mmm yyyy`, `mmm dd, yyyy`,
+ `mm/dd/yyyy`, `dd/mm/yyyy`, `yyyy-mm-dd`, `d mmm yyyy`, `dddd, mmmm d, yyyy`) and
+ **Custom date and time…** (`components/DateFormatDialog.tsx`), which takes any
+ Excel date or time code with a live preview. Both store the code as the cell's
+ `numberFormat` with the `date` or `time` format, so they export to Excel as that
+ code and import back unchanged.
+ Typing a date into a cell (`core/cell-dates.ts`) stores its serial number with the
+ `date` format and a code like the typed text: `01/2026` and `Jan 2026` show as
+ `Jan 2026`, `Jan 01 2026` as `Jan 01, 2026`, `2026-01-01` as `2026-01-01`, and
+ `1/1/26` in the default `m/d/yyyy`. All-numeric dates read day and month in the
+ browser locale's order, once at entry, so collaborators in other locales see the
+ same date; month and weekday names are English, and a year is required. A cell
+ that already shows dates keeps its format, Plain text keeps the typed text, and
+ API and import values stay raw. Editing a date cell shows a numeric date in the
+ locale's order that reads back as the same day.
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.
+ typed dates, `DATE()`-style results and arithmetic on date cells, including
+ numbers in the `date` format (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 at
100% zoom; larger content remains available in the formula bar/editor.
- Internal copying preserves formatting and translates relative/mixed references
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
index 535f26714e..e1adab7b43 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
+++ b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
@@ -199,11 +199,16 @@ test('drag fill continues numbers and month-end dates and undo restores the empt
page.getByRole('button', { name: 'Drag to fill selection' }),
page.locator('[data-address="E4"]')
);
+ await expect(page.locator('[data-address="E3"]')).toHaveText('2026-03-31');
+ await expect(page.locator('[data-address="E4"]')).toHaveText('2026-04-30');
const cells = await page.evaluate(
() => window.spreadsheetFixture.snapshot()[0].cells
);
- expect(cells.E3.value).toBe('2026-03-31');
- expect(cells.E4.value).toBe('2026-04-30');
+ expect(cells.E4).toEqual({
+ value: '46142',
+ format: 'date',
+ numberFormat: 'yyyy-mm-dd',
+ });
});
test('types a spaced formula, picks another sheet by pointer, and returns to the source', async ({
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts
index 06d5e6915c..b2fdfaf6e1 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts
+++ b/apps/web/src/features/block-spreadsheet/browser-test/formatting.browser.e2e.ts
@@ -242,6 +242,80 @@ test('lays accounting figures across the cell with parentheses, dashes and digit
).toBeLessThanOrEqual(1);
});
+test('reads typed partial dates as dates and restyles them from Date formats', async ({
+ page,
+}) => {
+ for (const [address, value, shown] of [
+ ['F2', '01/2026', 'Jan 2026'],
+ ['F3', 'Jan 01 2026', 'Jan 01, 2026'],
+ ['F4', '1/1/26', '1/1/2026'],
+ ['F5', '=F2+31', '2/1/2026'],
+ ]) {
+ await page.locator(`[data-address="${address}"]`).dblclick();
+ const editor = page.getByRole('textbox', {
+ name: `Edit ${address}`,
+ exact: true,
+ });
+ await editor.fill(value);
+ await editor.press('Enter');
+ await expect(page.locator(`[data-address="${address}"]`)).toHaveText(shown);
+ }
+ const saved = await page.evaluate(
+ () => window.spreadsheetFixture.snapshot()[0].cells
+ );
+ expect(saved.F2).toEqual({
+ value: '46023',
+ format: 'date',
+ numberFormat: 'mmm yyyy',
+ });
+ await page.locator('[data-address="F2"]').click();
+ await expect(
+ page.getByRole('textbox', { name: 'Formula bar', exact: true })
+ ).toHaveText('1/1/2026');
+
+ await page.locator('[data-address="F4"]').click({ modifiers: ['Shift'] });
+ await page
+ .getByRole('button', { name: 'Number format', exact: true })
+ .click();
+ await page
+ .getByRole('menuitem', { name: 'Date formats', exact: true })
+ .click();
+ await page
+ .getByRole('menuitem', {
+ name: 'Thursday, September 17, 2026',
+ exact: true,
+ })
+ .click();
+ await expect(page.getByRole('grid', { name: 'Spreadsheet' })).toBeFocused();
+ await expect(page.locator('[data-address="F3"]')).toHaveText(
+ 'Thursday, January 1, 2026'
+ );
+
+ await page
+ .getByRole('button', { name: 'Number format', exact: true })
+ .click();
+ await page
+ .getByRole('menuitem', { name: 'Date formats', exact: true })
+ .click();
+ await page
+ .getByRole('menuitem', { name: 'Custom date and time…', exact: true })
+ .click();
+ const code = page.getByRole('textbox', { name: 'Format code', exact: true });
+ await expect(code).toHaveValue('dddd, mmmm d, yyyy');
+ await code.fill('d mmmm yyyy');
+ await expect(page.getByRole('status')).toHaveText('Preview: 1 January 2026');
+ await page.getByRole('button', { name: 'Apply', exact: true }).click();
+ await expect(page.getByRole('grid', { name: 'Spreadsheet' })).toBeFocused();
+ for (const address of ['F2', 'F3', 'F4'])
+ await expect(page.locator(`[data-address="${address}"]`)).toHaveText(
+ '1 January 2026'
+ );
+ expect(
+ (await page.evaluate(() => window.spreadsheetFixture.snapshot()[0].cells))
+ .F4
+ ).toEqual({ value: '46023', format: 'date', numberFormat: 'd mmmm yyyy' });
+});
+
test('edits formula-bar text and formulas directly with the production mention editor enabled', async ({
page,
}) => {
diff --git a/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.test.tsx b/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.test.tsx
new file mode 100644
index 0000000000..b13e0c8b64
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.test.tsx
@@ -0,0 +1,74 @@
+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 { DateFormatDialog } from './DateFormatDialog';
+
+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('custom date and time format dialog', () => {
+ it('previews the active cell in the typed code and applies its style', () => {
+ const onSave = vi.fn();
+ render(() => (
+ <DateFormatDialog
+ dialog={{ range: 'B2:B9', numberFormat: 'm/d/yyyy', sample: 46023 }}
+ onSave={onSave}
+ onClose={() => {}}
+ onRestoreFocus={() => {}}
+ />
+ ));
+ const code = screen.getByRole('textbox', { name: 'Format code' });
+ expect(screen.getByRole('status').textContent).toBe('Preview: 1/1/2026');
+ fireEvent.input(code, { target: { value: 'ddd, d mmm yyyy' } });
+ expect(screen.getByRole('status').textContent).toBe(
+ 'Preview: Thu, 1 Jan 2026'
+ );
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form')!);
+ expect(onSave).toHaveBeenCalledWith({
+ format: 'date',
+ numberFormat: 'ddd, d mmm yyyy',
+ });
+ });
+
+ it('refuses codes that do not show dates or times', () => {
+ const onSave = vi.fn();
+ render(() => (
+ <DateFormatDialog
+ dialog={{ range: 'A1', numberFormat: 'mmm yyyy' }}
+ onSave={onSave}
+ onClose={() => {}}
+ onRestoreFocus={() => {}}
+ />
+ ));
+ expect(screen.getByRole('status').textContent).toBe('Preview: Sep 2026');
+ fireEvent.input(screen.getByRole('textbox', { name: 'Format code' }), {
+ target: { value: '#,##0.00' },
+ });
+ expect(screen.getByRole('status').textContent).toContain(
+ 'Use date or time codes'
+ );
+ expect(
+ screen.getByRole('button', { name: 'Apply' }).hasAttribute('disabled')
+ ).toBe(true);
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form')!);
+ expect(onSave).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.tsx b/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.tsx
new file mode 100644
index 0000000000..eb8f0851e6
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/components/DateFormatDialog.tsx
@@ -0,0 +1,138 @@
+import { Button } from '@ui/components/Button';
+import { Result } from 'neverthrow';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { format as formatExcelNumber } from 'ssf';
+import { dateFormatStyle } from '../core/cell-dates';
+import type { SpreadsheetCellStyle } from '../core/spreadsheet-document';
+import { SpreadsheetDialog } from './SpreadsheetDialog';
+
+/** Thursday, 17 September 2026, 2:30 PM. */
+const SAMPLE_DATE = 46_282 + 14.5 / 24;
+const formatSample = Result.fromThrowable(
+ (code: string, sample: number) => formatExcelNumber(code, sample),
+ () => 'unsupported format' as const
+);
+
+const CODES = [
+ ['d dd', 'Day: 7, 07'],
+ ['ddd dddd', 'Weekday: Thu, Thursday'],
+ ['m mm mmm mmmm', 'Month: 9, 09, Sep, September'],
+ ['yy yyyy', 'Year: 26, 2026'],
+ ['h hh', 'Hour'],
+ ['mm ss', 'Minutes (after h), seconds'],
+ ['AM/PM', '12-hour clock'],
+ ['"text"', 'Text shown as written'],
+] as const;
+
+export type DateFormatDialogState = {
+ /** The cells the format applies to, such as B2:B20. */
+ range: string;
+ /** The format code the dialog starts with. */
+ numberFormat: string;
+ /** The active cell's number, which the preview shows. */
+ sample?: number;
+};
+
+/** Applies a custom Excel date or time format code to the selected cells. */
+export function DateFormatDialog(props: {
+ dialog: DateFormatDialogState | undefined;
+ onSave: (style: SpreadsheetCellStyle) => void;
+ onClose: () => void;
+ onRestoreFocus: () => void;
+}) {
+ return (
+ <SpreadsheetDialog
+ open={!!props.dialog}
+ onOpenChange={(open) => {
+ if (!open) props.onClose();
+ }}
+ onRestoreFocus={props.onRestoreFocus}
+ position="center"
+ class="w-96"
+ >
+ <Show when={props.dialog} keyed>
+ {(dialog) => <DateFormatForm {...props} dialog={dialog} />}
+ </Show>
+ </SpreadsheetDialog>
+ );
+}
+
+function DateFormatForm(props: {
+ dialog: DateFormatDialogState;
+ onSave: (style: SpreadsheetCellStyle) => void;
+ onClose: () => void;
+}) {
+ const [code, setCode] = createSignal(props.dialog.numberFormat);
+ const style = createMemo(() => dateFormatStyle(code().trim()));
+ const preview = createMemo(() =>
+ style()
+ ? formatSample(
+ code().trim(),
+ props.dialog.sample ?? SAMPLE_DATE
+ ).unwrapOr(undefined)
+ : undefined
+ );
+ return (
+ <form
+ class="flex flex-col gap-3 p-5 text-sm"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const chosen = style();
+ if (chosen && preview()) props.onSave(chosen);
+ }}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <SpreadsheetDialog.Title class="font-semibold">
+ Custom date and time format
+ </SpreadsheetDialog.Title>
+ <SpreadsheetDialog.Description class="text-ink-muted">
+ Cells {props.dialog.range} show their dates and times with this Excel
+ format code.
+ </SpreadsheetDialog.Description>
+ <input
+ aria-label="Format code"
+ required
+ autocomplete="off"
+ autocapitalize="off"
+ spellcheck={false}
+ value={code()}
+ onInput={(event) => setCode(event.currentTarget.value)}
+ class="w-full rounded border border-edge-muted bg-input px-3 py-2 font-mono text-ink outline-none focus:border-accent touch:text-[max(16px,1rem)]"
+ />
+ <p role="status" class="min-h-5 text-xs">
+ <Show
+ when={preview()}
+ fallback={
+ <span class="text-failure">
+ Use date or time codes, such as mmm d, yyyy or h:mm AM/PM.
+ </span>
+ }
+ >
+ {(shown) => (
+ <span class="text-ink-muted">
+ Preview: <span class="text-ink">{shown()}</span>
+ </span>
+ )}
+ </Show>
+ </p>
+ <dl class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs text-ink-muted">
+ <For each={CODES}>
+ {([codes, meaning]) => (
+ <>
+ <dt class="whitespace-pre font-mono text-ink">{codes}</dt>
+ <dd>{meaning}</dd>
+ </>
+ )}
+ </For>
+ </dl>
+ <div class="mt-1 flex justify-end gap-2">
+ <Button variant="ghost" type="button" onClick={props.onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="strong" disabled={!preview()}>
+ Apply
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx
index 1fa9810104..5400191e07 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbar.test.tsx
@@ -239,6 +239,30 @@ describe('spreadsheet toolbar', () => {
expect(view.onStyle).toHaveBeenCalledWith({ format: 'accounting' });
});
+ it.each([
+ ['Sep 2026', { style: { format: 'date', numberFormat: 'mmm yyyy' } }],
+ [
+ 'Thursday, September 17, 2026',
+ { style: { format: 'date', numberFormat: 'dddd, mmmm d, yyyy' } },
+ ],
+ ['Custom date and time…', { command: 'custom-date-format' }],
+ ])('offers %s under Number format → Date formats', async (item, expected) => {
+ const view = toolbar();
+ fireEvent.keyDown(view.getByRole('button', { name: 'Number format' }), {
+ key: 'ArrowDown',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', { name: 'Date formats' }),
+ { key: 'ArrowRight' }
+ );
+ fireEvent.keyDown(await screen.findByRole('menuitem', { name: item }), {
+ key: 'Enter',
+ });
+ if ('style' in expected)
+ expect(view.onStyle).toHaveBeenCalledWith(expected.style);
+ else expect(view.onCommand).toHaveBeenCalledWith(expected.command);
+ });
+
it.each([
{
role: 'button',
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbarMenus.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbarMenus.tsx
index 4205130765..ba9268357b 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbarMenus.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetToolbarMenus.tsx
@@ -1,4 +1,5 @@
import AlignMiddle from '@phosphor/align-center-vertical-simple.svg';
+import CaretRight from '@phosphor/caret-right.svg';
import Check from '@phosphor/check.svg';
import PaintBucket from '@phosphor/paint-bucket.svg';
import Sigma from '@phosphor/sigma.svg';
@@ -10,6 +11,7 @@ import TextAlignRight from '@phosphor/text-align-right.svg';
import { Dropdown } from '@ui/components/Dropdown';
import { For, type JSX, Match, type ParentProps, Show, Switch } from 'solid-js';
import {
+ SPREADSHEET_DATE_FORMATS,
SPREADSHEET_FUNCTIONS,
SPREADSHEET_NUMBER_FORMATS,
SPREADSHEET_ZOOM_LEVELS,
@@ -116,6 +118,52 @@ export function ZoomMenu(props: SpreadsheetToolbarProps) {
);
}
+function DateFormatsMenu(props: SpreadsheetToolbarProps) {
+ return (
+ <Dropdown.Sub>
+ <Dropdown.SubTrigger
+ disabled={props.readonly}
+ class="h-8 gap-2 touch:h-auto touch:min-h-[44px]"
+ >
+ <span class="size-3.5 shrink-0" />
+ <span class="flex-1">Date formats</span>
+ <CaretRight class="size-3.5 shrink-0" />
+ </Dropdown.SubTrigger>
+ <Dropdown.SubContent class="max-w-[calc(100vw-1rem)] text-sm text-ink touch:text-[max(14px,0.875rem)]">
+ <Dropdown.Group>
+ <For each={SPREADSHEET_DATE_FORMATS}>
+ {(date) => (
+ <Choice
+ disabled={props.readonly}
+ selected={
+ props.cell?.format === 'date' &&
+ props.cell.numberFormat === date.numberFormat
+ }
+ onSelect={() =>
+ props.onStyle({
+ format: 'date',
+ numberFormat: date.numberFormat,
+ })
+ }
+ >
+ {date.example}
+ </Choice>
+ )}
+ </For>
+ </Dropdown.Group>
+ <Dropdown.Group>
+ <Choice
+ disabled={props.readonly}
+ onSelect={() => props.onCommand('custom-date-format')}
+ >
+ Custom date and time…
+ </Choice>
+ </Dropdown.Group>
+ </Dropdown.SubContent>
+ </Dropdown.Sub>
+ );
+}
+
export function NumberFormatMenu(props: SpreadsheetToolbarProps) {
return (
<ToolbarMenu
@@ -126,14 +174,19 @@ export function NumberFormatMenu(props: SpreadsheetToolbarProps) {
>
<For each={SPREADSHEET_NUMBER_FORMATS}>
{(format) => (
- <Choice
- disabled={props.readonly}
- selected={(props.cell?.format ?? 'general') === format.value}
- description={format.example}
- onSelect={() => props.onStyle({ format: format.value })}
- >
- {format.label}
- </Choice>
+ <>
+ <Choice
+ disabled={props.readonly}
+ selected={(props.cell?.format ?? 'general') === format.value}
+ description={format.example}
+ onSelect={() => props.onStyle({ format: format.value })}
+ >
+ {format.label}
+ </Choice>
+ <Show when={format.value === 'date'}>
+ <DateFormatsMenu {...props} />
+ </Show>
+ </>
)}
</For>
</ToolbarMenu>
diff --git a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts b/apps/web/src/features/block-spreadsheet/core/calculation.test.ts
index 0dd97dcb72..369d27884d 100644
--- a/apps/web/src/features/block-spreadsheet/core/calculation.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/calculation.test.ts
@@ -299,6 +299,30 @@ describe('spreadsheet calculation with IronCalc', () => {
expect(result.A14.display).toBe('46300.0');
});
+ it('shows serials in date formats as dates, and formulas on them inherit a date display', () => {
+ const result = calculator.calculate({
+ A1: { value: '46023', format: 'date', numberFormat: 'mmm yyyy' },
+ A2: { value: '=A1+31' },
+ A3: {
+ value: '46282',
+ format: 'date',
+ numberFormat: 'dddd, mmmm d, yyyy',
+ },
+ A4: { value: '=A3-A1' },
+ A5: { value: '46023', format: 'date' },
+ A6: { value: '=A1+31', format: 'number', decimals: 0 },
+ });
+ expect(result.A1).toEqual({ display: 'Jan 2026', number: 46023 });
+ expect(result.A2).toEqual({ display: '2/1/2026', number: 46054 });
+ expect(result.A3).toEqual({
+ display: 'Thursday, September 17, 2026',
+ number: 46282,
+ });
+ expect(result.A4).toEqual({ display: '259', number: 259 });
+ expect(result.A5).toEqual({ display: '1/1/2026', number: 46023 });
+ expect(result.A6.display).toBe('46,054');
+ });
+
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-dates.test.ts b/apps/web/src/features/block-spreadsheet/core/cell-dates.test.ts
new file mode 100644
index 0000000000..b16822b011
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/cell-dates.test.ts
@@ -0,0 +1,145 @@
+import { format as formatExcelNumber } from 'ssf';
+import { describe, expect, it } from 'vitest';
+import { dateFormatStyle, parseTypedDate, typedDateText } from './cell-dates';
+import { SPREADSHEET_DATE_FORMATS } from './toolbar-types';
+
+const isoDate = (serial: number) => formatExcelNumber('yyyy-mm-dd', serial);
+
+describe('typed dates', () => {
+ it.each([
+ ['01/2026', '2026-01-01', 'mmm yyyy'],
+ ['1-2026', '2026-01-01', 'mmm yyyy'],
+ ['Jan 2026', '2026-01-01', 'mmm yyyy'],
+ ['jan. 2026', '2026-01-01', 'mmm yyyy'],
+ ['January, 2026', '2026-01-01', 'mmmm yyyy'],
+ ['Sept 2026', '2026-09-01', 'mmm yyyy'],
+ ['Jan 01 2026', '2026-01-01', 'mmm dd, yyyy'],
+ ['Jan 1, 2026', '2026-01-01', 'mmm d, yyyy'],
+ ['January 17th, 2026', '2026-01-17', 'mmmm dd, yyyy'],
+ ['Thursday, January 1, 2026', '2026-01-01', 'dddd, mmmm d, yyyy'],
+ ['Thu Jan 1 2026', '2026-01-01', 'ddd, mmm d, yyyy'],
+ ['1 Jan 2026', '2026-01-01', 'd mmm yyyy'],
+ ['01-Jan-26', '2026-01-01', 'dd-mmm-yyyy'],
+ ['17 September 2026', '2026-09-17', 'dd mmmm yyyy'],
+ ['2026-01-01', '2026-01-01', 'yyyy-mm-dd'],
+ ['2026/9/17', '2026-09-17', 'yyyy/mm/dd'],
+ ['9-17-2026', '2026-09-17', 'm-d-yyyy'],
+ ])('reads %s as %s shown as %s', (input, date, numberFormat) => {
+ const typed = parseTypedDate(input, 'en-US');
+ expect(typed?.numberFormat).toBe(numberFormat);
+ expect(isoDate(typed!.serial)).toBe(date);
+ });
+
+ it('shows month/day/year input in the default date format', () => {
+ expect(parseTypedDate('1/1/2026', 'en-US')).toEqual({ serial: 46023 });
+ expect(parseTypedDate(' 1/1/26 ', 'en-US')).toEqual({ serial: 46023 });
+ expect(parseTypedDate('12/31/2026', 'en-US')).toEqual({ serial: 46387 });
+ });
+
+ it('reads two-digit years as Excel does', () => {
+ expect(isoDate(parseTypedDate('1/1/29', 'en-US')!.serial)).toBe(
+ '2029-01-01'
+ );
+ expect(isoDate(parseTypedDate('1/1/30', 'en-US')!.serial)).toBe(
+ '1930-01-01'
+ );
+ });
+
+ it('reads numeric day and month in the locale’s order', () => {
+ expect(parseTypedDate('03/04/2026', 'en-US')).toEqual({ serial: 46085 });
+ expect(parseTypedDate('03/04/2026', 'en-GB')).toEqual({
+ serial: 46115,
+ numberFormat: 'd/m/yyyy',
+ });
+ expect(parseTypedDate('3.4.2026', 'de-DE')).toEqual({
+ serial: 46115,
+ numberFormat: 'd.m.yyyy',
+ });
+ expect(parseTypedDate('17/09/2026', 'en-US')).toBeUndefined();
+ expect(parseTypedDate('17/09/2026', 'fr-FR')?.serial).toBe(46282);
+ // Month names and year-first dates read the same everywhere.
+ expect(parseTypedDate('Mar 4, 2026', 'en-GB')?.serial).toBe(46085);
+ expect(parseTypedDate('2026-03-04', 'de-DE')?.serial).toBe(46085);
+ expect(parseTypedDate('3/4/2026', 'not a locale')?.serial).toBe(46085);
+ });
+
+ it.each([
+ '2/30/2026',
+ '13/1/2026',
+ 'Jan 32 2026',
+ 'Friday, January 1, 2026',
+ 'due Jan 1 2026',
+ 'Jan 26',
+ '1/2',
+ '01/26',
+ '2026',
+ '2026-01',
+ 'Jan',
+ 'Ma 2026',
+ 'Junk 2026',
+ 'revenue 2026',
+ '1.5',
+ '12345',
+ '1/1/1899',
+ '1/1/1900',
+ '=DATE(2026,1,1)',
+ '',
+ ])('leaves %j as text', (input) => {
+ expect(parseTypedDate(input, 'en-US')).toBeUndefined();
+ });
+
+ it('edits a date as text that reads back as the same date', () => {
+ expect(typedDateText(46085, 'en-US')).toBe('3/4/2026');
+ expect(typedDateText(46085, 'en-GB')).toBe('4/3/2026');
+ expect(typedDateText(46085, 'ja-JP')).toBe('2026/3/4');
+ for (const locale of ['en-US', 'en-GB', 'de-DE', 'fr-FR', 'ja-JP', 'ko-KR'])
+ for (const serial of [61, 10_000, 46_023, 46_085, 2_958_465])
+ expect(
+ parseTypedDate(typedDateText(serial, locale)!, locale)?.serial
+ ).toBe(serial);
+ });
+
+ it('leaves times of day and out-of-range serials to the raw number', () => {
+ expect(typedDateText(46023.5, 'en-US')).toBeUndefined();
+ expect(typedDateText(60, 'en-US')).toBeUndefined();
+ expect(typedDateText(2_958_466, 'en-US')).toBeUndefined();
+ });
+});
+
+describe('date format codes', () => {
+ it('maps date and time codes to cell styles', () => {
+ expect(dateFormatStyle('mmm yyyy')).toEqual({
+ format: 'date',
+ numberFormat: 'mmm yyyy',
+ });
+ expect(dateFormatStyle('mmmm')).toEqual({
+ format: 'date',
+ numberFormat: 'mmmm',
+ });
+ expect(dateFormatStyle('m/d/yyyy')).toEqual({ format: 'date' });
+ expect(dateFormatStyle('h:mm')).toEqual({
+ format: 'time',
+ numberFormat: 'h:mm',
+ });
+ expect(dateFormatStyle('h:mm:ss AM/PM')).toEqual({ format: 'time' });
+ });
+
+ it.each(['', 'General', '0.00', '$#,##0', '@', `${'d'.repeat(513)}`])(
+ 'rejects %j, which is not a date or time code',
+ (code) => {
+ expect(dateFormatStyle(code)).toBeUndefined();
+ }
+ );
+
+ it('shows each preset as its menu example', () => {
+ for (const preset of SPREADSHEET_DATE_FORMATS) {
+ expect(formatExcelNumber(preset.numberFormat, 46_282)).toBe(
+ preset.example
+ );
+ expect(dateFormatStyle(preset.numberFormat)).toEqual({
+ format: 'date',
+ numberFormat: preset.numberFormat,
+ });
+ }
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/cell-dates.ts b/apps/web/src/features/block-spreadsheet/core/cell-dates.ts
new file mode 100644
index 0000000000..c5533c0580
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/cell-dates.ts
@@ -0,0 +1,246 @@
+import { Result } from 'neverthrow';
+import { format as formatExcelNumber, is_date } from 'ssf';
+import type { SpreadsheetCellStyle } from './spreadsheet-document';
+import { readNumberFormat } from './xlsx-styles';
+
+const DAY_MILLISECONDS = 86_400_000;
+const SERIAL_EPOCH = Date.UTC(1899, 11, 30);
+/** 1 March 1900: earlier serials count Excel's fictitious 29 February 1900. */
+const FIRST_SERIAL = 61;
+const MONTHS = [
+ 'january',
+ 'february',
+ 'march',
+ 'april',
+ 'may',
+ 'june',
+ 'july',
+ 'august',
+ 'september',
+ 'october',
+ 'november',
+ 'december',
+];
+const WEEKDAYS = [
+ 'sunday',
+ 'monday',
+ 'tuesday',
+ 'wednesday',
+ 'thursday',
+ 'friday',
+ 'saturday',
+];
+const NAME = '([a-z]+)\\.?';
+const ORDINAL = '(?:st|nd|rd|th)?';
+const monthYear = new RegExp(`^${NAME},?[ -](\\d{4})$`);
+const monthDayYear = new RegExp(
+ `^(?:${NAME},? )?${NAME}[ -](\\d{1,2})${ORDINAL},?[ -](\\d{2}|\\d{4})$`
+);
+const dayMonthYear = new RegExp(
+ `^(?:${NAME},? )?(\\d{1,2})${ORDINAL}([ -])${NAME},?[ -](\\d{2}|\\d{4})$`
+);
+
+/** A typed date as an Excel serial, with the Excel format that shows it the
+ * way it was typed; without one it shows as Macro's default m/d/yyyy. */
+export type TypedDate = { serial: number; numberFormat?: string };
+
+const localeDateParts = Result.fromThrowable(
+ (locale: string) =>
+ new Intl.DateTimeFormat(locale, { timeZone: 'UTC' })
+ .formatToParts(0)
+ .map((part) => part.type),
+ () => 'unknown locale' as const
+);
+
+/** The order of day, month and year in the locale's numeric dates. */
+function dateOrder(locale: string): 'dmy' | 'mdy' | 'ymd' {
+ const parts = localeDateParts(locale);
+ if (parts.isErr()) return 'mdy';
+ const day = parts.value.indexOf('day');
+ const month = parts.value.indexOf('month');
+ if (parts.value.indexOf('year') < Math.min(day, month)) return 'ymd';
+ return day < month ? 'dmy' : 'mdy';
+}
+
+/** A full or abbreviated (three letters or more) English name's index. */
+function nameIndex(names: string[], text: string) {
+ const index =
+ text.length < 3 ? -1 : names.findIndex((name) => name.startsWith(text));
+ return index < 0 ? undefined : { index, full: names[index] === text };
+}
+
+/** Two-digit years 00–29 are this century and 30–99 the last, as in Excel. */
+function fullYear(text: string) {
+ const year = Number(text);
+ if (text.length === 4) return year;
+ return year < 30 ? 2000 + year : 1900 + year;
+}
+
+/** The leading weekday of a date code, as long as the typed one. */
+function weekdayCode(weekday: string | undefined) {
+ if (weekday === undefined) return '';
+ return nameIndex(WEEKDAYS, weekday)?.full ? 'dddd, ' : 'ddd, ';
+}
+
+function typedDate(
+ year: number,
+ month: number,
+ day: number,
+ numberFormat: string | undefined,
+ weekday?: string
+): TypedDate | undefined {
+ const time = Date.UTC(year, month - 1, day);
+ const date = new Date(time);
+ if (
+ date.getUTCFullYear() !== year ||
+ date.getUTCMonth() !== month - 1 ||
+ date.getUTCDate() !== day
+ )
+ return;
+ if (
+ weekday !== undefined &&
+ nameIndex(WEEKDAYS, weekday)?.index !== date.getUTCDay()
+ )
+ return;
+ const serial = (time - SERIAL_EPOCH) / DAY_MILLISECONDS;
+ if (serial < FIRST_SERIAL) return;
+ return numberFormat === undefined ? { serial } : { serial, numberFormat };
+}
+
+/** `2026-01-01`, `1/1/26` or `01/2026`. */
+function numericDate(text: string, locale: string) {
+ let match = /^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})$/.exec(text);
+ if (match) {
+ const [, year, separator, month, day] = match;
+ return typedDate(
+ Number(year),
+ Number(month),
+ Number(day),
+ `yyyy${separator}mm${separator}dd`
+ );
+ }
+ match = /^(\d{1,2})([-/.])(\d{1,2})\2(\d{2}|\d{4})$/.exec(text);
+ if (match) {
+ const [, first, separator, second, year] = match;
+ const dayFirst = dateOrder(locale) === 'dmy';
+ const code = dayFirst
+ ? `d${separator}m${separator}yyyy`
+ : `m${separator}d${separator}yyyy`;
+ return typedDate(
+ fullYear(year),
+ Number(dayFirst ? second : first),
+ Number(dayFirst ? first : second),
+ code === 'm/d/yyyy' ? undefined : code
+ );
+ }
+ match = /^(\d{1,2})[-/.](\d{4})$/.exec(text);
+ if (match)
+ return typedDate(Number(match[2]), Number(match[1]), 1, 'mmm yyyy');
+}
+
+/** `Jan 2026`, `Thursday, January 1, 2026` or `1 Jan 2026`. */
+function namedDate(text: string) {
+ let match = monthYear.exec(text);
+ if (match) {
+ const month = nameIndex(MONTHS, match[1]);
+ return (
+ month &&
+ typedDate(
+ Number(match[2]),
+ month.index + 1,
+ 1,
+ `${month.full ? 'mmmm' : 'mmm'} yyyy`
+ )
+ );
+ }
+ match = monthDayYear.exec(text);
+ if (match) {
+ const [, weekday, name, day, year] = match;
+ const month = nameIndex(MONTHS, name);
+ return (
+ month &&
+ typedDate(
+ fullYear(year),
+ month.index + 1,
+ Number(day),
+ `${weekdayCode(weekday)}${month.full ? 'mmmm' : 'mmm'} ${day.length === 2 ? 'dd' : 'd'}, yyyy`,
+ weekday
+ )
+ );
+ }
+ match = dayMonthYear.exec(text);
+ if (match) {
+ const [, weekday, day, separator, name, year] = match;
+ const month = nameIndex(MONTHS, name);
+ return (
+ month &&
+ typedDate(
+ fullYear(year),
+ month.index + 1,
+ Number(day),
+ `${weekdayCode(weekday)}${day.length === 2 ? 'dd' : 'd'}${separator}${month.full ? 'mmmm' : 'mmm'}${separator}yyyy`,
+ weekday
+ )
+ );
+ }
+}
+
+/**
+ * A date typed into a cell, such as `01/2026`, `Jan 2026`, `Jan 01 2026`,
+ * `1 January 2026`, `2026-01-01` or `1/1/26`. All-numeric dates read day and
+ * month in the locale's order; names are English. Text that is not a whole
+ * date, a day that does not exist, or a weekday that does not match it is
+ * undefined, as are dates before March 1900.
+ */
+export function parseTypedDate(
+ input: string,
+ locale: string
+): TypedDate | undefined {
+ const text = input.trim().toLowerCase().replace(/\s+/g, ' ');
+ return numericDate(text, locale) ?? namedDate(text);
+}
+
+/**
+ * A whole-day serial as the numeric date `parseTypedDate` reads back in the
+ * same locale, for editing a date cell. Undefined for times of day and
+ * serials outside the dates it reads.
+ */
+export function typedDateText(
+ serial: number,
+ locale: string
+): string | undefined {
+ if (!Number.isInteger(serial) || serial < FIRST_SERIAL) return;
+ const date = new Date(SERIAL_EPOCH + serial * DAY_MILLISECONDS);
+ const year = date.getUTCFullYear();
+ if (!(year <= 9999)) return;
+ const month = date.getUTCMonth() + 1;
+ const day = date.getUTCDate();
+ switch (dateOrder(locale)) {
+ case 'ymd':
+ return `${year}/${month}/${day}`;
+ case 'dmy':
+ return `${day}/${month}/${year}`;
+ case 'mdy':
+ return `${month}/${day}/${year}`;
+ }
+}
+
+const readDateFormat = Result.fromThrowable(
+ (code: string): SpreadsheetCellStyle | undefined => {
+ if (!is_date(code)) return;
+ formatExcelNumber(code, 0);
+ const style = readNumberFormat(code);
+ return { ...style, format: style.format === 'time' ? 'time' : 'date' };
+ },
+ () => 'unsupported format' as const
+);
+
+/**
+ * The cell style for an Excel date or time format code, or undefined when the
+ * code is not one Macro can display.
+ */
+export function dateFormatStyle(
+ code: string
+): SpreadsheetCellStyle | undefined {
+ return readDateFormat(code).unwrapOr(undefined);
+}
diff --git a/apps/web/src/features/block-spreadsheet/core/cell-input.test.ts b/apps/web/src/features/block-spreadsheet/core/cell-input.test.ts
index 9ffe1974c1..a48e0900bc 100644
--- a/apps/web/src/features/block-spreadsheet/core/cell-input.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/cell-input.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { cellEditValue, normalizeCellInput } from './cell-input';
+import { cellEditValue, cellInputEdit } from './cell-input';
describe('percentage cell entry', () => {
it.each([
@@ -11,9 +11,9 @@ describe('percentage cell entry', () => {
['1e-3', '1e-3%'],
['0', '0%'],
])('treats typed %s as percentage points', (input, expected) => {
- expect(normalizeCellInput(input, { value: '', format: 'percent' })).toBe(
- expected
- );
+ expect(
+ cellInputEdit(input, { value: '', format: 'percent' }, 'en-US')
+ ).toEqual({ value: expected });
});
it.each([
@@ -28,22 +28,34 @@ describe('percentage cell entry', () => {
])(
'does not reinterpret formula, explicit percentage, or text %s',
(input) => {
- expect(normalizeCellInput(input, { value: '', format: 'percent' })).toBe(
- input
- );
+ expect(
+ cellInputEdit(input, { value: '', format: 'percent' }, 'en-US')
+ ).toEqual({ value: input });
}
);
it('respects imported Excel percentage formats without treating literal percent labels as numeric formats', () => {
expect(
- normalizeCellInput('5', { value: '', numberFormat: '0.00%;[Red](0.00%)' })
+ cellInputEdit(
+ '5',
+ { value: '', numberFormat: '0.00%;[Red](0.00%)' },
+ 'en-US'
+ ).value
).toBe('5%');
for (const numberFormat of ['0"%"', '0\\%', '0" percent"', '0.00']) {
- expect(normalizeCellInput('5', { value: '', numberFormat })).toBe('5');
+ expect(cellInputEdit('5', { value: '', numberFormat }, 'en-US')).toEqual({
+ value: '5',
+ });
}
- expect(normalizeCellInput('5', { value: '', format: 'number' })).toBe('5');
expect(
- normalizeCellInput('5', { value: '', format: 'text', numberFormat: '0%' })
+ cellInputEdit('5', { value: '', format: 'number' }, 'en-US').value
+ ).toBe('5');
+ expect(
+ cellInputEdit(
+ '5',
+ { value: '', format: 'text', numberFormat: '0%' },
+ 'en-US'
+ ).value
).toBe('5');
});
@@ -58,8 +70,90 @@ describe('percentage cell entry', () => {
'shows stored %s as %s when editing without double scaling',
(value, expected) => {
const cell = { value, format: 'percent' as const };
- expect(cellEditValue(cell)).toBe(expected);
- expect(normalizeCellInput(cellEditValue(cell), cell)).toBe(expected);
+ expect(cellEditValue(cell, 'en-US')).toBe(expected);
+ expect(
+ cellInputEdit(cellEditValue(cell, 'en-US'), cell, 'en-US').value
+ ).toBe(expected);
}
);
});
+
+describe('date cell entry', () => {
+ it('stores a typed date as its serial, shown like the typed text', () => {
+ expect(cellInputEdit('01/2026', undefined, 'en-US')).toEqual({
+ value: '46023',
+ format: 'date',
+ numberFormat: 'mmm yyyy',
+ });
+ expect(cellInputEdit('Jan 01 2026', { value: 'x' }, 'en-US')).toEqual({
+ value: '46023',
+ format: 'date',
+ numberFormat: 'mmm dd, yyyy',
+ });
+ expect(cellInputEdit('1/1/26', undefined, 'en-US')).toEqual({
+ value: '46023',
+ format: 'date',
+ });
+ expect(cellInputEdit('1/2/2026', undefined, 'en-GB')).toEqual({
+ value: '46054',
+ format: 'date',
+ numberFormat: 'd/m/yyyy',
+ });
+ });
+
+ it('turns a number format into a date format for a typed date', () => {
+ expect(
+ cellInputEdit(
+ 'Jan 2026',
+ { value: '', format: 'currency', decimals: 0 },
+ 'en-US'
+ )
+ ).toEqual({ value: '46023', format: 'date', numberFormat: 'mmm yyyy' });
+ });
+
+ it('keeps the format of a cell that already shows dates', () => {
+ for (const cell of [
+ { value: '', format: 'date' as const },
+ { value: '', format: 'date' as const, numberFormat: 'yyyy-mm-dd' },
+ { value: '', numberFormat: 'd-mmm-yy' },
+ ])
+ expect(cellInputEdit('Jan 2026', cell, 'en-US')).toEqual({
+ value: '46023',
+ });
+ });
+
+ it('leaves text cells, formulas and other text as typed', () => {
+ expect(
+ cellInputEdit('1/1/2026', { value: '', format: 'text' }, 'en-US')
+ ).toEqual({ value: '1/1/2026' });
+ expect(cellInputEdit('=DATE(2026,1,1)', undefined, 'en-US')).toEqual({
+ value: '=DATE(2026,1,1)',
+ });
+ expect(cellInputEdit("'Jan 2026", undefined, 'en-US')).toEqual({
+ value: "'Jan 2026",
+ });
+ expect(cellInputEdit('Q1 2026', undefined, 'en-US')).toEqual({
+ value: 'Q1 2026',
+ });
+ });
+
+ it('edits a stored date in the locale’s order and reads it back unchanged', () => {
+ const cell = {
+ value: '46085',
+ format: 'date' as const,
+ numberFormat: 'mmm yyyy',
+ };
+ expect(cellEditValue(cell, 'en-US')).toBe('3/4/2026');
+ expect(cellEditValue(cell, 'en-GB')).toBe('4/3/2026');
+ for (const locale of ['en-US', 'en-GB'])
+ expect(cellInputEdit(cellEditValue(cell, locale), cell, locale)).toEqual({
+ value: '46085',
+ });
+ });
+
+ it('edits date times, formulas and text in date cells as stored', () => {
+ for (const value of ['46085.25', '=TODAY()', 'TBD'])
+ expect(cellEditValue({ value, format: 'date' }, 'en-US')).toBe(value);
+ expect(cellEditValue({ value: '46085' }, 'en-US')).toBe('46085');
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/cell-input.ts b/apps/web/src/features/block-spreadsheet/core/cell-input.ts
index 68c1df5215..3817719309 100644
--- a/apps/web/src/features/block-spreadsheet/core/cell-input.ts
+++ b/apps/web/src/features/block-spreadsheet/core/cell-input.ts
@@ -1,3 +1,5 @@
+import { is_date } from 'ssf';
+import { parseTypedDate, typedDateText } from './cell-dates';
import type { SpreadsheetCell } from './spreadsheet-document';
const numericInput = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
@@ -13,19 +15,53 @@ function isPercentCell(cell?: SpreadsheetCell) {
return format.includes('%');
}
-/** User input in percentage cells uses percentage points; API/import values stay raw. */
-export function normalizeCellInput(value: string, cell?: SpreadsheetCell) {
+function isDateCell(cell?: SpreadsheetCell) {
+ return (
+ cell?.format === 'date' ||
+ (cell?.format !== 'text' &&
+ !!cell?.numberFormat &&
+ is_date(cell.numberFormat))
+ );
+}
+
+/**
+ * The edit for what a user typed into a cell. Percentage cells take
+ * percentage points, and a date becomes its serial number shown as a date:
+ * in the cell's own date format, or else in one like the typed text.
+ * API and import values stay raw.
+ */
+export function cellInputEdit(
+ value: string,
+ cell: SpreadsheetCell | undefined,
+ locale: string
+): Partial<SpreadsheetCell> {
+ if (cell?.format === 'text') return { value };
const trimmed = value.trim();
- return isPercentCell(cell) &&
+ if (
+ isPercentCell(cell) &&
numericInput.test(trimmed) &&
Number.isFinite(Number(trimmed))
- ? `${trimmed}%`
- : value;
+ )
+ return { value: `${trimmed}%` };
+ const date = parseTypedDate(value, locale);
+ if (!date) return { value };
+ if (isDateCell(cell)) return { value: String(date.serial) };
+ return {
+ value: String(date.serial),
+ format: 'date',
+ ...(date.numberFormat && { numberFormat: date.numberFormat }),
+ };
}
-/** Show an existing numeric percentage in the editor without changing its value. */
-export function cellEditValue(cell?: SpreadsheetCell) {
+/** Show an existing number the way it would be typed: dates as dates, and
+ * percentages without changing their value. */
+export function cellEditValue(
+ cell: SpreadsheetCell | undefined,
+ locale: string
+) {
const value = cell?.value ?? '';
+ if (isDateCell(cell) && numericInput.test(value.trim()))
+ return typedDateText(Number(value), locale) ?? value;
if (!isPercentCell(cell) || !numericInput.test(value.trim())) return value;
const percent = Number(value) * 100;
if (!Number.isFinite(percent)) return value;
diff --git a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts b/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts
index 87f648e083..7d1f551d61 100644
--- a/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts
+++ b/apps/web/src/features/block-spreadsheet/core/toolbar-types.ts
@@ -26,6 +26,7 @@ export type SpreadsheetCommand =
| 'trim-whitespace'
| 'dropdown'
| 'goal-seek'
+ | 'custom-date-format'
| 'border-all'
| 'border-outer'
| 'border-none'
@@ -78,3 +79,18 @@ export const SPREADSHEET_NUMBER_FORMATS = [
{ value: 'scientific', label: 'Scientific', example: '1.23E+03' },
{ value: 'text', label: 'Plain text', example: '1234' },
] as const;
+
+/** Excel date codes offered beside the default Date format, with how each
+ * shows Thursday, 17 September 2026. */
+export const SPREADSHEET_DATE_FORMATS = [
+ { numberFormat: 'mmm yyyy', example: 'Sep 2026' },
+ { numberFormat: 'mmm dd, yyyy', example: 'Sep 17, 2026' },
+ { numberFormat: 'mm/dd/yyyy', example: '09/17/2026' },
+ { numberFormat: 'dd/mm/yyyy', example: '17/09/2026' },
+ { numberFormat: 'yyyy-mm-dd', example: '2026-09-17' },
+ { numberFormat: 'd mmm yyyy', example: '17 Sep 2026' },
+ {
+ numberFormat: 'dddd, mmmm d, yyyy',
+ example: 'Thursday, September 17, 2026',
+ },
+] as const;
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.ts
index 7b547af9d3..941d3350a2 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
@@ -199,6 +199,36 @@ describe('Excel workbook files', () => {
});
});
+ it('exports date and time formats as their Excel codes and imports them back', async () => {
+ const sheet = simpleSheet();
+ sheet.cells = {
+ A1: { value: '46023', format: 'date', numberFormat: 'mmm yyyy' },
+ A2: { value: '46023', format: 'date', numberFormat: 'mmm dd, yyyy' },
+ A3: { value: '46023', format: 'date', numberFormat: 'mm/dd/yyyy' },
+ A4: { value: '46023', format: 'date', numberFormat: 'dd/mm/yyyy' },
+ A5: { value: '46023', format: 'date', numberFormat: 'yyyy-mm-dd' },
+ A6: {
+ value: '46023',
+ format: 'date',
+ numberFormat: 'dddd, mmmm d, yyyy',
+ },
+ A7: { value: '46023', format: 'date' },
+ A8: { value: '0.5', format: 'time', numberFormat: 'h:mm AM/PM' },
+ };
+ const encoded = await encodeXlsx({ sheets: [sheet] });
+ const workbook = new ExcelJS.Workbook();
+ await workbook.xlsx.load(encoded.bytes.slice().buffer);
+ const exported = workbook.worksheets[0];
+ expect(exported.getCell('A1').value).toEqual(
+ new Date(Date.UTC(2026, 0, 1))
+ );
+ expect(exported.getCell('A1').numFmt).toBe('mmm yyyy');
+ expect(exported.getCell('A6').numFmt).toBe('dddd, mmmm d, yyyy');
+ expect(exported.getCell('A7').numFmt).toBe('m/d/yyyy');
+ const decoded = await decodeXlsx(encoded.bytes);
+ expect(decoded.sheets[0].cells).toEqual(sheet.cells);
+ });
+
it('imports dollar formats with a repeated fill as accounting, keeping variants for export', async () => {
const variant = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
const workbook = new ExcelJS.Workbook();
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.ts
index a44edb47a6..f9a24bdb97 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
@@ -407,6 +407,23 @@ describe('spreadsheet clipboard and formatting', () => {
B1: { value: '=A1*2', format: 'percent', bold: true },
});
});
+
+ it('formats a captured range after the selection has moved', () => {
+ const { grid, cells } = setup({
+ A1: { value: '1' },
+ A2: { value: '2' },
+ C3: { value: '3' },
+ });
+ grid.selectRange({ row: 0, column: 0 }, { row: 1, column: 0 });
+ const captured = grid.selection();
+ grid.selectRange({ row: 2, column: 2 }, { row: 2, column: 2 });
+ grid.format({ format: 'date', numberFormat: 'yyyy-mm-dd' }, captured);
+ expect(cells()).toEqual({
+ A1: { value: '1', format: 'date', numberFormat: 'yyyy-mm-dd' },
+ A2: { value: '2', format: 'date', numberFormat: 'yyyy-mm-dd' },
+ C3: { value: '3' },
+ });
+ });
});
describe('spreadsheet read-only permissions', () => {
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.ts
index 7643eaa0e5..c8537559cd 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
@@ -14,7 +14,7 @@ import {
rangeCopies,
readCopiedRange,
} from '../core/cell-copy';
-import { cellEditValue, normalizeCellInput } from '../core/cell-input';
+import { cellEditValue, cellInputEdit } from '../core/cell-input';
import {
type FormulaTextSelection,
formulaRangeReference,
@@ -299,7 +299,7 @@ export function createGridController(source: GridSource) {
}
}
const edits = {
- [address]: { value: normalizeCellInput(value, originalCell) },
+ [address]: cellInputEdit(value, originalCell, navigator.language),
};
if (target && source.setSheetCells)
source.setSheetCells(target.sheetId, edits);
@@ -342,7 +342,7 @@ export function createGridController(source: GridSource) {
return;
}
originalCell = source.cells()[activeAddress()];
- originalValue = cellEditValue(originalCell);
+ originalValue = cellEditValue(originalCell, navigator.language);
editTarget = source.sheetId
? { sheetId: source.sheetId(), address: activeAddress() }
: undefined;
@@ -464,13 +464,17 @@ export function createGridController(source: GridSource) {
);
}
- function format(patch: Partial<SpreadsheetCell>) {
+ /** Styles `target`, by default the current selection. */
+ function format(
+ patch: Partial<SpreadsheetCell>,
+ target: CellSelection = selection()
+ ) {
commit();
if (!source.canEdit()) return;
cancelPendingCopy();
source.setCells(
Object.fromEntries(
- selectionAddresses(selection()).map((address) => [address, patch])
+ selectionAddresses(target).map((address) => [address, patch])
)
);
}
diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
index b5fd6e2e45..83c7bd92b1 100644
--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
@@ -20,6 +20,10 @@ import {
} from 'solid-js';
import { match } from 'ts-pattern';
import { ChartDialog } from '../components/ChartDialog';
+import {
+ DateFormatDialog,
+ type DateFormatDialogState,
+} from '../components/DateFormatDialog';
import {
DropdownDialog,
type DropdownDialogState,
@@ -50,6 +54,7 @@ import { chartData, createChartReader } from '../core/chart-data';
import { encodeCsv } from '../core/csv-export';
import { formulaRangeReference } from '../core/formula-reference';
import {
+ type CellSelection,
cellAddress,
positionFromAddress,
selectionBounds,
@@ -67,11 +72,13 @@ import type { SpreadsheetCommentAnchor } from '../core/spreadsheet-comments';
import {
SPREADSHEET_MAX_COLUMNS,
SPREADSHEET_MAX_ROWS,
+ type SpreadsheetCellStyle,
} from '../core/spreadsheet-document';
import { spreadsheetCursors } from '../core/spreadsheet-presence';
import type { SpreadsheetCommand } from '../core/toolbar-types';
import { SPREADSHEET_MAX_SHEETS } from '../core/workbook-document';
import { CSV_MAX_BYTES } from '../core/workbook-file-types';
+import { cellNumberFormat } from '../core/xlsx-styles';
import { createCalculation } from '../primitives/create-calculation';
import { createCalculationStatus } from '../primitives/create-calculation-status';
import { createDrawingActions } from '../primitives/create-drawing-actions';
@@ -259,6 +266,31 @@ export function SpreadsheetEditor(props: {
);
}
}
+ // The dialog styles the cells it names, even if the selection moves while
+ // it is open (comment links can select a range).
+ const [dateFormatDialog, setDateFormatDialog] = createSignal<
+ DateFormatDialogState & { sheetId: string; selection: CellSelection }
+ >();
+ function openDateFormatDialog() {
+ if (!editable()) return;
+ const cell = activeCell();
+ setDateFormatDialog({
+ sheetId: props.store.activeSheetId(),
+ selection: grid.selection(),
+ range: selectionRange(),
+ numberFormat:
+ cell?.format === 'date' || cell?.format === 'time'
+ ? cellNumberFormat(cell)
+ : 'm/d/yyyy',
+ sample: values()[grid.activeAddress()]?.number,
+ });
+ }
+ function changeDateFormat(style: SpreadsheetCellStyle) {
+ const dialog = dateFormatDialog();
+ setDateFormatDialog(undefined);
+ if (dialog?.sheetId === props.store.activeSheetId())
+ grid.format(style, dialog.selection);
+ }
const workbookActions = createWorkbookActions({
store: props.store,
values: calculation.workbookValues,
@@ -397,7 +429,8 @@ export function SpreadsheetEditor(props: {
goalSeek.open() ||
workbookActions.preview() ||
workbookActions.sheetDialog() ||
- dropdownDialog()
+ dropdownDialog() ||
+ dateFormatDialog()
)
return;
if (grid.editing() === 'cell') {
@@ -416,7 +449,11 @@ export function SpreadsheetEditor(props: {
};
const menuCommand = (action: SpreadsheetCommand) => {
// Create a new focus owner only after the menu's focus trap has closed.
- if (action.startsWith('insert-') || action === 'dropdown')
+ if (
+ action.startsWith('insert-') ||
+ action === 'dropdown' ||
+ action === 'custom-date-format'
+ )
pendingMenuAction = action;
else command(action);
};
@@ -542,6 +579,7 @@ export function SpreadsheetEditor(props: {
})
.with('trim-whitespace', actions.trimWhitespace)
.with('dropdown', openDropdownDialog)
+ .with('custom-date-format', openDateFormatDialog)
.with('border-all', () => actions.borders('all'))
.with('border-outer', () => actions.borders('outer'))
.with('border-none', () => actions.borders('none'))
@@ -900,7 +938,11 @@ export function SpreadsheetEditor(props: {
? grid.editingAddress()
: formulaRangeReference(grid.selection())
}
- value={grid.editing() ? grid.draft() : cellEditValue(activeCell())}
+ value={
+ grid.editing()
+ ? grid.draft()
+ : cellEditValue(activeCell(), navigator.language)
+ }
readonly={!editable()}
onNavigate={(address) => {
const parts = address.split(':');
@@ -1283,6 +1325,12 @@ export function SpreadsheetEditor(props: {
onClose={() => setDropdownDialog(undefined)}
onRestoreFocus={focusGrid}
/>
+ <DateFormatDialog
+ dialog={dateFormatDialog()}
+ onSave={changeDateFormat}
+ onClose={() => setDateFormatDialog(undefined)}
+ onRestoreFocus={focusGrid}
+ />
<SpreadsheetSheetDialog
onRestoreFocus={() => {
focusGrid();
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.ts
index 17ca4296b2..8882e30ed3 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
@@ -5001,7 +5001,10 @@ export interface SpreadsheetReadCell {
*/
export interface SpreadsheetStyle {
/**
- * Exact Excel number format, up to 512 characters.
+ * Exact Excel number format, up to 512 characters; it overrides the display of `format`.
+ * Show dates with format=date and a date code such as mmm yyyy (Jan 2026), mmm dd, yyyy,
+ * mm/dd/yyyy, dd/mm/yyyy, yyyy-mm-dd, d mmm yyyy or dddd, mmmm d, yyyy; times with
+ * format=time and a code such as h:mm AM/PM.
*/
numberFormat?: string | null;
/**
diff --git a/crates/documents/src/domain/spreadsheet/models.rs b/crates/documents/src/domain/spreadsheet/models.rs
index 4fb9506a0a..57eafb09a3 100644
--- a/crates/documents/src/domain/spreadsheet/models.rs
+++ b/crates/documents/src/domain/spreadsheet/models.rs
@@ -54,9 +54,9 @@ pub enum SpreadsheetNumberFormat {
Accounting,
/// Percent.
Percent,
- /// Date.
+ /// Date, shown as m/d/yyyy unless numberFormat gives another date code.
Date,
- /// Time.
+ /// Time, shown as h:mm:ss AM/PM unless numberFormat gives another time code.
Time,
/// Scientific.
Scientific,
@@ -103,7 +103,10 @@ pub enum SpreadsheetBorderStyle {
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SpreadsheetStyle {
- /// Exact Excel number format, up to 512 characters.
+ /// Exact Excel number format, up to 512 characters; it overrides the display of `format`.
+ /// Show dates with format=date and a date code such as mmm yyyy (Jan 2026), mmm dd, yyyy,
+ /// mm/dd/yyyy, dd/mm/yyyy, yyyy-mm-dd, d mmm yyyy or dddd, mmmm d, yyyy; times with
+ /// format=time and a code such as h:mm AM/PM.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub number_format: Option<String>,
/// Exact Excel font name, up to 128 characters.
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 8d87e01ef5..c94e2deeee 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -375,10 +375,20 @@ Formula references to mention cells use literal labels, never execute a label as
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.
+Excel export writes a dated number rather than the label. Typing a date stores it
+as a date in a matching format: `01/2026` or `Jan 2026` shows `Jan 2026`,
+`Jan 01 2026` shows `Jan 01, 2026`, `2026-01-01` stays ISO and `1/1/26` shows
+`1/1/2026` (day first in day-first browser locales). The snapshot value is the
+serial (`46023`) with `format: 'date'` and a `numberFormat` such as `mmm yyyy`;
+the formula bar and cell editor show `1/1/2026`. A cell already formatted as a
+date keeps its format, and text without a year (`Jan 26`, `1/2`) stays text.
+`=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. **Number format → Date
+formats** lists presets (`Sep 2026`, `Sep 17, 2026`, `09/17/2026`, `17/09/2026`,
+`2026-09-17`, `17 Sep 2026`, `Thursday, September 17, 2026`) and **Custom date and
+time…**, a dialog with a **Format code** field, a live `Preview:` status of the
+active cell, and **Apply** (disabled for codes that are not dates or times).
CSV imports a file up to 20 MB into the selection, adding rows if needed within the
100,000 × 16,384 limit. Existing cells in that rectangle
@@ -532,6 +542,8 @@ formulas, typed results, errors, and formatting. **CalculateSpreadsheet** evalua
scratch formulas and what-if inputs without changing the workbook.
**EditSpreadsheet** applies a validated batch of cell/formula/format edits, fill,
row additions, column resizing, and sheet creation/rename/duplication/deletion.
+`format_cells` shows dates in any Excel date code with
+`{ "format": "date", "numberFormat": "mmm yyyy" }`.
Edits require a revision from a fresh read; a concurrent change rejects the entire
batch so the AI can reread. Tool rows expand to show the actual results and warnings.
diff --git a/packages/spreadsheet/src/ai-formatting.test.ts b/packages/spreadsheet/src/ai-formatting.test.ts
index fc53d4eb76..70f12ceb3d 100644
--- a/packages/spreadsheet/src/ai-formatting.test.ts
+++ b/packages/spreadsheet/src/ai-formatting.test.ts
@@ -168,4 +168,57 @@ describe('AI formatting preserves spreadsheet values', () => {
doc.free();
}
});
+
+ it('shows dates in the Excel date code a format operation gives', () => {
+ const doc = new LoroDoc();
+ try {
+ doc.getMap('spreadsheetMeta').set('formatVersion', 1);
+ writeSpreadsheetCells(doc, {
+ A1: { value: '1/1/2026' },
+ A2: { value: '=DATE(2026,9,17)' },
+ A3: { value: '46023' },
+ });
+ const prepared = prepareSpreadsheetEdit(
+ doc,
+ {
+ action: 'edit',
+ expectedRevision: 'v',
+ operations: [
+ {
+ type: 'format_cells',
+ sheetId: 'sheet1',
+ range: 'A1:A2',
+ style: { format: 'date', numberFormat: 'mmm yyyy' },
+ },
+ {
+ type: 'format_cells',
+ sheetId: 'sheet1',
+ range: 'A3',
+ style: { format: 'date', numberFormat: 'dddd, mmmm d, yyyy' },
+ },
+ ],
+ },
+ calculator
+ );
+ doc.import(prepared.update);
+ expect(readSpreadsheetCells(doc).A1).toEqual({
+ value: '1/1/2026',
+ format: 'date',
+ numberFormat: 'mmm yyyy',
+ });
+ const result = readSpreadsheetForAi(
+ doc,
+ 'v',
+ { action: 'read', ranges: ['A1:A3'], includeStyles: true },
+ calculator
+ );
+ expect(result.ranges[0].cells.map(({ display }) => display)).toEqual([
+ 'Jan 2026',
+ 'Sep 2026',
+ 'Thursday, January 1, 2026',
+ ]);
+ } finally {
+ doc.free();
+ }
+ });
});
diff --git a/packages/spreadsheet/src/calculation.ts b/packages/spreadsheet/src/calculation.ts
index 6e0b66bb2b..dcba7433e2 100644
--- a/packages/spreadsheet/src/calculation.ts
+++ b/packages/spreadsheet/src/calculation.ts
@@ -925,8 +925,10 @@ function enterCell(
}
}
if (!enteredArray) model.setUserInput(sheetIndex, row + 1, column + 1, input);
- // A date pill is a date value: formulas referencing it inherit the format.
- if (dateMention) model.updateRangeStyle(area, 'num_fmt', 'm/d/yyyy');
+ // A date pill or a number formatted as a date is a date value: formulas
+ // referencing it inherit the format.
+ if (dateMention || (cell.format === 'date' && numericLiteral.test(value)))
+ model.updateRangeStyle(area, 'num_fmt', 'm/d/yyyy');
// Typed exponents get a 3-digit scientific format that formulas would
// inherit; numeric literals never need an inferred display format.
else if (!literal && /e/i.test(value) && numericLiteral.test(value))