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.

12.8 KB
Raw Blame
import { MemoryRouter, Route } from '@solidjs/router';
import { cleanup, fireEvent, render } from '@solidjs/testing-library';
import { ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import {
  CreateContextProvider,
  useCreateContext,
} from './context/create-context';

const host = vi.hoisted(() => ({
  popoverSplit: vi.fn(),
  openWithSplit: vi.fn(),
  createFolder: vi.fn(),
  createSpreadsheet: vi.fn(async () => 'sheet-1' as string | undefined),
  createDatabase: vi.fn(),
  createForm: vi.fn(),
  projectFlag: (): boolean | undefined => true,
  carouselFlag: (): boolean | undefined => undefined,
}));

vi.mock('@components/app/split-layout/layout', () => ({
  useSplitLayout: () => host,
}));
vi.mock('@queries/storage/projects', () => ({
  createProject: host.createFolder,
}));
vi.mock('@queries/storage/databases', () => ({
  createDatabase: host.createDatabase,
}));
vi.mock('@queries/storage/forms', () => ({ createForm: host.createForm }));

// Other creation flows are independent of the native project composer.
vi.mock('@app/features/agents-view/primitives/open-composer', () => ({}));
vi.mock('@app/features/block-agent/context/pending-session', () => ({}));
vi.mock('@app/features/block-agent/ui/AgentInput', () => ({}));
vi.mock(
  '@app/features/block-spreadsheet/primitives/use-spreadsheet-access',
  () => ({ useSpreadsheetAccess: () => () => false })
);
vi.mock('@app/features/block-spreadsheet/queries/create-spreadsheet', () => ({
  createSpreadsheetDocument: host.createSpreadsheet,
}));
vi.mock('@app/features/block-ai/queries/create-ai', () => ({}));
vi.mock('@app/features/block-psd/queries/create-psd', () => ({}));
vi.mock('@app/features/block-fig/queries/create-fig', () => ({}));
vi.mock('@app/features/block-spreadsheet/queries/spreadsheet-access', () => ({
  isSpreadsheetEnabledForCurrentUser: () => true,
}));
vi.mock('@app/features/email-compose/core/constants', () => ({}));
vi.mock('@app/features/reminders/reminder-composer', () => ({}));
vi.mock('@app/lib/analytics/posthog', () => ({
  useFeatureFlag: (flag: { key: string }) => () => ({
    enabled:
      flag.key === 'enable-carousel-create-menu'
        ? host.carouselFlag() === true
        : flag.key === 'enable-projects' && host.projectFlag() === true,
    loading: flag.key === 'enable-projects' && host.projectFlag() === undefined,
  }),
}));
vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
  isFeatureEnabled: (flag: { key: string }) =>
    flag.key === 'enable-databases' ||
    flag.key === 'enable-forms' ||
    (flag.key === 'enable-projects' && host.projectFlag() === true),
}));
vi.mock('@block-md/observability', () => ({}));
vi.mock('@channel/CreateChannelModal', () => ({}));
vi.mock('@core/component/AI/component/input/ChatInput', () => ({}));
vi.mock('@core/component/EntityIcon', () => ({
  getIconConfig: () => ({ icon: () => null, foreground: 'text-ink' }),
}));
vi.mock('@core/directive/focusInput', () => ({}));
vi.mock('@core/hotkey/hotkeys', () => ({}));
vi.mock('@core/hotkey/state', () => ({ pressedKeys: () => new Set() }));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
vi.mock('@core/util/create', () => ({}));
vi.mock('@macro-inc/lexical-core/markdown-golden', () => ({}));
vi.mock('@ui', () => ({}));
vi.mock('@ui/components/Hotkey', () => ({}));
vi.mock('./mobile/MobileCreateSheet', () => ({}));
vi.mock('./DetailsLauncher', () => ({
  default: (props: LauncherInnerProps) => (
    <button onClick={() => props.onClose(false)}>
      Details: {props.blocks?.map((item) => item.label).join(', ')}
    </button>
  ),
}));
vi.mock('./CarouselLauncher', () => ({
  default: (props: LauncherInnerProps) => (
    <button onClick={() => props.onClose(false)}>
      Carousel: {props.blocks?.map((item) => item.label).join(', ')}
    </button>
  ),
}));

import {
  CREATABLE_BLOCKS,
  createMenuOpen,
  LauncherInner,
  type LauncherInnerProps,
  runCreateAction,
  setCreateMenuOpen,
  useCreateAction,
  useCreateCommands,
  useCreateMenuBlocks,
} from './Launcher';

beforeEach(() => {
  host.projectFlag = () => true;
  host.carouselFlag = () => undefined;
});

it.each([false, undefined])(
  'uses the detailed launcher when the carousel flag is %s',
  async (enabled) => {
    host.carouselFlag = () => enabled;
    const view = render(() => <LauncherInner onClose={vi.fn()} />);
    await view.findByText('Details:');
    expect(view.queryByText('Carousel:')).toBeNull();
  }
);

it('switches the launcher with the flag while forwarding sandbox choices and close behavior', async () => {
  const [enabled, setEnabled] = createSignal(false);
  host.carouselFlag = enabled;
  const onClose = vi.fn();
  const blocks = CREATABLE_BLOCKS.filter((item) => item.label === 'Task');
  const view = render(() => (
    <LauncherInner blocks={blocks} onClose={onClose} />
  ));
  await view.findByText('Details: Task');
  setEnabled(true);
  fireEvent.click(await view.findByText('Carousel: Task'));
  expect(onClose).toHaveBeenCalledExactlyOnceWith(false);
  expect(view.queryByText('Details: Task')).toBeNull();
  setEnabled(false);
  await view.findByText('Details: Task');
  expect(view.queryByText('Carousel: Task')).toBeNull();
});
afterEach(() => {
  cleanup();
  setCreateMenuOpen(false, false);
  vi.clearAllMocks();
});

it.each([false, undefined])(
  'blocks Project shortcuts and imperative creation while the flag is %s',
  (enabled) => {
    host.projectFlag = () => enabled;
    const project = CREATABLE_BLOCKS.find(
      (item) => item.blockName === 'initiative'
    );
    expect(project?.enabled?.()).toBe(false);
    project?.keyDownHandler();
    runCreateAction('initiative');
    expect(host.popoverSplit).not.toHaveBeenCalled();
  }
);

it('reactively adds and removes Project while retaining Task and Folder', () => {
  const [enabled, setEnabled] = createSignal<boolean | undefined>(undefined);
  host.projectFlag = enabled;
  const Menu = () => {
    const blocks = useCreateMenuBlocks();
    return (
      <div>
        {blocks()
          .map((item) => item.label)
          .join(', ')}
      </div>
    );
  };
  const view = render(() => (
    <CreateContextProvider focusedPaneId={() => undefined}>
      <MemoryRouter>
        <Route path="/" component={Menu} />
      </MemoryRouter>
    </CreateContextProvider>
  ));
  expect(view.container.textContent).not.toContain('Project');
  expect(view.container.textContent).toContain('Task');
  expect(view.container.textContent).toContain('Folder');
  setEnabled(true);
  expect(view.container.textContent).toContain('Project');
  setEnabled(false);
  expect(view.container.textContent).not.toContain('Project');
  expect(view.container.textContent).toContain('Folder');
});

it('offers Project in the shared create menu and opens its native composer', () => {
  const project = CREATABLE_BLOCKS.find((item) => item.label === 'Project');
  expect(
    project,
    'Project must be available in every shared Create menu'
  ).toBeDefined();
  if (!project) return;

  setCreateMenuOpen(true);
  host.popoverSplit.mockImplementationOnce(() => {
    // Transfer focus ownership before the launcher closes.
    expect(createMenuOpen()).toBe(true);
  });
  project.keyDownHandler();

  expect(host.popoverSplit).toHaveBeenCalledExactlyOnceWith({
    type: 'component',
    id: 'project-compose',
    params: undefined,
  });
  expect(createMenuOpen()).toBe(false);
  expect(host.openWithSplit).not.toHaveBeenCalled();
  expect(host.createFolder).not.toHaveBeenCalled();
});

it('shows a loading pane while a document is created, then opens it there', async () => {
  const replace = vi.fn();
  host.openWithSplit.mockReturnValueOnce({ split: { replace } });

  runCreateAction('spreadsheet', { projectId: 'folder-1', source: 'drive' });

  expect(host.openWithSplit).toHaveBeenCalledExactlyOnceWith(
    { type: 'component', id: 'loading' },
    { referredFrom: 'launcher', preferNewSplit: false }
  );
  await vi.waitFor(() => expect(replace).toHaveBeenCalledOnce());
  expect(replace).toHaveBeenCalledWith({
    next: { type: 'spreadsheet', id: 'sheet-1', params: undefined },
    mergeHistory: true,
    referredFrom: 'launcher',
  });
});

it('lets the requesting surface keep its content and open the new document itself', async () => {
  const openCreated = vi.fn(() => true);

  runCreateAction('spreadsheet', {
    projectId: 'folder-1',
    source: 'drive',
    openCreated,
  });

  await vi.waitFor(() =>
    expect(openCreated).toHaveBeenCalledExactlyOnceWith({
      blockName: 'spreadsheet',
      id: 'sheet-1',
    })
  );
  expect(host.createSpreadsheet).toHaveBeenCalledWith({
    projectId: 'folder-1',
    source: 'drive',
  });
  expect(host.openWithSplit).not.toHaveBeenCalled();
});

it.each([
  {
    blockName: 'database',
    arrange: () => host.createDatabase.mockResolvedValueOnce(ok('db-1')),
    id: 'db-1',
  },
  {
    blockName: 'form',
    arrange: () =>
      host.createForm.mockResolvedValueOnce(ok({ form: { id: 'form-1' } })),
    id: 'form-1',
  },
] as const)(
  'lets the requesting surface open a new $blockName the same way',
  async ({ blockName, arrange, id }) => {
    arrange();
    const openCreated = vi.fn(() => true);

    runCreateAction(blockName, { source: 'drive', openCreated });

    await vi.waitFor(() =>
      expect(openCreated).toHaveBeenCalledExactlyOnceWith({ blockName, id })
    );
    expect(host.openWithSplit).not.toHaveBeenCalled();
  }
);

it('opens the new document in a split when the requesting surface declines it', async () => {
  const openCreated = vi.fn(() => false);

  runCreateAction('spreadsheet', { openCreated });

  await vi.waitFor(() => expect(host.openWithSplit).toHaveBeenCalledOnce());
  expect(openCreated).toHaveBeenCalledOnce();
  expect(host.openWithSplit).toHaveBeenCalledWith(
    { type: 'spreadsheet', id: 'sheet-1' },
    { referredFrom: 'launcher', preferNewSplit: false }
  );
});

it('opens the Folder composer without creating a folder immediately', () => {
  const folder = CREATABLE_BLOCKS.find((item) => item.label === 'Folder');
  expect(folder).toBeDefined();
  folder?.keyDownHandler();
  expect(host.popoverSplit).toHaveBeenCalledExactlyOnceWith({
    type: 'component',
    id: 'folder-compose',
    params: {
      parentId: undefined,
      destination: undefined,
      source: 'create_menu',
    },
  });
  expect(host.createFolder).not.toHaveBeenCalled();
  expect(host.openWithSplit).not.toHaveBeenCalled();
});

it('binds create-menu and shortcut actions to the provider and snapshots before focus changes', () => {
  const [focusedPane, setFocusedPane] = createSignal('first');
  const first = { key: 'first', visiblePropertyIds: ['company'] };
  const Menu = () => {
    const context = useCreateContext();
    context.register('first', () => ({ task: first }));
    context.register('second', () => ({ task: { key: 'second' } }));
    const task = useCreateCommands().find((item) => item.blockName === 'task');
    return <button onClick={() => task?.keyDownHandler()}>New task</button>;
  };
  const view = render(() => (
    <CreateContextProvider focusedPaneId={focusedPane}>
      <MemoryRouter>
        <Route path="/" component={Menu} />
      </MemoryRouter>
    </CreateContextProvider>
  ));
  host.popoverSplit.mockImplementationOnce(() => setFocusedPane('second'));
  fireEvent.click(view.getByText('New task'));
  first.visiblePropertyIds.push('changed');
  expect(host.popoverSplit).toHaveBeenNthCalledWith(1, {
    type: 'component',
    id: 'task-compose',
    params: {
      composerContext: { key: 'first', visiblePropertyIds: ['company'] },
    },
  });
  fireEvent.click(view.getByText('New task'));
  expect(host.popoverSplit).toHaveBeenNthCalledWith(2, {
    type: 'component',
    id: 'task-compose',
    params: { composerContext: { key: 'second' } },
  });
});

it('lets explicit creation defaults override or suppress the focused preset', () => {
  const Action = () => {
    useCreateContext().register('pane', () => ({ task: { key: 'focused' } }));
    const create = useCreateAction();
    return (
      <>
        <button
          onClick={() =>
            create('task', { context: { task: { key: 'explicit' } } })
          }
        >
          Explicit
        </button>
        <button onClick={() => create('task', { context: { task: null } })}>
          Standard
        </button>
      </>
    );
  };
  const view = render(() => (
    <CreateContextProvider focusedPaneId={() => 'pane'}>
      <Action />
    </CreateContextProvider>
  ));
  fireEvent.click(view.getByText('Explicit'));
  expect(host.popoverSplit).toHaveBeenLastCalledWith({
    type: 'component',
    id: 'task-compose',
    params: { composerContext: { key: 'explicit' } },
  });
  fireEvent.click(view.getByText('Standard'));
  expect(host.popoverSplit).toHaveBeenLastCalledWith({
    type: 'component',
    id: 'task-compose',
    params: { composerContext: undefined },
  });
});