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.

fix(crm): give opened records and pipelines their own URLs (#8344)

gbirman317d6ae3f7fd
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
index 3aad7bbc3c..7b564b1550 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -6,7 +6,7 @@ import {
} from '@app/features/calendar-view/calendar-url';
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
import { channelsSearch } from '@app/features/channels-view/channels-route';
-import { crmPipelineSearch } from '@app/features/crm/crm-route';
+import { legacyCrmPipelineId } from '@app/features/crm/crm-route';
import {
driveDocumentFromContent,
drivePath,
@@ -35,6 +35,28 @@ type AppMiddlewareState = {
isTouchDevice: () => boolean;
};
+function crmPipelinePath(pipelineId: string): string {
+ return `/companies/pipeline/${encodeURIComponent(pipelineId)}`;
+}
+
+/** Customers showed a pipeline as a list tab before it had its own route. */
+function redirectLegacyCrmPipeline({
+ to,
+ cause,
+ externalSearch,
+ redirect,
+}: SplitRouterMiddlewareContext): SplitRouterMiddlewareResult | undefined {
+ if (to.location.route.matches.at(-1)?.id !== 'view-companies') return;
+
+ const pipelineId = legacyCrmPipelineId(
+ to.location.search,
+ cause === 'initial' || cause === 'external' ? externalSearch : undefined
+ );
+ if (!pipelineId) return;
+
+ return redirect(crmPipelinePath(pipelineId));
+}
+
/** Upgrade legacy component and block URLs when supported; on touch, keep
* document details in their full-block routes instead of inline Drive views. */
function redirectLegacyRoutes(
@@ -85,12 +107,8 @@ function redirectLegacyRoutes(
.with({ type: 'component' }, ({ id }) =>
routes.byId.has(`view-${id}`) ? `/${id}` : undefined
)
- // A pipeline has no view of its own; Customers opens on it, on touch too.
- .with({ type: 'pipeline' }, ({ id }) => {
- const query = new URLSearchParams();
- replacePaneSearchParams(query, [crmPipelineSearch(id)]);
- return `/companies?${query}`;
- })
+ // A pipeline opens in Customers, on touch too.
+ .with({ type: 'pipeline' }, ({ id }) => crmPipelinePath(id))
.when(
() => isTouch,
() => undefined
@@ -231,6 +249,7 @@ export function createAppSplitRouterMiddleware(
): readonly SplitRouterMiddleware[] {
return [
(context) => redirectLegacyRoutes(context, state),
+ redirectLegacyCrmPipeline,
migrateLegacySearch,
];
}
diff --git a/apps/web/src/features/block-pipeline/component/PipelineBlock.tsx b/apps/web/src/features/block-pipeline/component/PipelineBlock.tsx
index 6828db0ae5..7aa7fb15a9 100644
--- a/apps/web/src/features/block-pipeline/component/PipelineBlock.tsx
+++ b/apps/web/src/features/block-pipeline/component/PipelineBlock.tsx
@@ -1,17 +1,8 @@
-import { crmPipelineSearch } from '@app/features/crm/crm-route';
+import { crmPipelineContent } from '@app/features/crm/crm-hosted-content';
import { RedirectSplit } from '@components/app/split-layout/split-router/app-route-shell';
import { useBlockId } from '@core/block';
/** Routed opens redirect before mounting this; anything else lands here. */
export default function PipelineBlock() {
- return (
- <RedirectSplit
- to={{
- type: 'component',
- id: 'companies',
- entryMetadata: { search: crmPipelineSearch(useBlockId()) },
- }}
- mergeHistory
- />
- );
+ return <RedirectSplit to={crmPipelineContent(useBlockId())} mergeHistory />;
}
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index 1471eeef00..80298f14f5 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -18,7 +18,9 @@ crm/
crm-create.tsx / crm-link.tsx
crm-actions.ts / crm-hide-action.ts / crm-action-items.ts / crm-user-action.tsx
crm-search.ts / crm-tool-renderers.tsx
- route.tsx Authenticated route and shared-view decoding
+ crm-route.ts Route params, record trail, and legacy pipeline link decoding
+ route-views.tsx Authenticated route and shared-view decoding
+ crm-hosted-content.ts Split content that opens Customers on a pipeline
*-adapter.* Production sources, navigation, persistence, download, collection wiring
```
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index 9379f9a0c7..414d88df98 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -51,6 +51,7 @@ export type CrmContext = {
contactInitials(name: string | null | undefined, email: string): string;
userEmail(id: string): string;
copyViewLink(config: import('../core/saved-view').CrmViewConfig): void;
+ copyPipelineLink(pipelineId: string): void;
copyRecordLink(target: {
type: 'company' | 'contact';
id: string;
diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsx
index 794e81c2b5..f12862ead9 100644
--- a/apps/web/src/features/crm/context/workspace-context.tsx
+++ b/apps/web/src/features/crm/context/workspace-context.tsx
@@ -8,21 +8,26 @@ import {
import type { EntityActionListState } from '../../next-soup/actions/entity-action-context';
import type { SoupState } from '../../next-soup/create-soup-state';
import type { QueryStore } from '../../next-soup/filters/filter-store/query-store';
+import type { CrmRecordRef, CrmRecordSection } from '../core/record';
-export type CrmRouteSearch = {
- tab: Accessor<string>;
- setTab(
- tab: string,
- options?: { replace?: boolean; clearPipelineRequest?: boolean }
- ): void;
+/** Records opened inside the workspace; the route holds them. */
+export type CrmRecordNavigation = {
+ /** Records opened from the list, oldest first; empty on the list. */
+ records: Accessor<readonly CrmRecordRef[]>;
+ /** The shown record's tab; none is its Overview. */
+ section: Accessor<CrmRecordSection | undefined>;
+ /** Shows the last record of `trail` at its Overview. */
+ open(trail: readonly CrmRecordRef[]): void;
+ setSection(section: CrmRecordSection): void;
+ /** Returns to the list the records were opened from. */
+ close(): void;
};
-/** A pipeline another view asked the workspace to show. */
-export type CrmPipelineRequest = {
- /** A new `seek` repeats a request for the same pipeline. */
- current: Accessor<{ pipelineId: string; seek: string } | undefined>;
- /** Forgets the request once the workspace shows something else. */
- release(): void;
+/** The Customers location: a list tab, and the records opened from it. */
+export type CrmRoute = CrmRecordNavigation & {
+ tab: Accessor<string>;
+ /** Shows the list of `tab`, closing any open record. */
+ setTab(tab: string, options?: { replace?: boolean }): void;
};
/** Collection capabilities consumed by CRM views, supplied by the host adapter. */
@@ -35,7 +40,7 @@ export type CrmWorkspace = {
openCompany(entity: EntityData, newSplit: boolean): void;
openSettings(): void;
openTeamSettings(): void;
- pipelineRequest: CrmPipelineRequest['current'];
+ record: CrmRecordNavigation;
};
soup: EntityActionListState & {
diff --git a/apps/web/src/features/crm/core/record.ts b/apps/web/src/features/crm/core/record.ts
index 6fdba5b7a9..b313e921fd 100644
--- a/apps/web/src/features/crm/core/record.ts
+++ b/apps/web/src/features/crm/core/record.ts
@@ -21,6 +21,13 @@ export function sameRecordScope(
return false;
}
+/** A CRM record shown inside the workspace, with its fallback label. */
+export type CrmRecordRef = {
+ type: 'company' | 'contact';
+ id: string;
+ name: string;
+};
+
/** Tabs of a CRM record, in display order per record type. */
export const COMPANY_SECTIONS = [
'overview',
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index 833ba5bba8..9c3744e5e5 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -38,6 +38,7 @@ import {
import { createAppCrmDisplayOptions } from './display-adapter';
import { downloadCrmCsv } from './download-adapter';
import {
+ copyCrmPipelineLink,
copyCrmRecordLink,
copyCrmViewLink,
createAppCrmNavigation,
@@ -188,6 +189,7 @@ export function createAppCrmContext(): CrmContext {
createNavigation: createAppCrmNavigation,
copyRecordLink: copyCrmRecordLink,
copyViewLink: copyCrmViewLink,
+ copyPipelineLink: copyCrmPipelineLink,
listsEnabled() {
const flag = useFeatureFlag(enableCrmLists);
return () => flag().enabled;
diff --git a/apps/web/src/features/crm/crm-hosted-content.ts b/apps/web/src/features/crm/crm-hosted-content.ts
new file mode 100644
index 0000000000..3122358712
--- /dev/null
+++ b/apps/web/src/features/crm/crm-hosted-content.ts
@@ -0,0 +1,16 @@
+import { paneRoute } from '@app/routes/app-route';
+import type { SplitContent } from '@components/app/split-layout/layoutManager';
+
+/** Customers showing `pipelineId`, without mounting a legacy pipeline block. */
+export function crmPipelineContent(pipelineId: string): SplitContent {
+ return {
+ type: 'component',
+ id: 'companies',
+ entryMetadata: {
+ route: paneRoute(
+ { id: 'view-companies', params: {} },
+ { id: 'companies-pipeline', params: { pipelineId } }
+ ),
+ },
+ };
+}
diff --git a/apps/web/src/features/crm/crm-route.test.ts b/apps/web/src/features/crm/crm-route.test.ts
index 1cc8d725fe..2708ab82c4 100644
--- a/apps/web/src/features/crm/crm-route.test.ts
+++ b/apps/web/src/features/crm/crm-route.test.ts
@@ -1,12 +1,19 @@
import {
createRoutesManifest,
+ decodePane,
type Entry,
+ type NavigationCause,
+ type SerializedSearchParams,
type SplitRoutes,
+ type SplitSearchState,
} from '@app/lib/split-router';
import { paneRoute } from '@app/routes/app-route';
import {
appRoute,
companiesRoute,
+ crmPipelineRecordRoute,
+ crmPipelineRoute,
+ crmRecordRoute,
legacyContentRoute,
notFoundRoute,
} from '@app/routes/routes';
@@ -33,38 +40,114 @@ vi.mock('@service-connection/websocket', () => ({
}));
const pipelineId = '01a1212c-74e5-79bd-8767-0d4943d55b15';
+const companyId = '01a1212c-74e5-79bd-8767-0d4943d55b16';
+const contactId = '01a1212c-74e5-79bd-8767-0d4943d55b17';
const routes = createRoutesManifest({
definitions: [
{
...appRoute,
- children: [companiesRoute, legacyContentRoute, notFoundRoute],
+ children: [
+ {
+ ...companiesRoute,
+ children: [
+ { ...crmPipelineRoute, children: [crmPipelineRecordRoute] },
+ crmRecordRoute,
+ ],
+ },
+ legacyContentRoute,
+ notFoundRoute,
+ ],
},
],
defaultRoute: () => paneRoute({ id: companiesRoute.id, params: {} }),
} satisfies SplitRoutes);
const resolveMention = createMacroMentionLinkResolver(routes);
+const appUrl = (path: string) => `${window.location.origin}/app${path}`;
const crmViewLink = (view: CrmViewConfig) =>
- `${window.location.origin}/app/companies?crmView=${encodeCrmViewParam(view)}`;
+ appUrl(`/companies?crmView=${encodeCrmViewParam(view)}`);
+
+const leafOf = (path: string) => {
+ const route = decodePane(routes, path.split('/').filter(Boolean));
+ const leaf = route?.matches.at(-1);
+ return leaf && { id: leaf.id, params: leaf.params };
+};
describe('crm tab search params', () => {
- it.each([
- 'active',
- 'people',
- 'hidden',
- pipelineTab(pipelineId),
- 'list:favorites',
- ])('keeps the %s tab through the URL', (tab) => {
- const params = crmSearchCodec.serialize({ tab, pipeline: '', seek: '' });
- if (tab === 'active') {
- expect(params).toBeUndefined();
- } else {
- expect(params).toEqual({ tab: [tab] });
+ it.each(['active', 'people', 'hidden', 'list:favorites'])(
+ 'keeps the %s tab through the URL',
+ (tab) => {
+ const params = crmSearchCodec.serialize({ tab });
+ if (tab === 'active') {
+ expect(params).toBeUndefined();
+ } else {
+ expect(params).toEqual({ tab: [tab] });
+ }
+ expect(crmSearchCodec.parse(params)).toEqual({
+ value: { tab },
+ valid: true,
+ });
}
- expect(crmSearchCodec.parse(params)).toEqual({
- value: { tab, pipeline: '', seek: '' },
- valid: true,
+ );
+});
+
+describe('record and pipeline URLs', () => {
+ it('matches a record opened from a Customers list', () => {
+ expect(leafOf(`companies/company/${companyId}`)).toEqual({
+ id: crmRecordRoute.id,
+ params: { recordType: 'company', recordId: companyId },
+ });
+ expect(leafOf(`companies/contact/${contactId}/emails`)).toEqual({
+ id: crmRecordRoute.id,
+ params: {
+ recordType: 'contact',
+ recordId: contactId,
+ section: 'emails',
+ },
+ });
+ });
+
+ it('matches a pipeline and a record opened from it', () => {
+ expect(leafOf(`companies/pipeline/${pipelineId}`)).toEqual({
+ id: crmPipelineRoute.id,
+ params: { pipelineId },
});
+ expect(
+ leafOf(`companies/pipeline/${pipelineId}/company/${companyId}/team`)
+ ).toEqual({
+ id: crmPipelineRecordRoute.id,
+ params: {
+ recordType: 'company',
+ recordId: companyId,
+ section: 'team',
+ },
+ });
+ });
+
+ it.each([
+ `companies/deal/${companyId}`,
+ `companies/company/${companyId}/garbage`,
+ ])('does not match %s as a record', (path) => {
+ const leaf = leafOf(path);
+ expect(leaf?.id).not.toBe(crmRecordRoute.id);
+ });
+
+ it.each([
+ [`/companies/company/${companyId}`, 'company', companyId],
+ [`/companies/contact/${contactId}/emails`, 'contact', contactId],
+ [
+ `/companies/pipeline/${pipelineId}/company/${companyId}`,
+ 'company',
+ companyId,
+ ],
+ ])('pastes %s as a mention of the record', (path, block, id) => {
+ expect(resolveMention(appUrl(path))).toEqual({ id, block, params: {} });
+ });
+
+ it('pastes a pipeline URL as a mention of the pipeline', () => {
+ expect(resolveMention(appUrl(`/companies/pipeline/${pipelineId}`))).toEqual(
+ { id: pipelineId, block: 'pipeline', params: {} }
+ );
});
});
@@ -81,9 +164,7 @@ describe('pipeline links', () => {
'pastes a Customers link with %s as a mention of the pipeline',
(key) => {
expect(
- resolveMention(
- `${window.location.origin}/app/companies?${key}=${pipelineTab(pipelineId)}`
- )
+ resolveMention(appUrl(`/companies?${key}=${pipelineTab(pipelineId)}`))
).toEqual({ id: pipelineId, block: 'pipeline', params: {} });
}
);
@@ -92,21 +173,59 @@ describe('pipeline links', () => {
crmViewLink({ kind: 'crm', activeTab: 'active' }),
crmViewLink({ kind: 'crm', activeTab: 'list:favorites' }),
crmViewLink({ kind: 'crm', activeTab: pipelineTab('not-a-uuid') }),
- `${window.location.origin}/app/companies?crmView=garbage`,
- `${window.location.origin}/app/companies`,
- `${window.location.origin}/app/companies?s0.crm.tab=people`,
- `${window.location.origin}/app/companies?s0.crm.tab=${pipelineTab('not-a-uuid')}`,
- `${window.location.origin}/app/companies?crmView=${encodeCrmViewParam({ kind: 'crm', activeTab: 'active' })}&s0.crm.tab=${pipelineTab(pipelineId)}`,
+ appUrl('/companies?crmView=garbage'),
+ appUrl('/companies'),
+ appUrl('/companies?s0.crm.tab=people'),
+ appUrl(`/companies?s0.crm.tab=${pipelineTab('not-a-uuid')}`),
+ appUrl(
+ `/companies?crmView=${encodeCrmViewParam({ kind: 'crm', activeTab: 'active' })}&s0.crm.tab=${pipelineTab(pipelineId)}`
+ ),
])('leaves other Customers links as links: %s', (url) => {
expect(resolveMention(url)).toBeUndefined();
});
+});
+
+describe('legacy pipeline URLs', () => {
+ const run = (
+ to: Entry,
+ options: {
+ touch?: boolean;
+ cause?: NavigationCause;
+ externalSearch?: string;
+ } = {}
+ ) => {
+ const middleware = createAppSplitRouterMiddleware({
+ isTouchDevice: () => options.touch ?? false,
+ });
+ for (const handler of middleware) {
+ const result = handler({
+ routes,
+ from: undefined,
+ to,
+ path: '',
+ cause: options.cause ?? 'navigate',
+ externalSearch: options.externalSearch,
+ signal: new AbortController().signal,
+ redirect: (path) => ({ type: 'redirect', to: path }),
+ cancel: () => ({ type: 'cancel' }),
+ });
+ if (result instanceof Promise) throw new Error('Unexpected async');
+ if (result) return result;
+ }
+ return undefined;
+ };
+ const customers = (search?: SplitSearchState): Entry => ({
+ id: 'entry',
+ location: {
+ route: paneRoute({ id: companiesRoute.id, params: {} }),
+ search,
+ },
+ });
+ const pipelinePath = `/companies/pipeline/${pipelineId}`;
it.each([false, true])(
- 'opens a pipeline in Customers, on that pipeline (touch: %s)',
+ 'opens a pipeline block in Customers, on that pipeline (touch: %s)',
(touch) => {
- const [redirectLegacy] = createAppSplitRouterMiddleware({
- isTouchDevice: () => touch,
- });
const to: Entry = {
id: 'entry',
location: {
@@ -116,32 +235,53 @@ describe('pipeline links', () => {
}),
},
};
- const open = () => {
- const result = redirectLegacy!({
- routes,
- from: undefined,
- to,
- path: `/pipeline/${pipelineId}`,
- cause: 'navigate',
- signal: new AbortController().signal,
- redirect: (path) => ({ type: 'redirect', to: path }),
- cancel: () => ({ type: 'cancel' }),
- });
- if (!result || result instanceof Promise || result.type !== 'redirect')
- throw new Error('Expected a redirect');
- return new URL(result.to, window.location.origin);
- };
-
- const first = open();
- expect(first.pathname).toBe('/companies');
- expect(first.searchParams.get('s0.crm.tab')).toBe(
- pipelineTab(pipelineId)
- );
- expect(first.searchParams.get('s0.crm.pipeline')).toBe(pipelineId);
- // Opening the same pipeline again is a new request.
- expect(open().searchParams.get('s0.crm.seek')).not.toBe(
- first.searchParams.get('s0.crm.seek')
- );
+ expect(run(to, { touch })).toEqual({
+ type: 'redirect',
+ to: pipelinePath,
+ });
}
);
+
+ it.each<SerializedSearchParams>([
+ { tab: [pipelineTab(pipelineId)] },
+ { tab: [pipelineTab(pipelineId)], pipeline: [pipelineId], seek: ['x'] },
+ { pipeline: [pipelineId], seek: ['x'] },
+ ])('moves the Customers pipeline search %o to its route', (crm) => {
+ expect(run(customers({ crm }))).toEqual({
+ type: 'redirect',
+ to: pipelinePath,
+ });
+ });
+
+ it('moves a shared pipeline view link to its route on entry', () => {
+ const externalSearch = `crmView=${encodeCrmViewParam({
+ kind: 'crm',
+ activeTab: pipelineTab(pipelineId),
+ })}`;
+ expect(run(customers(), { cause: 'external', externalSearch })).toEqual({
+ type: 'redirect',
+ to: pipelinePath,
+ });
+ // Later navigation inside Customers keeps its own tab.
+ expect(run(customers(), { externalSearch })).toBeUndefined();
+ });
+
+ it('leaves other Customers lists and records in place', () => {
+ expect(run(customers({ crm: { tab: ['people'] } }))).toBeUndefined();
+ expect(
+ run({
+ id: 'entry',
+ location: {
+ route: paneRoute(
+ { id: companiesRoute.id, params: {} },
+ {
+ id: crmRecordRoute.id,
+ params: { recordType: 'company', recordId: companyId },
+ }
+ ),
+ search: { crm: { tab: ['people'] } },
+ },
+ })
+ ).toBeUndefined();
+ });
});
diff --git a/apps/web/src/features/crm/crm-route.ts b/apps/web/src/features/crm/crm-route.ts
index 3109a951f8..f236c9bcc4 100644
--- a/apps/web/src/features/crm/crm-route.ts
+++ b/apps/web/src/features/crm/crm-route.ts
@@ -1,41 +1,70 @@
import {
createSearchParamsCodec,
+ type SerializedSearchParams,
type SplitReference,
type SplitSearchState,
} from '@app/lib/split-router';
import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
import { z } from 'zod';
-import { pipelineIdOfTab, pipelineTab } from './core/navigation';
+import { pipelineIdOfTab } from './core/navigation';
+import { COMPANY_SECTIONS, CONTACT_SECTIONS } from './core/record';
import {
CRM_VIEW_URL_PARAM,
decodeCrmViewParam,
} from './queries/saved-view-codec';
-/** Customers pane search. `tab` is the open view. A new `seek` repeats a pipeline request. */
+/** Customers pane search. `tab` is the open list; a pipeline is its own route. */
export const crmSearch = {
namespace: 'crm',
- schema: z.object({
- tab: z.string(),
- pipeline: z.string(),
- seek: z.string(),
- }),
- defaults: { tab: 'active', pipeline: '', seek: '' },
+ schema: z.object({ tab: z.string() }),
+ defaults: { tab: 'active' },
};
export type CrmSearchParams = z.infer<typeof crmSearch.schema>;
export const crmSearchCodec = createSearchParamsCodec(crmSearch);
-/** The Customers pane search that opens it on `pipelineId`. */
-export function crmPipelineSearch(pipelineId: string): SplitSearchState {
- return {
- [crmSearch.namespace]:
- crmSearchCodec.serialize({
- tab: pipelineTab(pipelineId),
- pipeline: pipelineId,
- seek: crypto.randomUUID(),
- }) ?? {},
- };
+export const crmPipelineParams = z.object({ pipelineId: z.string().min(1) });
+
+/** A company or contact opened inside Customers; no section is its Overview. */
+export const crmRecordParams = z.object({
+ recordType: z.enum(['company', 'contact']),
+ recordId: z.string().min(1),
+ section: z
+ .enum([...new Set([...COMPANY_SECTIONS, ...CONTACT_SECTIONS])])
+ .optional(),
+});
+
+export type CrmRecordParams = z.infer<typeof crmRecordParams>;
+
+/** Records opened on the way to the shown one, kept with its history entry. */
+export const crmRecordTrailSchema = z
+ .array(
+ z.object({
+ type: z.enum(['company', 'contact']),
+ id: z.string().min(1),
+ name: z.string(),
+ })
+ )
+ .min(1);
+
+export function crmRecordClaim({ recordType, recordId }: CrmRecordParams) {
+ return { namespace: 'block', id: `${recordType}:${recordId}` };
+}
+
+export function crmRecordReference({
+ recordType,
+ recordId,
+}: CrmRecordParams): SplitReference | undefined {
+ return uuidRouteReference(recordId, recordType);
+}
+
+/** A pipeline link references the pipeline, not a place within it. */
+export function crmPipelineReference(
+ pipelineId: string
+): SplitReference | undefined {
+ const reference = uuidRouteReference(pipelineId, 'pipeline');
+ return reference && { ...reference, params: {} };
}
function crmTabFromQuery(query: URLSearchParams): string | undefined {
@@ -47,22 +76,34 @@ function crmTabFromQuery(query: URLSearchParams): string | undefined {
return undefined;
}
+/** A Customers list link that shows a pipeline references the pipeline. */
+export function crmViewReference(
+ query: URLSearchParams
+): SplitReference | undefined {
+ const id = pipelineIdOfTab(crmTabFromQuery(query));
+ return id ? crmPipelineReference(id) : undefined;
+}
+
/** The pipeline a shared `crmView` link shows, if any. */
export function crmViewPipelineId(query: URLSearchParams): string | undefined {
const view = query.get(CRM_VIEW_URL_PARAM);
- return pipelineIdOfTab(
- view ? decodeCrmViewParam(view)?.activeTab : undefined
- );
+ return view
+ ? pipelineIdOfTab(decodeCrmViewParam(view)?.activeTab)
+ : undefined;
}
-/** A shared Customers link that shows a pipeline references the pipeline. */
-export function crmViewReference(
- query: URLSearchParams
-): SplitReference | undefined {
- const reference = uuidRouteReference(
- pipelineIdOfTab(crmTabFromQuery(query)),
- 'pipeline'
+/**
+ * The pipeline a Customers list URL from before pipelines had their own route
+ * shows: its tab, its one-time pipeline request, or a shared view's tab.
+ */
+export function legacyCrmPipelineId(
+ search: SplitSearchState | undefined,
+ externalSearch: string | undefined
+): string | undefined {
+ const crm: SerializedSearchParams | undefined = search?.[crmSearch.namespace];
+ return (
+ pipelineIdOfTab(crm?.tab?.at(-1)) ??
+ crm?.pipeline?.at(-1) ??
+ crmViewPipelineId(new URLSearchParams(externalSearch))
);
- // The rest of the shared view state is no place within the pipeline.
- return reference && { ...reference, params: {} };
}
diff --git a/apps/web/src/features/crm/crm.tsx b/apps/web/src/features/crm/crm.tsx
index acbc67a51c..a123772e58 100644
--- a/apps/web/src/features/crm/crm.tsx
+++ b/apps/web/src/features/crm/crm.tsx
@@ -3,8 +3,7 @@ import { SoupViewStateProvider } from '../next-soup/soup-view/soup-view-context'
import { ViewTour } from '../tours/ViewTour';
import { CrmProvider } from './context/crm-context';
import {
- type CrmPipelineRequest,
- type CrmRouteSearch,
+ type CrmRoute,
CrmWorkspaceProvider,
} from './context/workspace-context';
import type { CrmViewConfig } from './core/saved-view';
@@ -14,18 +13,9 @@ import { Companies } from './views/companies';
import { CrmDefaultViewLoader } from './views/default-view';
import { createCrmWorkspace } from './workspace-adapter';
-export function Crm(props: {
- initialView?: CrmViewConfig;
- pipelineRequest?: CrmPipelineRequest;
- routeSearch?: CrmRouteSearch;
-}) {
+export function Crm(props: { initialView?: CrmViewConfig; route: CrmRoute }) {
const crm = createAppCrmContext();
- const workspace = createCrmWorkspace(
- crm,
- props.initialView,
- props.pipelineRequest,
- props.routeSearch
- );
+ const workspace = createCrmWorkspace(crm, props.route, props.initialView);
return (
<CrmProvider value={crm}>
<SoupViewStateProvider state={workspace.state}>
diff --git a/apps/web/src/features/crm/navigation-adapter.ts b/apps/web/src/features/crm/navigation-adapter.ts
index 6e13b18ab0..8953247a80 100644
--- a/apps/web/src/features/crm/navigation-adapter.ts
+++ b/apps/web/src/features/crm/navigation-adapter.ts
@@ -19,8 +19,20 @@ export function buildCrmViewShareUrl(config: CrmViewConfig): string {
}
export async function copyCrmViewLink(config: CrmViewConfig) {
+ await copyCrmLink(buildCrmViewShareUrl(config));
+}
+/** A pipeline's link opens Customers on it. */
+export async function copyCrmPipelineLink(pipelineId: string) {
+ await copyCrmLink(
+ new URL(
+ `/app/companies/pipeline/${encodeURIComponent(pipelineId)}`,
+ getWebOrigin()
+ ).toString()
+ );
+}
+async function copyCrmLink(url: string) {
try {
- await navigator.clipboard.writeText(buildCrmViewShareUrl(config));
+ await navigator.clipboard.writeText(url);
toast.success('Link copied to clipboard');
} catch {
toast.failure('Failed to copy link');
diff --git a/apps/web/src/features/crm/route-adapter.test.tsx b/apps/web/src/features/crm/route-adapter.test.tsx
new file mode 100644
index 0000000000..441f04673b
--- /dev/null
+++ b/apps/web/src/features/crm/route-adapter.test.tsx
@@ -0,0 +1,194 @@
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ SplitRouter,
+ type SplitRouter as SplitRouterInstance,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import { createTestPolicy } from '@app/lib/split-router/tests/fixtures';
+import { paneRoute } from '@app/routes/app-route';
+import {
+ appRoute,
+ companiesRoute,
+ crmPipelineRecordRoute,
+ crmPipelineRoute,
+ crmRecordRoute,
+} from '@app/routes/routes';
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { For, onCleanup } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import type { CrmRoute } from './context/workspace-context';
+import { createCrmRoute } from './route-adapter';
+
+vi.mock('@components/app/split-layout/componentRegistry', () => ({
+ resolveComponent: vi.fn(() => ({ type: 'mock-component' })),
+}));
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+afterEach(cleanup);
+
+let route: CrmRoute;
+
+function Customers() {
+ route = createCrmRoute();
+ return (
+ <p data-testid="customers">
+ {`tab:${route.tab()} section:${route.section() ?? '-'} records:${route
+ .records()
+ .map((record) => `${record.type}:${record.id}:${record.name}`)
+ .join(',')}`}
+ </p>
+ );
+}
+
+const routes: SplitRoutes = {
+ definitions: [
+ {
+ ...appRoute,
+ children: [
+ {
+ ...companiesRoute,
+ component: Customers,
+ children: [
+ { ...crmPipelineRoute, children: [crmPipelineRecordRoute] },
+ crmRecordRoute,
+ ],
+ },
+ ],
+ },
+ ],
+ defaultRoute: () => paneRoute({ id: companiesRoute.id, params: {} }),
+};
+
+function renderCustomers(url: string) {
+ const history = createMemoryHistory(url);
+ let router: SplitRouterInstance | undefined;
+ render(() => {
+ const created = createSplitRouter({
+ routes,
+ history,
+ paneStore: createMemoryPaneStore(),
+ policy: createTestPolicy().policy,
+ });
+ router = created;
+ onCleanup(() => created.dispose());
+ return (
+ <SplitRouter.Root router={created}>
+ <For each={created.panes()}>
+ {(pane) => <SplitRouter.Outlet pane={pane} />}
+ </For>
+ </SplitRouter.Root>
+ );
+ });
+ const pane = () => router!.panes()[0]!;
+ return {
+ url: () => {
+ const location = history.read();
+ return `${location.path}${location.search ?? ''}`;
+ },
+ shows: (text: string) =>
+ vi.waitFor(() =>
+ expect(screen.getByTestId('customers').textContent).toBe(text)
+ ),
+ canGo: (delta: number) => router!.canGo(pane(), delta),
+ go: (delta: number) => router!.navigatePane(pane(), delta),
+ };
+}
+
+const acme = { type: 'company' as const, id: 'acme', name: 'Acme' };
+const maya = { type: 'contact' as const, id: 'maya', name: 'Maya' };
+
+it('opens a People contact at its own URL and returns to the list entry', async () => {
+ const { url, shows, canGo } = renderCustomers('/companies?s0.crm.tab=people');
+ await shows('tab:people section:- records:');
+
+ route.open([maya]);
+ await shows('tab:people section:- records:contact:maya:Maya');
+ expect(url()).toBe('/companies/contact/maya?s0.crm.tab=people');
+
+ route.close();
+ await shows('tab:people section:- records:');
+ expect(url()).toBe('/companies?s0.crm.tab=people');
+ // It went back to the list's entry rather than adding one.
+ expect(canGo(-1)).toBe(false);
+ expect(canGo(1)).toBe(true);
+});
+
+it('keeps the trail with each record and its tab in the path', async () => {
+ const { url, shows } = renderCustomers('/companies');
+ route.open([acme]);
+ await shows('tab:active section:- records:company:acme:Acme');
+
+ route.open([acme, maya]);
+ await shows(
+ 'tab:active section:- records:company:acme:Acme,contact:maya:Maya'
+ );
+ expect(url()).toBe('/companies/contact/maya');
+
+ route.setSection('emails');
+ await shows(
+ 'tab:active section:emails records:company:acme:Acme,contact:maya:Maya'
+ );
+ expect(url()).toBe('/companies/contact/maya/emails');
+
+ route.setSection('overview');
+ await shows(
+ 'tab:active section:- records:company:acme:Acme,contact:maya:Maya'
+ );
+ expect(url()).toBe('/companies/contact/maya');
+});
+
+it('shows a record link on its own, without a trail', async () => {
+ const { url, shows, canGo } = renderCustomers('/companies/company/acme/team');
+ await shows('tab:active section:team records:company:acme:');
+
+ // No list entry precedes it, so the list opens as a new entry.
+ route.close();
+ await shows('tab:active section:- records:');
+ expect(url()).toBe('/companies');
+ expect(canGo(-1)).toBe(true);
+});
+
+it('opens pipelines and their records under the pipeline path', async () => {
+ const { url, shows } = renderCustomers('/companies');
+ route.setTab('pipeline:sales');
+ await shows('tab:pipeline:sales section:- records:');
+ expect(url()).toBe('/companies/pipeline/sales');
+
+ route.open([acme]);
+ await shows('tab:pipeline:sales section:- records:company:acme:Acme');
+ expect(url()).toBe('/companies/pipeline/sales/company/acme');
+
+ route.close();
+ await shows('tab:pipeline:sales section:- records:');
+ expect(url()).toBe('/companies/pipeline/sales');
+
+ route.setTab('people');
+ await shows('tab:people section:- records:');
+ expect(url()).toBe('/companies?s0.crm.tab=people');
+});
+
+it('shows another list in place of an open record', async () => {
+ const { url, shows, go } = renderCustomers('/companies');
+ route.open([acme]);
+ await shows('tab:active section:- records:company:acme:Acme');
+
+ route.setTab('people');
+ await shows('tab:people section:- records:');
+ expect(url()).toBe('/companies?s0.crm.tab=people');
+
+ // Back returns to the record, with its trail.
+ await go(-1);
+ await shows('tab:active section:- records:company:acme:Acme');
+ expect(url()).toBe('/companies/company/acme');
+});
diff --git a/apps/web/src/features/crm/route-adapter.ts b/apps/web/src/features/crm/route-adapter.ts
new file mode 100644
index 0000000000..5783680eb3
--- /dev/null
+++ b/apps/web/src/features/crm/route-adapter.ts
@@ -0,0 +1,137 @@
+import {
+ createSearchParams,
+ type Entry,
+ useNavigate,
+ usePaneHistory,
+ useParams,
+ useRouteState,
+} from '@app/lib/split-router';
+import {
+ companiesRoute,
+ crmPipelineRecordRoute,
+ crmPipelineRoute,
+ crmRecordRoute,
+} from '@app/routes/routes';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { CrmRoute } from './context/workspace-context';
+import { pipelineIdOfTab, pipelineTab } from './core/navigation';
+import type { CrmRecordRef, CrmRecordSection } from './core/record';
+import { type CrmRecordParams, crmSearch, crmSearchCodec } from './crm-route';
+
+type CrmBranchParams = Partial<CrmRecordParams> & { pipelineId?: string };
+
+/** The list tab an entry shows, or undefined for a record. */
+function listTab(entry: Entry): string | undefined {
+ const leaf = entry.location.route.matches.at(-1);
+ if (leaf?.id === crmPipelineRoute.id) {
+ const { pipelineId } = leaf.params;
+ return typeof pipelineId === 'string' ? pipelineTab(pipelineId) : undefined;
+ }
+ if (leaf?.id !== companiesRoute.id) return;
+ return crmSearchCodec.parse(entry.location.search?.[crmSearch.namespace])
+ .value.tab;
+}
+
+/** The Customers location held by the pane's route. */
+export function createCrmRoute(): CrmRoute {
+ const [search] = createSearchParams(crmSearch);
+ const params = useParams<CrmBranchParams>();
+ const routeTrail = useRouteState(companiesRoute);
+ const navigate = useNavigate();
+ const history = usePaneHistory();
+
+ const tab = () =>
+ params.pipelineId ? pipelineTab(params.pipelineId) : search.tab;
+
+ const shown = (): CrmRecordRef | undefined =>
+ params.recordType && params.recordId
+ ? { type: params.recordType, id: params.recordId, name: '' }
+ : undefined;
+
+ const records = (): readonly CrmRecordRef[] => {
+ const record = shown();
+ if (!record) return [];
+ const trail = routeTrail();
+ const end = trail?.at(-1);
+ if (trail && end?.type === record.type && end.id === record.id)
+ return trail;
+ return [record];
+ };
+
+ // Records open where the user asks, even when another split shows them too.
+ const showRecord = (
+ trail: readonly CrmRecordRef[],
+ section: CrmRecordSection | undefined
+ ) => {
+ const record = trail.at(-1);
+ if (!record) return;
+ const recordParams = {
+ recordType: record.type,
+ recordId: record.id,
+ section: section === 'overview' ? undefined : section,
+ };
+ const options = { allowDuplicate: true, state: [...trail] };
+ const pipelineId = params.pipelineId;
+ fireAndForget(
+ pipelineId
+ ? navigate(
+ {
+ route: crmPipelineRecordRoute,
+ params: { pipelineId, ...recordParams },
+ },
+ options
+ )
+ : navigate({ route: crmRecordRoute, params: recordParams }, options),
+ 'crm'
+ );
+ };
+
+ const showList = (next: string, replace?: boolean) => {
+ const pipelineId = pipelineIdOfTab(next);
+ const options = {
+ allowDuplicate: true,
+ replace,
+ search: {
+ [crmSearch.namespace]: pipelineId
+ ? undefined
+ : crmSearchCodec.serialize({ tab: next }),
+ },
+ };
+ fireAndForget(
+ pipelineId
+ ? navigate({ route: crmPipelineRoute, params: { pipelineId } }, options)
+ : navigate({ route: companiesRoute, params: {} }, options),
+ 'crm'
+ );
+ };
+
+ const close = () => {
+ if (!shown()) return;
+ const current = tab();
+ // The list's own entry restores its scroll position.
+ const snapshot = history();
+ if (snapshot) {
+ for (let index = snapshot.index - 1; index >= 0; index--) {
+ const entry = snapshot.entries[index];
+ const matches = entry.location.route.matches;
+ if (!matches.some((match) => match.id === companiesRoute.id)) break;
+ const entryTab = listTab(entry);
+ if (entryTab === undefined) continue;
+ if (entryTab !== current) break;
+ fireAndForget(navigate(index - snapshot.index), 'crm');
+ return;
+ }
+ }
+ showList(current);
+ };
+
+ return {
+ tab,
+ setTab: (next, options) => showList(next, options?.replace),
+ records,
+ section: () => params.section,
+ open: (trail) => showRecord(trail, undefined),
+ setSection: (section) => showRecord(records(), section),
+ close,
+ };
+}
diff --git a/apps/web/src/features/crm/route-views.test.tsx b/apps/web/src/features/crm/route-views.test.tsx
index 296804c572..4993bdd8aa 100644
--- a/apps/web/src/features/crm/route-views.test.tsx
+++ b/apps/web/src/features/crm/route-views.test.tsx
@@ -6,7 +6,7 @@ import { encodeCrmViewParam } from './queries/saved-view-codec';
import { CompaniesRouteView } from './route-views';
const fixture = vi.hoisted(() => ({
- setSearch: vi.fn(),
+ setTab: vi.fn(),
search: undefined as unknown as () => string,
}));
@@ -19,12 +19,8 @@ vi.mock('@core/constant/featureFlags', () => ({
enableCrm: 'crm',
isFeatureEnabled: () => true,
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- createSearchParams: () => [
- { tab: 'active', pipeline: '', seek: '' },
- fixture.setSearch,
- ],
+vi.mock('./route-adapter', () => ({
+ createCrmRoute: () => ({ setTab: fixture.setTab }),
}));
vi.mock('@solidjs/router', () => ({
useLocation: () => ({
@@ -37,32 +33,28 @@ vi.mock('./crm', () => ({ Crm: () => null }));
afterEach(() => {
cleanup();
- fixture.setSearch.mockReset();
+ fixture.setTab.mockReset();
});
const pipelineId = '01a1212c-74e5-79bd-8767-0d4943d55b15';
const link = (activeTab: string) =>
`?crmView=${encodeCrmViewParam({ kind: 'crm', activeTab })}`;
-it('opens a shared pipeline link followed while Customers is open', () => {
+it('opens an older shared pipeline link followed while Customers is open', () => {
const [search, setSearch] = createSignal('?s0.crm.tab=people');
fixture.search = search;
render(() => <CompaniesRouteView />);
setSearch(link(pipelineTab(pipelineId)));
- expect(fixture.setSearch).toHaveBeenCalledExactlyOnceWith(
- {
- tab: pipelineTab(pipelineId),
- pipeline: pipelineId,
- seek: expect.any(String),
- },
- { mode: 'merge', history: 'replace' }
+ expect(fixture.setTab).toHaveBeenCalledExactlyOnceWith(
+ pipelineTab(pipelineId),
+ { replace: true }
);
// Moving between Customers tabs keeps the link in the URL.
setSearch(`${link(pipelineTab(pipelineId))}&s0.crm.tab=people`);
setSearch(link(pipelineTab(pipelineId)));
- expect(fixture.setSearch).toHaveBeenCalledOnce();
+ expect(fixture.setTab).toHaveBeenCalledOnce();
});
it('leaves links to other Customers views alone', () => {
@@ -71,5 +63,5 @@ it('leaves links to other Customers views alone', () => {
render(() => <CompaniesRouteView />);
setSearch(link('people'));
- expect(fixture.setSearch).not.toHaveBeenCalled();
+ expect(fixture.setTab).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/features/crm/route-views.tsx b/apps/web/src/features/crm/route-views.tsx
index a39104a795..4d51636edd 100644
--- a/apps/web/src/features/crm/route-views.tsx
+++ b/apps/web/src/features/crm/route-views.tsx
@@ -1,4 +1,3 @@
-import { createSearchParams } from '@app/lib/split-router';
import {
RedirectSplit,
usePageViewTracking,
@@ -6,14 +5,14 @@ import {
} from '@components/app/split-layout/split-router/app-route-shell';
import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';
import { useLocation } from '@solidjs/router';
-import { createEffect, createMemo, lazy, on, untrack } from 'solid-js';
-import type { CrmRouteSearch } from './context/workspace-context';
-import { pipelineIdOfTab, pipelineTab } from './core/navigation';
-import { crmSearch, crmViewPipelineId } from './crm-route';
+import { createEffect, createMemo, lazy, on } from 'solid-js';
+import { pipelineTab } from './core/navigation';
+import { crmViewPipelineId } from './crm-route';
import {
CRM_VIEW_URL_PARAM,
decodeCrmViewParam,
} from './queries/saved-view-codec';
+import { createCrmRoute } from './route-adapter';
const Crm = lazy(async () => ({
default: (await import('./crm')).Crm,
@@ -23,12 +22,7 @@ export const CompaniesRouteView = withAuth(() => {
if (!isFeatureEnabled(enableCrm))
return <RedirectSplit to={{ type: 'component', id: 'home' }} />;
usePageViewTracking('companies');
- const [search, setSearch] = createSearchParams(crmSearch);
- const pipelineRequest = () =>
- search.pipeline
- ? { pipelineId: search.pipeline, seek: search.seek }
- : undefined;
- const requested = untrack(pipelineRequest);
+ const route = createCrmRoute();
const crmView = new URLSearchParams(window.location.search).get(
CRM_VIEW_URL_PARAM
);
@@ -36,64 +30,22 @@ export const CompaniesRouteView = withAuth(() => {
const linkedPipelineId = createMemo(() =>
crmViewPipelineId(new URLSearchParams(location.search))
);
- // A shared pipeline link followed while Customers is already open.
+ // An older shared pipeline link followed while Customers is open leaves the
+ // pane's own location unchanged, so the router has nothing to redirect.
createEffect(
on(
linkedPipelineId,
(pipelineId) => {
- if (!pipelineId) return;
- setSearch(
- {
- tab: pipelineTab(pipelineId),
- pipeline: pipelineId,
- seek: crypto.randomUUID(),
- },
- { mode: 'merge', history: 'replace' }
- );
+ if (pipelineId)
+ route.setTab(pipelineTab(pipelineId), { replace: true });
},
{ defer: true }
)
);
- const routeSearch: CrmRouteSearch = {
- tab: () => search.tab,
- setTab: (
- tab: string,
- options?: { replace?: boolean; clearPipelineRequest?: boolean }
- ) => {
- const nextTab = tab || 'active';
- const clearRequest =
- options?.clearPipelineRequest ||
- (untrack(() => search.pipeline) !== '' &&
- pipelineIdOfTab(nextTab) !== untrack(() => search.pipeline));
- setSearch(
- clearRequest
- ? { tab: nextTab, pipeline: '', seek: '' }
- : { tab: nextTab },
- {
- mode: 'merge',
- history: options?.replace ? 'replace' : 'push',
- }
- );
- },
- };
return (
<Crm
- initialView={
- requested
- ? { kind: 'crm', activeTab: pipelineTab(requested.pipelineId) }
- : crmView
- ? decodeCrmViewParam(crmView)
- : undefined
- }
- pipelineRequest={{
- current: pipelineRequest,
- release: () =>
- setSearch(
- { pipeline: '', seek: '' },
- { mode: 'merge', history: 'replace' }
- ),
- }}
- routeSearch={routeSearch}
+ initialView={crmView ? decodeCrmViewParam(crmView) : undefined}
+ route={route}
/>
);
});
diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsx
index d5468dd8b1..f640772274 100644
--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx
@@ -183,10 +183,11 @@ vi.mock('../components/pipeline-dialog', () => ({
vi.mock('./record-detail', () => ({
CrmRecordDetail: (props: {
viewName: string;
- record: { type: string; id: string };
+ records: { type: string; id: string }[];
}) => (
<div>
- {props.viewName} record {props.record.type}:{props.record.id}
+ {props.viewName} record{' '}
+ {props.records.map((record) => `${record.type}:${record.id}`).join(' ')}
</div>
),
}));
@@ -264,21 +265,32 @@ afterEach(() => {
fixture.setCollapsed.mockReset();
});
+/** A workspace whose route shows another tab's list when the tab changes. */
function setup(initialTab = 'active') {
- const [activeTab, setActiveTab] = createSignal<string | undefined>(
- initialTab
- );
- const [pipelineRequest, setPipelineRequest] = createSignal<
- { pipelineId: string; seek: string } | undefined
- >();
+ const [activeTab, setTab] = createSignal<string | undefined>(initialTab);
+ const [records, setRecords] = createSignal<
+ readonly { type: 'company' | 'contact'; id: string; name: string }[]
+ >([]);
+ const record = {
+ records,
+ section: () => undefined,
+ open: vi.fn(setRecords),
+ setSection: vi.fn(),
+ close: vi.fn(() => setRecords([])),
+ };
+ const setActiveTab = (tab: string) => {
+ setRecords([]);
+ setTab(tab);
+ };
+ const captureEntryState = vi.fn();
fixture.workspace = {
activeTab,
setActiveTab,
host: {
scopeId: 'crm',
isActive: () => true,
- captureEntryState: vi.fn(),
- pipelineRequest,
+ captureEntryState,
+ record,
},
source: {},
queryFilters: { state: { include: {} }, replace: vi.fn() },
@@ -286,7 +298,7 @@ function setup(initialTab = 'active') {
render(() => (
<CrmWorkspaceView>{() => <div>Record list</div>}</CrmWorkspaceView>
));
- return { activeTab, setActiveTab, setPipelineRequest };
+ return { activeTab, record, captureEntryState };
}
it('keeps sidebar destinations in the mobile header when switching records, pipelines and lists', () => {
@@ -327,24 +339,27 @@ it('omits pipelines and lists when those features are disabled', () => {
).toEqual(['Companies', 'People']);
});
-it('shows the company of a pipeline row in place of the pipeline on desktop', () => {
+it('opens the company of a pipeline row through the route on desktop', () => {
fixture.touch = false;
- setup('pipeline:sales');
+ const { record, captureEntryState } = setup('pipeline:sales');
fireEvent.click(screen.getByRole('button', { name: 'Open Acme' }));
+ expect(captureEntryState).toHaveBeenCalledBefore(record.open);
+ expect(record.open).toHaveBeenCalledExactlyOnceWith([
+ { type: 'company', id: 'acme', name: '' },
+ ]);
expect(screen.getByText('Sales record company:acme')).toBeTruthy();
expect(screen.queryByText('Sales table')).toBeNull();
expect(fixture.openWithSplit).not.toHaveBeenCalled();
});
-it('shows a pipeline another view asks for, in place of an open record', () => {
+it('returns to the pipeline when its record is open and the pipeline is picked again', () => {
fixture.touch = false;
- const { activeTab, setPipelineRequest } = setup('pipeline:sales');
+ const { activeTab, record } = setup('pipeline:sales');
fireEvent.click(screen.getByRole('button', { name: 'Open Acme' }));
- expect(screen.queryByText('Sales table')).toBeNull();
- setPipelineRequest({ pipelineId: 'sales', seek: 'first' });
+ fireEvent.click(screen.getByRole('button', { name: 'Sales' }));
+ expect(record.close).toHaveBeenCalledOnce();
expect(activeTab()).toBe('pipeline:sales');
expect(screen.getByText('Sales table')).toBeTruthy();
- expect(screen.queryByText('Sales record company:acme')).toBeNull();
});
it('keeps the split close in the header and offers no collapse in the narrow navigation menu', () => {
@@ -384,12 +399,22 @@ it('opens the company of a pipeline row in its own split on touch', () => {
expect(screen.getByText('Sales table')).toBeTruthy();
});
-it('closes an open record when activeTab changes via history navigation', () => {
+it('returns to the list when the open record’s tab is picked again', () => {
fixture.touch = false;
- const { setActiveTab } = setup('pipeline:sales');
+ const { record } = setup('people');
+ record.open([{ type: 'contact', id: 'maya', name: 'Maya' }]);
+ expect(screen.getByText('People record contact:maya')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'People' }));
+ expect(record.close).toHaveBeenCalledOnce();
+ expect(screen.getByText('Record list')).toBeTruthy();
+});
+
+it('shows another tab’s list in place of an open record without closing it first', () => {
+ fixture.touch = false;
+ const { activeTab, record } = setup('pipeline:sales');
fireEvent.click(screen.getByRole('button', { name: 'Open Acme' }));
- expect(screen.getByText('Sales record company:acme')).toBeTruthy();
- setActiveTab('people');
- expect(screen.queryByText(/record company:acme/)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'People' }));
+ expect(record.close).not.toHaveBeenCalled();
+ expect(activeTab()).toBe('people');
expect(screen.getByText('Record list')).toBeTruthy();
});
diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsx
index 5ecf3fe68e..c8a96032f3 100644
--- a/apps/web/src/features/crm/views/crm-workspace.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.tsx
@@ -32,7 +32,6 @@ import {
createEffect,
createSignal,
type JSX,
- on,
onCleanup,
onMount,
Show,
@@ -46,12 +45,13 @@ import { PipelineSidebar } from '../components/pipeline-sidebar';
import { useCrmContext } from '../context/crm-context';
import { useCrmWorkspace } from '../context/workspace-context';
import { CRM_RECORDS, pipelineIdOfTab, pipelineTab } from '../core/navigation';
+import type { CrmRecordRef } from '../core/record';
import { createCrmExportLoader } from '../primitives/export-source';
import { useApplyCrmView } from './apply-view';
import { CrmExport } from './export-companies';
import { CrmImport } from './import-companies';
import { PipelineView } from './pipeline';
-import { CrmRecordDetail, type CrmRecordRef } from './record-detail';
+import { CrmRecordDetail } from './record-detail';
import { CompanyDisplayMenu, CompanyViewsMenu } from './saved-views-menu';
import {
useCrmLists,
@@ -214,25 +214,16 @@ export function CrmWorkspaceView(props: {
openCreateContact: openCreateContactModal,
exportCompanies: fetchCrmExportCompanies,
PipelineEditor,
- copyViewLink,
+ copyPipelineLink,
} = useCrmContext();
const view = useCrmWorkspace();
const { openWithSplit } = useCrmContext().createNavigation();
- const [selectedRecord, setSelectedRecord] = createSignal<CrmRecordRef>();
- const closeRecord = () => setSelectedRecord(undefined);
- // Back and Forward change the tab without going through sidebar navigation.
- createEffect(
- on(
- view.activeTab,
- () => {
- closeRecord();
- },
- { defer: true }
- )
- );
+ const records = view.host.record.records;
+ const recordOpen = () => records().length > 0;
const showRecord = (record: CrmRecordRef) => {
+ // The list unmounts; its entry keeps the scroll position for the return.
view.host.captureEntryState();
- setSelectedRecord(record);
+ view.host.record.open([record]);
};
const openRecord = (entity: EntityData) => {
const type = isCrmCompanyEntity(entity)
@@ -274,20 +265,11 @@ export function CrmWorkspaceView(props: {
pipelinesEnabled() ? pipelineIdOfTab(view.activeTab()) : undefined;
const activePipeline = () =>
pipelines.pipelines().find((pipeline) => pipeline.id === pipelineId());
+ // Another tab's list replaces an open record; the same tab returns to its list.
const selectPipeline = (id: string) => {
- closeRecord();
- view.setActiveTab(pipelineTab(id));
+ if (pipelineTab(id) === view.activeTab()) view.host.record.close();
+ else view.setActiveTab(pipelineTab(id));
};
- // The first request already chose the initial tab.
- createEffect(
- on(
- view.host.pipelineRequest,
- (request) => {
- if (request) selectPipeline(request.pipelineId);
- },
- { defer: true }
- )
- );
const listsEnabled = useCrmContext().listsEnabled();
const lists = useCrmLists(() => (listsEnabled() ? teamId() : undefined));
const [editing, setEditing] = createSignal<{
@@ -334,7 +316,8 @@ export function CrmWorkspaceView(props: {
'Companies';
const navigate = (id: string) => {
if (!listsEnabled() && id.startsWith('list:')) id = 'active';
- closeRecord();
+ if (id !== 'people' && !id.startsWith('list:')) id = 'active';
+ if (id === active()) view.host.record.close();
if (id === 'people') {
// Re-applying would clear a search the People search bar still shows.
if (peopleActive()) return;
@@ -347,7 +330,6 @@ export function CrmWorkspaceView(props: {
});
return;
}
- if (!id.startsWith('list:')) id = 'active';
const preset = getViewPreset('companies');
const list = lists.lists().find((list) => `list:${list.id}` === id);
const filters = structuredClone(preset?.filters ?? {});
@@ -423,7 +405,7 @@ export function CrmWorkspaceView(props: {
</Suspense>
</ViewShell.Aside>
<ViewShell.Main>
- <Show when={isTouchDevice() && !selectedRecord()}>
+ <Show when={isTouchDevice() && !recordOpen()}>
<ViewShell.Header>
<CrmMobileTabs
active={activeRecord()}
@@ -449,22 +431,23 @@ export function CrmWorkspaceView(props: {
</Suspense>
</Show>
</Show>
- <Show when={selectedRecord()} keyed>
- {(record) => (
- <CrmRecordDetail
- record={record}
- viewName={activePipeline()?.name ?? title()}
- onClose={closeRecord}
- onOpenPipeline={selectPipeline}
- navigation={
- <NavigationToggle onExpand={() => setCollapsed(false)}>
- <Suspense>{sidebar()}</Suspense>
- </NavigationToggle>
- }
- />
- )}
+ <Show when={recordOpen()}>
+ <CrmRecordDetail
+ records={records()}
+ section={view.host.record.section()}
+ viewName={activePipeline()?.name ?? title()}
+ onOpen={view.host.record.open}
+ onSectionChange={view.host.record.setSection}
+ onClose={view.host.record.close}
+ onOpenPipeline={selectPipeline}
+ navigation={
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ }
+ />
</Show>
- <Show when={!selectedRecord() && pipelineId()} keyed>
+ <Show when={!recordOpen() && pipelineId()} keyed>
{(id) => (
<Show when={activePipeline()}>
{(pipeline) => (
@@ -477,12 +460,7 @@ export function CrmWorkspaceView(props: {
}}
Sharing={useCrmContext().PipelineSharing}
Editor={PipelineEditor}
- onCopyLink={() =>
- copyViewLink({
- kind: 'crm',
- activeTab: pipelineTab(id),
- })
- }
+ onCopyLink={() => copyPipelineLink(id)}
onTrashed={() => navigate('active')}
onOpenRecord={openPipelineRecord}
navigation={
@@ -511,7 +489,7 @@ export function CrmWorkspaceView(props: {
</Button>
</div>
</Show>
- <Show when={!selectedRecord() && !pipelineId()}>
+ <Show when={!recordOpen() && !pipelineId()}>
<Show when={!isTouchDevice() || peopleActive()}>
<Show when={!isTouchDevice()}>
<div class="flex h-12 shrink-0 items-center gap-3 px-4">
diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsx
index d720b387f8..bff9c84071 100644
--- a/apps/web/src/features/crm/views/record-detail.test.tsx
+++ b/apps/web/src/features/crm/views/record-detail.test.tsx
@@ -14,6 +14,7 @@ import {
} from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
import type { CrmContact } from '../core/contact';
+import type { CrmRecordRef, CrmRecordSection } from '../core/record';
import { CrmRecordDetail } from './record-detail';
vi.mock('@ui', async () => ({
@@ -31,7 +32,13 @@ vi.mock('@components/app/side-panel', () => ({
}));
vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));
vi.mock('./copy-link-button', () => ({ CrmCopyLinkButton: () => null }));
-vi.mock('../components/record-tabs', () => ({ RecordTabs: () => null }));
+vi.mock('../components/record-tabs', () => ({
+ RecordTabs: (props: { onChange(section: CrmRecordSection): void }) => (
+ <button type="button" onClick={() => props.onChange('emails')}>
+ Show emails
+ </button>
+ ),
+}));
vi.mock('./use-crm', () => ({
useCompanyQuery: () => ({
query: { isError: false },
@@ -75,64 +82,82 @@ vi.mock('./contact-detail', () => ({
}));
afterEach(cleanup);
-it('removes contact breadcrumbs safely when returning to the company and reopening details', () => {
+/** Stands in for the route: each open hands the detail a new trail. */
+function renderDetail(record: CrmRecordRef, viewName: string) {
+ const [records, setRecords] = createSignal<readonly CrmRecordRef[]>([record]);
+ const [section, setSection] = createSignal<CrmRecordSection>();
+ const open = (trail: readonly CrmRecordRef[]) =>
+ setRecords(trail.map((entry) => ({ ...entry })));
+ const close = vi.fn(() => setRecords([]));
const failed = vi.fn(() => <div>Navigation failed</div>);
- const [selected, setSelected] = createSignal(true);
render(() => (
<ErrorBoundary fallback={failed}>
<Show
- when={selected()}
+ when={records().length > 0}
fallback={
- <button onClick={() => setSelected(true)}>Open company</button>
+ <button onClick={() => setRecords([record])}>
+ Reopen {record.name}
+ </button>
}
>
<CrmRecordDetail
- record={{ type: 'company', id: 'company-1', name: 'Northstar' }}
- viewName="Pipeline"
- onClose={() => setSelected(false)}
+ records={records()}
+ section={section()}
+ viewName={viewName}
+ onOpen={open}
+ onSectionChange={(next) => {
+ setSection(next);
+ open(records());
+ }}
+ onClose={close}
navigation={null}
/>
</Show>
</ErrorBoundary>
));
+ return { close, records, failed };
+}
+
+const crumbs = () =>
+ within(screen.getByRole('navigation', { name: 'CRM record location' }))
+ .getAllByRole('button')
+ .map((button) => button.textContent);
+
+it('removes contact breadcrumbs safely when returning to the company and reopening details', () => {
+ const { failed } = renderDetail(
+ { type: 'company', id: 'company-1', name: 'Northstar' },
+ 'Pipeline'
+ );
for (let round = 0; round < 2; round++) {
fireEvent.click(screen.getByRole('button', { name: 'Open Maya' }));
- const breadcrumbs = () =>
- within(screen.getByRole('navigation', { name: 'CRM record location' }));
- expect(breadcrumbs().getAllByRole('button')).toHaveLength(3);
+ expect(crumbs()).toEqual(['Pipeline', 'Northstar', 'Maya']);
expect(screen.getByText('Contact content: contact-1')).toBeTruthy();
- fireEvent.click(breadcrumbs().getByRole('button', { name: 'Northstar' }));
- expect(failed).not.toHaveBeenCalled();
- expect(breadcrumbs().getAllByRole('button')).toHaveLength(2);
+ fireEvent.click(screen.getByRole('button', { name: 'Northstar' }));
+ expect(crumbs()).toEqual(['Pipeline', 'Northstar']);
expect(screen.getByRole('button', { name: 'Open Maya' })).toBeTruthy();
- fireEvent.click(breadcrumbs().getByRole('button', { name: 'Pipeline' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Pipeline' }));
expect(
screen.queryByRole('navigation', { name: 'CRM record location' })
).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'Open company' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Reopen Northstar' }));
}
expect(failed).not.toHaveBeenCalled();
});
it('opens a People contact in place and follows its company without duplicating the trail', () => {
- const close = vi.fn();
- render(() => (
- <CrmRecordDetail
- record={{ type: 'contact', id: 'contact-1', name: 'Maya' }}
- viewName="People"
- onClose={close}
- navigation={null}
- />
- ));
- const crumbs = () =>
- within(screen.getByRole('navigation', { name: 'CRM record location' }))
- .getAllByRole('button')
- .map((button) => button.textContent);
+ const { close, records } = renderDetail(
+ { type: 'contact', id: 'contact-1', name: 'Maya' },
+ 'People'
+ );
expect(crumbs()).toEqual(['People', 'Maya']);
expect(screen.getByText('Contact content: contact-1')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Open contact company' }));
expect(crumbs()).toEqual(['People', 'Maya', 'Company']);
+ expect(records().map((record) => record.id)).toEqual([
+ 'contact-1',
+ 'company-1',
+ ]);
// The company's contact is already in the trail, so opening it returns there.
fireEvent.click(screen.getByRole('button', { name: 'Open Maya' }));
@@ -141,3 +166,11 @@ it('opens a People contact in place and follows its company without duplicating
fireEvent.click(screen.getByRole('button', { name: 'People' }));
expect(close).toHaveBeenCalledOnce();
});
+
+it('keeps the shown record mounted while the route only changes its tab', () => {
+ renderDetail({ type: 'contact', id: 'contact-1', name: 'Maya' }, 'People');
+ const content = screen.getByText('Contact content: contact-1');
+ fireEvent.click(screen.getByRole('button', { name: 'Show emails' }));
+ expect(screen.getByText('Contact content: contact-1')).toBe(content);
+ expect(crumbs()).toEqual(['People', 'Maya']);
+});
diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsx
index a2a6bfc437..5b5b52ac70 100644
--- a/apps/web/src/features/crm/views/record-detail.tsx
+++ b/apps/web/src/features/crm/views/record-detail.tsx
@@ -5,13 +5,14 @@ import { fireAndForget } from '@core/util/fireAndForget';
import SpinnerIcon from '@phosphor/spinner.svg';
import { Button, Tooltip } from '@ui';
import {
- createSignal,
+ createMemo,
ErrorBoundary,
For,
type JSX,
onMount,
Show,
Suspense,
+ untrack,
} from 'solid-js';
import { RecordTabs } from '../components/record-tabs';
import {
@@ -19,19 +20,14 @@ import {
CONTACT_SECTIONS,
type CompanySection,
type ContactSection,
+ type CrmRecordRef,
+ type CrmRecordSection,
} from '../core/record';
import { Company } from './company-detail';
import { Contact } from './contact-detail';
import { CrmCopyLinkButton } from './copy-link-button';
import { useCompanyQuery, useContactQuery } from './use-crm';
-/** A CRM record shown inside the workspace, with its fallback label. */
-export type CrmRecordRef = {
- type: 'company' | 'contact';
- id: string;
- name: string;
-};
-
const recordKey = (record: CrmRecordRef) => `${record.type}:${record.id}`;
function createRecordName(record: CrmRecordRef): () => string {
@@ -48,34 +44,48 @@ function createRecordName(record: CrmRecordRef): () => string {
};
}
+function sectionOf<T extends CrmRecordSection>(
+ sections: readonly T[],
+ section: CrmRecordSection | undefined
+): T {
+ return sections.find((candidate) => candidate === section) ?? sections[0]!;
+}
+
/**
* Records opened inside the CRM workspace. Each opened record appends a
* breadcrumb after the originating view; reopening one already in the trail
* returns to it.
*/
export function CrmRecordDetail(props: {
- record: CrmRecordRef;
+ /** Opened records, oldest first; the last one is shown. */
+ records: readonly CrmRecordRef[];
+ section: CrmRecordSection | undefined;
viewName: string;
+ onOpen: (records: readonly CrmRecordRef[]) => void;
+ onSectionChange: (section: CrmRecordSection) => void;
onClose: () => void;
navigation: JSX.Element;
onOpenPipeline?: (pipelineId: string) => void;
}) {
- const [trail, setTrail] = createSignal<CrmRecordRef[]>([props.record]);
- const current = () => trail()[trail().length - 1];
- const [companySection, setCompanySection] =
- createSignal<CompanySection>('overview');
- const [contactSection, setContactSection] =
- createSignal<ContactSection>('overview');
- const returnTo = (index: number) =>
- setTrail((records) => records.slice(0, index + 1));
+ const trail = () => props.records;
+ // Each navigation brings new record objects; only another record remounts.
+ const current = createMemo(() => trail()[trail().length - 1]!, undefined, {
+ equals: (left, right) => recordKey(left) === recordKey(right),
+ });
+ const companySection = (): CompanySection =>
+ sectionOf(COMPANY_SECTIONS, props.section);
+ const contactSection = (): ContactSection =>
+ sectionOf(CONTACT_SECTIONS, props.section);
+ const returnTo = (index: number) => {
+ if (index === trail().length - 1) return;
+ props.onOpen(trail().slice(0, index + 1));
+ };
const open = (record: CrmRecordRef) => {
const index = trail().findIndex(
(entry) => recordKey(entry) === recordKey(record)
);
if (index !== -1) return returnTo(index);
- if (record.type === 'company') setCompanySection('overview');
- else setContactSection('overview');
- setTrail((records) => [...records, record]);
+ props.onOpen([...trail(), record]);
};
const back = () =>
trail().length > 1 ? returnTo(trail().length - 2) : props.onClose();
@@ -109,12 +119,15 @@ export function CrmRecordDetail(props: {
</Tooltip>
)}
</ViewBreadcrumbs.Item>
- <For each={trail()}>
- {(record, index) => {
+ <For each={trail().map(recordKey)}>
+ {(key, index) => {
+ const record = untrack(
+ () => trail().find((entry) => recordKey(entry) === key)!
+ );
const name = createRecordName(record);
return (
<ViewBreadcrumbs.Item
- value={recordKey(record)}
+ value={key}
metadata={{ type: record.type, id: record.id }}
order={index() + 1}
>
@@ -159,14 +172,14 @@ export function CrmRecordDetail(props: {
<RecordTabs
sections={COMPANY_SECTIONS}
value={companySection()}
- onChange={setCompanySection}
+ onChange={props.onSectionChange}
/>
}
>
<RecordTabs
sections={CONTACT_SECTIONS}
value={contactSection()}
- onChange={setContactSection}
+ onChange={props.onSectionChange}
/>
</Show>
</div>
diff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsx
index 3d2a21cafd..947e3a8af3 100644
--- a/apps/web/src/features/crm/workspace-adapter.tsx
+++ b/apps/web/src/features/crm/workspace-adapter.tsx
@@ -19,12 +19,7 @@ import { useSoupFilterPersistence } from '../next-soup/use-soup-filter-persisten
import { openEntityInSplitFromUnifiedList } from '../next-soup/utils';
import type { CrmContext } from './context/crm-context';
import type { DealStages } from './context/crm-sources';
-import type {
- CrmPipelineRequest,
- CrmRouteSearch,
- CrmWorkspace,
-} from './context/workspace-context';
-import { pipelineIdOfTab } from './core/navigation';
+import type { CrmRoute, CrmWorkspace } from './context/workspace-context';
import type { CrmViewConfig } from './core/saved-view';
import { createCrmCollectionFilters } from './filter-adapter';
import { COMPANY_GROUP_OPTIONS } from './group-options';
@@ -75,9 +70,8 @@ function applySharedSubFilters(
export function createCrmWorkspace(
crm: CrmContext,
- sharedView?: CrmViewConfig,
- pipelineRequest?: CrmPipelineRequest,
- routeSearch?: CrmRouteSearch
+ route: CrmRoute,
+ sharedView?: CrmViewConfig
) {
const soup = useSoup();
const panel = useSplitPanelOrThrow();
@@ -120,9 +114,11 @@ export function createCrmWorkspace(
const soupView = { ...state.context, ...filters.state };
const preset = getViewPreset('companies');
const initialUrlTab = untrack(() => {
- const tab = routeSearch?.tab();
- return tab && tab !== VIEW_TAB_PRESETS.companies.default ? tab : undefined;
+ const tab = route.tab();
+ return tab !== VIEW_TAB_PRESETS.companies.default ? tab : undefined;
});
+ // A record link names its list; nothing may move it off the record.
+ const initialRecordOpen = untrack(() => route.records().length > 0);
const initialTabPreset =
initialUrlTab && initialUrlTab in VIEW_TAB_PRESETS.companies.tabs
? getViewPreset('companies', initialUrlTab)
@@ -155,23 +151,21 @@ export function createCrmWorkspace(
const initialCrmView = sharedView;
// A default saved view only applies to a fresh Customers entry. Restored
- // entries, share links, and an explicit URL tab keep their own state.
+ // entries, share links, record links, and an explicit URL tab keep their own state.
const applyDefaultCrmView =
initialCrmView === undefined &&
initialUrlTab === undefined &&
+ !initialRecordOpen &&
persistedFilters === undefined &&
persistedPredicates === undefined;
const fallbackPreset = initialTabPreset ?? preset;
- const defaultTab = VIEW_TAB_PRESETS.companies.default;
- const rememberedTab = routeSearch
- ? defaultTab
- : (soupView.getPersistedActiveTab('companies') ?? defaultTab);
- const initialActiveTab =
- initialCrmView?.activeTab ??
- initialUrlTab ??
- persistedActiveTab ??
- rememberedTab;
+ const initialActiveTab = initialRecordOpen
+ ? untrack(route.tab)
+ : (initialCrmView?.activeTab ??
+ initialUrlTab ??
+ persistedActiveTab ??
+ VIEW_TAB_PRESETS.companies.default);
const initialGroupBy = resolveInitialGroupBy(
initialCrmView,
persistedGroupBy,
@@ -208,8 +202,8 @@ export function createCrmWorkspace(
);
soupView.setActiveTab(initialActiveTab);
- if (routeSearch && initialActiveTab !== untrack(routeSearch.tab)) {
- routeSearch.setTab(initialActiveTab, { replace: true });
+ if (initialActiveTab !== untrack(route.tab)) {
+ route.setTab(initialActiveTab, { replace: true });
}
if (initialCrmView) {
@@ -218,49 +212,34 @@ export function createCrmWorkspace(
});
});
- if (routeSearch) {
- createEffect(
- on(
- routeSearch.tab,
- (urlTab) => {
- const target = urlTab || VIEW_TAB_PRESETS.companies.default;
- const current =
- untrack(soupView.activeTab) ?? VIEW_TAB_PRESETS.companies.default;
- if (target === current) return;
- batch(() => {
- soupView.setActiveTab(target);
- if (target in VIEW_TAB_PRESETS.companies.tabs) {
- const tabPreset = getViewPreset('companies', target);
- if (tabPreset) {
- soupView.queryFilters.replace(tabPreset.filters);
- soup.predicates.set(tabPreset.clientFilters);
- soup.grouping.setActiveGroupId(tabPreset.groupBy);
- }
- }
- });
- },
- { defer: true }
- )
- );
- }
-
- createEffect(() => {
- panel.handle.setDisplayName('Customers');
- });
-
- // Only a tab change releases: a new request arrives before its tab does.
createEffect(
on(
- soupView.activeTab,
- (tab) => {
- const request = untrack(() => pipelineRequest?.current());
- if (request && pipelineIdOfTab(tab) !== request.pipelineId)
- pipelineRequest?.release();
+ route.tab,
+ (urlTab) => {
+ const target = urlTab || VIEW_TAB_PRESETS.companies.default;
+ const current =
+ untrack(soupView.activeTab) ?? VIEW_TAB_PRESETS.companies.default;
+ if (target === current) return;
+ batch(() => {
+ soupView.setActiveTab(target);
+ if (target in VIEW_TAB_PRESETS.companies.tabs) {
+ const tabPreset = getViewPreset('companies', target);
+ if (tabPreset) {
+ soupView.queryFilters.replace(tabPreset.filters);
+ soup.predicates.set(tabPreset.clientFilters);
+ soup.grouping.setActiveGroupId(tabPreset.groupBy);
+ }
+ }
+ });
},
{ defer: true }
)
);
+ createEffect(() => {
+ panel.handle.setDisplayName('Customers');
+ });
+
// Bridge live soup sort state back to preferences. `defer: true` skips the
// initial run on mount, so we only write when the user actually changes it.
createEffect(
@@ -289,14 +268,8 @@ export function createCrmWorkspace(
const target =
(typeof next === 'function' ? resolved : next) ??
VIEW_TAB_PRESETS.companies.default;
- if (routeSearch && target !== untrack(routeSearch.tab)) {
- const request = untrack(() => pipelineRequest?.current());
- routeSearch.setTab(target, {
- replace: replaceNextTab || target === previous,
- clearPipelineRequest:
- request !== undefined &&
- pipelineIdOfTab(target) !== request.pipelineId,
- });
+ if (target !== untrack(route.tab)) {
+ route.setTab(target, { replace: replaceNextTab || target === previous });
}
return resolved;
};
@@ -325,7 +298,7 @@ export function createCrmWorkspace(
},
openSettings: () => openSettings('CRM'),
openTeamSettings: () => openSettings('Team'),
- pipelineRequest: () => pipelineRequest?.current(),
+ record: route,
},
};
return { state, context, applyDefaultCrmView, withReplaceHistory };
diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsx
index 61567d8b01..8a18d12fa9 100644
--- a/apps/web/src/routes/app-router-view.tsx
+++ b/apps/web/src/routes/app-router-view.tsx
@@ -99,6 +99,9 @@ import {
channelsSplitRoute,
codersRoute,
companiesRoute,
+ crmPipelineRecordRoute,
+ crmPipelineRoute,
+ crmRecordRoute,
debugRoutes,
driveCallRoute,
driveFolderDocumentRoute,
@@ -399,7 +402,12 @@ export function AppRouterView() {
<Route definition={callsCallRoute} component={CallsCallDetail} />
</Route>
<Route definition={callDetailRoute} component={CallDetailRouteView} />
- <Route definition={companiesRoute} component={CompaniesRouteView} />
+ <Route definition={companiesRoute} component={CompaniesRouteView}>
+ <Route definition={crmPipelineRoute}>
+ <Route definition={crmPipelineRecordRoute} />
+ </Route>
+ <Route definition={crmRecordRoute} />
+ </Route>
<Route definition={foldersRoute} component={FoldersRouteView} />
<Route definition={searchRoute} component={SearchRouteView} />
<Route definition={prDetailRoute} component={PrDetailRouteView} />
diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.ts
index a27c86b309..bdb48589f9 100644
--- a/apps/web/src/routes/routes.ts
+++ b/apps/web/src/routes/routes.ts
@@ -10,7 +10,15 @@ import {
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
import { changesSearch } from '@app/features/changes/changes-search';
import { mobileSearchRouteStateSchema } from '@app/features/command/mobile/mobile-search-route-state';
-import { crmViewReference } from '@app/features/crm/crm-route';
+import {
+ crmPipelineParams,
+ crmPipelineReference,
+ crmRecordClaim,
+ crmRecordParams,
+ crmRecordReference,
+ crmRecordTrailSchema,
+ crmViewReference,
+} from '@app/features/crm/crm-route';
import { driveDetailTrailSchema } from '@app/features/drive-view/primitives/drive-detail-trail';
import {
DRIVE_DETAIL_TYPES,
@@ -620,10 +628,42 @@ export const companiesRoute = defineRoute({
path: 'companies',
search: '*' as const,
externalSearch: ['crmView'],
+ state: crmRecordTrailSchema,
claim: () => ({ namespace: 'component', id: 'companies' }),
toReference: (_, query) => crmViewReference(query),
});
+/** A company or contact opened from a Customers list. */
+export const crmRecordRoute = defineRoute({
+ id: 'companies-record',
+ path: ':recordType/:recordId/:section?',
+ params: crmRecordParams,
+ state: crmRecordTrailSchema,
+ claim: crmRecordClaim,
+ toReference: crmRecordReference,
+});
+
+export const crmPipelineRecordRoute = defineRoute({
+ id: 'companies-pipeline-record',
+ path: ':recordType/:recordId/:section?',
+ params: crmRecordParams,
+ state: crmRecordTrailSchema,
+ claim: crmRecordClaim,
+ toReference: crmRecordReference,
+});
+
+export const crmPipelineRoute = defineRoute({
+ id: 'companies-pipeline',
+ path: 'pipeline/:pipelineId',
+ params: crmPipelineParams,
+ state: crmRecordTrailSchema,
+ claim: ({ pipelineId }) => ({
+ namespace: 'block',
+ id: `pipeline:${pipelineId}`,
+ }),
+ toReference: ({ pipelineId }) => crmPipelineReference(pipelineId),
+});
+
export const foldersRoute = defineRoute({
id: 'view-folders',
path: 'folders',
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 9fe9399396..13dc81cfcc 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -10,11 +10,13 @@ There are no built-in company views or Board/List layout. Companies and People
are plain soup lists with the shared pagination. Existing personal/team saved
views stay in the toolbar's Views menu.
-The selected Customers tab is stored on the pane as `sN.crm.tab`. People uses
-`people`, a pipeline uses `pipeline:<uuid>`, a list uses `list:<uuid>`, and
-hidden companies use `hidden`. Companies is the default and omits the key.
-Choosing Companies, People, a pipeline, or a list updates that parameter.
-Browser Back and Forward restore the tab and close an open record.
+The selected Customers list is stored on the pane as `sN.crm.tab`. People uses
+`people`, a list uses `list:<uuid>`, and hidden companies use `hidden`.
+Companies is the default and omits the key. A pipeline has its own path,
+`/app/companies/pipeline/<uuid>`; older `sN.crm.tab=pipeline:<uuid>` URLs and
+shared `crmView` links that show a pipeline redirect there. Choosing Companies,
+People, a pipeline, or a list updates the URL, and browser Back and Forward
+restore it.
Companies lists every visible company, grouped by Stage by default, with Owner,
Revenue and Last Interaction columns. A Stage column is off by default; turn it
@@ -54,17 +56,24 @@ row navigates in place.
On desktop, clicking a company or a person in the list (or pressing Enter on a
focused row) opens its details inside the CRM workspace, keeping the left
-navigation visible. The top breadcrumb reads `<Companies, People or list> >
-<record>`; click the first segment to return with the same filters and list
-scroll position. Selecting another sidebar entry closes the details. Shift-click
-still opens the record in a separate split. Direct company and contact links use
-the standalone pages.
-Each record opened from the details appends a breadcrumb: a contact from a
-company's Team tab gives `Companies > <company> > <contact>`, and a person's
-Company link gives `People > <contact> > <company>`. Opening a record already in
-the trail (such as the contact's own company from `Companies > <company> >
-<contact>`) returns to it instead of adding a duplicate. The CRM sidebar stays
-visible throughout.
+navigation visible. Each record has its own URL: `/app/companies/company/<uuid>`
+or `/app/companies/contact/<uuid>`, keeping the list's `sN.crm.tab`, and
+`/app/companies/pipeline/<uuid>/company/<uuid>` (or `/contact/<uuid>`) for a
+record opened from a pipeline. A record tab other than Overview adds its name,
+as in `/app/companies/company/<uuid>/team`. Browser Back returns to the list
+with the same filters and list scroll position, and Forward reopens the record.
+The top breadcrumb reads `<Companies, People, list or pipeline> > <record>`;
+click the first segment to return the same way. Selecting another sidebar entry
+shows that list in place of the details; selecting the record's own list returns
+to it. Shift-click still opens the record in a separate split. Direct company and
+contact links use the standalone pages.
+Each record opened from the details appends a breadcrumb and a history entry: a
+contact from a company's Team tab gives `Companies > <company> > <contact>`, and
+a person's Company link gives `People > <contact> > <company>`. Opening a record
+already in the trail (such as the contact's own company from `Companies >
+<company> > <contact>`) returns to it instead of adding a duplicate. Back and
+Forward restore the trail; a reloaded or shared record URL shows only `<list> >
+<record>`. The CRM sidebar stays visible throughout.
Company and contact headers have `Copy link` beside the side-panel toggle.
Their information panel starts closed and opens as a floating bubble at every
width, without shrinking the record content. Click outside the bubble or use
@@ -186,8 +195,8 @@ Pick people or channels and an access level, and the message carries the pipelin
The **People** list changes or removes their access. A teammate who receives a private
pipeline sees it in their Customers sidebar. Only the owner sees **Team access**:
choose **Edit** to share with the team or **None** to make the pipeline private.
-Viewers see only **Copy Link**. **Copy Link** copies a CRM link that opens this pipeline for
-anyone who has access, including when followed inside a split already showing Customers;
+Viewers see only **Copy Link**. **Copy Link** copies the pipeline's
+`/app/companies/pipeline/<uuid>` URL, which opens it for anyone who has access;
pasted into an editor it becomes a pipeline mention (see
[CRM pipeline mentions](documents.md#crm-pipeline-mentions)). On mobile, team
access is in the **Team** tab.
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index a024d78d7f..260d251e96 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -2389,17 +2389,16 @@ them.
Pipelines are not in the `@` menu or the command menu. Pasting a pipeline link
into an editor or composer inserts a document mention with a table icon and the
pipeline's current name: the pipeline's copy-link action
+(`/app/companies/pipeline/<id>`), an older shared view link
(`/app/companies?crmView=…` whose view is that pipeline) and
-`/app/pipeline/<id>` both work. Copied Customers links for other views
+`/app/pipeline/<id>` all work. Copied Customers links for other views
(Companies, People, lists) stay plain links. A pipeline you cannot read shows
**No Access**; a trashed one shows **Deleted**.
Clicking the mention, or pressing Enter on it, opens Customers on the pipeline
-(on touch devices too). If Customers is already open in a split, that split
-switches to the pipeline instead of a second one opening. The request travels
-as the Customers pane search `crm.pipeline` (with a `crm.seek` that makes a
-repeat click a new request), which Customers drops once you leave the
-pipeline.
+at `/app/companies/pipeline/<id>` (on touch devices too), in the mention's split
+like other entity mentions. A split already showing that pipeline is brought
+forward instead.
The mention is stored as
`<m-document-mention>{"documentId":"<pipeline id>","blockName":"pipeline",…}</m-document-mention>`.
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 3b54e81ff6..50b6220a25 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -121,7 +121,9 @@ successfully rather than hashing the empty JavaScript placeholder.
| `/app/coders/<uuid>` | Code session with the Agents sidebar |
| `/app/agents/chat/<uuid>` | Legacy AI chat opened in the Agents workspace (`/app/agent-chats/<uuid>` remains a compatibility alias) |
| `/app/calls` | Calls list |
-| `/app/companies` | Customers (CRM; needs a team). The selected tab is `sN.crm.tab` |
+| `/app/companies` | Customers (CRM; needs a team). The selected list is `sN.crm.tab` |
+| `/app/companies/<company-or-contact>/<uuid>` | Customers with a company or contact opened inline, keeping its list's `sN.crm.tab`; a record tab other than Overview adds `/<team-emails-files-tasks-or-calls>` |
+| `/app/companies/pipeline/<uuid>` | Customers on a pipeline; `/<company-or-contact>/<uuid>` after it opens a record from the pipeline. `/app/pipeline/<uuid>` redirects here |
| `/app/activity` | Activity heatmap + feed |
| `/app/calendar/<month-or-week-or-day>` | Calendar; the focused event, its occurrence, and the locator range use `sN.calendar.*` |
| `/app/scheduling` | Scheduling workspace: booking links, availability, bookings, insights, and booking page |
@@ -202,8 +204,8 @@ namespaced query parameters such as `s0.drive.sort=created_at`. Route identity
and breadcrumb nesting remain in the path. Home, Email, Tasks, Channels, and
Customers store the selected tab under `sN.home.tab`, `sN.mail.tab`,
`sN.tasks.tab`, `sN.channels.tab`, and `sN.crm.tab`. Customers uses `people`,
-`pipeline:<uuid>`, `list:<uuid>`, or `hidden`. Companies is the default and
-omits the key. Omitted tab keys mean each view's default. Mobile Channels always opens its
+`list:<uuid>`, or `hidden`; a pipeline is a path instead. Companies is the
+default and omits the key. Omitted tab keys mean each view's default. Mobile Channels always opens its
Recent conversation feed and ignores legacy mobile-tab selections.
Changing tabs updates the URL, and browser Back and Forward restore the
selection independently in each pane. Inline detail links preserve these keys.