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.

63.7 KB
Raw Blame
import {
  cleanup,
  fireEvent,
  render,
  screen,
  waitFor,
} from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
import { createSignal, onMount } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CellMentionEditor } from '../../../components/cell-text-editor/CellMentionEditor';
import type { DatabaseMention } from '../core/column-inference';
import type {
  DatabaseCellValue,
  DatabaseViewColumn,
} from '../core/database-view';
import type { GridCellControl } from '../core/grid-cell-editor';
import {
  type DatabaseMentionPickerProps,
  type DatabaseTextEditorProps,
  GridCell,
} from './grid-cell';

// JSDOM has no intersection observer to drive the date selector's focus.
vi.mock('@property/utils/focus', () => ({
  // Like the real helper, focus after the menu has taken focus on open.
  useSearchInputFocus: (input: () => HTMLElement | undefined) =>
    setTimeout(() => input()?.focus(), 100),
  useAutoFocus: (element: () => HTMLElement | undefined) =>
    setTimeout(() => element()?.focus(), 100),
}));

const column: DatabaseViewColumn = {
  id: 'name',
  name: 'Name',
  dataType: 'STRING',
  options: [],
  isMultiSelect: false,
  writable: true,
};
beforeEach(() => {
  const style = document.createElement('style');
  style.textContent =
    '[role="menu"], [role="dialog"] { animation-name: none; }';
  document.head.append(style);
  vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
  Element.prototype.scrollIntoView = vi.fn();
});
afterEach(() => {
  cleanup();
  document.head.querySelectorAll('style').forEach((style) => style.remove());
  vi.restoreAllMocks();
});

const mention: DatabaseMention = {
  id: 'user-1',
  entityType: 'USER',
  label: 'Maya',
};
function MentionPicker(props: DatabaseMentionPickerProps) {
  let input!: HTMLInputElement;
  onMount(() => input.focus());
  return (
    <div role="dialog" aria-label="Choose linked item">
      <input
        ref={input}
        aria-label="Find an item"
        value={props.search}
        onInput={(event) => props.onSearchChange?.(event.currentTarget.value)}
        onKeyDown={(event) => {
          event.stopPropagation();
          if (event.key === 'Escape') {
            event.preventDefault();
            props.onClose();
          }
          if (event.key === 'Enter' || event.key === 'Tab') {
            event.preventDefault();
            props.onSelect(
              mention,
              event.key === 'Tab' ? (event.shiftKey ? -1 : 1) : undefined
            );
          }
        }}
      />
    </div>
  );
}

describe('grid cell', () => {
  it.each([true, false])(
    'preserves inline editor bounds only when requested (%s)',
    async (preserveSize) => {
      let width = 54;
      vi.spyOn(
        HTMLButtonElement.prototype,
        'getBoundingClientRect'
      ).mockImplementation(() => new DOMRect(0, 0, width, 24));
      const { container } = render(() => (
        <GridCell
          column={column}
          value="Original"
          canEdit
          preserveSize={preserveSize}
          onWrite={vi.fn(async () => true)}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      const cell = container.firstElementChild as HTMLDivElement;
      fireEvent.click(screen.getByRole('button', { name: /Name: Original/ }));
      expect(cell.style.width).toBe(preserveSize ? '54px' : '');
      expect(cell.style.height).toBe(preserveSize ? '24px' : '');
      fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' });
      await waitFor(() => expect(cell.style.width).toBe(''));
      expect(cell.style.height).toBe('');
      width = 72;
      fireEvent.keyDown(
        screen.getByRole('button', { name: /Name: Original/ }),
        {
          key: 'F2',
        }
      );
      expect(cell.style.width).toBe(preserveSize ? '72px' : '');
      fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' });
    }
  );
  it('keeps the active text editor and draft when an earlier save infers the column type', () => {
    const [schema, setSchema] = createSignal({ ...column, inferType: true });
    const onWrite = vi.fn(async () => true);
    const onNavigate = vi.fn(() => true);
    render(() => (
      <GridCell
        column={schema()}
        value={null}
        canEdit
        renderTextEditor={(props) => (
          <CellMentionEditor
            {...props}
            convertPaste={(text) => text}
            renderMenu={() => null}
          />
        )}
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onNavigate={onNavigate}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));
    const editor = screen.getByRole('textbox', { name: 'Edit Name' });
    editor.textContent = '456';
    fireEvent.input(editor);
    setSchema({ ...column, dataType: 'NUMBER', inferType: false });
    expect(screen.getByRole('textbox', { name: 'Edit Name' })).toBe(editor);
    expect(document.activeElement).toBe(editor);
    expect(editor.textContent).toBe('456');
    fireEvent.keyDown(editor, { key: 'Tab' });
    expect(onWrite).toHaveBeenCalledExactlyOnceWith(456);
    expect(onNavigate).toHaveBeenCalledExactlyOnceWith(1);
  });
  it.each(['STRING', 'NUMBER', 'BOOLEAN', 'SELECT_STRING'] as const)(
    'clears a selected %s cell with either Delete key',
    async (dataType) => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={{
            ...column,
            dataType,
            options: [{ id: 'open', label: 'Open', color: null }],
          }}
          value={
            dataType === 'STRING' || dataType === 'SELECT_STRING' ? 'Open' : 12
          }
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      const trigger =
        dataType === 'BOOLEAN'
          ? screen.getByRole('checkbox')
          : screen.getByRole('button');
      trigger.focus();
      for (const key of ['Delete', 'Backspace']) {
        fireEvent.keyDown(trigger, { key });
        await waitFor(() => expect(onWrite).toHaveBeenLastCalledWith(null));
      }
      expect(onWrite).toHaveBeenCalledTimes(2);
      expect(screen.queryByRole('textbox')).toBeNull();
    }
  );

  it('keeps an empty cell visually blank when the host supplies no placeholder', () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value={null}
        emptyLabel=""
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    const cell = screen.getByRole('button', {
      name: 'Name: Empty. Click to edit',
    });
    expect(cell.textContent).toBe('');
    fireEvent.click(cell);
    const input = screen.getByRole('textbox', {
      name: 'Edit Name',
    }) as HTMLInputElement;
    expect(input.placeholder).toBe('');
    fireEvent.keyDown(input, { key: 'Enter' });
    expect(onWrite).not.toHaveBeenCalled();
  });
  it.each(['STRING', 'SELECT_STRING'] as const)(
    'lets Tab leave a %s editor at a grid boundary',
    async (dataType) => {
      let control: GridCellControl | undefined;
      render(() => (
        <>
          <button type="button">Before grid</button>
          <GridCell
            column={{
              ...column,
              dataType,
              options: [
                { id: 'original', label: 'Original', color: null },
                { id: 'done', label: 'Done', color: null },
              ],
            }}
            value="Original"
            canEdit
            onWrite={vi.fn(async () => true)}
            onAddOption={vi.fn(async () => true)}
            onReady={(ready) => {
              control = ready;
            }}
            onNavigate={() => false}
          />
          <button type="button">After grid</button>
        </>
      ));
      control?.edit();
      if (dataType === 'SELECT_STRING') {
        const search = await screen.findByRole('combobox', {
          name: 'Search Name options',
        });
        await waitFor(() => expect(document.activeElement).toBe(search));
      }
      await userEvent.tab();
      await waitFor(() =>
        expect(document.activeElement).toBe(
          screen.getByRole('button', { name: 'After grid' })
        )
      );
      control?.edit();
      if (dataType === 'SELECT_STRING') {
        const search = await screen.findByRole('combobox', {
          name: 'Search Name options',
        });
        await waitFor(() => expect(document.activeElement).toBe(search));
      }
      await userEvent.tab({ shift: true });
      await waitFor(() =>
        expect(document.activeElement).toBe(
          screen.getByRole('button', { name: 'Before grid' })
        )
      );
    }
  );

  it('toggles the shared checkbox with pointer and keyboard and keeps grid Tab navigation', async () => {
    const [value, setValue] = createSignal<DatabaseCellValue>(0);
    const write = vi.fn(async (next: DatabaseCellValue) => {
      setValue(next);
      return true;
    });
    const navigate = vi.fn(() => true);
    let control: GridCellControl | undefined;
    render(() => (
      <GridCell
        column={{ ...column, dataType: 'BOOLEAN' }}
        value={value()}
        canEdit
        onWrite={write}
        onNavigate={navigate}
        onAddOption={vi.fn(async () => true)}
        onReady={(ready) => {
          control = ready;
        }}
      />
    ));
    const checkbox = screen.getByRole('checkbox', {
      name: 'Name',
    }) as HTMLInputElement;
    await userEvent.click(screen.getByText('Name', { selector: 'label' }));
    expect(write).toHaveBeenLastCalledWith(1);
    expect(checkbox.checked).toBe(true);
    control?.focus();
    expect(document.activeElement).toBe(checkbox);
    await userEvent.keyboard(' ');
    expect(write).toHaveBeenLastCalledWith(0);
    expect(checkbox.checked).toBe(false);
    await userEvent.tab();
    expect(navigate).toHaveBeenCalledWith(1);
  });

  it('focuses the read-only boolean wrapper without enabling its checkbox', async () => {
    let control: GridCellControl | undefined;
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, dataType: 'BOOLEAN' }}
        value={1}
        canEdit={false}
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onReady={(ready) => {
          control = ready;
        }}
      />
    ));
    const checkbox = screen.getByRole('checkbox') as HTMLInputElement;
    await userEvent.click(screen.getByText('Name', { selector: 'label' }));
    control?.focus();
    expect(checkbox.disabled).toBe(true);
    expect(checkbox.readOnly).toBe(true);
    expect(document.activeElement).toBe(checkbox.parentElement);
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('shows the host empty label for an unset read-only select', () => {
    const [value, setValue] = createSignal<DatabaseCellValue>(null);
    render(() => (
      <GridCell
        column={{
          ...column,
          dataType: 'SELECT_STRING',
          options: [{ id: 'open', label: 'Open', color: null }],
        }}
        value={value()}
        emptyLabel="—"
        canEdit={false}
        onWrite={vi.fn(async () => true)}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    expect(screen.getByText('—')).toBeTruthy();
    setValue('Open');
    expect(screen.queryByText('—')).toBeNull();
    expect(screen.getByText('Open')).toBeTruthy();
  });

  it.each([true, false])(
    'distinguishes an unset boolean from false with a host empty label (editable: %s)',
    async (canEdit) => {
      const [value, setValue] = createSignal<DatabaseCellValue>(null);
      const onWrite = vi.fn(async (next: DatabaseCellValue) => {
        setValue(next);
        return true;
      });
      render(() => (
        <GridCell
          column={{ ...column, dataType: 'BOOLEAN' }}
          value={value()}
          emptyLabel="—"
          canEdit={canEdit}
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      const checkbox = screen.getByRole('checkbox') as HTMLInputElement;
      expect(screen.getByText('—')).toBeTruthy();
      expect(checkbox.indeterminate).toBe(true);
      if (canEdit) {
        await userEvent.click(screen.getByText('—'));
        expect(onWrite).toHaveBeenLastCalledWith(1);
        expect(checkbox.checked).toBe(true);
      }
      setValue(0);
      expect(screen.queryByText('—')).toBeNull();
      expect(checkbox.checked).toBe(false);
      expect(checkbox.indeterminate).toBe(false);
      setValue(1);
      expect(checkbox.checked).toBe(true);
      expect(checkbox.indeterminate).toBe(false);
    }
  );

  it('shows Unnamed for an empty title without saving placeholder text', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value={null}
        emptyLabel="Unnamed"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    const button = screen.getByRole('button', {
      name: 'Name: Unnamed. Click to edit',
    });
    expect(button.textContent).toBe('Unnamed');
    fireEvent.click(button);
    const input = screen.getByRole('textbox', {
      name: 'Edit Name',
    }) as HTMLInputElement;
    expect(input.value).toBe('');
    expect(input.placeholder).toBe('Unnamed');
    fireEvent.keyDown(input, { key: 'Enter' });
    await Promise.resolve();
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('opens an inferred text mention without a blur write and restores its search draft on Escape', async () => {
    const onWrite = vi.fn(async () => true);
    const onMention = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, inferType: true }}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
      />
    ));
    const button = screen.getByRole('button', { name: /Name: Empty/ });
    button.focus();
    fireEvent.keyDown(button, { key: '@' });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    await waitFor(() => expect(document.activeElement).toBe(search));
    fireEvent.input(search, { target: { value: 'Maya' } });
    expect(onWrite).not.toHaveBeenCalled();
    await userEvent.keyboard('{Escape}');
    const draft = screen.getByRole('textbox', {
      name: 'Edit Name',
    }) as HTMLInputElement;
    await waitFor(() => expect(document.activeElement).toBe(draft));
    expect(draft.value).toBe('@Maya');
    expect(screen.queryByRole('dialog')).toBeNull();
    expect(onWrite).not.toHaveBeenCalled();
    expect(onMention).not.toHaveBeenCalled();
    await userEvent.keyboard('{Escape}');
    expect(screen.queryByRole('textbox')).toBeNull();
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('never blur-saves the raw @ draft after a native first-mention selection', async () => {
    const onWrite = vi.fn(async () => true);
    const onMention = vi.fn(async () => true);
    let editor: DatabaseTextEditorProps | undefined;
    render(() => (
      <GridCell
        column={{ ...column, inferType: true }}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionPicker={() => null}
        renderTextEditor={(props) => {
          editor = props;
          return (
            <input
              aria-label={props.label}
              value={props.value}
              onInput={(event) => props.onInput(event.currentTarget.value)}
            />
          );
        }}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));
    fireEvent.input(screen.getByRole('textbox', { name: 'Edit Name' }), {
      target: { value: '@Maya' },
    });
    editor?.onInferMention?.(mention);
    editor?.onBlur();
    await waitFor(() =>
      expect(onMention).toHaveBeenCalledExactlyOnceWith(mention)
    );
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('adds and removes multi-select members while preserving the other selections', async () => {
    const write = vi.fn(
      async (value: DatabaseCellValue) => value !== undefined
    );
    render(() => {
      const [value, setValue] = createSignal<DatabaseCellValue>('["Alpha"]');
      return (
        <GridCell
          column={{
            ...column,
            name: 'Labels',
            dataType: 'SELECT_STRING',
            isMultiSelect: true,
            options: [
              { id: 'alpha', label: 'Alpha', color: null },
              { id: 'beta', label: 'Beta', color: null },
            ],
          }}
          value={value()}
          canEdit
          onAddOption={vi.fn(async () => true)}
          onWrite={async (next) => {
            setValue(next);
            return write(next);
          }}
        />
      );
    });
    await userEvent.click(
      screen.getByRole('button', { name: /Labels: Alpha/ })
    );
    expect(
      screen
        .getByRole('listbox', { name: 'Labels options' })
        .getAttribute('aria-multiselectable')
    ).toBe('true');
    await userEvent.click(await screen.findByRole('option', { name: 'Beta' }));
    await waitFor(() =>
      expect(write).toHaveBeenLastCalledWith('["Alpha","Beta"]')
    );
    expect(
      screen.getByRole('option', { name: 'Beta' }).getAttribute('aria-selected')
    ).toBe('true');
    await userEvent.click(screen.getByRole('option', { name: 'Alpha' }));
    await waitFor(() => expect(write).toHaveBeenLastCalledWith('["Beta"]'));
    expect(
      screen
        .getByRole('option', { name: 'Alpha' })
        .getAttribute('aria-selected')
    ).toBe('false');
    await userEvent.click(screen.getByRole('option', { name: 'Beta' }));
    await waitFor(() => expect(write).toHaveBeenLastCalledWith(null));
    expect(
      screen.getByRole('listbox', { name: 'Labels options' })
    ).toBeTruthy();
  });

  it('keeps explicit text columns as literal text when @ is typed', async () => {
    const onWrite = vi.fn(async () => true);
    const picker = vi.fn((props: DatabaseMentionPickerProps) => (
      <MentionPicker {...props} />
    ));
    render(() => (
      <GridCell
        column={{ ...column, inferType: false }}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={vi.fn(async () => true)}
        renderMentionPicker={picker}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const input = screen.getByRole('textbox', { name: 'Edit Name' });
    fireEvent.input(input, { target: { value: '@Maya' } });
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() =>
      expect(onWrite).toHaveBeenCalledExactlyOnceWith('@Maya')
    );
    expect(picker).not.toHaveBeenCalled();
  });

  it('keeps focus on the clicked control when the mention picker closes from outside', async () => {
    let picker: DatabaseMentionPickerProps | undefined;
    const onWrite = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={{ ...column, inferType: true }}
          value={null}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onMention={vi.fn(async () => true)}
          renderMentionPicker={(props) => {
            picker = props;
            return <MentionPicker {...props} />;
          }}
        />
        <button type="button" onClick={() => picker?.onClose(false)}>
          Another cell
        </button>
      </>
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    fireEvent.input(search, { target: { value: 'Maya' } });
    const another = screen.getByRole('button', { name: 'Another cell' });
    await userEvent.click(another);
    expect(document.activeElement).toBe(another);
    expect(screen.queryByRole('dialog')).toBeNull();
    expect(
      (screen.getByRole('textbox', { name: 'Edit Name' }) as HTMLInputElement)
        .value
    ).toBe('@Maya');
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('selects a mention with Tab and immediately edits the next field without saving raw text', async () => {
    const onWrite = vi.fn(async () => true);
    const onMention = vi.fn(async () => true);
    let next: GridCellControl | undefined;
    render(() => (
      <>
        <GridCell
          column={{ ...column, inferType: true }}
          value={null}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onMention={onMention}
          renderMentionPicker={(props) => <MentionPicker {...props} />}
          onNavigate={(direction) => {
            if (direction !== 1) return false;
            next?.edit();
            return true;
          }}
        />
        <GridCell
          column={{ ...column, id: 'notes', name: 'Notes' }}
          value={null}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onReady={(ready) => {
            next = ready;
          }}
        />
      </>
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    search.focus();
    await userEvent.tab();
    const input = await screen.findByRole('textbox', { name: 'Edit Notes' });
    await waitFor(() => expect(document.activeElement).toBe(input));
    expect(onMention).toHaveBeenCalledExactlyOnceWith(mention);
    expect(onWrite).not.toHaveBeenCalled();
    expect(screen.queryByRole('dialog')).toBeNull();
  });

  it('renders an entity label, opens its picker, cancels unchanged and clears with Delete', async () => {
    const onWrite = vi.fn(async () => true);
    const onMention = vi.fn(async () => true);
    const renderValue = vi.fn(() => <span>Maya</span>);
    render(() => (
      <GridCell
        column={{ ...column, dataType: 'ENTITY', specificEntityType: 'USER' }}
        value="user-1"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionValue={renderValue}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
      />
    ));
    const button = screen.getByRole('button', {
      name: 'Name: Maya',
    });
    expect(button.textContent).toBe('Name: Maya');
    expect(button.getAttribute('aria-description')).toBe('Click to edit');
    expect(button.title).toBe('');
    expect(renderValue).toHaveBeenCalledWith('user-1', 'USER');
    fireEvent.click(button);
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    search.focus();
    await userEvent.keyboard('{Escape}');
    await waitFor(() =>
      expect(document.activeElement).toBe(
        screen.getByRole('button', { name: 'Name: Maya' })
      )
    );
    expect(onWrite).not.toHaveBeenCalled();
    expect(onMention).not.toHaveBeenCalled();
    await userEvent.keyboard('{Delete}');
    expect(onWrite).toHaveBeenCalledExactlyOnceWith(null);
  });

  it('opens an entity it is given an opener for on click and Enter, and still edits with F2', async () => {
    const onOpenMention = vi.fn();
    const onWrite = vi.fn(async () => true);
    const [value, setValue] = createSignal<DatabaseCellValue>('company-1');
    render(() => (
      <GridCell
        column={{
          ...column,
          name: 'Company',
          dataType: 'ENTITY',
          specificEntityType: 'COMPANY',
        }}
        value={value()}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={vi.fn(async () => true)}
        onOpenMention={onOpenMention}
        renderMentionValue={() => <span>Acme</span>}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
      />
    ));
    const button = screen.getByRole('button', { name: 'Company: Acme' });
    expect(button.getAttribute('aria-description')).toBe('Click to open');
    fireEvent.click(button);
    expect(onOpenMention).toHaveBeenLastCalledWith('company-1', 'COMPANY');
    expect(screen.queryByRole('dialog')).toBeNull();
    fireEvent.keyDown(button, { key: 'Enter' });
    expect(onOpenMention).toHaveBeenCalledTimes(2);
    expect(screen.queryByRole('dialog')).toBeNull();
    fireEvent.keyDown(button, { key: 'F2' });
    await screen.findByRole('textbox', { name: 'Find an item' });
    await userEvent.keyboard('{Escape}');
    await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
    // An empty cell has nothing to open, so a click picks one.
    setValue(null);
    fireEvent.click(screen.getByRole('button', { name: /Company: Empty/ }));
    await screen.findByRole('textbox', { name: 'Find an item' });
    expect(onOpenMention).toHaveBeenCalledTimes(2);
    expect(onWrite).not.toHaveBeenCalled();
  });

  it.each([true, false])(
    'right-click changes an openable reference only when editable (%s)',
    async (canEdit) => {
      const onOpenMention = vi.fn();
      const onMention = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={{
            ...column,
            name: 'File',
            dataType: 'ENTITY',
            specificEntityType: 'DOCUMENT',
          }}
          value="project-plan"
          canEdit={canEdit}
          onWrite={vi.fn(async () => true)}
          onAddOption={vi.fn(async () => true)}
          onOpenMention={onOpenMention}
          onMention={onMention}
          renderMentionValue={() => <span>Project plan</span>}
          renderMentionPicker={(props) => <MentionPicker {...props} />}
        />
      ));
      const button = screen.getByRole('button', { name: 'File: Project plan' });
      fireEvent.contextMenu(button);
      expect(onOpenMention).not.toHaveBeenCalled();
      if (canEdit) {
        await screen.findByRole('textbox', { name: 'Find an item' });
        await userEvent.keyboard('{Escape}');
        await waitFor(() => expect(document.activeElement).toBe(button));
        expect(onMention).not.toHaveBeenCalled();
      } else {
        expect(screen.queryByRole('dialog')).toBeNull();
        fireEvent.click(button);
        expect(onOpenMention).toHaveBeenCalledExactlyOnceWith(
          'project-plan',
          'DOCUMENT'
        );
      }
    }
  );

  it('keeps the selected label through a delayed write and hands it to the entity renderer when the schema arrives', async () => {
    const [value, setValue] = createSignal<DatabaseCellValue>(null);
    const [schema, setSchema] = createSignal<DatabaseViewColumn>({
      ...column,
      inferType: true,
    });
    let finishWrite!: () => void;
    const written = new Promise<void>((resolve) => {
      finishWrite = resolve;
    });
    const onMention = vi.fn(async (selected: DatabaseMention) => {
      await written;
      setValue(selected.id);
      return true;
    });
    render(() => (
      <GridCell
        column={schema()}
        value={value()}
        canEdit
        onWrite={vi.fn(async () => true)}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
        renderMentionValue={(id) => (
          <span>{id === mention.id ? 'Maya from cache' : 'Avery'}</span>
        )}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    fireEvent.keyDown(search, { key: 'Enter' });
    expect(screen.getByRole('button', { name: /Name: Maya/ }).textContent).toBe(
      'Maya'
    );
    expect(value()).toBeNull();
    finishWrite();
    await waitFor(() => expect(value()).toBe(mention.id));
    expect(screen.getByRole('button', { name: /Name: Maya/ }).textContent).toBe(
      'Maya'
    );
    setSchema({
      ...column,
      dataType: 'ENTITY',
      specificEntityType: 'USER',
    });
    expect(
      screen.getByRole('button', { name: 'Name: Maya from cache' }).textContent
    ).toBe('Name: Maya from cache');
    setValue('user-2');
    expect(
      screen.getByRole('button', { name: 'Name: Avery' }).textContent
    ).toBe('Name: Avery');
  });

  it('exposes the full resolved mention name to assistive technology in read-only cells', () => {
    const [label, setLabel] = createSignal('Person');
    render(() => (
      <GridCell
        column={{
          ...column,
          name: 'Owner',
          dataType: 'ENTITY',
          specificEntityType: 'USER',
        }}
        value="user-1"
        canEdit={false}
        onWrite={vi.fn(async () => true)}
        onAddOption={vi.fn(async () => true)}
        renderMentionValue={() => <span class="truncate">{label()}</span>}
      />
    ));
    const button = screen.getByRole('button', { name: 'Owner: Person' });
    setLabel('[email protected]');
    expect(
      screen.getByRole('button', {
        name: 'Owner: [email protected]',
      })
    ).toBe(button);
    expect(button.getAttribute('aria-description')).toBeNull();
    expect(screen.getAllByRole('button')).toHaveLength(1);
    expect(screen.queryByRole('link')).toBeNull();
  });

  it('keeps a failed mention draft readable and clears its label when the cell value changes', async () => {
    const [value, setValue] = createSignal<DatabaseCellValue>(null);
    const onMention = vi.fn(async (selected: DatabaseMention) => {
      setValue(selected.id);
      return false;
    });
    render(() => (
      <GridCell
        column={{ ...column, inferType: true }}
        value={value()}
        canEdit
        onWrite={vi.fn(async () => true)}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    fireEvent.keyDown(search, { key: 'Enter' });
    await waitFor(() => expect(onMention).toHaveResolvedWith(false));
    expect(screen.getByRole('button', { name: /Name: Maya/ }).textContent).toBe(
      'Maya'
    );
    setValue(null);
    expect(
      screen.getByRole('button', { name: /Name: Empty/ }).textContent
    ).toBe('—');
    setValue('Avery');
    expect(
      screen.getByRole('button', { name: /Name: Avery/ }).textContent
    ).toBe('Avery');
    expect(screen.queryByText('Maya')).toBeNull();
  });

  it('lets a new text edit replace a failed mention before its value is acknowledged', async () => {
    const onMention = vi.fn(async () => false);
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, inferType: true }}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
        onMention={onMention}
        renderMentionPicker={(props) => <MentionPicker {...props} />}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: '@',
    });
    const search = await screen.findByRole('textbox', { name: 'Find an item' });
    fireEvent.keyDown(search, { key: 'Enter' });
    await waitFor(() => expect(onMention).toHaveResolvedWith(false));
    const button = screen.getByRole('button', { name: /Name: Maya/ });
    expect(button.textContent).toBe('Maya');
    fireEvent.keyDown(button, { key: 'A' });
    const input = screen.getByRole('textbox', { name: 'Edit Name' });
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() => expect(onWrite).toHaveBeenCalledExactlyOnceWith('A'));
    expect(screen.queryByText('Maya')).toBeNull();
  });

  it('starts typing with the pressed character and saves a one-character replacement', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value="Original"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    const cell = screen.getByRole('button', { name: /Name: Original/ });
    cell.focus();
    fireEvent.keyDown(cell, { key: 'A' });
    const input = screen.getByRole('textbox', {
      name: 'Edit Name',
    }) as HTMLInputElement;
    expect(input.value).toBe('A');
    expect(document.activeElement).toBe(input);
    expect(input.selectionStart).toBe(1);
    expect(input.selectionEnd).toBe(1);
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() => expect(onWrite).toHaveBeenCalledExactlyOnceWith('A'));
  });

  it('commits Tab and Shift+Tab directly into the adjacent editor', async () => {
    const onWrite = vi.fn(async () => true);
    let first: GridCellControl | undefined;
    let next: GridCellControl | undefined;
    render(() => (
      <>
        <GridCell
          column={column}
          value="Original"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onReady={(control) => {
            first = control;
          }}
          onNavigate={(direction) => {
            if (direction !== 1 || !next) return false;
            next.edit();
            return true;
          }}
        />
        <GridCell
          column={{ ...column, id: 'notes', name: 'Notes' }}
          value="Old notes"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onReady={(control) => {
            next = control;
          }}
          onNavigate={(direction) => {
            if (direction !== -1 || !first) return false;
            first.edit();
            return true;
          }}
        />
      </>
    ));
    first?.edit('A');
    fireEvent.keyDown(screen.getByRole('textbox', { name: 'Edit Name' }), {
      key: 'Tab',
    });
    const notes = screen.getByRole('textbox', {
      name: 'Edit Notes',
    }) as HTMLInputElement;
    expect(document.activeElement).toBe(notes);
    expect(notes.selectionEnd).toBe(notes.value.length);
    await waitFor(() => expect(onWrite).toHaveBeenCalledExactlyOnceWith('A'));
    fireEvent.input(notes, { target: { value: 'New notes' } });
    fireEvent.keyDown(notes, { key: 'Tab', shiftKey: true });
    expect(document.activeElement).toBe(
      screen.getByRole('textbox', { name: 'Edit Name' })
    );
    await waitFor(() => expect(onWrite).toHaveBeenLastCalledWith('New notes'));
  });

  it('does not commit or cancel while an IME is composing', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: /Name: Empty/ }), {
      key: 'Process',
      isComposing: true,
    });
    const input = screen.getByRole('textbox', { name: 'Edit Name' });
    fireEvent.input(input, { target: { value: '企画' } });
    fireEvent.keyDown(input, { key: 'Enter', isComposing: true });
    fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 });
    fireEvent.keyDown(input, { key: 'Escape', isComposing: true });
    expect(onWrite).not.toHaveBeenCalled();
    expect(screen.getByRole('textbox', { name: 'Edit Name' })).toBe(input);
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() =>
      expect(onWrite).toHaveBeenCalledExactlyOnceWith('企画')
    );
  });

  it.each([1, -1] as const)(
    'lets Tab leave an invalid number in direction %s without saving',
    async (direction) => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <>
          <button type="button">Before grid</button>
          <GridCell
            column={{ ...column, dataType: 'NUMBER' }}
            value={12}
            canEdit
            onWrite={onWrite}
            onAddOption={vi.fn(async () => true)}
          />
          <button type="button">After grid</button>
        </>
      ));
      fireEvent.keyDown(screen.getByRole('button', { name: /Name: 12/ }), {
        key: 'x',
      });
      const input = screen.getByRole('textbox', { name: 'Edit Name' });
      await userEvent.tab({ shift: direction === -1 });
      expect(document.activeElement).toBe(
        screen.getByRole('button', {
          name: direction === -1 ? 'Before grid' : 'After grid',
        })
      );
      expect(screen.queryByRole('alert')).toBeNull();
      expect(input.getAttribute('aria-invalid')).toBe('true');
      expect((input as HTMLInputElement).value).toBe('x');
      expect(onWrite).not.toHaveBeenCalled();
    }
  );

  it('hides validation on blur but keeps the draft invalid and allows another field to save', async () => {
    const writeNumber = vi.fn(async () => true);
    const writeNotes = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={{ ...column, dataType: 'NUMBER' }}
          value={12}
          canEdit
          onWrite={writeNumber}
          onAddOption={vi.fn(async () => true)}
        />
        <GridCell
          column={{ ...column, id: 'notes', name: 'Notes' }}
          value="Original"
          canEdit
          onWrite={writeNotes}
          onAddOption={vi.fn(async () => true)}
        />
      </>
    ));
    await userEvent.click(screen.getByRole('button', { name: /Name: 12/ }));
    const input = screen.getByRole('textbox', {
      name: 'Edit Name',
    }) as HTMLInputElement;
    fireEvent.input(input, { target: { value: 'invalid' } });
    fireEvent.keyDown(input, { key: 'Enter' });
    expect(screen.getByRole('alert').textContent).toBe('Enter a valid number');
    expect(input.getAttribute('aria-invalid')).toBe('true');
    await userEvent.click(
      screen.getByRole('button', { name: /Notes: Original/ })
    );
    const notes = screen.getByRole('textbox', { name: 'Edit Notes' });
    expect(document.activeElement).toBe(notes);
    expect(screen.queryByRole('alert')).toBeNull();
    expect(input.value).toBe('invalid');
    expect(input.getAttribute('aria-invalid')).toBe('true');
    expect(
      document.getElementById(input.getAttribute('aria-errormessage')!)
        ?.textContent
    ).toBe('Enter a valid number');
    fireEvent.input(notes, { target: { value: 'Updated notes' } });
    fireEvent.keyDown(notes, { key: 'Enter' });
    await waitFor(() =>
      expect(writeNotes).toHaveBeenCalledExactlyOnceWith('Updated notes')
    );
    expect(writeNumber).not.toHaveBeenCalled();
    await userEvent.click(input);
    expect(screen.getByRole('alert').textContent).toBe('Enter a valid number');
    fireEvent.input(input, { target: { value: 'still invalid' } });
    expect(input.getAttribute('aria-invalid')).toBe('true');
    fireEvent.input(input, { target: { value: '24' } });
    expect(input.getAttribute('aria-invalid')).toBe('false');
    expect(screen.queryByRole('alert')).toBeNull();
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() =>
      expect(writeNumber).toHaveBeenCalledExactlyOnceWith(24)
    );
  });

  it('validates on blur without reopening the hint or taking focus back', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={{ ...column, dataType: 'NUMBER' }}
          value={12}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
        <button type="button">Another control</button>
      </>
    ));
    await userEvent.click(screen.getByRole('button', { name: /Name: 12/ }));
    const input = screen.getByRole('textbox', { name: 'Edit Name' });
    fireEvent.input(input, { target: { value: 'invalid' } });
    const outside = screen.getByRole('button', { name: 'Another control' });
    await userEvent.click(outside);
    expect(document.activeElement).toBe(outside);
    expect(input.getAttribute('aria-invalid')).toBe('true');
    expect(screen.queryByRole('alert')).toBeNull();
    await userEvent.click(input);
    expect(screen.getByRole('alert').textContent).toBe('Enter a valid number');
    await userEvent.keyboard('{Escape}');
    expect(screen.queryByRole('textbox')).toBeNull();
    expect(screen.queryByRole('alert')).toBeNull();
    expect(onWrite).not.toHaveBeenCalled();
  });

  it.each(['Tab', 'ArrowDown', 'ArrowUp'])(
    'navigates from an invalid number to another grid editor with %s',
    async (key) => {
      const onWrite = vi.fn(async () => true);
      let next: GridCellControl | undefined;
      const navigate = vi.fn(() => {
        next?.edit();
        return Boolean(next);
      });
      render(() => (
        <>
          <GridCell
            column={{ ...column, dataType: 'NUMBER' }}
            value={12}
            canEdit
            onWrite={onWrite}
            onAddOption={vi.fn(async () => true)}
            onNavigate={navigate}
            onNavigateRow={navigate}
          />
          <GridCell
            column={{ ...column, id: 'notes', name: 'Notes' }}
            value="Original"
            canEdit
            onWrite={onWrite}
            onAddOption={vi.fn(async () => true)}
            onReady={(control) => {
              next = control;
            }}
          />
        </>
      ));
      fireEvent.keyDown(screen.getByRole('button', { name: /Name: 12/ }), {
        key: 'x',
      });
      const input = screen.getByRole('textbox', { name: 'Edit Name' });
      fireEvent.keyDown(input, { key });
      expect(navigate).toHaveBeenCalledWith(key === 'ArrowUp' ? -1 : 1);
      expect(document.activeElement).toBe(
        screen.getByRole('textbox', { name: 'Edit Notes' })
      );
      expect(input.getAttribute('aria-invalid')).toBe('true');
      expect(screen.queryByRole('alert')).toBeNull();
      expect(onWrite).not.toHaveBeenCalled();
    }
  );

  it.each(['9007199254740993', '-9007199254740993', '0x10', '1e309'])(
    'keeps the numeric draft %s instead of silently coercing it on save',
    (draft) => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={{ ...column, dataType: 'NUMBER' }}
          value={12}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      fireEvent.click(screen.getByRole('button', { name: /Name: 12/ }));
      const input = screen.getByRole('textbox', { name: 'Edit Name' });
      fireEvent.input(input, { target: { value: draft } });
      fireEvent.keyDown(input, { key: 'Enter' });
      expect(screen.getByRole('alert').textContent).toBe(
        'Enter a valid number'
      );
      expect(document.activeElement).toBe(input);
      expect((input as HTMLInputElement).value).toBe(draft);
      expect(onWrite).not.toHaveBeenCalled();
    }
  );

  it.each([
    ['9007199254740991', Number.MAX_SAFE_INTEGER],
    ['-12.5', -12.5],
    ['.75', 0.75],
    ['1.25e3', 1250],
  ])('saves the numeric draft %s without losing its value', (draft, value) => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, dataType: 'NUMBER' }}
        value={12}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: 12/ }));
    fireEvent.input(screen.getByRole('textbox', { name: 'Edit Name' }), {
      target: { value: draft },
    });
    fireEvent.keyDown(screen.getByRole('textbox', { name: 'Edit Name' }), {
      key: 'Enter',
    });
    expect(onWrite).toHaveBeenCalledExactlyOnceWith(value);
  });

  it('opens a select through its editor control and tabs directly to a text field', async () => {
    let select: GridCellControl | undefined;
    let next: GridCellControl | undefined;
    const onWrite = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={{
            ...column,
            id: 'status',
            name: 'Status',
            dataType: 'SELECT_STRING',
            options: [
              { id: 'to-do', label: 'To do', color: null },
              { id: 'done', label: 'Done', color: null },
            ],
          }}
          value="To do"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onReady={(control) => {
            select = control;
          }}
          onNavigate={() => {
            next?.edit();
            return true;
          }}
        />
        <GridCell
          column={column}
          value="Original"
          canEdit
          onWrite={vi.fn(async () => true)}
          onAddOption={vi.fn(async () => true)}
          onReady={(control) => {
            next = control;
          }}
        />
      </>
    ));
    select?.edit();
    const option = await screen.findByRole('option', { name: 'Done' });
    const search = screen.getByRole('combobox', {
      name: 'Search Status options',
    });
    await waitFor(() => expect(document.activeElement).toBe(search));
    // Clear value is a footer button; only To do and Done are list options.
    await userEvent.keyboard('{ArrowDown}{ArrowDown}');
    expect(search.getAttribute('aria-activedescendant')).toBe(option.id);
    expect(document.activeElement).toBe(search);
    await userEvent.tab();
    const input = await screen.findByRole('textbox', { name: 'Edit Name' });
    await waitFor(() => expect(document.activeElement).toBe(input));
    expect(
      screen
        .getByRole('button', { name: 'Status: To do' })
        .getAttribute('aria-expanded')
    ).toBe('false');
    expect(onWrite).toHaveBeenCalledExactlyOnceWith('Done');
  });

  it('saves a typed select match with Tab and sends ArrowDown to the matching choice', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={{
            ...column,
            dataType: 'SELECT_STRING',
            options: [
              { id: 'to-do', label: 'To do', color: null },
              { id: 'done', label: 'Done', color: null },
            ],
          }}
          value="To do"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onNavigate={() => false}
        />
        <button>After grid</button>
      </>
    ));
    screen.getByRole('button', { name: 'Name: To do' }).focus();
    await userEvent.keyboard('Done');
    const search = screen.getByRole('combobox', {
      name: 'Search Name options',
    }) as HTMLInputElement;
    expect(search.value).toBe('Done');
    expect(screen.getAllByRole('option').map((row) => row.textContent)).toEqual(
      ['Done']
    );
    await userEvent.keyboard('{ArrowDown}');
    expect(search.getAttribute('aria-activedescendant')).toBe(
      screen.getByRole('option', { name: 'Done' }).id
    );
    await userEvent.keyboard('{Escape}Done{Tab}');
    expect(onWrite).toHaveBeenCalledExactlyOnceWith('Done');
    await waitFor(() =>
      expect(document.activeElement).toBe(
        screen.getByRole('button', { name: 'After grid' })
      )
    );
  });

  it('filters select options from typed text and commits the matching option', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{
          ...column,
          name: 'Status',
          dataType: 'SELECT_STRING',
          options: [
            { id: 'to-do', label: 'To do', color: null },
            { id: 'done', label: 'Done', color: null },
          ],
        }}
        value="To do"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.keyDown(screen.getByRole('button', { name: 'Status: To do' }), {
      key: 'D',
    });
    const input = (await screen.findByRole('combobox', {
      name: 'Search Status options',
    })) as HTMLInputElement;
    expect(input.value).toBe('D');
    fireEvent.input(input, { target: { value: 'Done' } });
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() =>
      expect(onWrite).toHaveBeenCalledExactlyOnceWith('Done')
    );
  });

  it('opens the select picker again with an empty search after a pick', async () => {
    const onWrite = vi.fn(async () => true);
    const onAddOption = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{
          ...column,
          name: 'Going',
          dataType: 'SELECT_STRING',
          options: [
            { id: 'yes', label: 'Yes', color: null },
            { id: 'no', label: 'No', color: null },
          ],
        }}
        value={null}
        canEdit
        onWrite={onWrite}
        onAddOption={onAddOption}
      />
    ));
    await userEvent.click(screen.getByRole('button', { name: 'Going: Empty' }));
    const first = await screen.findByRole('combobox', {
      name: 'Search Going options',
    });
    await waitFor(() => expect(document.activeElement).toBe(first));
    await userEvent.keyboard('Yes{Enter}');
    await waitFor(() => expect(onWrite).toHaveBeenCalledExactlyOnceWith('Yes'));
    await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull());

    await userEvent.click(screen.getByRole('button', { name: 'Going: Empty' }));
    const second = (await screen.findByRole('combobox', {
      name: 'Search Going options',
    })) as HTMLInputElement;
    expect(second.value).toBe('');
    await waitFor(() => expect(document.activeElement).toBe(second));
    await userEvent.keyboard('Maybe');
    expect(second.value).toBe('Maybe');
    expect(screen.getByRole('option', { name: 'Create “Maybe”' })).toBeTruthy();
    expect(onAddOption).not.toHaveBeenCalled();
  });

  it('canonicalizes a new numeric option before saving its SQL label', async () => {
    const onAddOption = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{
          ...column,
          dataType: 'SELECT_NUMBER',
          options: [{ id: 'two', label: '2', color: null }],
        }}
        value="2"
        canEdit
        onWrite={vi.fn(async () => true)}
        onAddOption={onAddOption}
      />
    ));
    const trigger = screen.getByRole('button', { name: 'Name: 2' });
    trigger.focus();
    fireEvent.keyDown(trigger, { key: 'Enter' });
    const search = await screen.findByRole('combobox', {
      name: 'Search Name options',
    });
    fireEvent.input(search, { target: { value: '1.0' } });
    expect(screen.getByRole('option', { name: 'Create “1”' })).toBeTruthy();
    fireEvent.keyDown(search, { key: 'Enter' });
    await waitFor(() =>
      expect(onAddOption).toHaveBeenCalledExactlyOnceWith('1')
    );
  });

  it('creates a typed select option, closes the popover and returns focus to the cell', async () => {
    const onAddOption = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{
          ...column,
          dataType: 'SELECT_STRING',
          options: [
            { id: 'to-do', label: 'To do', color: null },
            { id: 'done', label: 'Done', color: null },
          ],
        }}
        value="To do"
        canEdit
        onWrite={vi.fn(async () => true)}
        onAddOption={onAddOption}
      />
    ));
    const trigger = screen.getByRole('button', { name: 'Name: To do' });
    trigger.focus();
    fireEvent.keyDown(trigger, { key: 'Enter' });
    const search = await screen.findByRole('combobox', {
      name: 'Search Name options',
    });
    await waitFor(() => expect(document.activeElement).toBe(search));
    await userEvent.keyboard('In review');
    await userEvent.click(
      screen.getByRole('option', { name: 'Create “In review”' })
    );
    await waitFor(() =>
      expect(onAddOption).toHaveBeenCalledExactlyOnceWith('In review')
    );
    await waitFor(() =>
      expect(document.activeElement).toBe(
        screen.getByRole('button', { name: 'Name: To do' })
      )
    );
    expect(screen.queryByRole('listbox')).toBeNull();
  });

  it('edits with Enter, restores focus, and saves the exact text', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value="Old name"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: Old name/ }));
    const input = screen.getByRole('textbox', { name: 'Edit Name' });
    expect(document.activeElement).toBe(input);
    fireEvent.input(input, { target: { value: "O'Reilly's launch" } });
    fireEvent.keyDown(input, { key: 'Enter' });
    await waitFor(() =>
      expect(onWrite).toHaveBeenCalledWith("O'Reilly's launch")
    );
    expect(document.activeElement).toBe(
      screen.getByRole('button', { name: /Name: Old name/ })
    );
  });

  it('cancels with Escape without writing and does not write an unchanged edit', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={column}
        value="Old name"
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: Old name/ }));
    fireEvent.input(screen.getByRole('textbox'), {
      target: { value: 'Discard me' },
    });
    fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' });
    fireEvent.click(screen.getByRole('button', { name: /Name: Old name/ }));
    fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
    await Promise.resolve();
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('does not take focus back after blur saves a cell', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <>
        <GridCell
          column={column}
          value="Old name"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
        <button type="button">Next field</button>
      </>
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: Old name/ }));
    const input = screen.getByRole('textbox');
    fireEvent.input(input, { target: { value: 'New name' } });
    screen.getByRole('button', { name: 'Next field' }).focus();
    await waitFor(() => expect(onWrite).toHaveBeenCalledWith('New name'));
    expect(document.activeElement).toBe(
      screen.getByRole('button', { name: 'Next field' })
    );
  });

  it('rejects an invalid number without silently clearing it', async () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, dataType: 'NUMBER' }}
        value={12}
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.click(screen.getByRole('button', { name: /Name: 12/ }));
    fireEvent.input(screen.getByRole('textbox'), {
      target: { value: 'twelve' },
    });
    fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });
    expect(screen.getByRole('alert').textContent).toBe('Enter a valid number');
    expect(onWrite).not.toHaveBeenCalled();
  });

  it('does not let viewers or multi-select values use a scalar editor', () => {
    const onWrite = vi.fn(async () => true);
    render(() => (
      <GridCell
        column={{ ...column, isMultiSelect: true }}
        value='["one","two"]'
        canEdit
        onWrite={onWrite}
        onAddOption={vi.fn(async () => true)}
      />
    ));
    fireEvent.click(screen.getByRole('button'));
    expect(screen.queryByRole('textbox')).toBeNull();
    expect(screen.getByRole('button').textContent).toContain('one, two');
    expect(onWrite).not.toHaveBeenCalled();
  });

  describe('time-range cells', () => {
    const trip: DatabaseViewColumn = {
      ...column,
      id: 'trip',
      name: 'Trip',
      dataType: 'DATE_RANGE',
    };
    /** A day of the shown month; days of the months around it are disabled. */
    const day = (label: string) =>
      screen
        .getAllByRole('gridcell')
        .find(
          (cell) => cell.textContent === label && !cell.hasAttribute('disabled')
        );

    const renderTrip = (value: DatabaseCellValue) => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={trip}
          value={value}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      return onWrite;
    };
    const field = (end: 'start' | 'end') =>
      screen.getByRole('button', { name: `Edit Trip ${end} date` });
    const time = (end: 'start' | 'end') =>
      screen.getByRole('combobox', { name: `Trip ${end} time` });
    // The open menu hides the rest of the page from the accessibility tree.
    const cell = () =>
      screen.getByRole('button', { name: /^Trip: /, hidden: true });

    it('opens on the start field and keeps the menu open while picking days', async () => {
      const onWrite = renderTrip(
        '2026-03-02T00:00:00.000Z/2026-03-03T00:00:00.000Z'
      );
      cell().focus();
      await userEvent.keyboard('{Enter}');
      await waitFor(() => expect(document.activeElement).toBe(field('start')));

      await userEvent.click(field('end'));
      await userEvent.click(day('20')!);
      expect(onWrite).toHaveBeenLastCalledWith(
        '2026-03-02T00:00:00.000Z/2026-03-20T00:00:00.000Z'
      );
      expect(cell().getAttribute('aria-expanded')).toBe('true');

      // A new start carries the end along, keeping the range's days.
      await userEvent.click(field('start'));
      await userEvent.click(day('10')!);
      expect(onWrite).toHaveBeenLastCalledWith(
        '2026-03-10T00:00:00.000Z/2026-03-28T00:00:00.000Z'
      );
      expect(cell().getAttribute('aria-expanded')).toBe('true');
    });

    it('turns off All day at the next full hour, then picks and types times', async () => {
      vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 2, 1, 14, 20) });
      const onWrite = renderTrip(
        '2026-03-02T00:00:00.000Z/2026-03-03T00:00:00.000Z'
      );
      await userEvent.click(cell());
      await userEvent.click(
        await screen.findByRole('switch', { name: 'All day' })
      );
      expect(onWrite).toHaveBeenLastCalledWith(
        `${new Date(2026, 2, 2, 15).toISOString()}/${new Date(2026, 2, 3, 16).toISOString()}`
      );

      await userEvent.click(time('end'));
      await userEvent.click(screen.getByRole('option', { name: '6:30 PM' }));
      expect(onWrite).toHaveBeenLastCalledWith(
        `${new Date(2026, 2, 2, 15).toISOString()}/${new Date(2026, 2, 3, 18, 30).toISOString()}`
      );

      // A typed start keeps the range's length.
      await userEvent.click(time('start'));
      await userEvent.keyboard('9a{Enter}');
      expect(onWrite).toHaveBeenLastCalledWith(
        `${new Date(2026, 2, 2, 9).toISOString()}/${new Date(2026, 2, 3, 12, 30).toISOString()}`
      );
      expect((time('start') as HTMLInputElement).value).toBe('9:00 AM');
      expect(cell().getAttribute('aria-expanded')).toBe('true');
      vi.useRealTimers();
    });

    it('shows an end before the start without saving it', async () => {
      const onWrite = renderTrip(
        '2026-03-10T00:00:00.000Z/2026-03-12T00:00:00.000Z'
      );
      await userEvent.click(screen.getByRole('button', { name: /^Trip: Mar/ }));
      await userEvent.click(field('end'));
      await userEvent.click(day('4')!);
      expect(screen.getByRole('alert').textContent).toBe(
        'The end can’t be before the start.'
      );
      expect(onWrite).not.toHaveBeenCalled();
    });

    it('starts an empty range on the first day picked, and clears a range', async () => {
      vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 2, 1, 9) });
      const onWrite = renderTrip(null);
      await userEvent.click(cell());
      expect(field('start').textContent).toContain('Start date');
      await userEvent.click(field('start'));
      await userEvent.click(day('16')!);
      expect(onWrite).toHaveBeenLastCalledWith(
        '2026-03-16T00:00:00.000Z/2026-03-16T00:00:00.000Z'
      );

      await userEvent.click(screen.getByRole('button', { name: 'Clear Trip' }));
      expect(onWrite).toHaveBeenLastCalledWith(null);
      await waitFor(() =>
        expect(cell().getAttribute('aria-expanded')).toBe('false')
      );
      vi.useRealTimers();
    });

    it('closes a date list on Escape, then the menu', async () => {
      renderTrip('2026-03-02T00:00:00.000Z/2026-03-03T00:00:00.000Z');
      await userEvent.click(cell());
      await userEvent.click(field('end'));
      await userEvent.keyboard('{Escape}');
      await waitFor(() =>
        expect(field('end').getAttribute('aria-expanded')).toBe('false')
      );
      expect(cell().getAttribute('aria-expanded')).toBe('true');
      await userEvent.keyboard('{Escape}');
      await waitFor(() =>
        expect(cell().getAttribute('aria-expanded')).toBe('false')
      );
    });
  });

  describe('date cells', () => {
    const date: DatabaseViewColumn = {
      ...column,
      id: 'due',
      name: 'Due',
      dataType: 'DATE',
    };

    it('picks a typed date through the shared date selector and stores its day', async () => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={date}
          value={null}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      const trigger = screen.getByRole('button', {
        name: 'Due: Empty. Click to edit',
      });
      trigger.focus();
      await userEvent.keyboard('{Enter}');
      const search = await screen.findByPlaceholderText('Set due...');
      await waitFor(() => expect(document.activeElement).toBe(search));
      await userEvent.keyboard('2030-12-31');
      expect((search as HTMLInputElement).value).toBe('2030-12-31');
      await screen.findByText('Dec 31, 2030');
      await userEvent.keyboard('{Enter}');
      await waitFor(() =>
        expect(onWrite).toHaveBeenCalledExactlyOnceWith(
          '2030-12-31T00:00:00.000Z'
        )
      );
    });

    it('opens the selector on click, returns focus on Escape and opens again', async () => {
      render(() => (
        <GridCell
          column={date}
          value={null}
          canEdit
          onWrite={vi.fn(async () => true)}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      await userEvent.click(
        screen.getByRole('button', { name: 'Due: Empty. Click to edit' })
      );
      await screen.findByPlaceholderText('Set due...');
      await userEvent.keyboard('{Escape}');
      const trigger = screen.getByRole('button', {
        name: 'Due: Empty. Click to edit',
      });
      await waitFor(() => expect(document.activeElement).toBe(trigger));
      expect(screen.queryByPlaceholderText('Set due...')).toBeNull();
      await userEvent.click(trigger);
      expect(await screen.findByPlaceholderText('Set due...')).toBeTruthy();
    });

    it('clears a date with Delete without opening the selector', () => {
      const onWrite = vi.fn(async () => true);
      render(() => (
        <GridCell
          column={date}
          value="2025-07-19T00:00:00.000Z"
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
        />
      ));
      fireEvent.keyDown(
        screen.getByRole('button', {
          name: 'Due: Jul 19, 2025. Click to edit',
        }),
        { key: 'Delete' }
      );
      expect(onWrite).toHaveBeenCalledExactlyOnceWith(null);
      expect(screen.queryByPlaceholderText('Set due...')).toBeNull();
    });

    it('leaves the selector with Tab into the next cell without writing', async () => {
      const onWrite = vi.fn(async () => true);
      const onNavigate = vi.fn(() => true);
      let control: GridCellControl | undefined;
      render(() => (
        <GridCell
          column={date}
          value={null}
          canEdit
          onWrite={onWrite}
          onAddOption={vi.fn(async () => true)}
          onNavigate={onNavigate}
          onReady={(ready) => {
            control = ready;
          }}
        />
      ));
      control?.edit();
      await screen.findByPlaceholderText('Set due...');
      await userEvent.tab();
      await waitFor(() => expect(onNavigate).toHaveBeenCalledWith(1));
      expect(onWrite).not.toHaveBeenCalled();
    });
  });
});