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(crm): add deal and contact form to pipelines (#8211)

teo3d64634e348a
diff --git a/apps/web/src/features/block-database/database-mentions.tsx b/apps/web/src/features/block-database/database-mentions.tsx
index 800bd23a3e..fc16d5a179 100644
--- a/apps/web/src/features/block-database/database-mentions.tsx
+++ b/apps/web/src/features/block-database/database-mentions.tsx
@@ -49,6 +49,7 @@ export function DatabaseMentionPicker(props: DatabaseMentionPickerProps) {
animate={false}
menu={operations}
anchor={anchor()}
+ portalMount={props.mount}
{...databaseMentionScope(props.specificEntityType)}
includeContacts={false}
showOpenTabs={false}
diff --git a/apps/web/src/features/crm/components/record-search.tsx b/apps/web/src/features/crm/components/record-search.tsx
new file mode 100644
index 0000000000..73124483ed
--- /dev/null
+++ b/apps/web/src/features/crm/components/record-search.tsx
@@ -0,0 +1,144 @@
+import type { CollectionNode } from '@kobalte/core';
+import { Combobox } from '@kobalte/core/combobox';
+import PlusIcon from '@phosphor/plus.svg';
+import { Layer } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { PropertyIcon } from '../../database/components/property-icon';
+import type { Pipeline } from '../core/pipeline';
+import { type RecordOption, recordDetail } from '../core/pipeline-record';
+
+/** A search result row: a record to pick, or the search itself as a record to create. */
+type SearchItem =
+ | { kind: 'record'; record: RecordOption }
+ | { kind: 'create'; search: string };
+
+const MAX_RESULTS = 50;
+
+/** Find a company or contact by name or detail, or start a new one from the search. */
+export function RecordSearch(props: {
+ recordType: Pipeline['recordType'];
+ options: RecordOption[];
+ loading: boolean;
+ /** Mount the menu here, e.g. a modal dialog's content, which hides body portals. */
+ mount?: HTMLElement;
+ onPick: (record: RecordOption) => void;
+ onCreate: (search: string) => void;
+}) {
+ const [search, setSearch] = createSignal('');
+ const noun = () => (props.recordType === 'company' ? 'company' : 'contact');
+ const items = (): SearchItem[] => {
+ const query = search().trim();
+ const lower = query.toLowerCase();
+ const matches = props.options
+ .filter(
+ (option) =>
+ option.name.toLowerCase().includes(lower) ||
+ option.detail.toLowerCase().includes(lower)
+ )
+ .slice(0, MAX_RESULTS)
+ .map((record): SearchItem => ({ kind: 'record', record }));
+ return query ? [...matches, { kind: 'create', search: query }] : matches;
+ };
+ return (
+ <Combobox<SearchItem>
+ multiple={false}
+ options={items()}
+ value={null}
+ onChange={(item) => {
+ if (!item) return;
+ if (item.kind === 'record') props.onPick(item.record);
+ else props.onCreate(item.search);
+ }}
+ onInputChange={setSearch}
+ optionValue={(item) =>
+ item.kind === 'record' ? item.record.id : 'create'
+ }
+ optionTextValue={(item) =>
+ item.kind === 'record'
+ ? `${item.record.name} ${item.record.detail}`
+ : item.search
+ }
+ optionLabel={() => ''}
+ defaultFilter={() => true}
+ allowsEmptyCollection
+ placement="bottom-start"
+ gutter={8}
+ sameWidth
+ itemComponent={(itemProps: { item: CollectionNode<SearchItem> }) => (
+ <Combobox.Item
+ item={itemProps.item}
+ class="flex w-full cursor-default items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm data-highlighted:bg-ink/5"
+ >
+ <Show
+ when={
+ itemProps.item.rawValue.kind === 'record' &&
+ itemProps.item.rawValue.record
+ }
+ fallback={
+ <>
+ <PlusIcon class="size-3.5 shrink-0 text-ink-muted" />
+ <Combobox.ItemLabel class="min-w-0 truncate text-ink">
+ Add {noun()} “{search().trim()}”
+ </Combobox.ItemLabel>
+ </>
+ }
+ >
+ {(record) => (
+ <>
+ <PropertyIcon
+ type="ENTITY"
+ entityType={
+ props.recordType === 'company' ? 'COMPANY' : 'CONTACT'
+ }
+ />
+ <Combobox.ItemLabel class="min-w-0 truncate text-ink">
+ {record().name}
+ </Combobox.ItemLabel>
+ <span class="ml-auto min-w-0 shrink-[2] truncate text-xs text-ink-extra-muted">
+ {recordDetail(record())}
+ </span>
+ </>
+ )}
+ </Show>
+ </Combobox.Item>
+ )}
+ >
+ <Combobox.Control class="flex min-w-0 flex-1 items-center gap-2">
+ <PropertyIcon
+ type="ENTITY"
+ entityType={props.recordType === 'company' ? 'COMPANY' : 'CONTACT'}
+ class="size-5 shrink-0 text-ink-muted"
+ />
+ <Combobox.Input
+ aria-label={`Find or add a ${noun()}`}
+ placeholder={`Find or add a ${noun()}…`}
+ autocomplete="off"
+ data-1p-ignore
+ class="ph-no-capture w-full min-w-0 bg-transparent text-xl/7 font-medium text-ink outline-none placeholder:text-ink-placeholder"
+ />
+ </Combobox.Control>
+ <Combobox.Portal mount={props.mount}>
+ <Layer depth={2}>
+ <Combobox.Content class="menu-surface z-action-menu overflow-hidden">
+ {/* Pressing an option must not move focus to the dialog, which
+ closes the menu before the click selects it. */}
+ <div class="p-1" onMouseDown={(event) => event.preventDefault()}>
+ <Show
+ when={items().length}
+ fallback={
+ <div class="px-2 py-3 text-center text-xs text-ink-muted">
+ {props.loading
+ ? `Loading ${noun() === 'company' ? 'companies' : 'contacts'}…`
+ : `Type a name to add a ${noun()}`}
+ </div>
+ }
+ >
+ <Combobox.Listbox class="max-h-64 overflow-y-auto scrollbar-hidden" />
+ </Show>
+ </div>
+ </Combobox.Content>
+ </Layer>
+ </Combobox.Portal>
+ </Combobox>
+ );
+}
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index fc93b6d102..9379f9a0c7 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -108,6 +108,10 @@ export type CrmContext = {
>;
query: { readonly isLoading: boolean };
};
+ createContactSuggestions(): {
+ contacts: Accessor<{ id: string; name: string; email: string }[]>;
+ query: { readonly isLoading: boolean };
+ };
exportCompanies(
signal: AbortSignal,
progress: (count: number) => void
diff --git a/apps/web/src/features/crm/core/pipeline-record.test.ts b/apps/web/src/features/crm/core/pipeline-record.test.ts
new file mode 100644
index 0000000000..b70b1bd354
--- /dev/null
+++ b/apps/web/src/features/crm/core/pipeline-record.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest';
+import {
+ contactCompany,
+ newRecordChoice,
+ recordChoiceProblem,
+ recordDetail,
+} from './pipeline-record';
+
+const companies = [{ id: 'acme', domain: 'Acme.com' }];
+
+describe('newRecordChoice', () => {
+ it('puts a searched domain in the domain and names the company after it', () => {
+ expect(newRecordChoice('company', ' Acme.com ')).toEqual({
+ kind: 'new-company',
+ name: 'Acme',
+ domain: 'acme.com',
+ });
+ });
+
+ it('takes any other company search as the name', () => {
+ expect(newRecordChoice('company', 'Acme Corp')).toEqual({
+ kind: 'new-company',
+ name: 'Acme Corp',
+ domain: '',
+ });
+ });
+
+ it('puts a searched email in the email and anything else in the name', () => {
+ expect(newRecordChoice('contact', '[email protected]')).toEqual({
+ kind: 'new-contact',
+ name: '',
+ email: '[email protected]',
+ });
+ expect(newRecordChoice('contact', 'Jane Doe')).toEqual({
+ kind: 'new-contact',
+ name: 'Jane Doe',
+ email: '',
+ });
+ });
+});
+
+describe('contactCompany', () => {
+ it("finds the company by the email's domain", () => {
+ expect(contactCompany(' [email protected]', companies)).toEqual(companies[0]);
+ expect(contactCompany('[email protected]', companies)).toBeUndefined();
+ expect(contactCompany('not an email', companies)).toBeUndefined();
+ });
+});
+
+describe('recordChoiceProblem', () => {
+ it('accepts an existing record as is', () => {
+ expect(
+ recordChoiceProblem(
+ { kind: 'existing', record: { id: 'acme', name: '', detail: '' } },
+ []
+ )
+ ).toBeUndefined();
+ });
+
+ it('asks a new company for a name and a valid domain', () => {
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-company', name: ' ', domain: 'acme.com' },
+ []
+ )
+ ).toBe('Enter a company name');
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-company', name: 'Acme', domain: 'https://acme' },
+ []
+ )
+ ).toBe('Enter a valid domain like acme.com');
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-company', name: 'Acme', domain: 'acme.com' },
+ []
+ )
+ ).toBeUndefined();
+ });
+
+ it('asks a new contact for a name and an email at a known company', () => {
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-contact', name: '', email: '[email protected]' },
+ companies
+ )
+ ).toBe('Enter a name');
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-contact', name: 'Jane', email: 'jane' },
+ companies
+ )
+ ).toBe('Enter an email like [email protected]');
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-contact', name: 'Jane', email: '[email protected]' },
+ companies
+ )
+ ).toBe('No company uses other.com. Add the company first.');
+ expect(
+ recordChoiceProblem(
+ { kind: 'new-contact', name: 'Jane', email: '[email protected]' },
+ companies
+ )
+ ).toBeUndefined();
+ });
+});
+
+describe('recordDetail', () => {
+ it('hides a detail that repeats the name', () => {
+ expect(
+ recordDetail({
+ id: 'n',
+ name: '43north.studio',
+ detail: '43North.Studio ',
+ })
+ ).toBe('');
+ });
+
+ it('keeps a detail that adds to the name', () => {
+ expect(
+ recordDetail({ id: 'g', name: 'Globex', detail: 'globex.com' })
+ ).toBe('globex.com');
+ });
+});
diff --git a/apps/web/src/features/crm/core/pipeline-record.ts b/apps/web/src/features/crm/core/pipeline-record.ts
new file mode 100644
index 0000000000..9a9fa3764f
--- /dev/null
+++ b/apps/web/src/features/crm/core/pipeline-record.ts
@@ -0,0 +1,81 @@
+import type { Pipeline } from './pipeline';
+
+// Light client-side check for a bare domain like "acme.com"; the server
+// enforces the real rules (no scheme/path/@, not a generic email provider).
+const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i;
+const EMAIL_PATTERN = /^[^\s@]+@([^\s@]+)$/;
+
+export const isCompanyDomain = (value: string) => DOMAIN_PATTERN.test(value);
+
+/** A company or contact someone can pick for a pipeline row. */
+export type RecordOption = { id: string; name: string; detail: string };
+
+/** The detail worth showing beside a record's name: none when it only repeats the name. */
+export const recordDetail = (record: RecordOption) =>
+ record.detail.trim().toLowerCase() === record.name.trim().toLowerCase()
+ ? ''
+ : record.detail;
+
+/** A company a new contact can join, by the domain of its email. */
+export type DomainCompany = { id: string; domain: string };
+
+/** Whom a new pipeline row is about: a record that exists, or one created with the row. */
+export type RecordChoice =
+ | { kind: 'existing'; record: RecordOption }
+ | { kind: 'new-company'; name: string; domain: string }
+ | { kind: 'new-contact'; name: string; email: string };
+
+/** A new record seeded from what was searched: a domain or email goes in its field, anything else is the name. */
+export function newRecordChoice(
+ recordType: Pipeline['recordType'],
+ search: string
+): RecordChoice {
+ const query = search.trim();
+ if (recordType === 'company') {
+ const domain = query.toLowerCase();
+ if (!isCompanyDomain(domain))
+ return { kind: 'new-company', name: query, domain: '' };
+ const label = domain.split('.')[0];
+ return {
+ kind: 'new-company',
+ name: label.charAt(0).toUpperCase() + label.slice(1),
+ domain,
+ };
+ }
+ return query.includes('@')
+ ? { kind: 'new-contact', name: '', email: query.toLowerCase() }
+ : { kind: 'new-contact', name: query, email: '' };
+}
+
+/** The company whose domain a contact's email uses. */
+export function contactCompany(
+ email: string,
+ companies: readonly DomainCompany[]
+): DomainCompany | undefined {
+ const domain = EMAIL_PATTERN.exec(email.trim().toLowerCase())?.[1];
+ return domain
+ ? companies.find((company) => company.domain.toLowerCase() === domain)
+ : undefined;
+}
+
+/** Why the record cannot be saved as entered, or nothing when it can. */
+export function recordChoiceProblem(
+ choice: RecordChoice,
+ companies: readonly DomainCompany[]
+): string | undefined {
+ if (choice.kind === 'existing') return undefined;
+ if (!choice.name.trim())
+ return choice.kind === 'new-company'
+ ? 'Enter a company name'
+ : 'Enter a name';
+ if (choice.kind === 'new-company')
+ return isCompanyDomain(choice.domain.trim())
+ ? undefined
+ : 'Enter a valid domain like acme.com';
+ const email = choice.email.trim();
+ const domain = EMAIL_PATTERN.exec(email)?.[1];
+ if (!domain) return 'Enter an email like [email protected]';
+ return contactCompany(email, companies)
+ ? undefined
+ : `No company uses ${domain.toLowerCase()}. Add the company first.`;
+}
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index 6256a392cc..833ba5bba8 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -81,6 +81,7 @@ import {
useResetCrmStagesMutation,
} from './queries/stages';
import { useTeamCrmConfig } from './queries/team-config';
+import { useQuickAccessCrmContactsQuery } from './record-adapter';
import { createAppDealStages } from './stage-adapter';
// Loaded on demand: the Tasks list imports soup, which imports CRM entry points.
@@ -224,6 +225,7 @@ export function createAppCrmContext(): CrmContext {
exportCompanies: (...args) =>
fetchCrmExportCompanies(deps.storage, ...args),
createCompanySuggestions: useQuickAccessCrmCompaniesQuery,
+ createContactSuggestions: useQuickAccessCrmContactsQuery,
hydrateCompany(company) {
if (company.properties) return company;
const cached = getSoupEntityById(company.id);
diff --git a/apps/web/src/features/crm/pipeline-adapter.tsx b/apps/web/src/features/crm/pipeline-adapter.tsx
index 89cd1fdd76..f3558712f1 100644
--- a/apps/web/src/features/crm/pipeline-adapter.tsx
+++ b/apps/web/src/features/crm/pipeline-adapter.tsx
@@ -29,6 +29,7 @@ import {
import { DatabaseToolbar } from '../database/components/database-toolbar';
import { DatabaseProvider, useDatabase } from '../database/context/database';
import type { CardMove } from '../database/core/board-moves';
+import type { DatabaseCellValue } from '../database/core/database-view';
import type { ViewChange } from '../database/core/view-state';
import { allRecordsView, boardLayout } from '../database/core/views';
import {
@@ -45,6 +46,7 @@ import {
type PipelineViews,
usePipelineTableQuery,
} from './queries/pipeline-views';
+import { AddPipelineRecordDialog } from './views/add-pipeline-record';
/** Pipelines supply their own identity and owner to the existing share dialog. */
export function PipelineShare(props: {
@@ -159,6 +161,8 @@ function PipelineRecords(props: {
const canEdit = () =>
props.pipeline.grant === 'owner' || props.pipeline.grant === 'edit';
const api = createPipelineApi(storageServiceClient, props.pipeline);
+ const [composing, setComposing] =
+ createSignal<Record<string, DatabaseCellValue>>();
return (
<StaticMarkdownContext>
<DatabaseProvider
@@ -177,6 +181,7 @@ function PipelineRecords(props: {
changeView({ query: { ...view().query, filter: null } })
}
boardPositions={boardPositions}
+ onComposeRecord={setComposing}
renderTextEditor={(editor) => <DatabaseTextEditor {...editor} />}
renderTextValue={(value) => <DatabaseTextValue value={value} />}
renderMentionPicker={(picker) => (
@@ -198,7 +203,9 @@ function PipelineRecords(props: {
view={view()}
selectedViewId={selectedView()?.id}
canEdit={canEdit()}
- recordType={props.pipeline.recordType}
+ pipeline={props.pipeline}
+ composing={composing()}
+ onCompose={setComposing}
onSelectView={setSelectedViewId}
onChangeView={changeView}
actions={actions}
@@ -218,7 +225,10 @@ function PipelineToolbar(props: {
view: DatabaseView;
selectedViewId: string | undefined;
canEdit: boolean;
- recordType: Pipeline['recordType'];
+ pipeline: Pipeline;
+ /** The new record's starting values while its form is open. */
+ composing: Record<string, DatabaseCellValue> | undefined;
+ onCompose: (values: Record<string, DatabaseCellValue> | undefined) => void;
onSelectView: (id: string | undefined) => void;
onChangeView: (change: ViewChange) => void;
actions: DatabaseRecordsActions;
@@ -278,15 +288,34 @@ function PipelineToolbar(props: {
actions={
<>
<Show when={props.canEdit}>
- <Button
- variant="outline"
- disabled={props.actions.pending()}
- onClick={() => void props.actions.createRecord()}
- >
+ <Button variant="outline" onClick={() => props.onCompose({})}>
<PlusIcon class="size-4" />
- {props.recordType === 'company' ? 'Add company' : 'Add contact'}
+ {props.pipeline.recordType === 'company'
+ ? 'Add deal'
+ : 'Add contact'}
</Button>
</Show>
+ <Show when={props.canEdit && props.composing} keyed>
+ {(initialValues) => (
+ <AddPipelineRecordDialog
+ pipeline={props.pipeline}
+ columns={columns()}
+ initialValues={initialValues}
+ onCreate={props.actions.createRow}
+ onClose={() => props.onCompose(undefined)}
+ renderTextEditor={(editor) => (
+ <DatabaseTextEditor {...editor} />
+ )}
+ renderTextValue={(value) => <DatabaseTextValue value={value} />}
+ renderMentionPicker={(picker) => (
+ <DatabaseMentionPicker {...picker} />
+ )}
+ renderMentionValue={(id, entityType) => (
+ <DatabaseMentionValue id={id} entityType={entityType} />
+ )}
+ />
+ )}
+ </Show>
{props.pipelineActions}
</>
}
diff --git a/apps/web/src/features/crm/views/add-pipeline-record.test.tsx b/apps/web/src/features/crm/views/add-pipeline-record.test.tsx
new file mode 100644
index 0000000000..148448d256
--- /dev/null
+++ b/apps/web/src/features/crm/views/add-pipeline-record.test.tsx
@@ -0,0 +1,223 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import { AddPipelineRecordDialog } from './add-pipeline-record';
+
+const crm = vi.hoisted(() => ({
+ createCompany: vi.fn(async (_input: { name: string; domain: string }) => ({
+ id: 'new-company',
+ })),
+ createContact: vi.fn(),
+}));
+vi.mock('./use-crm', () => ({
+ useCreateCompanyMutation: () => ({ mutateAsync: crm.createCompany }),
+ useCreateContactMutation: () => ({ mutateAsync: crm.createContact }),
+ useQuickAccessCrmCompaniesQuery: () => ({
+ companies: () => [
+ { id: 'acme', name: 'Acme', domains: [{ domain: 'acme.com' }] },
+ ],
+ query: { isLoading: false },
+ }),
+ useQuickAccessCrmContactsQuery: () => ({
+ contacts: () => [],
+ query: { isLoading: false },
+ }),
+}));
+
+const columns: DatabaseViewColumn[] = [
+ {
+ id: 'company',
+ name: 'Company',
+ dataType: 'ENTITY',
+ specificEntityType: 'COMPANY',
+ isMultiSelect: false,
+ options: [],
+ writable: true,
+ },
+ {
+ id: 'stage',
+ name: 'Stage',
+ dataType: 'SELECT_STRING',
+ isMultiSelect: false,
+ options: [
+ { id: 'lead', label: 'Lead', color: null },
+ { id: 'won', label: 'Won', color: null },
+ ],
+ writable: true,
+ },
+ {
+ id: 'amount',
+ name: 'Amount',
+ dataType: 'NUMBER',
+ isMultiSelect: false,
+ options: [],
+ writable: true,
+ },
+];
+
+function setup() {
+ const onCreate = vi.fn(async () => true);
+ const onClose = vi.fn();
+ render(() => (
+ <AddPipelineRecordDialog
+ pipeline={{ name: 'Sales', recordType: 'company' }}
+ columns={columns}
+ initialValues={{ stage: 'Won' }}
+ onCreate={onCreate}
+ onClose={onClose}
+ />
+ ));
+ return { onCreate, onClose };
+}
+
+beforeEach(() => {
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+describe('AddPipelineRecordDialog', () => {
+ it('waits for a company, then creates one row with the lane stage and every field', async () => {
+ const { onCreate, onClose } = setup();
+ const submit = screen.getByRole('button', { name: /^Add deal/ });
+ expect(submit).toHaveProperty('disabled', true);
+ expect(screen.getByRole('button', { name: /Stage: Won/ })).toBeTruthy();
+
+ await userEvent.type(
+ screen.getByRole('combobox', { name: 'Find or add a company' }),
+ 'acm'
+ );
+ await userEvent.click(await screen.findByRole('option', { name: /Acme/ }));
+ expect(screen.getByText('acme.com')).toBeTruthy();
+
+ await userEvent.click(screen.getByRole('button', { name: /Amount/ }));
+ const amount = screen.getByRole('textbox', { name: 'Edit Amount' });
+ fireEvent.input(amount, { target: { value: '5000' } });
+ fireEvent.keyDown(amount, { key: 'Enter' });
+
+ expect(submit).toHaveProperty('disabled', false);
+ fireEvent.click(submit);
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(onCreate).toHaveBeenCalledExactlyOnceWith({
+ values: { company: 'acme', stage: 'Won', amount: 5000 },
+ open: false,
+ intentId: expect.stringMatching(/^pipeline-record:/),
+ option: undefined,
+ });
+ });
+
+ it('keeps a field still being edited when the form submits', async () => {
+ const { onCreate } = setup();
+ await userEvent.type(
+ screen.getByRole('combobox', { name: 'Find or add a company' }),
+ 'acme'
+ );
+ await userEvent.click(await screen.findByRole('option', { name: /Acme/ }));
+ await userEvent.click(screen.getByRole('button', { name: /Amount/ }));
+ await userEvent.type(
+ screen.getByRole('textbox', { name: 'Edit Amount' }),
+ '750'
+ );
+ fireEvent.submit(screen.getByRole('form', { name: /^Add deal/ }));
+ await waitFor(() =>
+ expect(onCreate).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ values: { company: 'acme', stage: 'Won', amount: 750 },
+ })
+ )
+ );
+ });
+
+ it('creates a new select option with the row', async () => {
+ const { onCreate } = setup();
+ await userEvent.type(
+ screen.getByRole('combobox', { name: 'Find or add a company' }),
+ 'acme'
+ );
+ await userEvent.click(await screen.findByRole('option', { name: /Acme/ }));
+ await userEvent.click(screen.getByRole('button', { name: /Stage: Won/ }));
+ await userEvent.type(
+ await screen.findByRole('combobox', { name: 'Search Stage options' }),
+ 'Negotiation'
+ );
+ await userEvent.click(await screen.findByText('Create “Negotiation”'));
+ expect(
+ screen.getByRole('button', { name: /Stage: Negotiation/ })
+ ).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Add deal/ }));
+ await waitFor(() =>
+ expect(onCreate).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ values: { company: 'acme', stage: 'Negotiation' },
+ option: 'Negotiation',
+ })
+ )
+ );
+ });
+
+ it('creates a company searched by domain before its row, and keeps it on a retry', async () => {
+ const { onCreate, onClose } = setup();
+ onCreate.mockResolvedValueOnce(false);
+ await userEvent.type(
+ screen.getByRole('combobox', { name: 'Find or add a company' }),
+ 'globex.com'
+ );
+ await userEvent.click(
+ await screen.findByRole('option', { name: 'Add company “globex.com”' })
+ );
+ expect(
+ screen.getByRole('textbox', { name: 'Company name' })
+ ).toHaveProperty('value', 'Globex');
+ expect(screen.getByRole('textbox', { name: 'Domain' })).toHaveProperty(
+ 'value',
+ 'globex.com'
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /^Add deal/ }));
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'Could not add this deal. Try again.'
+ );
+ expect(onClose).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Add deal/ }));
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(crm.createCompany).toHaveBeenCalledExactlyOnceWith({
+ name: 'Globex',
+ domain: 'globex.com',
+ });
+ const [first, second] = onCreate.mock.calls as unknown as [
+ { values: object; intentId: string },
+ { values: object; intentId: string },
+ ][];
+ expect(first[0].values).toEqual({ company: 'new-company', stage: 'Won' });
+ expect(second[0]).toEqual(first[0]);
+ });
+
+ it('explains a new company it cannot save instead of submitting it', async () => {
+ const { onCreate } = setup();
+ await userEvent.type(
+ screen.getByRole('combobox', { name: 'Find or add a company' }),
+ 'Initech'
+ );
+ await userEvent.click(
+ await screen.findByRole('option', { name: 'Add company “Initech”' })
+ );
+ fireEvent.click(screen.getByRole('button', { name: /^Add deal/ }));
+ expect(screen.getByRole('alert').textContent).toBe(
+ 'Enter a valid domain like acme.com'
+ );
+ expect(crm.createCompany).not.toHaveBeenCalled();
+ expect(onCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/crm/views/add-pipeline-record.tsx b/apps/web/src/features/crm/views/add-pipeline-record.tsx
new file mode 100644
index 0000000000..9d8caab5c7
--- /dev/null
+++ b/apps/web/src/features/crm/views/add-pipeline-record.tsx
@@ -0,0 +1,527 @@
+import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
+import EnvelopeIcon from '@phosphor/envelope.svg';
+import GlobeIcon from '@phosphor/globe.svg';
+import TableIcon from '@phosphor/table.svg';
+import XIcon from '@phosphor/x.svg';
+import { Key } from '@solid-primitives/keyed';
+import {
+ Button,
+ buttonClasses,
+ Dialog,
+ EntityComposer,
+ Hotkey,
+ Panel,
+} from '@ui';
+import {
+ createSignal,
+ createUniqueId,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import {
+ GridCell,
+ type GridCellProps,
+} from '../../database/components/grid-cell';
+import { PropertyIcon } from '../../database/components/property-icon';
+import type {
+ DatabaseCellValue,
+ DatabaseViewColumn,
+} from '../../database/core/database-view';
+import { canEditCell, titleColumn } from '../../database/core/table';
+import type { RecordCreation } from '../../database/primitives/record-actions';
+import { RecordSearch } from '../components/record-search';
+import type { Pipeline } from '../core/pipeline';
+import {
+ contactCompany,
+ newRecordChoice,
+ type RecordChoice,
+ type RecordOption,
+ recordChoiceProblem,
+ recordDetail,
+} from '../core/pipeline-record';
+import { companyCreationError } from './create-company';
+import { contactCreationError } from './create-contact';
+import {
+ useCreateCompanyMutation,
+ useCreateContactMutation,
+ useQuickAccessCrmCompaniesQuery,
+ useQuickAccessCrmContactsQuery,
+} from './use-crm';
+
+type CellRenderers = Pick<
+ GridCellProps,
+ | 'renderTextEditor'
+ | 'renderTextValue'
+ | 'renderMentionPicker'
+ | 'renderMentionValue'
+>;
+
+/** A form for a whole pipeline row: its company or contact, then every field the pipeline has. */
+export function AddPipelineRecordDialog(
+ props: CellRenderers & {
+ pipeline: Pick<Pipeline, 'name' | 'recordType'>;
+ columns: DatabaseViewColumn[];
+ /** Values the row starts with, such as the stage of the board lane it was added in. */
+ initialValues: Record<string, DatabaseCellValue>;
+ onCreate: (creation: RecordCreation) => Promise<boolean>;
+ onClose: () => void;
+ }
+) {
+ const company = props.pipeline.recordType === 'company';
+ const createCompany = useCreateCompanyMutation();
+ const createContact = useCreateContactMutation();
+ const companies = useQuickAccessCrmCompaniesQuery();
+ const contacts = company ? undefined : useQuickAccessCrmContactsQuery();
+ const options = (): RecordOption[] =>
+ contacts
+ ? contacts.contacts().map((contact) => ({
+ id: contact.id,
+ name: contact.name || contact.email,
+ detail: contact.email,
+ }))
+ : companies.companies().map((entry) => ({
+ id: entry.id,
+ name: entry.name,
+ detail: entry.domains[0]?.domain ?? '',
+ }));
+ const domainCompanies = () =>
+ companies
+ .companies()
+ .flatMap((entry) =>
+ entry.domains.map((domain) => ({ id: entry.id, domain: domain.domain }))
+ );
+ // One intent per dialog, so submitting again never adds a second row.
+ const intentId = `pipeline-record:${createUniqueId()}`;
+ const [choice, setChoice] = createSignal<RecordChoice>();
+ const [values, setValues] = createSignal(props.initialValues);
+ const [newOption, setNewOption] = createSignal<string>();
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ const [dialog, setDialog] = createSignal<HTMLElement>();
+ let fieldList: HTMLDivElement | undefined;
+ const title = () => titleColumn(props.columns);
+ const fields = () =>
+ props.columns.filter(
+ (column) =>
+ column.id !== title()?.id && !column.relation && canEditCell(column)
+ );
+ const noun = company ? 'deal' : 'contact';
+ const submitLabel = company ? 'Add deal' : 'Add contact';
+ const existing = () => {
+ const current = choice();
+ return current?.kind === 'existing' ? current.record : undefined;
+ };
+ const newCompany = () => {
+ const current = choice();
+ return current?.kind === 'new-company' ? current : undefined;
+ };
+ const newContact = () => {
+ const current = choice();
+ return current?.kind === 'new-contact' ? current : undefined;
+ };
+ const changeChoice = (next: RecordChoice | undefined) => {
+ setChoice(next);
+ setError(undefined);
+ };
+ const write = (columnId: string, value: DatabaseCellValue) => {
+ setValues((current) => ({ ...current, [columnId]: value }));
+ return Promise.resolve(true);
+ };
+
+ /** The record's id, creating it first when it is new; a created record stays picked for a retry. */
+ async function savedRecordId(current: RecordChoice): Promise<string> {
+ if (current.kind === 'existing') return current.record.id;
+ if (current.kind === 'new-company') {
+ const domain = current.domain.trim().toLowerCase();
+ const { id } = await createCompany.mutateAsync({
+ name: current.name.trim(),
+ domain,
+ });
+ setChoice({
+ kind: 'existing',
+ record: { id, name: current.name.trim(), detail: domain },
+ });
+ return id;
+ }
+ const email = current.email.trim().toLowerCase();
+ const joins = contactCompany(email, domainCompanies());
+ if (!joins) throw new Error('A new contact needs a company.');
+ const { id } = await createContact.mutateAsync({
+ companyId: joins.id,
+ name: current.name.trim(),
+ email,
+ });
+ setChoice({
+ kind: 'existing',
+ record: { id, name: current.name.trim(), detail: email },
+ });
+ return id;
+ }
+
+ const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope(
+ 'add-pipeline-record',
+ true
+ );
+ registerHotkey({
+ hotkey: 'cmd+enter',
+ scopeId: hotkeyScope,
+ description: submitLabel,
+ keyDownHandler: () => {
+ void submit();
+ return true;
+ },
+ runWithInputFocused: true,
+ });
+
+ async function submit() {
+ // A field still being edited saves its value when it loses focus.
+ const editing = document.activeElement;
+ if (editing instanceof HTMLElement && fieldList?.contains(editing))
+ editing.blur();
+ const current = choice();
+ const titleField = title();
+ if (pending() || !current || !titleField) return;
+ const problem = recordChoiceProblem(current, domainCompanies());
+ if (problem) {
+ setError(problem);
+ return;
+ }
+ setError(undefined);
+ setPending(true);
+ try {
+ const recordId = await savedRecordId(current);
+ const saved = await props.onCreate({
+ values: { ...values(), [titleField.id]: recordId },
+ open: false,
+ intentId,
+ option: newOption(),
+ });
+ if (saved) props.onClose();
+ else setError(`Could not add this ${noun}. Try again.`);
+ } catch (cause) {
+ console.error(`Failed to add a pipeline ${noun}`, cause);
+ setError(
+ company ? companyCreationError(cause) : contactCreationError(cause)
+ );
+ } finally {
+ setPending(false);
+ }
+ }
+
+ function close() {
+ if (!pending()) props.onClose();
+ }
+
+ const recordPicker = () => (
+ <Switch
+ fallback={
+ <RecordSearch
+ recordType={props.pipeline.recordType}
+ options={options()}
+ loading={(contacts ?? companies).query.isLoading}
+ mount={dialog()}
+ onPick={(record) => changeChoice({ kind: 'existing', record })}
+ onCreate={(search) =>
+ changeChoice(newRecordChoice(props.pipeline.recordType, search))
+ }
+ />
+ }
+ >
+ <Match when={existing()}>
+ {(record) => (
+ <PickedRecord
+ recordType={props.pipeline.recordType}
+ record={record()}
+ disabled={pending()}
+ onChange={() => changeChoice(undefined)}
+ />
+ )}
+ </Match>
+ <Match when={newCompany()}>
+ {(draft) => (
+ <NewRecordFields
+ name={draft().name}
+ namePlaceholder="Company name"
+ disabled={pending()}
+ onName={(name) => changeChoice({ ...draft(), name })}
+ onCancel={() => changeChoice(undefined)}
+ cancelLabel="Choose an existing company"
+ >
+ <GlobeIcon
+ aria-hidden="true"
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ <input
+ aria-label="Domain"
+ placeholder="Domain, like acme.com"
+ autocomplete="off"
+ spellcheck={false}
+ data-1p-ignore
+ class="ph-no-capture w-full min-w-0 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ value={draft().domain}
+ disabled={pending()}
+ onInput={(event) =>
+ changeChoice({
+ ...draft(),
+ domain: event.currentTarget.value,
+ })
+ }
+ />
+ </NewRecordFields>
+ )}
+ </Match>
+ <Match when={newContact()}>
+ {(draft) => (
+ <NewRecordFields
+ name={draft().name}
+ namePlaceholder="Contact name"
+ disabled={pending()}
+ onName={(name) => changeChoice({ ...draft(), name })}
+ onCancel={() => changeChoice(undefined)}
+ cancelLabel="Choose an existing contact"
+ >
+ <EnvelopeIcon
+ aria-hidden="true"
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ <input
+ aria-label="Email"
+ placeholder="Email, like [email protected]"
+ type="email"
+ autocomplete="off"
+ spellcheck={false}
+ data-1p-ignore
+ class="ph-no-capture w-full min-w-0 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ value={draft().email}
+ disabled={pending()}
+ onInput={(event) =>
+ changeChoice({
+ ...draft(),
+ email: event.currentTarget.value,
+ })
+ }
+ />
+ </NewRecordFields>
+ )}
+ </Match>
+ </Switch>
+ );
+
+ const cell = (column: () => DatabaseViewColumn) => (
+ <GridCell
+ column={column()}
+ value={values()[column().id] ?? null}
+ emptyLabel="Empty"
+ canEdit={!pending()}
+ renderTextEditor={props.renderTextEditor}
+ renderTextValue={props.renderTextValue}
+ renderMentionPicker={props.renderMentionPicker}
+ renderMentionValue={props.renderMentionValue}
+ popupMount={dialog()}
+ onMention={(mention) => write(column().id, mention.id)}
+ onWrite={(value) => write(column().id, value)}
+ onAddOption={(label, value) => {
+ setNewOption(label);
+ return write(column().id, value ?? label);
+ }}
+ />
+ );
+
+ return (
+ <Dialog
+ open
+ class="sm:w-140"
+ onOpenChange={(open) => !open && close()}
+ contentRef={(element) => {
+ setDialog(element);
+ attachHotkeys(element);
+ }}
+ onEscapeKeyDown={(event) => {
+ // Escape in a field's editor cancels that edit, not the whole form.
+ if (
+ event.target instanceof HTMLElement &&
+ fieldList?.contains(event.target) &&
+ event.target.closest('input, textarea, [contenteditable="true"]')
+ )
+ event.preventDefault();
+ }}
+ >
+ <Panel hideBorder class="bg-transparent rounded-[inherit] *:max-h-[80vh]">
+ <Panel.Body>
+ <form
+ class="h-full min-h-0"
+ aria-label={submitLabel}
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <EntityComposer.Root class="gap-0 p-0">
+ <EntityComposer.Header class="border-b border-edge-muted/60 px-5 py-3">
+ <Dialog.Title class="flex min-w-0 flex-1 items-center gap-2 text-sm font-semibold">
+ {submitLabel}
+ <span class="flex min-w-0 items-center gap-1 rounded-md bg-hover px-1.5 py-0.5 text-xs font-medium text-ink-muted">
+ <TableIcon class="size-3.5 shrink-0" />
+ <span class="truncate">{props.pipeline.name}</span>
+ </span>
+ </Dialog.Title>
+ <Dialog.CloseButton
+ tabIndex={-1}
+ aria-label="Close"
+ class={buttonClasses({ size: 'icon-composer' })}
+ disabled={pending()}
+ >
+ <XIcon />
+ </Dialog.CloseButton>
+ </EntityComposer.Header>
+ <EntityComposer.Main class="gap-5 overflow-y-auto px-5 py-5">
+ <StackedField column={title()}>
+ <div
+ class={`${FIELD_BOX} flex min-h-9 flex-col justify-center gap-2 px-2.5 py-1.5 [&_input]:text-[13px] [&_input]:font-normal [&_svg]:size-4 [&>label]:border-t [&>label]:border-edge-muted/60 [&>label]:pt-2`}
+ >
+ {recordPicker()}
+ </div>
+ </StackedField>
+ <div ref={fieldList} class="flex flex-col gap-5">
+ <Key each={fields()} by="id">
+ {(column) => (
+ <StackedField column={column()}>
+ <div class={FIELD_BOX}>{cell(column)}</div>
+ </StackedField>
+ )}
+ </Key>
+ </div>
+ <Show when={error()}>
+ {(message) => (
+ <p role="alert" class="text-sm text-failure">
+ {message()}
+ </p>
+ )}
+ </Show>
+ </EntityComposer.Main>
+ <EntityComposer.Footer class="items-center justify-end border-t border-edge-muted/60 px-5 py-3">
+ <Button
+ variant="outline"
+ class="gap-3 not-touch:h-[33.75px] not-touch:px-[15px]"
+ disabled={pending()}
+ onClick={close}
+ >
+ Cancel
+ <Hotkey shortcut="escape" theme="subtle" />
+ </Button>
+ <EntityComposer.Submit
+ type="submit"
+ hasContent={!!choice()}
+ disabled={!choice() || pending()}
+ >
+ {pending() ? 'Adding…' : submitLabel}
+ </EntityComposer.Submit>
+ </EntityComposer.Footer>
+ </EntityComposer.Root>
+ </form>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
+
+const FIELD_BOX =
+ 'rounded-lg border border-edge-frame bg-control transition-[border-color,box-shadow] duration-120 focus-within:border-ink/40 focus-within:ring-2 focus-within:ring-ink/10 motion-reduce:transition-none [&_[data-cell-display]]:hover:bg-transparent [&_[data-cell-display]]:focus-visible:ring-0 [&_[data-cell-text-editor]]:border-0 [&_[data-cell-text-editor]]:bg-transparent [&_[data-cell-text-editor]]:ring-0';
+
+/** A field with its label stacked above the input. */
+function StackedField(props: {
+ column: DatabaseViewColumn | undefined;
+ children: JSX.Element;
+}) {
+ return (
+ <div class="flex min-w-0 flex-col gap-1.5">
+ <Show when={props.column}>
+ {(column) => (
+ <div class="flex min-w-0 items-center gap-1.5 text-xs font-medium text-ink-muted">
+ <PropertyIcon
+ type={column().dataType}
+ relation={!!column().relation}
+ entityType={column().specificEntityType}
+ />
+ <span class="truncate">{column().name}</span>
+ </div>
+ )}
+ </Show>
+ {props.children}
+ </div>
+ );
+}
+
+function PickedRecord(props: {
+ recordType: Pipeline['recordType'];
+ record: RecordOption;
+ disabled: boolean;
+ onChange: () => void;
+}) {
+ return (
+ <div class="flex min-w-0 items-center gap-2">
+ <span class="min-w-0 truncate text-[13px] font-medium">
+ {props.record.name}
+ </span>
+ <Show when={recordDetail(props.record)}>
+ {(detail) => (
+ <span class="min-w-0 shrink-[2] truncate text-xs text-ink-extra-muted">
+ {detail()}
+ </span>
+ )}
+ </Show>
+ <Button
+ variant="ghost"
+ size="xs"
+ class="ml-auto shrink-0"
+ disabled={props.disabled}
+ onClick={props.onChange}
+ >
+ Change {props.recordType}
+ </Button>
+ </div>
+ );
+}
+
+/** A record being added with the row: its name as the title, then its identifying field. */
+function NewRecordFields(props: {
+ name: string;
+ namePlaceholder: string;
+ disabled: boolean;
+ cancelLabel: string;
+ onName: (name: string) => void;
+ onCancel: () => void;
+ children: JSX.Element;
+}) {
+ return (
+ <>
+ <div class="flex min-w-0 items-center gap-2">
+ <input
+ ref={(element) => queueMicrotask(() => element.focus())}
+ aria-label={props.namePlaceholder}
+ placeholder={props.namePlaceholder}
+ autocomplete="off"
+ data-1p-ignore
+ class="ph-no-capture w-full min-w-0 bg-transparent text-xl/7 font-medium outline-none placeholder:text-ink-placeholder"
+ value={props.name}
+ disabled={props.disabled}
+ onInput={(event) => props.onName(event.currentTarget.value)}
+ />
+ <Button
+ variant="ghost"
+ size="xs"
+ class="shrink-0"
+ disabled={props.disabled}
+ onClick={props.onCancel}
+ >
+ {props.cancelLabel}
+ </Button>
+ </div>
+ <label class="flex min-w-0 items-center gap-2 text-sm">
+ {props.children}
+ </label>
+ </>
+ );
+}
diff --git a/apps/web/src/features/crm/views/create-company.tsx b/apps/web/src/features/crm/views/create-company.tsx
index af6df6a448..4169819782 100644
--- a/apps/web/src/features/crm/views/create-company.tsx
+++ b/apps/web/src/features/crm/views/create-company.tsx
@@ -4,13 +4,10 @@ import GlobeIcon from '@phosphor/globe.svg';
import XIcon from '@phosphor/x.svg';
import { Button, Dialog, EntityComposer, Panel } from '@ui';
import { createMemo, createSignal, Show } from 'solid-js';
+import { isCompanyDomain } from '../core/pipeline-record';
import { useCreateCompanyMutation } from './use-crm';
-// Light client-side check for a bare domain like "acme.com"; the server
-// enforces the real rules (no scheme/path/@, not a generic email provider).
-const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i;
-
-function createErrorMessage(cause: unknown): string {
+export function companyCreationError(cause: unknown): string {
if (cause instanceof ThrownResultError) {
if (cause.errors.some((e) => e.code === 'CONFLICT')) {
return 'A company with this domain already exists.';
@@ -62,7 +59,7 @@ export function CreateCompanyModal(props: {
setError('Enter a company name');
return;
}
- if (!DOMAIN_PATTERN.test(companyDomain())) {
+ if (!isCompanyDomain(companyDomain())) {
setError('Enter a valid domain like acme.com');
return;
}
@@ -77,7 +74,7 @@ export function CreateCompanyModal(props: {
props.onCreated(id);
} catch (cause) {
console.error('Failed to create company', cause);
- setError(createErrorMessage(cause));
+ setError(companyCreationError(cause));
}
}
diff --git a/apps/web/src/features/crm/views/create-contact.tsx b/apps/web/src/features/crm/views/create-contact.tsx
index 93269159ae..4f876d3d6e 100644
--- a/apps/web/src/features/crm/views/create-contact.tsx
+++ b/apps/web/src/features/crm/views/create-contact.tsx
@@ -15,7 +15,7 @@ import {
// The part before the @: non-empty, no whitespace or a second @.
const LOCAL_PART_PATTERN = /^[^\s@]+$/;
-function createErrorMessage(cause: unknown): string {
+export function contactCreationError(cause: unknown): string {
if (cause instanceof ThrownResultError) {
if (cause.errors.some((e) => e.code === 'CONFLICT')) {
return 'A contact with this email already exists.';
@@ -146,7 +146,7 @@ export function CreateContactModal(props: {
props.onCreated(id);
} catch (cause) {
console.error('Failed to create contact', cause);
- setError(createErrorMessage(cause));
+ setError(contactCreationError(cause));
}
}
diff --git a/apps/web/src/features/crm/views/use-crm.ts b/apps/web/src/features/crm/views/use-crm.ts
index 70b1149ebb..9ef2171023 100644
--- a/apps/web/src/features/crm/views/use-crm.ts
+++ b/apps/web/src/features/crm/views/use-crm.ts
@@ -78,3 +78,6 @@ export const useResetCrmStagesMutation = (
export const useQuickAccessCrmCompaniesQuery = (
...args: Parameters<CrmContext['createCompanySuggestions']>
) => useCrmContext().createCompanySuggestions(...args);
+export const useQuickAccessCrmContactsQuery = (
+ ...args: Parameters<CrmContext['createContactSuggestions']>
+) => useCrmContext().createContactSuggestions(...args);
diff --git a/apps/web/src/features/database/README.md b/apps/web/src/features/database/README.md
index 26748f663f..2c0e9b2d5c 100644
--- a/apps/web/src/features/database/README.md
+++ b/apps/web/src/features/database/README.md
@@ -57,6 +57,10 @@ to the host's API/service; UI capabilities only determine which controls appear.
props supply persisted board positions, conversion previews, relationships,
presence, and stored-view changes. Omit an unsupported action. A board can render
without a position writer; it cannot offer card moves that pretend to persist.
+`onComposeRecord` replaces a board lane's inline card with the host's own form,
+seeded with the lane's values; the form creates its row with the actions'
+`createRow`. A `GridCell` rendered inside a modal dialog takes `popupMount` so
+its menus stay inside the dialog, which blocks the page around it.
View preferences in the example are local; hosts that save views pass their own
view state and authorized persistence callback. Shared filter, sort, toolbar and
view components are in `components/`.
diff --git a/apps/web/src/features/database/components/database-board.test.tsx b/apps/web/src/features/database/components/database-board.test.tsx
index b94f6256c7..babbb86899 100644
--- a/apps/web/src/features/database/components/database-board.test.tsx
+++ b/apps/web/src/features/database/components/database-board.test.tsx
@@ -711,6 +711,63 @@ describe('database board', () => {
);
});
+ it("hands a lane's new record to the host's form instead of an inline card", () => {
+ const status: DatabaseViewColumn = {
+ id: 'status',
+ name: 'Status',
+ dataType: 'SELECT_STRING',
+ isMultiSelect: false,
+ options: [{ id: 'todo', label: 'To do', color: null }],
+ writable: true,
+ };
+ const onCreate = vi.fn(async () => true);
+ const onCompose = vi.fn();
+ render(() => (
+ <DatabaseBoard
+ rows={[]}
+ columns={[
+ {
+ id: 'title',
+ name: 'Name',
+ dataType: 'STRING',
+ isMultiSelect: false,
+ options: [],
+ writable: true,
+ },
+ status,
+ ]}
+ board={{
+ lanes: [
+ { key: { kind: 'option', id: 'todo' }, hidden: false, cards: [] },
+ ],
+ }}
+ layout={{
+ kind: 'board',
+ groupBy: 'status',
+ title: 'title',
+ lanes: [],
+ cardFields: [],
+ hideEmptyLanes: false,
+ }}
+ groupColumn={status}
+ canEdit
+ rowPending={() => false}
+ onOpen={vi.fn()}
+ onMove={vi.fn()}
+ onCreate={onCreate}
+ onCompose={onCompose}
+ />
+ ));
+ const lane = boardLane('To do lane');
+ fireEvent.click(within(lane).getByRole('button', { name: 'New record' }));
+ expect(onCompose).toHaveBeenCalledExactlyOnceWith({
+ kind: 'option',
+ id: 'todo',
+ });
+ expect(within(lane).queryByRole('textbox')).toBeNull();
+ expect(onCreate).not.toHaveBeenCalled();
+ });
+
it("moves a card from its Move menu into the chosen lane's option", async () => {
const status: DatabaseViewColumn = {
id: 'status',
diff --git a/apps/web/src/features/database/components/database-board.tsx b/apps/web/src/features/database/components/database-board.tsx
index c82d483b79..00c72e92b0 100644
--- a/apps/web/src/features/database/components/database-board.tsx
+++ b/apps/web/src/features/database/components/database-board.tsx
@@ -90,6 +90,8 @@ type DatabaseBoardProps = {
intentId: string,
options?: { open: true }
) => Promise<boolean>;
+ /** Starts a record in `lane` in the host's form in place of an inline card. */
+ onCompose?: (lane: LaneKey) => void;
onAddGroup?: (label: string) => Promise<DatabaseGroupAdded>;
/** Hands the host a way to start a card, as the toolbar's New record does. */
controlsRef?: (controls: DatabaseBoardControls) => void;
@@ -177,6 +179,10 @@ export function DatabaseBoard(props: DatabaseBoardProps) {
setDrafts((drafts) => drafts.filter((draft) => draft.id !== id));
};
function startDraft(lane: string) {
+ if (props.onCompose) {
+ props.onCompose(laneOf(lane));
+ return;
+ }
const open = laneDrafts(lane).find(
(draft) => !isSaving(draft) && !draft.title.trim()
);
diff --git a/apps/web/src/features/database/components/grid-cell.tsx b/apps/web/src/features/database/components/grid-cell.tsx
index 03239d437a..784ba0a4b0 100644
--- a/apps/web/src/features/database/components/grid-cell.tsx
+++ b/apps/web/src/features/database/components/grid-cell.tsx
@@ -53,6 +53,8 @@ export type DatabaseMentionPickerProps = {
onSearchChange?: (search: string) => void;
onSelect: (mention: DatabaseMention, direction?: 1 | -1) => void;
onClose: (restoreFocus?: boolean) => void;
+ /** Where the picker mounts in place of the page body. */
+ mount?: HTMLElement;
};
export type DatabaseTextEditorProps = CellTextEditorProps & {
@@ -69,6 +71,8 @@ export type GridCellProps = GridCellEditorOptions & {
renderTextValue?: (value: string) => JSX.Element;
renderMentionPicker?: (props: DatabaseMentionPickerProps) => JSX.Element;
renderMentionValue?: (id: string, type: DatabaseEntityType) => JSX.Element;
+ /** Where the cell's popups mount in place of the page body, such as inside a modal dialog. */
+ popupMount?: HTMLElement;
onMention?: (mention: DatabaseMention) => Promise<boolean>;
/** Click and Enter open the cell's mention instead of editing it; F2 and typing still edit. */
onOpenMention?: (id: string, type: DatabaseEntityType) => void;
@@ -449,6 +453,9 @@ export function GridCell(props: GridCellProps) {
get search() {
return mentionSearch();
},
+ get mount() {
+ return props.popupMount;
+ },
onSearchChange: (value) => {
setMentionSearch(value);
if (!isEntity()) setDraft(`@${value}`);
@@ -1010,7 +1017,15 @@ function SelectCell(props: GridCellProps) {
<Show
when={label()}
fallback={
- <span class="text-xs text-ink-placeholder opacity-40">—</span>
+ <span
+ class="text-ink-placeholder opacity-40"
+ classList={{
+ 'text-xs': !props.emptyLabel,
+ 'text-[13px] leading-5': !!props.emptyLabel,
+ }}
+ >
+ {props.emptyLabel || '—'}
+ </span>
}
>
<span class="flex min-w-0 flex-wrap gap-1">
@@ -1051,9 +1066,9 @@ function SelectCell(props: GridCellProps) {
gutter={4}
>
<Popover.Trigger {...trigger}>{shown()}</Popover.Trigger>
- <Popover.Portal>
+ <Popover.Portal mount={props.popupMount}>
<Popover.Content
- class="menu-surface z-action-menu p-1 outline-none"
+ class="menu-surface z-action-menu min-w-[var(--kb-popper-anchor-width)] max-w-[min(32rem,calc(100vw-16px))] p-1.5 outline-none"
onOpenAutoFocus={(event) => {
event.preventDefault();
searchInput?.focus();
diff --git a/apps/web/src/features/database/components/option-picker.tsx b/apps/web/src/features/database/components/option-picker.tsx
index ac218f9572..65a18151d1 100644
--- a/apps/web/src/features/database/components/option-picker.tsx
+++ b/apps/web/src/features/database/components/option-picker.tsx
@@ -1,7 +1,7 @@
import CheckIcon from '@phosphor/check.svg';
import PlusIcon from '@phosphor/plus.svg';
+import XIcon from '@phosphor/x.svg';
import { Key } from '@solid-primitives/keyed';
-import { Button } from '@ui/components/Button';
import {
createMemo,
createSignal,
@@ -129,37 +129,39 @@ export function OptionPicker(props: {
);
};
return (
- <div class="flex w-56 flex-col">
- <input
- ref={(element) => {
- input = element;
- props.inputRef?.(element);
- }}
- role="combobox"
- aria-label={`Search ${props.column.name} options`}
- aria-expanded="true"
- aria-controls={listId}
- aria-activedescendant={active() >= 0 ? rowId(active()) : undefined}
- aria-autocomplete="list"
- placeholder="Search or create…"
- value={props.search}
- maxlength={200}
- class="mb-1 h-7 w-full rounded border border-edge-muted bg-input px-2 text-xs outline-none placeholder:text-ink-placeholder focus:border-ink/50"
- onInput={(event) => {
- props.onSearch(event.currentTarget.value);
- setActive(event.currentTarget.value.trim() ? 0 : -1);
- }}
- onKeyDown={(event) => {
- if (event.isComposing || event.keyCode === 229) return;
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- event.preventDefault();
- move(event.key === 'ArrowDown' ? 1 : -1);
- } else if (event.key === 'Enter') {
- event.preventDefault();
- activate(rows()[Math.max(active(), 0)]);
- } else props.onKeyDown?.(event, chosen());
- }}
- />
+ <div class="flex w-full min-w-56 flex-col">
+ <div class="-mx-1.5 -mt-1.5 mb-1.5 border-b border-edge-divider">
+ <input
+ ref={(element) => {
+ input = element;
+ props.inputRef?.(element);
+ }}
+ role="combobox"
+ aria-label={`Search ${props.column.name} options`}
+ aria-expanded="true"
+ aria-controls={listId}
+ aria-activedescendant={active() >= 0 ? rowId(active()) : undefined}
+ aria-autocomplete="list"
+ placeholder="Search or create…"
+ value={props.search}
+ maxlength={200}
+ class="h-9 w-full bg-transparent px-3.5 text-xs text-ink outline-none placeholder:text-ink-placeholder"
+ onInput={(event) => {
+ props.onSearch(event.currentTarget.value);
+ setActive(event.currentTarget.value.trim() ? 0 : -1);
+ }}
+ onKeyDown={(event) => {
+ if (event.isComposing || event.keyCode === 229) return;
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ move(event.key === 'ArrowDown' ? 1 : -1);
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ activate(rows()[Math.max(active(), 0)]);
+ } else props.onKeyDown?.(event, chosen());
+ }}
+ />
+ </div>
<div
id={listId}
role="listbox"
@@ -177,7 +179,7 @@ export function OptionPicker(props: {
role="option"
aria-selected={isPicked(row())}
data-active={active() === index() ? '' : undefined}
- class="group/option flex h-7 shrink-0 items-center gap-1.5 rounded px-1.5 text-xs data-active:bg-hover hover:bg-hover"
+ class="group/option flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs data-active:bg-hover hover:bg-hover"
onPointerMove={() => setActive(index())}
onPointerDown={(event) => event.preventDefault()}
onClick={() => activate(row())}
@@ -224,15 +226,14 @@ export function OptionPicker(props: {
)}
</Key>
<Show when={!rows().length}>
- <p class="px-1.5 py-1 text-xs text-ink-placeholder">No options</p>
+ <p class="px-2 py-1 text-xs text-ink-placeholder">No options</p>
</Show>
</div>
<Show when={props.selected.length}>
- <div class="mt-2 flex items-center justify-end border-t border-edge-divider pt-2 pb-2">
- <Button
+ <div class="-mx-1.5 mt-1.5 border-t border-edge-divider px-1.5 pt-1.5">
+ <button
type="button"
- variant="ghost"
- size="sm"
+ class="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left text-xs text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:bg-hover focus-visible:text-ink"
ref={clearButton}
onClick={props.onClear}
onKeyDown={(event) => {
@@ -250,12 +251,13 @@ export function OptionPicker(props: {
} else props.onKeyDown?.(event, undefined);
}}
>
+ <XIcon class="size-3.5 shrink-0" />
Clear value
- </Button>
+ </button>
</div>
</Show>
<Show when={props.error}>
- <p role="alert" class="px-1.5 pt-1 text-xs text-failure-ink">
+ <p role="alert" class="px-2 pt-1 text-xs text-failure-ink">
{props.error}
</p>
</Show>
diff --git a/apps/web/src/features/database/primitives/record-actions.ts b/apps/web/src/features/database/primitives/record-actions.ts
index 69a43ad18c..5bf4963913 100644
--- a/apps/web/src/features/database/primitives/record-actions.ts
+++ b/apps/web/src/features/database/primitives/record-actions.ts
@@ -38,6 +38,8 @@ export type RecordCreation = {
titleColumn?: string;
open: boolean;
intentId?: string;
+ /** A label among `values` that the write may add as a new option. */
+ option?: string;
};
/**
@@ -268,7 +270,11 @@ export function createRecordActions(options: {
values[titleField.id] = creation.title;
const saved = await controller.save(
{ kind: 'create', values },
- { label: 'new record', createIntentId: creation.intentId }
+ {
+ label: 'new record',
+ createIntentId: creation.intentId,
+ option: creation.option,
+ }
);
if (saved.isErr()) return false;
const rowId = saved.value.insertedRowIds[0];
diff --git a/apps/web/src/features/database/views/database-board-view.tsx b/apps/web/src/features/database/views/database-board-view.tsx
index 0e62c202aa..5e9f640b0b 100644
--- a/apps/web/src/features/database/views/database-board-view.tsx
+++ b/apps/web/src/features/database/views/database-board-view.tsx
@@ -38,6 +38,7 @@ import {
} from '../core/board-moves';
import type { DatabaseEntityType } from '../core/column-inference';
import {
+ type DatabaseCellValue,
type DatabaseViewColumn,
isBoardGroupColumn,
isOptionColumn,
@@ -84,6 +85,7 @@ type DatabaseBoardViewProps = {
createComplete: (intentId: string) => boolean;
onOpen: (rowId: string) => void;
onCreate: (creation: RecordCreation) => Promise<boolean>;
+ onCompose?: (values: Record<string, DatabaseCellValue>) => void;
/** Adds an option to the group column; absent for viewers. */
onAddGroup?: (
columnId: string,
@@ -291,15 +293,18 @@ function GroupedBoard(
);
if (move) write(move);
}
+ const laneValues = (lane: LaneKey) => {
+ const value = laneValue(props.groupColumn, lane);
+ return value === undefined ? {} : { [props.groupColumn.id]: value };
+ };
function create(
lane: LaneKey,
title: string,
intentId: string,
options?: { open: true }
) {
- const value = laneValue(props.groupColumn, lane);
return props.onCreate({
- values: value === undefined ? {} : { [props.groupColumn.id]: value },
+ values: laneValues(lane),
title,
titleColumn: props.layout.title,
intentId,
@@ -356,6 +361,11 @@ function GroupedBoard(
: undefined
}
onCreate={create}
+ onCompose={
+ props.onCompose
+ ? (lane) => props.onCompose?.(laneValues(lane))
+ : undefined
+ }
onAddGroup={addGroup()}
controlsRef={props.controlsRef}
/>
diff --git a/apps/web/src/features/database/views/database-records-view.tsx b/apps/web/src/features/database/views/database-records-view.tsx
index eda3d6e034..bd7ae8cb97 100644
--- a/apps/web/src/features/database/views/database-records-view.tsx
+++ b/apps/web/src/features/database/views/database-records-view.tsx
@@ -63,7 +63,10 @@ import {
import { createColumnLayout } from '../primitives/column-layout';
import { createDraftRows } from '../primitives/draft-rows';
import { createHeldGridRows } from '../primitives/held-grid-rows';
-import { createRecordActions } from '../primitives/record-actions';
+import {
+ createRecordActions,
+ type RecordCreation,
+} from '../primitives/record-actions';
import { createTableController } from '../primitives/table-controller';
import { type BoardPositions, DatabaseBoardView } from './database-board-view';
import { DatabaseTableView } from './database-table-view';
@@ -71,6 +74,8 @@ import { DatabaseTableView } from './database-table-view';
/** What the toolbar and the block can ask of the records on screen. */
export type DatabaseRecordsActions = {
createRecord: () => Promise<boolean>;
+ /** Saves a record with its values set; resolves whether it was saved. */
+ createRow: (creation: RecordCreation) => Promise<boolean>;
focusFirstCell: () => Promise<void>;
focusColumn: (columnId: string) => boolean;
openRecord: (rowId: string) => void;
@@ -110,6 +115,8 @@ export type DatabaseRecordsViewProps = {
onClearConstraints?: () => void;
/** A board's card places. */
boardPositions?: BoardPositions;
+ /** Starts a record in the host's own form in place of a board's inline card, with its lane's values. */
+ onComposeRecord?: (values: Record<string, DatabaseCellValue>) => void;
renderTextEditor?: GridCellProps['renderTextEditor'];
renderTextValue?: GridCellProps['renderTextValue'];
renderMentionPicker?: GridCellProps['renderMentionPicker'];
@@ -228,6 +235,7 @@ export function DatabaseRecordsView(props: DatabaseRecordsViewProps) {
layoutKind() === 'table'
? records.focusBlankRow()
: boardControls?.addCard() || records.createRow({ open: true }),
+ createRow: records.createRow,
focusFirstCell: records.focusFirstCell,
focusColumn,
// A grid just mounted for a record from elsewhere has no rows to find it in yet.
@@ -483,6 +491,7 @@ export function DatabaseRecordsView(props: DatabaseRecordsViewProps) {
createComplete={controller.createComplete}
onOpen={records.open}
onCreate={records.createRow}
+ onCompose={props.onComposeRecord}
controlsRef={(controls) => {
boardControls = controls;
}}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index a9d7e403c3..3b65b615ec 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -87,6 +87,8 @@ type MentionsMenuProps = {
/** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */
useBlockBoundary?: boolean;
portalScope?: PortalScope;
+ /** Mounts the menu here instead of by `portalScope`. */
+ portalMount?: HTMLElement;
block?: BlockName;
anchor?: HTMLElement | null;
onUserMention?: (mention: UserMentionRecord) => void;
@@ -691,7 +693,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
return (
<Show when={menuOpen()}>
- <ScopedPortal scope={props.portalScope}>
+ <ScopedPortal scope={props.portalScope} mount={props.portalMount}>
<div
class="w-96 max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content"
classList={{ 'menu-open-animation': props.animate !== false }}
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 49259da1e5..d69ade5dd1 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -208,9 +208,23 @@ tabs. Its header shows the name, edited in place by editors, a **Pipeline
actions** menu (**Rename** and **Import CSV** for editors, **Export CSV** for
anyone who can open it, **Trash pipeline** for the owner) and **Share**. The
toolbar below has **All records**, the pipeline's stored views and **New view**
-(Table or Board), plus Group by (boards), Filter and Sort, then **Add company**
-or **Add contact** (by the pipeline's record type) for editors, which starts a
-row whose reference cell picks the record.
+(Table or Board), plus Group by (boards), Filter and Sort, then **Add deal**
+(company pipelines) or **Add contact** (contact pipelines) for editors. It opens
+a dialog titled **Add deal** (or **Add contact**) with the pipeline's name in a
+chip beside it and Close. Below the header, each field has its label stacked
+above a full-width bordered box: **Company** (or the contact column) first, with
+a **Find or add a company…** (or contact) search, then every pipeline field with
+the table's own cell editors (unset ones read **Empty**). The body scrolls while
+the footer stays pinned with **Cancel** (Esc) and **Add deal**. Select
+fields can create a new option. Choosing **Add company “…”** creates the company
+with the row: a searched domain fills the domain and the name. **Add contact “…”**
+works the same way, and a new contact's email must use a company's domain.
+**Add deal** stays disabled until a record is chosen, and Command-Enter submits.
+The form makes one row with every value set. A board lane's **New record** opens
+the same dialog with the lane's stage filled in. The table's blank row at the
+bottom still adds a row inline. On mobile the dialog is a bottom drawer. To verify
+the person picker, choose an **Owner** in the dialog: its menu must accept the
+click.
Stored views are everyone's and are written through the pipeline, so changing one
changes it for all viewers; All records is each viewer's own. A board can move a
card to another group from its card menu or by dragging, which sets the row's
diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.md
index 301f6dd4d4..66915dbda3 100644
--- a/docs/agent-guide/databases.md
+++ b/docs/agent-guide/databases.md
@@ -214,13 +214,14 @@ inside a sentence preserves Text.
### Select options
-A select or multi-select cell opens a compact option picker with its search field
-focused (**Search or create…**). Typing filters the options; when the typed name is
+A select or multi-select cell opens an option picker at least as wide as the cell,
+with its search field focused (**Search or create…**) as a borderless row above a
+divider. Typing filters the options; when the typed name is
not an option yet, a **Create “…”** row adds it, picks it, and keeps focus (on the
cell for a single select, in the search for a multi-select, which stays open). Arrow
-keys move through the rows and Enter picks. The **Clear value** Button sits on the
-right of a separate, bottom-padded footer below the option list. It sizes to its
-label and empties the cell; it stays available while searching.
+keys move through the rows and Enter picks. **Clear value** is a full-width row
+below a divider at the bottom, aligned with the options. It empties the cell and
+stays available while searching.
From a freshly opened picker, Down starts at the first option and Up starts at the
last. With no search text, Down after the last option focuses **Clear value** when present; Enter clears.
From that button, Up returns to the last option and Down returns to the first.