Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
refactor(app): CMP-59 harden CRM UI foundations (#61)
grimd8123e6dd6a0
diff --git a/apps/app/app/(app)/[slug]/companies/companies-table.tsx b/apps/app/app/(app)/[slug]/companies/companies-table.tsxindex f3a6cce0..09439783 100644--- a/apps/app/app/(app)/[slug]/companies/companies-table.tsx+++ b/apps/app/app/(app)/[slug]/companies/companies-table.tsx@@ -11,21 +11,21 @@ import {type EntityLogoTone,} from "@crm/ui/components/entity-logo";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";import { useMemo } from "react";-import {- ENRICHMENT_FACET_OPTIONS,- ENRICHMENT_POLL_MS,- EnrichmentIndicator,- isEnriching,-} from "@/components/crm/enrichment-status";+import { EnrichmentIndicator } from "@/components/crm/enrichment-status";import { useFieldColumns } from "@/components/crm/fields/field-columns";import { OwnerCell } from "@/components/crm/owner-cell";import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";+import { LocalRelativeTime } from "@/components/local-date-time";+import {+ ENRICHMENT_FACET_OPTIONS,+ ENRICHMENT_POLL_MS,+ isEnriching,+} from "@/lib/enrichment-status";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { CompaniesBulkActions } from "./companies-bulk-actions";@@ -113,8 +113,8 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [width: "w-[10%]",defaultHidden: true,cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.createdAt)}+ <span className="text-muted-foreground">+ <LocalRelativeTime date={row.createdAt} /></span>),},@@ -126,8 +126,12 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [width: "w-[12%]",hideBelow: "sm",cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.lastActivityAt)}+ <span className="text-muted-foreground">+ {row.lastActivityAt ? (+ <LocalRelativeTime date={row.lastActivityAt} />+ ) : (+ <EmptyCellValue />+ )}</span>),},diff --git a/apps/app/app/(app)/[slug]/companies/page.tsx b/apps/app/app/(app)/[slug]/companies/page.tsxindex ab53f7a6..95f0f247 100644--- a/apps/app/app/(app)/[slug]/companies/page.tsx+++ b/apps/app/app/(app)/[slug]/companies/page.tsx@@ -50,9 +50,10 @@ export default function CompaniesPage({async function Companies({searchParams,}: Pick<PageProps<"/[slug]/companies">, "searchParams">) {- await requireSession();-- const values = await companiesSearchParams.load(searchParams);+ const [, values] = await Promise.all([+ requireSession(),+ companiesSearchParams.load(searchParams),+ ]);const trpc = getServerTrpc();const queryClient = getServerQueryClient();diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsxindex 97b7ef54..313a273d 100644--- a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx+++ b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx@@ -8,7 +8,6 @@ import {import { EmptyCellValue } from "@crm/ui/components/empty-cell";import { PersonAvatar } from "@crm/ui/components/person-avatar";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";import { useMemo } from "react";import { CompanyCell } from "@/components/crm/company-cell";@@ -19,6 +18,7 @@ import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetchimport { useOpenRecord } from "@/components/crm/record-sheet/record-stack";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";+import { LocalRelativeTime } from "@/components/local-date-time";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { ContactsBulkActions } from "./contacts-bulk-actions";@@ -95,8 +95,8 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [width: "w-[10%]",defaultHidden: true,cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.createdAt)}+ <span className="text-muted-foreground">+ <LocalRelativeTime date={row.createdAt} /></span>),},@@ -108,8 +108,12 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [width: "w-[12%]",hideBelow: "sm",cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.lastActivityAt)}+ <span className="text-muted-foreground">+ {row.lastActivityAt ? (+ <LocalRelativeTime date={row.lastActivityAt} />+ ) : (+ <EmptyCellValue />+ )}</span>),},diff --git a/apps/app/app/(app)/[slug]/contacts/page.tsx b/apps/app/app/(app)/[slug]/contacts/page.tsxindex f1e2801b..f5717e61 100644--- a/apps/app/app/(app)/[slug]/contacts/page.tsx+++ b/apps/app/app/(app)/[slug]/contacts/page.tsx@@ -48,9 +48,10 @@ export default function ContactsPage({async function Contacts({searchParams,}: Pick<PageProps<"/[slug]/contacts">, "searchParams">) {- await requireSession();-- const values = await contactsSearchParams.load(searchParams);+ const [, values] = await Promise.all([+ requireSession(),+ contactsSearchParams.load(searchParams),+ ]);const trpc = getServerTrpc();const queryClient = getServerQueryClient();diff --git a/apps/app/app/(app)/[slug]/dashboard-summary.tsx b/apps/app/app/(app)/[slug]/dashboard-summary.tsxindex 1ba1a716..f1d5138a 100644--- a/apps/app/app/(app)/[slug]/dashboard-summary.tsx+++ b/apps/app/app/(app)/[slug]/dashboard-summary.tsx@@ -25,23 +25,18 @@ import {import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { TableCell } from "@crm/ui/components/table";-import {- formatCount,- formatMoneyCompact,- relativeTimeFromIso,-} from "@crm/ui/lib/format";+import { formatCount, formatMoneyCompact } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import Link from "next/link";import { useQueryState } from "nuqs";-import type { CSSProperties } from "react";+import type { CSSProperties, ReactNode } from "react";import { toast } from "sonner";-import {- DealStageIndicator,- dealStageColor,-} from "@/components/crm/deal-stage";+import { DealStageIndicator } from "@/components/crm/deal-stage";import { RecordLink } from "@/components/crm/record-sheet/record-link";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";-import { activityLabel } from "@/components/crm/timeline/activity-icon";+import { LocalRelativeTime } from "@/components/local-date-time";+import { activityLabel } from "@/lib/activity-presentation";+import { dealStageColor } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import { useWorkspaceUrl } from "@/lib/use-workspace-url";@@ -49,6 +44,49 @@ import { overviewParsers } from "./overview-search-params";import { SalesDashboard } from "./sales-dashboard";const CELL = "px-3 py-2.5 align-middle";+const OPEN_COLUMNS: SimpleTableColumn[] = [+ { id: "deal", header: "Deal" },+ {+ id: "stage",+ header: "Stage",+ width: "w-32",+ className: "hidden lg:table-cell",+ },+ {+ id: "share",+ srLabel: "Share of the largest",+ width: "w-24",+ className: "hidden sm:table-cell",+ },+ { id: "value", header: "Value", width: "w-20", align: "right" },+];+const TASK_COLUMNS: SimpleTableColumn[] = [+ { id: "done", srLabel: "Done", width: "w-8" },+ { id: "task", header: "Task" },+ { id: "overdue", header: "Overdue", width: "w-24", align: "right" },+];+const ACTIVITY_COLUMNS: SimpleTableColumn[] = [+ { id: "activity", header: "Activity" },+ {+ id: "company",+ header: "Company",+ width: "w-44",+ className: "hidden md:table-cell",+ },+ {+ id: "deal",+ header: "Deal",+ width: "w-48",+ className: "hidden lg:table-cell",+ },+ {+ id: "who",+ header: "Who",+ width: "w-32",+ className: "hidden md:table-cell",+ },+ { id: "when", header: "When", width: "w-20", align: "right" },+];export function DashboardSummary() {const trpc = useTRPC();@@ -85,31 +123,6 @@ export function DashboardSummary() {const mine = scope === "me";const largestOpenCents = biggestOpen[0]?.baseAmountCents ?? 0;- const openColumns: SimpleTableColumn[] = [- { header: "Deal" },- { header: "Stage", width: "w-32", className: "hidden lg:table-cell" },- {- srLabel: "Share of the largest",- width: "w-24",- className: "hidden sm:table-cell",- },- { header: "Value", width: "w-20", align: "right" },- ];-- const taskColumns: SimpleTableColumn[] = [- { srLabel: "Done", width: "w-8" },- { header: "Task" },- { header: "Overdue", width: "w-24", align: "right" },- ];-- const activityColumns: SimpleTableColumn[] = [- { header: "Activity" },- { header: "Company", width: "w-44", className: "hidden md:table-cell" },- { header: "Deal", width: "w-48", className: "hidden lg:table-cell" },- { header: "Who", width: "w-32", className: "hidden md:table-cell" },- { header: "When", width: "w-20", align: "right" },- ];-return (<div className="flex flex-col gap-6"><SalesDashboard summary={summary} />@@ -133,7 +146,11 @@ export function DashboardSummary() {Nothing open. Time to fill the pipeline.</CardPanelEmpty>) : (- <SimpleTable variant="panel" surface="page" columns={openColumns}>+ <SimpleTable+ variant="panel"+ surface="page"+ columns={OPEN_COLUMNS}+ >{biggestOpen.map((deal) => (<SimpleTableRowkey={deal.id}@@ -144,7 +161,7 @@ export function DashboardSummary() {<DealCellname={deal.name}company={deal.company}- meta={relativeTimeFromIso(deal.stageChangedAt)}+ meta={<LocalRelativeTime date={deal.stageChangedAt} />}/></TableCell><TableCell className={`${CELL} hidden lg:table-cell`}>@@ -188,7 +205,11 @@ export function DashboardSummary() {{overdueTasks.length === 0 ? (<CardPanelEmpty>Nothing overdue. Good.</CardPanelEmpty>) : (- <SimpleTable variant="panel" surface="page" columns={taskColumns}>+ <SimpleTable+ variant="panel"+ surface="page"+ columns={TASK_COLUMNS}+ >{overdueTasks.map((task) => (<SimpleTableRow key={task.id}><TableCell className={CELL}>@@ -220,7 +241,13 @@ export function DashboardSummary() {<TableCell className={`${CELL} text-right`}><StatusIndicatortone="error"- label={relativeTimeFromIso(task.dueAt)}+ label={+ task.dueAt ? (+ <LocalRelativeTime date={task.dueAt} />+ ) : (+ "No due date"+ )+ }/></TableCell></SimpleTableRow>@@ -250,7 +277,7 @@ export function DashboardSummary() {{recentActivity.length === 0 ? (<CardTableEmpty>Nothing has happened yet.</CardTableEmpty>) : (- <SimpleTable columns={activityColumns}>+ <SimpleTable columns={ACTIVITY_COLUMNS}>{recentActivity.map((entry) => (<SimpleTableRow key={entry.id}><TableCell className={CELL}>@@ -284,9 +311,7 @@ export function DashboardSummary() {<TableCellclassName={`${CELL} text-right text-muted-foreground`}>- <span suppressHydrationWarning>- {relativeTimeFromIso(entry.createdAt)}- </span>+ <LocalRelativeTime date={entry.createdAt} /></TableCell></SimpleTableRow>))}@@ -309,7 +334,7 @@ function DealCell({iconDarkUrl: string | null;iconTone: string | null;};- meta?: string;+ meta?: ReactNode;}) {return (<span className="flex min-w-0 items-center gap-2">@@ -322,11 +347,14 @@ function DealCell({/><span className="flex min-w-0 flex-col"><span className="truncate font-medium">{name}</span>- <span- className="truncate text-muted-foreground"- suppressHydrationWarning- >- {meta ? `${company.name} · ${meta}` : company.name}+ <span className="truncate text-muted-foreground">+ {meta ? (+ <>+ {company.name} · {meta}+ </>+ ) : (+ company.name+ )}</span></span></span>diff --git a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsxindex 9b108338..a0d5a91d 100644--- a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx+++ b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx@@ -34,8 +34,8 @@ import { useMutation, useQuery } from "@tanstack/react-query";import { parseAsBoolean, useQueryState } from "nuqs";import { type ComponentProps, Suspense, useId, useState } from "react";import { toast } from "sonner";-import { dealStageLabel, OPEN_STAGES } from "@/components/crm/deal-stage";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";+import { dealStageLabel, OPEN_STAGES } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";diff --git a/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsxindex 7fcade36..4ea27817 100644--- a/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx+++ b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx@@ -32,7 +32,7 @@ import {BulkOwnerMenu,reportBulk,} from "@/components/crm/bulk-actions";-import { DEAL_STAGE_OPTIONS, LOSING_STAGES } from "@/components/crm/deal-stage";+import { DEAL_STAGE_OPTIONS, LOSING_STAGES } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";diff --git a/apps/app/app/(app)/[slug]/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsxindex 83c8ba20..dc9ac3f2 100644--- a/apps/app/app/(app)/[slug]/deals/deals-table.tsx+++ b/apps/app/app/(app)/[slug]/deals/deals-table.tsx@@ -7,12 +7,11 @@ import {} from "@crm/ui/components/data-table";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";-import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";+import { formatMoney } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";import { useMemo } from "react";import { CLOSING_OPTIONS } from "@/components/crm/closing-window";import { CompanyCell } from "@/components/crm/company-cell";-import { DEAL_STAGE_OPTIONS } from "@/components/crm/deal-stage";import { useFieldColumns } from "@/components/crm/fields/field-columns";import { OwnerCell } from "@/components/crm/owner-cell";import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";@@ -20,6 +19,8 @@ import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";import { DealStageMenu } from "@/components/crm/stage-change";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";+import { LocalDay, LocalRelativeTime } from "@/components/local-date-time";+import { DEAL_STAGE_OPTIONS } from "@/lib/deal-stage";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { DealsBulkActions } from "./deals-bulk-actions";@@ -27,12 +28,6 @@ import { dealsSearchParams } from "./deals-search-params";type DealRow = RouterOutputs["deals"]["list"]["rows"][number];-const dateFormat = new Intl.DateTimeFormat(undefined, {- month: "short",- day: "numeric",- year: "numeric",-});-const COLUMNS: DataTableColumn<DealRow>[] = [{id: "name",@@ -89,7 +84,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [cell: (row) =>row.expectedCloseDate ? (<span className="text-muted-foreground">- {dateFormat.format(new Date(row.expectedCloseDate))}+ <LocalDay date={row.expectedCloseDate} /></span>) : (<EmptyCellValue />@@ -104,8 +99,8 @@ const COLUMNS: DataTableColumn<DealRow>[] = [width: "w-[10%]",defaultHidden: true,cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.createdAt)}+ <span className="text-muted-foreground">+ <LocalRelativeTime date={row.createdAt} /></span>),},@@ -117,8 +112,12 @@ const COLUMNS: DataTableColumn<DealRow>[] = [width: "w-[12%]",hideBelow: "lg",cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.lastActivityAt)}+ <span className="text-muted-foreground">+ {row.lastActivityAt ? (+ <LocalRelativeTime date={row.lastActivityAt} />+ ) : (+ <EmptyCellValue />+ )}</span>),},@@ -147,9 +146,11 @@ export function DealsTable() {{id: "owner",label: "Owner",- options: (users.data ?? [])- .map((user) => ({ value: user.id, label: user.name }))- .filter((option) => (facetCounts?.owner?.[option.value] ?? 0) > 0),+ options: (users.data ?? []).flatMap((user) =>+ (facetCounts?.owner?.[user.id] ?? 0) > 0+ ? [{ value: user.id, label: user.name }]+ : [],+ ),},{id: "stage",@@ -161,9 +162,11 @@ export function DealsTable() {{id: "closing",label: "Closing",- options: CLOSING_OPTIONS.filter(- (option) => (facetCounts?.closing?.[option.value] ?? 0) > 0,- ).map((option) => ({ value: option.value, label: option.label })),+ options: CLOSING_OPTIONS.flatMap((option) =>+ (facetCounts?.closing?.[option.value] ?? 0) > 0+ ? [{ value: option.value, label: option.label }]+ : [],+ ),},];diff --git a/apps/app/app/(app)/[slug]/deals/page.tsx b/apps/app/app/(app)/[slug]/deals/page.tsxindex 1b6bbfd5..f1d7ab44 100644--- a/apps/app/app/(app)/[slug]/deals/page.tsx+++ b/apps/app/app/(app)/[slug]/deals/page.tsx@@ -50,9 +50,10 @@ export default function DealsPage({async function Deals({searchParams,}: Pick<PageProps<"/[slug]/deals">, "searchParams">) {- await requireSession();-- const values = await dealsSearchParams.load(searchParams);+ const [, values] = await Promise.all([+ requireSession(),+ dealsSearchParams.load(searchParams),+ ]);const trpc = getServerTrpc();const queryClient = getServerQueryClient();diff --git a/apps/app/app/(app)/[slug]/layout.tsx b/apps/app/app/(app)/[slug]/layout.tsxindex e837aca7..b993c211 100644--- a/apps/app/app/(app)/[slug]/layout.tsx+++ b/apps/app/app/(app)/[slug]/layout.tsx@@ -1,4 +1,5 @@import { notFound, unstable_rethrow } from "next/navigation";+import { connection } from "next/server";import { Suspense } from "react";import { AppHeader, AppHeaderFallback } from "@/components/app-header";import { AppIconRail, AppIconRailFallback } from "@/components/app-icon-rail";@@ -42,17 +43,18 @@ export default function AppLayout({async function WorkspaceHeader({params,}: Pick<LayoutProps<"/[slug]">, "params">) {- const [{ user }, { slug }] = await Promise.all([- requireMailboxAccess(),- params,- ]);-- const workspace = await getServerQueryClient()+ await connection();+ const workspacePromise = getServerQueryClient().fetchQuery(getServerTrpc().workspace.get.queryOptions()).catch((error: unknown) => {unstable_rethrow(error);return null;});+ const [{ user }, { slug }, workspace] = await Promise.all([+ requireMailboxAccess(),+ params,+ workspacePromise,+ ]);if (workspace && workspace.slug !== slug) notFound();diff --git a/apps/app/app/(app)/[slug]/loading.tsx b/apps/app/app/(app)/[slug]/loading.tsxnew file mode 100644index 00000000..cbdc12bf--- /dev/null+++ b/apps/app/app/(app)/[slug]/loading.tsx@@ -0,0 +1,5 @@+import { PageShellFallback } from "@/components/page-shell";++export default function WorkspaceRouteLoading() {+ return <PageShellFallback />;+}diff --git a/apps/app/app/(app)/[slug]/page.tsx b/apps/app/app/(app)/[slug]/page.tsxindex 6bd6589d..feaf6017 100644--- a/apps/app/app/(app)/[slug]/page.tsx+++ b/apps/app/app/(app)/[slug]/page.tsx@@ -49,9 +49,10 @@ export default function OverviewPage({ searchParams }: PageProps<"/[slug]">) {async function Summary({searchParams,}: Pick<PageProps<"/[slug]">, "searchParams">) {- await requireSession();-- const { scope } = await loadOverviewSearchParams(searchParams);+ const [, { scope }] = await Promise.all([+ requireSession(),+ loadOverviewSearchParams(searchParams),+ ]);const queryClient = getServerQueryClient();await queryClient.prefetchQuery(diff --git a/apps/app/app/(app)/[slug]/sales-dashboard.tsx b/apps/app/app/(app)/[slug]/sales-dashboard.tsxindex a7594794..cba5acee 100644--- a/apps/app/app/(app)/[slug]/sales-dashboard.tsx+++ b/apps/app/app/(app)/[slug]/sales-dashboard.tsx@@ -17,8 +17,8 @@ import {} from "@crm/ui/lib/format";import Link from "next/link";import type { ReactNode } from "react";-import { dealStageColor, dealStageLabel } from "@/components/crm/deal-stage";import { AreaTrend, DonutStat } from "@/components/dashboard-charts";+import { dealStageColor, dealStageLabel } from "@/lib/deal-stage";import type { RouterOutputs } from "@/lib/trpc/types";import { useWorkspaceUrl } from "@/lib/use-workspace-url";@@ -66,15 +66,19 @@ export function SalesDashboard({ summary }: { summary: Summary }) {const hasTrend = trend.some((point) => point.won > 0 || point.created > 0);- const stageSlices = pipeline.stages- .map((stage) => ({- key: stage.stage,- label: dealStageLabel(stage.stage),- value: stage.valueCents,- color: dealStageColor(stage.stage),- count: stage.count,- }))- .filter((slice) => slice.value > 0);+ const stageSlices = pipeline.stages.flatMap((stage) =>+ stage.valueCents > 0+ ? [+ {+ key: stage.stage,+ label: dealStageLabel(stage.stage),+ value: stage.valueCents,+ color: dealStageColor(stage.stage),+ count: stage.count,+ },+ ]+ : [],+ );return (<div className="flex flex-col gap-6">diff --git a/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsxindex 77378805..a124f658 100644--- a/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx@@ -37,12 +37,12 @@ import { Label } from "@crm/ui/components/label";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import Link from "next/link";import { useState } from "react";import { toast } from "sonner";-import { isSyncing, SYNC_POLL_MS } from "@/components/crm/sync-status";+import { LocalRelativeTime } from "@/components/local-date-time";+import { isSyncing, SYNC_POLL_MS } from "@/lib/sync-status";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -95,11 +95,13 @@ function failureSignature(lastError: string | null;}[],): string {- return sources- .filter((source) => source.status === "NEEDS_RECONNECT" || source.lastError)- .map((source) => `${source.source}:${source.lastError ?? "reconnect"}`)- .sort()- .join("|");+ const failures: string[] = [];+ for (const source of sources) {+ if (source.status === "NEEDS_RECONNECT" || source.lastError) {+ failures.push(`${source.source}:${source.lastError ?? "reconnect"}`);+ }+ }+ return failures.sort().join("|");}function GoogleUnavailable() {@@ -346,9 +348,13 @@ export function GoogleConnection({ connectError }: { connectError?: string }) {})) : (<p className="text-muted-foreground text-xs">- {lastSyncedAt- ? `Last checked ${relativeTimeFromIso(lastSyncedAt)}`- : "Waiting for the first check"}+ {lastSyncedAt ? (+ <>+ Last checked <LocalRelativeTime date={lastSyncedAt} />+ </>+ ) : (+ "Waiting for the first check"+ )}</p>)}diff --git a/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsxindex 96736236..86ad3223 100644--- a/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx@@ -31,12 +31,12 @@ import { Label } from "@crm/ui/components/label";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import Link from "next/link";import { useState } from "react";import { toast } from "sonner";-import { isSyncing, SYNC_POLL_MS } from "@/components/crm/sync-status";+import { LocalRelativeTime } from "@/components/local-date-time";+import { isSyncing, SYNC_POLL_MS } from "@/lib/sync-status";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -255,9 +255,13 @@ export function MicrosoftConnection({))) : (<p className="text-muted-foreground text-xs">- {lastSyncedAt- ? `Last checked ${relativeTimeFromIso(lastSyncedAt)}`- : "Waiting for the first check"}+ {lastSyncedAt ? (+ <>+ Last checked <LocalRelativeTime date={lastSyncedAt} />+ </>+ ) : (+ "Waiting for the first check"+ )}</p>)}diff --git a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsxindex df7ff27a..c47ec66a 100644--- a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx+++ b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx@@ -29,27 +29,28 @@ import {import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { TableCell } from "@crm/ui/components/table";-import { formatCount, relativeTimeFromIso } from "@crm/ui/lib/format";+import { formatCount } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { useId, useState } from "react";import { toast } from "sonner";+import { LocalRelativeTime } from "@/components/local-date-time";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";const CELL = "px-3 py-2.5 align-middle";const RATE_COLUMNS: SimpleTableColumn[] = [- { header: "Currency" },- { header: "Rate", width: "w-32", align: "right" },- { header: "Source", width: "w-28" },- { header: "As of", width: "w-24", align: "right" },- { srLabel: "Actions", width: "w-20" },+ { id: "currency", header: "Currency" },+ { id: "rate", header: "Rate", width: "w-32", align: "right" },+ { id: "source", header: "Source", width: "w-28" },+ { id: "asOf", header: "As of", width: "w-24", align: "right" },+ { id: "actions", srLabel: "Actions", width: "w-20" },];const USAGE_COLUMNS: SimpleTableColumn[] = [- { header: "Currency" },- { header: "Deals", width: "w-20", align: "right" },- { header: "Convertible", width: "w-32", align: "right" },+ { id: "currency", header: "Currency" },+ { id: "deals", header: "Deals", width: "w-20", align: "right" },+ { id: "convertible", header: "Convertible", width: "w-32", align: "right" },];export function CurrencySettings() {@@ -274,9 +275,7 @@ export function CurrencySettings() {<TableCellclassName={`${CELL} text-right text-muted-foreground`}>- <span suppressHydrationWarning>- {relativeTimeFromIso(rate.asOf)}- </span>+ <LocalRelativeTime date={rate.asOf} /></TableCell><TableCell className={`${CELL} text-right`}>{rate.source === "MANUAL" ? (@@ -308,11 +307,7 @@ export function CurrencySettings() {{refreshedAt ? (<>{" "}- Rates last fetched{" "}- <span suppressHydrationWarning>- {relativeTimeFromIso(refreshedAt)}- </span>- .+ Rates last fetched <LocalRelativeTime date={refreshedAt} />.</>) : null}</CardDescription>diff --git a/apps/app/app/(app)/[slug]/settings/members/members-table.tsx b/apps/app/app/(app)/[slug]/settings/members/members-table.tsxindex 4290b9f0..023bdfb0 100644--- a/apps/app/app/(app)/[slug]/settings/members/members-table.tsx+++ b/apps/app/app/(app)/[slug]/settings/members/members-table.tsx@@ -15,11 +15,11 @@ import {} from "@crm/ui/components/dropdown-menu";import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";+import { LocalRelativeTime } from "@/components/local-date-time";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -90,8 +90,8 @@ function columns(width: "w-[14%]",hideBelow: "sm",cell: (row) => (- <span className="text-muted-foreground" suppressHydrationWarning>- {relativeTimeFromIso(row.joinedAt)}+ <span className="text-muted-foreground">+ <LocalRelativeTime date={row.joinedAt} /></span>),},@@ -159,9 +159,11 @@ export function MembersTable() {{id: "role",label: "Role",- options: (Object.keys(ROLE_LABEL) as Role[])- .map((role) => ({ value: role, label: ROLE_LABEL[role] }))- .filter((option) => (facetCounts?.role?.[option.value] ?? 0) > 0),+ options: (Object.keys(ROLE_LABEL) as Role[]).flatMap((role) =>+ (facetCounts?.role?.[role] ?? 0) > 0+ ? [{ value: role, label: ROLE_LABEL[role] }]+ : [],+ ),},];diff --git a/apps/app/app/(landing)/grant-access/grant-access.tsx b/apps/app/app/(landing)/grant-access/grant-access.tsxindex 6c8c4fa6..acf72981 100644--- a/apps/app/app/(landing)/grant-access/grant-access.tsx+++ b/apps/app/app/(landing)/grant-access/grant-access.tsx@@ -1,6 +1,6 @@"use client";-import { authClient, signOut } from "@crm/auth/client";+import { authClient } from "@crm/auth/client";import {type MailboxProviderId,MICROSOFT_SYNC_SCOPES,@@ -12,6 +12,7 @@ import { Button } from "@crm/ui/components/button";import { Spinner } from "@crm/ui/components/spinner";import { useState } from "react";import { toast } from "sonner";+import { signOutAndRedirect } from "@/lib/sign-out";const PROVIDERS = {google: {@@ -53,17 +54,6 @@ export function GrantAccess({if (error) fail(error.message);}- async function handleSignOut() {- const { error } = await signOut();-- if (error) {- toast.error(error.message ?? "Could not sign out.");- return;- }-- window.location.assign("/sign-in");- }-const single = providers.length === 1;return (@@ -94,7 +84,7 @@ export function GrantAccess({<ButtonclassName="w-full"onClick={() => {- handleSignOut().catch(() => toast.error("Could not sign out."));+ signOutAndRedirect().catch(() => toast.error("Could not sign out."));}}type="button"variant="ghost"diff --git a/apps/app/app/(landing)/onboarding/onboarding-form.tsx b/apps/app/app/(landing)/onboarding/onboarding-form.tsxindex 5801a375..7f813dbb 100644--- a/apps/app/app/(landing)/onboarding/onboarding-form.tsx+++ b/apps/app/app/(landing)/onboarding/onboarding-form.tsx@@ -1,5 +1,6 @@"use client";+import { workspaceSlug } from "@crm/db/workspace";import { Button } from "@crm/ui/components/button";import {Field,@@ -17,7 +18,7 @@ import {import { Spinner } from "@crm/ui/components/spinner";import { useMutation } from "@tanstack/react-query";import { useRouter } from "next/navigation";-import { useId } from "react";+import { useId, useRef, useState } from "react";import { toast } from "sonner";import { useTRPC } from "@/lib/trpc/client";@@ -26,7 +27,11 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {const router = useRouter();const nameId = useId();+ const slugId = useId();const websiteId = useId();+ const [name, setName] = useState("");+ const [slug, setSlug] = useState("");+ const slugEdited = useRef(false);const save = useMutation(trpc.workspace.update.mutationOptions({@@ -47,6 +52,7 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {save.mutate({name: String(form.get("name") ?? "").trim(),+ slug: workspaceSlug(String(form.get("slug") ?? "")),website: String(form.get("website") ?? "").trim(),});}}@@ -58,6 +64,12 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {<Inputid={nameId}name="name"+ value={name}+ onChange={(event) => {+ const next = event.target.value;+ setName(next);+ if (!slugEdited.current) setSlug(workspaceSlug(next));+ }}placeholder={placeholder}autoComplete="organization"autoFocus@@ -65,6 +77,36 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {/></Field>+ <Field>+ <FieldLabel htmlFor={slugId}>Workspace URL</FieldLabel>+ <InputGroup>+ <InputGroupAddon>+ <InputGroupText>/</InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ id={slugId}+ name="slug"+ value={slug}+ onChange={(event) => {+ slugEdited.current = true;+ setSlug(workspaceSlugDraft(event.target.value));+ }}+ onBlur={() =>+ setSlug((value) => (value ? workspaceSlug(value) : ""))+ }+ placeholder={workspaceSlug(placeholder)}+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ required+ />+ </InputGroup>+ <FieldDescription>+ Your team will use this address to open the CRM.+ </FieldDescription>+ </Field>+<Field><FieldLabel htmlFor={websiteId}>Website</FieldLabel><InputGroup>@@ -96,3 +138,11 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {</form>);}++function workspaceSlugDraft(value: string): string {+ return value+ .toLowerCase()+ .replace(/[^a-z0-9-]+/g, "-")+ .replace(/-{2,}/g, "-")+ .replace(/^-+/, "");+}diff --git a/apps/app/app/(landing)/onboarding/research/research-form.tsx b/apps/app/app/(landing)/onboarding/research/research-form.tsxindex 42b16873..30887d2e 100644--- a/apps/app/app/(landing)/onboarding/research/research-form.tsx+++ b/apps/app/app/(landing)/onboarding/research/research-form.tsx@@ -36,9 +36,7 @@ export function ResearchForm() {<formonSubmit={(event) => {event.preventDefault();-const form = new FormData(event.currentTarget);-save.mutate({ apiKey: String(form.get("apiKey") ?? "").trim() });}}className="flex flex-col gap-6"diff --git a/apps/app/app/layout.tsx b/apps/app/app/layout.tsxindex d8280e30..d22ba155 100644--- a/apps/app/app/layout.tsx+++ b/apps/app/app/layout.tsx@@ -5,6 +5,7 @@ import { cn } from "@crm/ui/lib/utils";import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import { NuqsAdapter } from "nuqs/adapters/next/app";+import { LocalDateTimeHydrator } from "@/components/local-date-time";import { ThemeProvider } from "@/components/theme-provider";import { TRPCReactProvider } from "@/lib/trpc/client";@@ -54,6 +55,7 @@ export default function RootLayout({</ThemeProvider></TRPCReactProvider></NuqsAdapter>+ <LocalDateTimeHydrator /></body></html>);diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsxindex 4dc31f70..c74f7d75 100644--- a/apps/app/components/app-header.tsx+++ b/apps/app/components/app-header.tsx@@ -5,7 +5,6 @@ import Light from "@carbon/icons-react/es/Light";import Logout from "@carbon/icons-react/es/Logout";import Menu from "@carbon/icons-react/es/Menu";import UserAvatar from "@carbon/icons-react/es/UserAvatar";-import { signOut } from "@crm/auth/client";import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";import { Button } from "@crm/ui/components/button";import {@@ -24,25 +23,13 @@ import Link from "next/link";import { useTheme } from "next-themes";import { toast } from "sonner";import { useMobileNav } from "@/components/mobile-nav";+import { signOutAndRedirect } from "@/lib/sign-out";import { useTRPC } from "@/lib/trpc/client";import { useWorkspaceUrl } from "@/lib/use-workspace-url";+import { workspaceLabel } from "@/lib/workspace-label";type User = { name: string; email: string; image: string | null };-/**- * The workspace arrives named `CRM` until somebody types something else — the- * deliberate placeholder — so appending the product name to it read "CRM CRM".- * A workspace genuinely called "Acme CRM" has the same problem, which is why- * this tests the name rather than comparing it to the default.- */-export function workspaceLabel(name: string | undefined): string {- const trimmed = name?.trim();-- if (!trimmed) return "CRM";-- return /\bcrm$/i.test(trimmed) ? trimmed : `${trimmed} CRM`;-}-export function AppHeader({ user }: { user: User }) {const { setOpen: setMobileNavOpen } = useMobileNav();const trpc = useTRPC();@@ -50,17 +37,6 @@ export function AppHeader({ user }: { user: User }) {const workspace = useQuery(trpc.workspace.get.queryOptions());const label = workspaceLabel(workspace.data?.name);- async function handleSignOut() {- const { error } = await signOut();-- if (error) {- toast.error(error.message ?? "Could not sign out.");- return;- }-- window.location.assign("/sign-in");- }-return (<header className="flex h-12 shrink-0 items-center gap-2 border-b px-3 [view-transition-name:app-header]"><div className="flex shrink-0 items-center gap-1">@@ -88,7 +64,9 @@ export function AppHeader({ user }: { user: User }) {<UserMenuuser={user}onSignOut={() => {- handleSignOut().catch(() => toast.error("Could not sign out."));+ signOutAndRedirect().catch(() =>+ toast.error("Could not sign out."),+ );}}/></div>diff --git a/apps/app/components/crm/agent-conversations.tsx b/apps/app/components/crm/agent-conversations.tsxindex 94e778ff..f2079dd1 100644--- a/apps/app/components/crm/agent-conversations.tsx+++ b/apps/app/components/crm/agent-conversations.tsx@@ -14,17 +14,18 @@ import {import { Icon } from "@crm/ui/components/icon";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";+import { LocalDateTime } from "@/components/local-date-time";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";export type Conversation = RouterOutputs["conversations"]["list"][number];-const dateFormat = new Intl.DateTimeFormat(undefined, {+const DATE_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",hour: "numeric",minute: "2-digit",-});+};export function ConversationPicker({conversations,@@ -42,7 +43,7 @@ export function ConversationPicker({const label = current?.title ?? "New conversation";return (- <div className="flex items-center gap-2 border-b px-5 py-2">+ <div className="flex min-w-0 items-center gap-2 border-b px-4 py-2 sm:px-5"><DropdownMenu><DropdownMenuTrigger asChild><Button@@ -68,7 +69,10 @@ export function ConversationPicker({{conversation.title ?? "Untitled"}</span><span className="shrink-0 text-muted-foreground text-xs">- {dateFormat.format(new Date(conversation.lastMessageAt))}+ <LocalDateTime+ date={conversation.lastMessageAt}+ options={DATE_OPTIONS}+ /></span></DropdownMenuItem>))diff --git a/apps/app/components/crm/deal-stage.tsx b/apps/app/components/crm/deal-stage.tsxindex 2ae37ae4..3bd98528 100644--- a/apps/app/components/crm/deal-stage.tsx+++ b/apps/app/components/crm/deal-stage.tsx@@ -1,59 +1,6 @@-import { DealStage } from "@crm/db/enums";-import {- StatusIndicator,- type StatusTone,-} from "@crm/ui/components/status-indicator";--const ORDER = [- DealStage.DEMO_BOOKED,- DealStage.QUALIFIED_TO_BUY,- DealStage.DECISION_MAKER_BOUGHT_IN,- DealStage.CONTRACT_SENT,- DealStage.CLOSED_WON,- DealStage.CLOSED_LOST,- DealStage.UNQUALIFIED_TO_BUY,-] as const;--const PRESENTATION: Record<DealStage, { label: string; tone: StatusTone }> = {- DEMO_BOOKED: { label: "Demo booked", tone: "neutral" },- QUALIFIED_TO_BUY: { label: "Qualified to buy", tone: "info" },- DECISION_MAKER_BOUGHT_IN: { label: "Decision maker in", tone: "info" },- CONTRACT_SENT: { label: "Contract sent", tone: "warning" },- CLOSED_WON: { label: "Closed won", tone: "success" },- CLOSED_LOST: { label: "Closed lost", tone: "error" },- UNQUALIFIED_TO_BUY: { label: "Unqualified", tone: "neutral" },-};--export const OPEN_STAGES = ORDER.slice(0, 4) as readonly DealStage[];--export function isClosedStage(stage: DealStage): boolean {- return !OPEN_STAGES.includes(stage);-}--export const LOSING_STAGES: readonly DealStage[] = [- DealStage.CLOSED_LOST,- DealStage.UNQUALIFIED_TO_BUY,-];--export const DEAL_STAGE_OPTIONS = ORDER.map((value) => ({- value,- label: PRESENTATION[value].label,-}));--const OPEN_STAGE_COLORS = [- "var(--chart-1)",- "var(--chart-2)",- "var(--chart-3)",- "var(--chart-4)",-] as const;--export function dealStageColor(stage: DealStage): string {- return OPEN_STAGE_COLORS[OPEN_STAGES.indexOf(stage)] ?? "var(--chart-5)";-}--export function dealStageLabel(stage: DealStage): string {- return PRESENTATION[stage].label;-}+import type { DealStage } from "@crm/db/enums";+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { dealStagePresentation } from "@/lib/deal-stage";export function DealStageIndicator({stage,@@ -62,6 +9,6 @@ export function DealStageIndicator({stage: DealStage;className?: string;}) {- const { label, tone } = PRESENTATION[stage];+ const { label, tone } = dealStagePresentation(stage);return <StatusIndicator tone={tone} label={label} className={className} />;}diff --git a/apps/app/components/crm/enrichment-status.tsx b/apps/app/components/crm/enrichment-status.tsxindex b93d9dba..17a98a2d 100644--- a/apps/app/components/crm/enrichment-status.tsx+++ b/apps/app/components/crm/enrichment-status.tsx@@ -1,25 +1,6 @@import type { EnrichmentStatus } from "@crm/db/enums";-import {- StatusIndicator,- type StatusTone,-} from "@crm/ui/components/status-indicator";--const PRESENTATION: Record<- EnrichmentStatus,- { label: string; tone: StatusTone; busy?: boolean }-> = {- PENDING: { label: "Not researched", tone: "neutral" },- RUNNING: { label: "Researching", tone: "info", busy: true },- COMPLETE: { label: "Enriched", tone: "success" },- FAILED: { label: "Enrichment failed", tone: "error" },- SKIPPED: { label: "Nothing found", tone: "neutral" },-};--const QUEUED = { label: "Queued", tone: "neutral" as StatusTone, busy: false };--function present(status: EnrichmentStatus, queued: boolean) {- return status === "PENDING" && queued ? QUEUED : PRESENTATION[status];-}+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { enrichmentPresentation } from "@/lib/enrichment-status";export function EnrichmentIndicator({status,@@ -32,7 +13,7 @@ export function EnrichmentIndicator({title?: string | null;className?: string;}) {- const { label, tone, busy } = present(status, queued);+ const { label, tone, busy } = enrichmentPresentation(status, queued);return (<StatusIndicator@@ -44,13 +25,3 @@ export function EnrichmentIndicator({/>);}--export function isEnriching(status: EnrichmentStatus, queued = false): boolean {- return status === "RUNNING" || (status === "PENDING" && queued);-}--export const ENRICHMENT_POLL_MS = 3_000;--export const ENRICHMENT_FACET_OPTIONS = (- Object.keys(PRESENTATION) as EnrichmentStatus[]-).map((value) => ({ value, label: PRESENTATION[value].label }));diff --git a/apps/app/components/crm/facts.tsx b/apps/app/components/crm/facts.tsxindex 420c68cf..97c802bc 100644--- a/apps/app/components/crm/facts.tsx+++ b/apps/app/components/crm/facts.tsx@@ -4,37 +4,22 @@ import { Provenance } from "@crm/ui/components/sourced-value";import { Suggestion } from "@crm/ui/components/suggestion";import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";+import { LocalDateTime } from "@/components/local-date-time";+import type { ContactFact } from "@/lib/contact-facts";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";-import type { RouterOutputs } from "@/lib/trpc/types";-type Contact = RouterOutputs["contacts"]["byId"];-export type Fact = Contact["facts"][number];--const dateFormat = new Intl.DateTimeFormat(undefined, {- month: "short",- day: "numeric",- year: "numeric",-});--export function factsByField(facts: Fact[]) {- const applied = new Map<string, Fact>();- const proposed = new Map<string, Fact>();-- for (const fact of facts) {- const bucket = fact.status === "APPLIED" ? applied : proposed;- if (!bucket.has(fact.field)) bucket.set(fact.field, fact);- }-- return { applied, proposed };-}--export function provenanceFor(fact: Fact) {+export function FactProvenance({ fact }: { fact: ContactFact }) {return (<Provenanceclaim={fact.value}reasons={fact.evidence.map((item) => item.detail)}- observedAt={dateFormat.format(new Date(fact.observedAt))}+ observedAt={+ <LocalDateTime+ date={fact.observedAt}+ options={{ month: "short", day: "numeric", year: "numeric" }}+ />+ }sourceUrl={fact.sourceUrl}/>);@@ -44,7 +29,7 @@ export function FactSuggestion({fact,contactId,}: {- fact: Fact;+ fact: ContactFact;contactId: string;}) {const trpc = useTRPC();diff --git a/apps/app/components/crm/quick-switcher.tsx b/apps/app/components/crm/quick-switcher.tsxindex 2152a4c8..6c1c6037 100644--- a/apps/app/components/crm/quick-switcher.tsx+++ b/apps/app/components/crm/quick-switcher.tsx@@ -14,10 +14,9 @@ import {type EntityLogoTone,} from "@crm/ui/components/entity-logo";import { PersonAvatar } from "@crm/ui/components/person-avatar";-import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";import { useQuery } from "@tanstack/react-query";import { parseAsBoolean, useQueryState } from "nuqs";-import { useState } from "react";+import { useEffect, useState } from "react";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";import { useTRPC } from "@/lib/trpc/client";@@ -36,7 +35,7 @@ export function QuickSwitcher() {const [open, setOpen] = useQueryState("k", parseAsBoolean.withDefault(false));const [query, setQuery] = useState("");- useMountEffect(() => {+ useEffect(() => {const onKeyDown = (event: KeyboardEvent) => {if (event.key === "k" && (event.metaKey || event.ctrlKey)) {event.preventDefault();@@ -46,7 +45,7 @@ export function QuickSwitcher() {document.addEventListener("keydown", onKeyDown);return () => document.removeEventListener("keydown", onKeyDown);- });+ }, [setOpen]);const results = useQuery({...trpc.search.quick.queryOptions({ q: query }),diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 93f559e6..92ca756f 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -25,22 +25,16 @@ import { formatMoney } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";-import { OPEN_STAGES } from "@/components/crm/deal-stage";import { EnrichmentActions } from "@/components/crm/enrichment-actions";-import {- ENRICHMENT_POLL_MS,- EnrichmentIndicator,- isEnriching,-} from "@/components/crm/enrichment-status";+import { EnrichmentIndicator } from "@/components/crm/enrichment-status";import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";import {InlineField,InlineSelectField,- savingField,savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";-import { CompanySocials, hasCompanyLinks } from "@/components/crm/social-links";+import { CompanySocials } from "@/components/crm/social-links";import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import {@@ -57,6 +51,11 @@ import {DetailSheetStats,type DetailSheetTab,} from "@/components/detail-sheet";+import { LocalDay } from "@/components/local-date-time";+import { OPEN_STAGES } from "@/lib/deal-stage";+import { ENRICHMENT_POLL_MS, isEnriching } from "@/lib/enrichment-status";+import { savingField } from "@/lib/pending-field";+import { hasCompanyLinks } from "@/lib/social-links";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -102,32 +101,26 @@ function companyConsequence(company: Company): string {}const CONTACT_COLUMNS = [- { srLabel: "Primary", width: "w-10", className: "pl-5" },- { header: "Name", width: "w-[28%]" },- { header: "Title", width: "w-[24%]" },- { header: "Email", width: "w-[26%]" },- { header: "Owner", width: "w-[22%]" },+ { id: "primary", srLabel: "Primary", width: "w-10", className: "pl-5" },+ { id: "name", header: "Name", width: "w-[28%]" },+ { id: "title", header: "Title", width: "w-[24%]" },+ { id: "email", header: "Email", width: "w-[26%]" },+ { id: "owner", header: "Owner", width: "w-[22%]" },];const DEAL_COLUMNS = [- { header: "Deal", width: "w-[32%]", className: "pl-5" },- { header: "Stage", width: "w-[24%]" },- { header: "Amount", width: "w-[16%]", align: "right" as const },- { header: "Close date", width: "w-[14%]" },- { header: "Owner", width: "w-[14%]" },+ { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-5" },+ { id: "stage", header: "Stage", width: "w-[24%]" },+ {+ id: "amount",+ header: "Amount",+ width: "w-[16%]",+ align: "right" as const,+ },+ { id: "close-date", header: "Close date", width: "w-[14%]" },+ { id: "owner", header: "Owner", width: "w-[14%]" },];-const dateFormat = new Intl.DateTimeFormat(undefined, {- month: "short",- day: "numeric",- year: "numeric",-});--const shortDateFormat = new Intl.DateTimeFormat(undefined, {- month: "short",- day: "numeric",-});-function nextClose(deals: CompanyDeal[]): string | null {const dates = deals.map((deal) => deal.expectedCloseDate)@@ -295,11 +288,7 @@ export function CompanySheet({ companyId }: { companyId: string }) {<span className="tabular-nums">{openDeals.length}</span></DetailSheetStat><DetailSheetStat label="Next close">- {closing ? (- shortDateFormat.format(new Date(closing))- ) : (- <EmptyCellValue />- )}+ {closing ? <LocalDay date={closing} /> : <EmptyCellValue />}</DetailSheetStat><DetailSheetStat label="Owner"><OwnerCell owner={company.owner} />@@ -651,7 +640,7 @@ function CompanyDeals({</TableCell><TableCell className="px-3 py-2.5 text-muted-foreground">{deal.expectedCloseDate ? (- dateFormat.format(new Date(deal.expectedCloseDate))+ <LocalDay date={deal.expectedCloseDate} />) : (<EmptyCellValue />)}diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 423eed3d..6ff1f005 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -26,25 +26,16 @@ import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import { contactName } from "@/components/crm/contact-name";import { ContactEnrichmentAction } from "@/components/crm/enrichment-actions";-import {- ENRICHMENT_POLL_MS,- EnrichmentIndicator,- isEnriching,-} from "@/components/crm/enrichment-status";-import {- FactSuggestion,- factsByField,- provenanceFor,-} from "@/components/crm/facts";+import { EnrichmentIndicator } from "@/components/crm/enrichment-status";+import { FactProvenance, FactSuggestion } from "@/components/crm/facts";import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";import {InlineField,InlineSelectField,- savingField,savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";-import { ContactSocials, hasContactLinks } from "@/components/crm/social-links";+import { ContactSocials } from "@/components/crm/social-links";import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import {@@ -58,6 +49,11 @@ import {DetailSheetStats,type DetailSheetTab,} from "@/components/detail-sheet";+import { LocalDateTime, LocalRelativeDate } from "@/components/local-date-time";+import { factsByField } from "@/lib/contact-facts";+import { ENRICHMENT_POLL_MS, isEnriching } from "@/lib/enrichment-status";+import { savingField } from "@/lib/pending-field";+import { hasContactLinks } from "@/lib/social-links";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -69,18 +65,23 @@ type Contact = RouterOutputs["contacts"]["byId"];const NONE = "none";-const dateFormat = new Intl.DateTimeFormat(undefined, {+const DATE_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",year: "numeric",-});+};const DEAL_COLUMNS = [- { header: "Deal", width: "w-[32%]", className: "pl-5" },- { header: "Role", width: "w-[16%]" },- { header: "Stage", width: "w-[22%]" },- { header: "Amount", width: "w-[16%]", align: "right" as const },- { header: "Owner", width: "w-[14%]" },+ { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-5" },+ { id: "role", header: "Role", width: "w-[16%]" },+ { id: "stage", header: "Stage", width: "w-[22%]" },+ {+ id: "amount",+ header: "Amount",+ width: "w-[16%]",+ align: "right" as const,+ },+ { id: "owner", header: "Owner", width: "w-[14%]" },];export function ContactSheet({ contactId }: { contactId: string }) {@@ -294,7 +295,7 @@ function ContactOverview({ contact }: { contact: Contact }) {const fact = applied.get(field);const suggestion = proposed.get(field);return {- provenance: fact ? provenanceFor(fact) : undefined,+ provenance: fact ? <FactProvenance fact={fact} /> : undefined,suggestion: suggestion ? (<FactSuggestion fact={suggestion} contactId={contact.id} />) : undefined,@@ -460,7 +461,7 @@ function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {</a>) : null}{brief.sourceUrl ? " · " : null}- {dateFormat.format(new Date(brief.refreshedAt))}+ <LocalDateTime date={brief.refreshedAt} options={DATE_OPTIONS} /></span>}>@@ -502,17 +503,6 @@ function PreviousRoles({ roles }: { roles: string[] }) {);}-const relativeFormat = new Intl.RelativeTimeFormat(undefined, {- numeric: "auto",-});--function daysAgo(iso: string): string {- const days = Math.round(- (Date.now() - new Date(iso).getTime()) / (1000 * 60 * 60 * 24),- );- return relativeFormat.format(-days, "day");-}-function WeKnowThem({relationship,contactName: name,@@ -535,9 +525,13 @@ function WeKnowThem({<span className="tabular-nums">{emails}</span><span className="text-muted-foreground">{" · "}- {lastReplyAt- ? `last reply ${daysAgo(lastReplyAt)}`- : `${first} has never replied`}+ {lastReplyAt ? (+ <>+ last reply <LocalRelativeDate date={lastReplyAt} />+ </>+ ) : (+ `${first} has never replied`+ )}</span></DetailSheetProperty>) : null}@@ -553,7 +547,10 @@ function WeKnowThem({{nextMeeting.title ?? "Meeting"}<span className="text-muted-foreground">{" · "}- {dateFormat.format(new Date(nextMeeting.startsAt))}+ <LocalDateTime+ date={nextMeeting.startsAt}+ options={DATE_OPTIONS}+ /></span></DetailSheetProperty>) : null}diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsxindex eade930f..78f37749 100644--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx@@ -20,11 +20,7 @@ import {TooltipContent,TooltipTrigger,} from "@crm/ui/components/tooltip";-import {- formatDay,- formatMoney,- relativeTimeFromIso,-} from "@crm/ui/lib/format";+import { formatMoney } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";@@ -36,7 +32,6 @@ import {InlineSelectField,InlineTextArea,InlineTextCell,- savingField,savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";@@ -53,6 +48,12 @@ import {DetailSheetStats,type DetailSheetTab,} from "@/components/detail-sheet";+import {+ LocalDateTime,+ LocalDay,+ LocalRelativeTime,+} from "@/components/local-date-time";+import { savingField } from "@/lib/pending-field";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -105,18 +106,18 @@ function ReportedValue({ deal }: { deal: Deal }) {}const CONTACT_COLUMNS = [- { header: "Name", width: "w-[28%]", className: "pl-5" },- { header: "Role", width: "w-[20%]" },- { header: "Title", width: "w-[22%]" },- { header: "Email", width: "w-[22%]" },- { srLabel: "Remove", width: "w-10" },+ { id: "name", header: "Name", width: "w-[28%]", className: "pl-5" },+ { id: "role", header: "Role", width: "w-[20%]" },+ { id: "title", header: "Title", width: "w-[22%]" },+ { id: "email", header: "Email", width: "w-[22%]" },+ { id: "remove", srLabel: "Remove", width: "w-10" },];-const dateFormat = new Intl.DateTimeFormat(undefined, {+const DATE_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",year: "numeric",-});+};export function DealSheet({ dealId }: { dealId: string }) {const trpc = useTRPC();@@ -222,13 +223,13 @@ export function DealSheet({ dealId }: { dealId: string }) {</DetailSheetStat><DetailSheetStat label="Expected close">{deal.expectedCloseDate ? (- formatDay(deal.expectedCloseDate)+ <LocalDay date={deal.expectedCloseDate} />) : (<EmptyCellValue />)}</DetailSheetStat><DetailSheetStat label="In stage">- {relativeTimeFromIso(deal.stageChangedAt)}+ <LocalRelativeTime date={deal.stageChangedAt} /></DetailSheetStat><DetailSheetStat label="Owner"><OwnerCell owner={deal.owner} />@@ -273,6 +274,21 @@ function DealOverview({ deal }: { deal: Deal }) {<DetailSheetBody><DetailSheetSection title="Stage"><StageStepper dealId={deal.id} stage={deal.stage} />++ {deal.closedReason ? (+ <DetailSheetProperties>+ <DetailSheetProperty label="Closed">+ {deal.closedAt ? (+ <LocalDateTime date={deal.closedAt} options={DATE_OPTIONS} />+ ) : (+ <EmptyCellValue />+ )}+ </DetailSheetProperty>+ <DetailSheetProperty label="Reason" wide>+ {deal.closedReason}+ </DetailSheetProperty>+ </DetailSheetProperties>+ ) : null}</DetailSheetSection><DetailSheetSection title="Details" action={<FieldsCog kind="deal" />}>@@ -364,16 +380,16 @@ function WhereItStands({ deal }: { deal: Deal }) {<DetailSheetSection title="Where it stands"><DetailSheetProperties><DetailSheetProperty label="Opened">- {dateFormat.format(new Date(deal.createdAt))}+ <LocalDateTime date={deal.createdAt} options={DATE_OPTIONS} /></DetailSheetProperty><DetailSheetProperty label="In stage since">- {dateFormat.format(new Date(deal.stageChangedAt))}+ <LocalDateTime date={deal.stageChangedAt} options={DATE_OPTIONS} /></DetailSheetProperty>{deal.closedAt ? (<DetailSheetProperty label="Closed">- {dateFormat.format(new Date(deal.closedAt))}+ <LocalDateTime date={deal.closedAt} options={DATE_OPTIONS} /></DetailSheetProperty>) : null}diff --git a/apps/app/components/crm/record-sheet/quick-add.tsx b/apps/app/components/crm/record-sheet/quick-add.tsxindex 77a1f998..957f714f 100644--- a/apps/app/components/crm/record-sheet/quick-add.tsx+++ b/apps/app/components/crm/record-sheet/quick-add.tsx@@ -37,10 +37,7 @@ function QuickAddForm({return (<formclassName="flex shrink-0 flex-col gap-4 border-b px-5 py-4"- onSubmit={(event) => {- event.preventDefault();- onSubmit();- }}+ action={onSubmit}><div className="grid gap-4 sm:grid-cols-2">{children}</div><div className="flex items-center justify-end gap-2">diff --git a/apps/app/components/crm/social-links.tsx b/apps/app/components/crm/social-links.tsxindex d1398eb7..a43a1845 100644--- a/apps/app/components/crm/social-links.tsx+++ b/apps/app/components/crm/social-links.tsx@@ -1,60 +1,23 @@-import LogoGithub from "@carbon/icons-react/es/LogoGithub";-import LogoLinkedin from "@carbon/icons-react/es/LogoLinkedin";-import LogoX from "@carbon/icons-react/es/LogoX";-import Money from "@carbon/icons-react/es/Money";-import UserMultiple from "@carbon/icons-react/es/UserMultiple";import { Button } from "@crm/ui/components/button";import type { CarbonIcon } from "@crm/ui/components/icon";import { Icon } from "@crm/ui/components/icon";--type Link<T> = { key: keyof T; label: string; icon: CarbonIcon };--export type CompanyLinks = {- linkedinUrl: string | null;- twitterUrl: string | null;- githubUrl: string | null;- pricingUrl: string | null;- careersUrl: string | null;-};--export type ContactLinks = {- linkedinUrl: string | null;- twitterUrl: string | null;- githubUrl: string | null;-};--const COMPANY_LINKS: Link<CompanyLinks>[] = [- { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },- { key: "twitterUrl", label: "X", icon: LogoX },- { key: "githubUrl", label: "GitHub", icon: LogoGithub },- { key: "pricingUrl", label: "Pricing", icon: Money },- { key: "careersUrl", label: "Careers", icon: UserMultiple },-];--const CONTACT_LINKS: Link<ContactLinks>[] = [- { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },- { key: "twitterUrl", label: "X", icon: LogoX },- { key: "githubUrl", label: "GitHub", icon: LogoGithub },-];--function present<T>(record: T, links: Link<T>[]) {- return links.flatMap((link) => {- const href = record[link.key];- return typeof href === "string" && href ? [{ ...link, href }] : [];- });-}--export function hasCompanyLinks(company: CompanyLinks): boolean {- return present(company, COMPANY_LINKS).length > 0;-}--export function hasContactLinks(contact: ContactLinks): boolean {- return present(contact, CONTACT_LINKS).length > 0;-}--function SocialLinks<T>({ record, links }: { record: T; links: Link<T>[] }) {- const rows = present(record, links);-+import {+ type CompanyLinks,+ type ContactLinks,+ companySocialLinks,+ contactSocialLinks,+} from "@/lib/social-links";++function SocialLinks({+ rows,+}: {+ rows: Array<{+ key: PropertyKey;+ label: string;+ icon: CarbonIcon;+ href: string;+ }>;+}) {if (rows.length === 0) return null;return (@@ -72,9 +35,9 @@ function SocialLinks<T>({ record, links }: { record: T; links: Link<T>[] }) {}export function CompanySocials({ company }: { company: CompanyLinks }) {- return <SocialLinks record={company} links={COMPANY_LINKS} />;+ return <SocialLinks rows={companySocialLinks(company)} />;}export function ContactSocials({ contact }: { contact: ContactLinks }) {- return <SocialLinks record={contact} links={CONTACT_LINKS} />;+ return <SocialLinks rows={contactSocialLinks(contact)} />;}diff --git a/apps/app/components/crm/stage-change.tsx b/apps/app/components/crm/stage-change.tsxindex 243caca5..e7a580d5 100644--- a/apps/app/components/crm/stage-change.tsx+++ b/apps/app/components/crm/stage-change.tsx@@ -26,13 +26,10 @@ import { useMutation } from "@tanstack/react-query";import { parseAsString, useQueryStates } from "nuqs";import { useId, useState } from "react";import { toast } from "sonner";+import { DEAL_STAGE_OPTIONS, LOSING_STAGES } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";-import {- DEAL_STAGE_OPTIONS,- DealStageIndicator,- LOSING_STAGES,-} from "./deal-stage";+import { DealStageIndicator } from "./deal-stage";const closeReasonParams = {closing: parseAsString,diff --git a/apps/app/components/crm/stage-stepper.tsx b/apps/app/components/crm/stage-stepper.tsxindex 849beac8..541d7e2d 100644--- a/apps/app/components/crm/stage-stepper.tsx+++ b/apps/app/components/crm/stage-stepper.tsx@@ -4,12 +4,8 @@ import { DealStage } from "@crm/db/enums";import { cn } from "@crm/ui/lib/utils";import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";-import {- DealStageIndicator,- dealStageLabel,- isClosedStage,- OPEN_STAGES,-} from "@/components/crm/deal-stage";+import { DealStageIndicator } from "@/components/crm/deal-stage";+import { dealStageLabel, isClosedStage, OPEN_STAGES } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";diff --git a/apps/app/components/crm/sync-status.tsx b/apps/app/components/crm/sync-status.tsxdeleted file mode 100644index 2e3e2f53..00000000--- a/apps/app/components/crm/sync-status.tsx+++ /dev/null@@ -1,53 +0,0 @@-import type { GoogleSyncStatus } from "@crm/db/enums";-import {- StatusIndicator,- type StatusTone,-} from "@crm/ui/components/status-indicator";--const PRESENTATION: Record<- GoogleSyncStatus,- { label: string; tone: StatusTone; busy?: boolean }-> = {- IDLE: { label: "Connected", tone: "success" },- RUNNING: { label: "Syncing", tone: "info", busy: true },- NEEDS_RECONNECT: { label: "Reconnect needed", tone: "warning" },- FAILED: { label: "Sync failed", tone: "error" },-};--export function SyncIndicator({- status,- title,- className,-}: {- status: GoogleSyncStatus | null;- title?: string | null;- className?: string;-}) {- if (status === null) {- return (- <StatusIndicator- tone="neutral"- label="Not connected"- className={className}- />- );- }-- const { label, tone, busy } = PRESENTATION[status];-- return (- <StatusIndicator- tone={tone}- busy={busy}- label={label}- title={title ?? undefined}- className={className}- />- );-}--export function isSyncing(status: GoogleSyncStatus | null): boolean {- return status === "RUNNING";-}--export const SYNC_POLL_MS = 5_000;diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsxindex a5d22174..6ef2d612 100644--- a/apps/app/components/crm/timeline/activity-composer.tsx+++ b/apps/app/components/crm/timeline/activity-composer.tsx@@ -19,16 +19,17 @@ import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";import { useMutation } from "@tanstack/react-query";import { useState } from "react";import { toast } from "sonner";+import { activityLabel } from "@/lib/activity-presentation";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";-import { ActivityIcon, activityLabel } from "./activity-icon";+import { ActivityIcon } from "./activity-icon";import type { TimelineAnchor } from "./timeline";const TYPES = ["NOTE", "CALL", "EMAIL", "MEETING", "TASK"] as const;type ComposableType = (typeof TYPES)[number];-const dueFormat = new Intl.DateTimeFormat(undefined, {+const dueFormat = new Intl.DateTimeFormat("en-US", {month: "short",day: "numeric",});diff --git a/apps/app/components/crm/timeline/activity-icon.tsx b/apps/app/components/crm/timeline/activity-icon.tsxindex 98885762..ab6c1058 100644--- a/apps/app/components/crm/timeline/activity-icon.tsx+++ b/apps/app/components/crm/timeline/activity-icon.tsx@@ -1,29 +1,7 @@-import ArrowRight from "@carbon/icons-react/es/ArrowRight";-import Chat from "@carbon/icons-react/es/Chat";-import Email from "@carbon/icons-react/es/Email";-import Events from "@carbon/icons-react/es/Events";-import MagicWand from "@carbon/icons-react/es/MagicWand";-import Phone from "@carbon/icons-react/es/Phone";-import Task from "@carbon/icons-react/es/Task";import type { ActivityType } from "@crm/db/enums";-import type { CarbonIcon } from "@crm/ui/components/icon";import { Icon } from "@crm/ui/components/icon";--const PRESENTATION: Record<ActivityType, { icon: CarbonIcon; label: string }> =- {- NOTE: { icon: Chat, label: "Note" },- CALL: { icon: Phone, label: "Call" },- EMAIL: { icon: Email, label: "Email" },- MEETING: { icon: Events, label: "Meeting" },- TASK: { icon: Task, label: "Task" },- STAGE_CHANGE: { icon: ArrowRight, label: "Stage change" },- ENRICHMENT: { icon: MagicWand, label: "Enrichment" },- };--export function activityLabel(type: ActivityType): string {- return PRESENTATION[type].label;-}+import { activityIcon } from "@/lib/activity-presentation";export function ActivityIcon({ type }: { type: ActivityType }) {- return <Icon icon={PRESENTATION[type].icon} />;+ return <Icon icon={activityIcon(type)} />;}diff --git a/apps/app/components/crm/timeline/email-thread-entry.tsx b/apps/app/components/crm/timeline/email-thread-entry.tsxindex 415411fc..3e3093f7 100644--- a/apps/app/components/crm/timeline/email-thread-entry.tsx+++ b/apps/app/components/crm/timeline/email-thread-entry.tsx@@ -10,14 +10,15 @@ import { Skeleton } from "@crm/ui/components/skeleton";import { ThreadMessage } from "@crm/ui/components/thread-message";import { useQuery } from "@tanstack/react-query";import { useState } from "react";+import { LocalDateTime } from "@/components/local-date-time";import { useTRPC } from "@/lib/trpc/client";-const timeFormat = new Intl.DateTimeFormat(undefined, {+const DATE_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",hour: "numeric",minute: "2-digit",-});+};export function EmailThreadEntry({threadId,@@ -65,7 +66,12 @@ export function EmailThreadEntry({from={message.fromName ?? message.fromEmail}fromEmail={message.fromEmail}fromImageUrl={message.fromImageUrl}- sentAt={timeFormat.format(new Date(message.sentAt))}+ sentAt={+ <LocalDateTime+ date={message.sentAt}+ options={DATE_OPTIONS}+ />+ }direction={message.direction}body={message.body}action={diff --git a/apps/app/components/crm/timeline/meeting-entry.tsx b/apps/app/components/crm/timeline/meeting-entry.tsxindex f95a89a9..f95e39e6 100644--- a/apps/app/components/crm/timeline/meeting-entry.tsx+++ b/apps/app/components/crm/timeline/meeting-entry.tsx@@ -2,24 +2,23 @@import { AttendeeList } from "@crm/ui/components/attendee-list";import { useQuery } from "@tanstack/react-query";+import {+ LocalDateTime,+ LocalDateTimeRange,+} from "@/components/local-date-time";import { useTRPC } from "@/lib/trpc/client";-const rangeFormat = new Intl.DateTimeFormat(undefined, {+const RANGE_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",hour: "numeric",minute: "2-digit",-});+};-const timeOnly = new Intl.DateTimeFormat(undefined, {- hour: "numeric",- minute: "2-digit",-});--const dayOnly = new Intl.DateTimeFormat(undefined, {+const DAY_OPTIONS: Intl.DateTimeFormatOptions = {month: "short",day: "numeric",-});+};export function MeetingEntry({eventId,@@ -46,7 +45,17 @@ export function MeetingEntry({return (<div className="flex flex-wrap items-center gap-x-4 gap-y-2"><span className="text-muted-foreground text-xs">- {formatRange(startsAt, endsAt, isAllDay)}+ {isAllDay ? (+ <>+ <LocalDateTime date={startsAt} options={DAY_OPTIONS} /> · All day+ </>+ ) : (+ <LocalDateTimeRange+ start={startsAt}+ end={endsAt}+ options={RANGE_OPTIONS}+ />+ )}</span>{event.data?.attendees && event.data.attendees.length > 0 ? (@@ -66,20 +75,3 @@ export function MeetingEntry({</div>);}--function formatRange(- startsAt: string,- endsAt: string,- isAllDay: boolean,-): string {- const start = new Date(startsAt);- const end = new Date(endsAt);-- if (isAllDay) return `${dayOnly.format(start)} · All day`;-- const sameDay = start.toDateString() === end.toDateString();-- return sameDay- ? `${rangeFormat.format(start)} – ${timeOnly.format(end)}`- : `${rangeFormat.format(start)} – ${rangeFormat.format(end)}`;-}diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsxindex da8ff5e7..8a86f98a 100644--- a/apps/app/components/crm/timeline/timeline-entry.tsx+++ b/apps/app/components/crm/timeline/timeline-entry.tsx@@ -2,16 +2,17 @@import { Checkbox } from "@crm/ui/components/checkbox";import { StatusIndicator } from "@crm/ui/components/status-indicator";-import { relativeTimeFromIso } from "@crm/ui/lib/format";import { cn } from "@crm/ui/lib/utils";import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";-import { dealStageLabel } from "@/components/crm/deal-stage";import { RecordLink } from "@/components/crm/record-sheet/record-link";+import { LocalDateTime, LocalRelativeTime } from "@/components/local-date-time";+import { activityLabel } from "@/lib/activity-presentation";+import { dealStageLabel } from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";-import { ActivityIcon, activityLabel } from "./activity-icon";+import { ActivityIcon } from "./activity-icon";import { EmailThreadEntry } from "./email-thread-entry";import { MeetingEntry } from "./meeting-entry";import type { TimelineAnchor } from "./timeline";@@ -19,10 +20,10 @@ import type { TimelineAnchor } from "./timeline";export type TimelineEntryData =RouterOutputs["activities"]["timeline"]["entries"][number];-const timeFormat = new Intl.DateTimeFormat(undefined, {+const TIME_OPTIONS: Intl.DateTimeFormatOptions = {hour: "numeric",minute: "2-digit",-});+};function stageChange(meta: Record<string, unknown> | null) {const from = typeof meta?.from === "string" ? meta.from : null;@@ -138,7 +139,7 @@ export function TimelineEntry({<span className="shrink-0 text-muted-foreground"><span className="hidden sm:inline">{author} · </span><span className="tabular-nums">- {timeFormat.format(new Date(when))}+ <LocalDateTime date={when} options={TIME_OPTIONS} /></span></span></div>@@ -163,15 +164,15 @@ export function TimelineEntry({{footnotes ? (<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground">- {overdue ? (+ {isTask && !done && entry.dueAt ? (<StatusIndicator- tone="error"- label={`Overdue ${relativeTimeFromIso(entry.dueAt)}`}- />- ) : isTask && !done && entry.dueAt ? (- <StatusIndicator- tone="info"- label={`Due ${relativeTimeFromIso(entry.dueAt)}`}+ tone={overdue ? "error" : "info"}+ label={+ <>+ {overdue ? "Overdue" : "Due"}{" "}+ <LocalRelativeTime date={entry.dueAt} />+ </>+ }/>) : null}diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsxindex 121382da..d2fde05f 100644--- a/apps/app/components/crm/timeline/timeline.tsx+++ b/apps/app/components/crm/timeline/timeline.tsx@@ -15,6 +15,7 @@ import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { useQueryState } from "nuqs";import { DetailSheetEmpty, SECTION_TITLE } from "@/components/detail-sheet";import { useTRPC } from "@/lib/trpc/client";+import { useHydrated } from "@/lib/use-hydrated";import { ActivityComposer } from "./activity-composer";import { TimelineEntry, type TimelineEntryData } from "./timeline-entry";import {@@ -83,47 +84,56 @@ const EMPTY_ICONS: Record<TimelineTab, CarbonIcon> = {done: Checkmark,};-const dayFormat = new Intl.DateTimeFormat(undefined, {+const dayFormat = new Intl.DateTimeFormat("en-US", {weekday: "short",month: "short",day: "numeric",year: "numeric",});-function dayLabel(at: Date): string {- const midnight = (date: Date) =>- new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+function dayLabel(day: string, local: boolean): string {+ const now = new Date();+ const today = dayKey(now.toISOString(), local);+ const yesterdayDate = local+ ? new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)+ : new Date(Date.now() - 86_400_000);+ const yesterday = dayKey(yesterdayDate.toISOString(), local);- const days = Math.round(- (midnight(new Date()) - midnight(at)) / (1000 * 60 * 60 * 24),- );-- if (days === 0) return "Today";- if (days === 1) return "Yesterday";- return dayFormat.format(at);+ if (day === today) return "Today";+ if (day === yesterday) return "Yesterday";+ return dayFormat.format(new Date(`${day}T00:00:00`));}-function byDay(entries: TimelineEntryData[]) {+function byDay(entries: TimelineEntryData[], local: boolean) {const groups = new Map<string,{ day: string; label: string; entries: TimelineEntryData[] }>();for (const entry of entries) {- const at = new Date(entry.occurredAt ?? entry.createdAt);- const day = at.toDateString();+ const day = dayKey(entry.occurredAt ?? entry.createdAt, local);const group = groups.get(day);if (group) {group.entries.push(entry);} else {- groups.set(day, { day, label: dayLabel(at), entries: [entry] });+ groups.set(day, { day, label: dayLabel(day, local), entries: [entry] });}}return [...groups.values()];}+function dayKey(value: string, local: boolean): string {+ if (!local) return value.slice(0, 10);+ const date = new Date(value);+ return [+ date.getFullYear(),+ String(date.getMonth() + 1).padStart(2, "0"),+ String(date.getDate()).padStart(2, "0"),+ ].join("-");+}+function TimelineDay({label,entries,@@ -149,6 +159,7 @@ function TimelineDay({export function Timeline({ anchor }: { anchor: TimelineAnchor }) {const trpc = useTRPC();+ const hydrated = useHydrated();const [tab, setTab] = useQueryState(TIMELINE_PARAM, timelineTabParser);@@ -220,7 +231,7 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {/>) : null}- {byDay(entries).map((group) => (+ {byDay(entries, hydrated).map((group) => (<TimelineDaykey={group.day}label={group.label}diff --git a/apps/app/components/data-table/list-search.tsx b/apps/app/components/data-table/list-search.tsxindex f97eedcf..c2c7cda7 100644--- a/apps/app/components/data-table/list-search.tsx+++ b/apps/app/components/data-table/list-search.tsx@@ -13,9 +13,25 @@ import { searchParsers } from "./list-search-params";export function ListSearch({ placeholder }: { placeholder: string }) {const [{ q }, setState] = useQueryStates(searchParsers);- const [value, setValue] = useSearchInput(q, (next) =>- setState({ q: next, page: 1 }),+ return (+ <ListSearchInput+ committed={q}+ commit={(next) => setState({ q: next, page: 1 })}+ placeholder={placeholder}+ />);+}++function ListSearchInput({+ committed,+ commit,+ placeholder,+}: {+ committed: string;+ commit: (value: string) => void;+ placeholder: string;+}) {+ const [value, setValue] = useSearchInput(committed, commit);return (<InputGroup className="w-full sm:w-64">diff --git a/apps/app/components/inline-script.tsx b/apps/app/components/inline-script.tsxnew file mode 100644index 00000000..ea27ff04--- /dev/null+++ b/apps/app/components/inline-script.tsx@@ -0,0 +1,10 @@+export function InlineScript({ html }: { html: string }) {+ return (+ <script+ type={typeof window === "undefined" ? "text/javascript" : "text/plain"}+ suppressHydrationWarning+ >+ {html}+ </script>+ );+}diff --git a/apps/app/components/landing/product-shot/company-sheet.tsx b/apps/app/components/landing/product-shot/company-sheet.tsxindex 46305bd6..1b1dc883 100644--- a/apps/app/components/landing/product-shot/company-sheet.tsx+++ b/apps/app/components/landing/product-shot/company-sheet.tsx@@ -45,7 +45,7 @@ export function CompanySheet() {);}-export function SheetHeader({ compact }: { compact?: boolean }) {+function SheetHeader({ compact }: { compact?: boolean }) {return (<divclassName={cn(@@ -93,7 +93,7 @@ export function SheetHeader({ compact }: { compact?: boolean }) {);}-export function SheetStats({ compact }: { compact?: boolean }) {+function SheetStats({ compact }: { compact?: boolean }) {if (compact) {return (<div className="grid shrink-0 grid-cols-2 border-border border-b bg-muted/40">@@ -165,7 +165,7 @@ function Stat({);}-export function SheetTabs({ compact }: { compact?: boolean }) {+function SheetTabs({ compact }: { compact?: boolean }) {return (<divclassName={cn(@@ -192,7 +192,7 @@ export function SheetTabs({ compact }: { compact?: boolean }) {);}-export function AgentEmptyState({ compact }: { compact?: boolean }) {+function AgentEmptyState({ compact }: { compact?: boolean }) {return (<divclassName={cn(@@ -231,7 +231,7 @@ export function AgentEmptyState({ compact }: { compact?: boolean }) {);}-export function SheetComposer({ compact }: { compact?: boolean }) {+function SheetComposer({ compact }: { compact?: boolean }) {return (<divclassName={cn(diff --git a/apps/app/components/local-date-time.tsx b/apps/app/components/local-date-time.tsxnew file mode 100644index 00000000..22f9fcd8--- /dev/null+++ b/apps/app/components/local-date-time.tsx@@ -0,0 +1,168 @@+"use client";++import { InlineScript } from "./inline-script";++const DAY_MS = 86_400_000;+const MINUTE_MS = 60_000;+const HOUR_MS = 60 * MINUTE_MS;+const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();+const relativeDateFormatter = new Intl.RelativeTimeFormat(undefined, {+ numeric: "auto",+});+const LOCAL_DAY_OPTIONS = {+ month: "short",+ day: "numeric",+ year: "numeric",+} as const;+const LOCAL_DATE_TIME_SCRIPT = `{var s="time[data-local-date-kind]",f=function(n){try{var k=n.dataset.localDateKind,v=n.dataset.localDateValue,e=n.dataset.localDateEnd,o=JSON.parse(n.dataset.localDateOptions||"{}"),d=new Date(v),t=d.getTime(),x=Date.now()-t,a=Math.abs(x),r;if(k==="date-time")r=new Intl.DateTimeFormat(void 0,o).format(d);else if(k==="date-range")r=new Intl.DateTimeFormat(void 0,o).formatRange(d,new Date(e));else if(k==="day")r=new Intl.DateTimeFormat(void 0,o).format(new Date(v+"T00:00:00"));else if(k==="relative-date"){var z=new Date(),q=(Date.UTC(z.getFullYear(),z.getMonth(),z.getDate())-Date.UTC(d.getFullYear(),d.getMonth(),d.getDate()))/${DAY_MS};r=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}).format(-q,"day")}else if(!Number.isFinite(t))r="—";else if(a<${MINUTE_MS})r="just now";else if(a>=${30 * DAY_MS})r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}).format(d);else{var u=a<${HOUR_MS}?Math.floor(a/${MINUTE_MS})+"m":a<${DAY_MS}?Math.floor(a/${HOUR_MS})+"h":Math.floor(a/${DAY_MS})+"d";r=x<0?"in "+u:u+" ago"}n.textContent=r}catch{}};var c=function(r){if(r.nodeType===1&&r.matches&&r.matches(s))f(r);if(r.querySelectorAll)r.querySelectorAll(s).forEach(f)};c(document);new MutationObserver(function(m){m.forEach(function(r){r.addedNodes.forEach(c)})}).observe(document.documentElement,{childList:true,subtree:true})}`;++export function LocalDateTime({+ date,+ options,+}: {+ date: string;+ options: Intl.DateTimeFormatOptions;+}) {+ return (+ <LocalTime+ kind="date-time"+ date={date}+ options={options}+ fallback={getDateTimeFormatter(options).format(new Date(date))}+ />+ );+}++export function LocalDateTimeRange({+ start,+ end,+ options,+}: {+ start: string;+ end: string;+ options: Intl.DateTimeFormatOptions;+}) {+ return (+ <LocalTime+ kind="date-range"+ date={start}+ end={end}+ options={options}+ fallback={getDateTimeFormatter(options).formatRange(+ new Date(start),+ new Date(end),+ )}+ />+ );+}++export function LocalRelativeDate({ date }: { date: string }) {+ return (+ <LocalTime+ kind="relative-date"+ date={date}+ fallback={formatRelativeDate(date)}+ />+ );+}++export function LocalRelativeTime({ date }: { date: string }) {+ return (+ <LocalTime+ kind="relative-time"+ date={date}+ fallback={formatRelativeTime(date)}+ />+ );+}++export function LocalDay({ date }: { date: string }) {+ const day = date.slice(0, 10);+ return (+ <LocalTime+ kind="day"+ date={day}+ options={LOCAL_DAY_OPTIONS}+ fallback={getDateTimeFormatter(LOCAL_DAY_OPTIONS).format(dayDate(day))}+ />+ );+}++export function LocalDateTimeHydrator() {+ return <InlineScript html={LOCAL_DATE_TIME_SCRIPT} />;+}++function LocalTime({+ kind,+ date,+ end,+ options,+ fallback,+}: {+ kind: "date-time" | "date-range" | "day" | "relative-date" | "relative-time";+ date: string;+ end?: string;+ options?: Intl.DateTimeFormatOptions;+ fallback: string;+}) {+ return (+ <time+ dateTime={date}+ data-local-date-kind={kind}+ data-local-date-value={date}+ data-local-date-end={end}+ data-local-date-options={options ? JSON.stringify(options) : undefined}+ suppressHydrationWarning+ >+ {fallback}+ </time>+ );+}++function formatRelativeDate(date: string): string {+ const now = new Date();+ const then = new Date(date);+ const days = (calendarDay(now) - calendarDay(then)) / DAY_MS;+ return relativeDateFormatter.format(-days, "day");+}++function formatRelativeTime(date: string): string {+ const then = new Date(date).getTime();+ if (!Number.isFinite(then)) return "—";+ const difference = Date.now() - then;+ const absolute = Math.abs(difference);+ if (absolute < MINUTE_MS) return "just now";+ if (absolute >= 30 * DAY_MS) {+ return getDateTimeFormatter({ month: "short", day: "numeric" }).format(+ new Date(then),+ );+ }++ const distance =+ absolute < HOUR_MS+ ? `${Math.floor(absolute / MINUTE_MS)}m`+ : absolute < DAY_MS+ ? `${Math.floor(absolute / HOUR_MS)}h`+ : `${Math.floor(absolute / DAY_MS)}d`;+ return difference < 0 ? `in ${distance}` : `${distance} ago`;+}++function calendarDay(date: Date): number {+ return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());+}++function dayDate(day: string): Date {+ return new Date(`${day}T00:00:00`);+}++function getDateTimeFormatter(+ options: Intl.DateTimeFormatOptions,+): Intl.DateTimeFormat {+ const key = JSON.stringify(options);+ const cached = dateTimeFormatters.get(key);+ if (cached) return cached;++ const formatter = new Intl.DateTimeFormat(undefined, options);+ dateTimeFormatters.set(key, formatter);+ return formatter;+}diff --git a/apps/app/components/mobile-nav.tsx b/apps/app/components/mobile-nav.tsxindex b4acbb1c..5b8e07ba 100644--- a/apps/app/components/mobile-nav.tsx+++ b/apps/app/components/mobile-nav.tsx@@ -1,6 +1,6 @@"use client";-import { createContext, useContext, useState } from "react";+import { createContext, useContext, useMemo, useState } from "react";type MobileNavContextValue = {open: boolean;@@ -11,8 +11,9 @@ const MobileNavContext = createContext<MobileNavContextValue | null>(null);export function MobileNavProvider({ children }: { children: React.ReactNode }) {const [open, setOpen] = useState(false);+ const value = useMemo(() => ({ open, setOpen }), [open]);return (- <MobileNavContext.Provider value={{ open, setOpen }}>+ <MobileNavContext.Provider value={value}>{children}</MobileNavContext.Provider>);diff --git a/apps/app/components/page-shell.tsx b/apps/app/components/page-shell.tsxindex 9f94acc6..8cd82710 100644--- a/apps/app/components/page-shell.tsx+++ b/apps/app/components/page-shell.tsx@@ -1,3 +1,4 @@+import { Skeleton } from "@crm/ui/components/skeleton";import { Spinner } from "@crm/ui/components/spinner";import { cn } from "@crm/ui/lib/utils";import type * as React from "react";@@ -129,11 +130,40 @@ function PageShellLoading() {);}+function PageShellFallback() {+ return (+ <PageShell aria-busy="true">+ <div className="flex flex-col gap-3" aria-hidden="true">+ <Skeleton className="h-8 w-48 max-w-full" />+ <Skeleton className="h-4 w-72 max-w-full" />+ </div>+ <div className="overflow-hidden rounded-lg border">+ {[0, 1, 2, 3, 4].map((row) => (+ <div+ key={row}+ className="flex min-h-14 items-center gap-4 border-t px-4 first:border-t-0 sm:px-5"+ >+ <Skeleton className="size-7 shrink-0 rounded-md" />+ <div className="min-w-0 flex-1 space-y-2">+ <Skeleton className="h-3 w-40 max-w-full" />+ <Skeleton className="h-2.5 w-64 max-w-full" />+ </div>+ </div>+ ))}+ </div>+ <span role="status" className="sr-only">+ Loading page+ </span>+ </PageShell>+ );+}+export {PageShell,PageShellActions,PageShellContent,PageShellDescription,+ PageShellFallback,PageShellHeader,PageShellHeading,PageShellLoading,diff --git a/apps/app/lib/activity-presentation.ts b/apps/app/lib/activity-presentation.tsnew file mode 100644index 00000000..47d04445--- /dev/null+++ b/apps/app/lib/activity-presentation.ts@@ -0,0 +1,28 @@+import ArrowRight from "@carbon/icons-react/es/ArrowRight";+import Chat from "@carbon/icons-react/es/Chat";+import Email from "@carbon/icons-react/es/Email";+import Events from "@carbon/icons-react/es/Events";+import MagicWand from "@carbon/icons-react/es/MagicWand";+import Phone from "@carbon/icons-react/es/Phone";+import Task from "@carbon/icons-react/es/Task";+import type { ActivityType } from "@crm/db/enums";+import type { CarbonIcon } from "@crm/ui/components/icon";++const PRESENTATION: Record<ActivityType, { icon: CarbonIcon; label: string }> =+ {+ NOTE: { icon: Chat, label: "Note" },+ CALL: { icon: Phone, label: "Call" },+ EMAIL: { icon: Email, label: "Email" },+ MEETING: { icon: Events, label: "Meeting" },+ TASK: { icon: Task, label: "Task" },+ STAGE_CHANGE: { icon: ArrowRight, label: "Stage change" },+ ENRICHMENT: { icon: MagicWand, label: "Enrichment" },+ };++export function activityLabel(type: ActivityType): string {+ return PRESENTATION[type].label;+}++export function activityIcon(type: ActivityType): CarbonIcon {+ return PRESENTATION[type].icon;+}diff --git a/apps/app/lib/contact-facts.ts b/apps/app/lib/contact-facts.tsnew file mode 100644index 00000000..37cf67d3--- /dev/null+++ b/apps/app/lib/contact-facts.ts@@ -0,0 +1,17 @@+import type { RouterOutputs } from "@/lib/trpc/types";++type Contact = RouterOutputs["contacts"]["byId"];++export type ContactFact = Contact["facts"][number];++export function factsByField(facts: ContactFact[]) {+ const applied = new Map<string, ContactFact>();+ const proposed = new Map<string, ContactFact>();++ for (const fact of facts) {+ const bucket = fact.status === "APPLIED" ? applied : proposed;+ if (!bucket.has(fact.field)) bucket.set(fact.field, fact);+ }++ return { applied, proposed };+}diff --git a/apps/app/lib/deal-stage.ts b/apps/app/lib/deal-stage.tsnew file mode 100644index 00000000..3da33ccd--- /dev/null+++ b/apps/app/lib/deal-stage.ts@@ -0,0 +1,57 @@+import { DealStage } from "@crm/db/enums";+import type { StatusTone } from "@crm/ui/components/status-indicator";++const ORDER = [+ DealStage.DEMO_BOOKED,+ DealStage.QUALIFIED_TO_BUY,+ DealStage.DECISION_MAKER_BOUGHT_IN,+ DealStage.CONTRACT_SENT,+ DealStage.CLOSED_WON,+ DealStage.CLOSED_LOST,+ DealStage.UNQUALIFIED_TO_BUY,+] as const;++const PRESENTATION: Record<DealStage, { label: string; tone: StatusTone }> = {+ DEMO_BOOKED: { label: "Demo booked", tone: "neutral" },+ QUALIFIED_TO_BUY: { label: "Qualified to buy", tone: "info" },+ DECISION_MAKER_BOUGHT_IN: { label: "Decision maker in", tone: "info" },+ CONTRACT_SENT: { label: "Contract sent", tone: "warning" },+ CLOSED_WON: { label: "Closed won", tone: "success" },+ CLOSED_LOST: { label: "Closed lost", tone: "error" },+ UNQUALIFIED_TO_BUY: { label: "Unqualified", tone: "neutral" },+};++export const OPEN_STAGES = ORDER.slice(0, 4) as readonly DealStage[];++export const LOSING_STAGES: readonly DealStage[] = [+ DealStage.CLOSED_LOST,+ DealStage.UNQUALIFIED_TO_BUY,+];++export const DEAL_STAGE_OPTIONS = ORDER.map((value) => ({+ value,+ label: PRESENTATION[value].label,+}));++const OPEN_STAGE_COLORS = [+ "var(--chart-1)",+ "var(--chart-2)",+ "var(--chart-3)",+ "var(--chart-4)",+] as const;++export function isClosedStage(stage: DealStage): boolean {+ return !OPEN_STAGES.includes(stage);+}++export function dealStageColor(stage: DealStage): string {+ return OPEN_STAGE_COLORS[OPEN_STAGES.indexOf(stage)] ?? "var(--chart-5)";+}++export function dealStageLabel(stage: DealStage): string {+ return PRESENTATION[stage].label;+}++export function dealStagePresentation(stage: DealStage) {+ return PRESENTATION[stage];+}diff --git a/apps/app/lib/enrichment-status.ts b/apps/app/lib/enrichment-status.tsnew file mode 100644index 00000000..4264ee42--- /dev/null+++ b/apps/app/lib/enrichment-status.ts@@ -0,0 +1,32 @@+import type { EnrichmentStatus } from "@crm/db/enums";+import type { StatusTone } from "@crm/ui/components/status-indicator";++const PRESENTATION: Record<+ EnrichmentStatus,+ { label: string; tone: StatusTone; busy?: boolean }+> = {+ PENDING: { label: "Not researched", tone: "neutral" },+ RUNNING: { label: "Researching", tone: "info", busy: true },+ COMPLETE: { label: "Enriched", tone: "success" },+ FAILED: { label: "Enrichment failed", tone: "error" },+ SKIPPED: { label: "Nothing found", tone: "neutral" },+};++const QUEUED = { label: "Queued", tone: "neutral" as StatusTone, busy: false };++export const ENRICHMENT_POLL_MS = 3_000;++export const ENRICHMENT_FACET_OPTIONS = (+ Object.keys(PRESENTATION) as EnrichmentStatus[]+).map((value) => ({ value, label: PRESENTATION[value].label }));++export function enrichmentPresentation(+ status: EnrichmentStatus,+ queued: boolean,+) {+ return status === "PENDING" && queued ? QUEUED : PRESENTATION[status];+}++export function isEnriching(status: EnrichmentStatus, queued = false): boolean {+ return status === "RUNNING" || (status === "PENDING" && queued);+}diff --git a/apps/app/lib/pending-field.ts b/apps/app/lib/pending-field.tsnew file mode 100644index 00000000..0e8bae68--- /dev/null+++ b/apps/app/lib/pending-field.ts@@ -0,0 +1,9 @@+export function savingField(update: {+ isPending: boolean;+ variables?: { data?: object } | undefined;+}): (field: string) => boolean {+ const fields = update.isPending+ ? Object.keys(update.variables?.data ?? {})+ : [];+ return (field) => fields.includes(field);+}diff --git a/apps/app/lib/sign-out.ts b/apps/app/lib/sign-out.tsnew file mode 100644index 00000000..53a4f5be--- /dev/null+++ b/apps/app/lib/sign-out.ts@@ -0,0 +1,15 @@+"use client";++import { signOut } from "@crm/auth/client";+import { toast } from "sonner";++export async function signOutAndRedirect() {+ const { error } = await signOut();++ if (error) {+ toast.error(error.message ?? "Could not sign out.");+ return;+ }++ window.location.assign("/sign-in");+}diff --git a/apps/app/lib/social-links.ts b/apps/app/lib/social-links.tsnew file mode 100644index 00000000..cfe73aff--- /dev/null+++ b/apps/app/lib/social-links.ts@@ -0,0 +1,59 @@+import LogoGithub from "@carbon/icons-react/es/LogoGithub";+import LogoLinkedin from "@carbon/icons-react/es/LogoLinkedin";+import LogoX from "@carbon/icons-react/es/LogoX";+import Money from "@carbon/icons-react/es/Money";+import UserMultiple from "@carbon/icons-react/es/UserMultiple";+import type { CarbonIcon } from "@crm/ui/components/icon";++type SocialLink<T> = { key: keyof T; label: string; icon: CarbonIcon };++export type CompanyLinks = {+ linkedinUrl: string | null;+ twitterUrl: string | null;+ githubUrl: string | null;+ pricingUrl: string | null;+ careersUrl: string | null;+};++export type ContactLinks = {+ linkedinUrl: string | null;+ twitterUrl: string | null;+ githubUrl: string | null;+};++const COMPANY_LINKS: SocialLink<CompanyLinks>[] = [+ { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },+ { key: "twitterUrl", label: "X", icon: LogoX },+ { key: "githubUrl", label: "GitHub", icon: LogoGithub },+ { key: "pricingUrl", label: "Pricing", icon: Money },+ { key: "careersUrl", label: "Careers", icon: UserMultiple },+];++const CONTACT_LINKS: SocialLink<ContactLinks>[] = [+ { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },+ { key: "twitterUrl", label: "X", icon: LogoX },+ { key: "githubUrl", label: "GitHub", icon: LogoGithub },+];++function present<T>(record: T, links: SocialLink<T>[]) {+ return links.flatMap((link) => {+ const href = record[link.key];+ return typeof href === "string" && href ? [{ ...link, href }] : [];+ });+}++export function companySocialLinks(company: CompanyLinks) {+ return present(company, COMPANY_LINKS);+}++export function contactSocialLinks(contact: ContactLinks) {+ return present(contact, CONTACT_LINKS);+}++export function hasCompanyLinks(company: CompanyLinks): boolean {+ return companySocialLinks(company).length > 0;+}++export function hasContactLinks(contact: ContactLinks): boolean {+ return contactSocialLinks(contact).length > 0;+}diff --git a/apps/app/lib/sync-status.ts b/apps/app/lib/sync-status.tsnew file mode 100644index 00000000..fd7d80df--- /dev/null+++ b/apps/app/lib/sync-status.ts@@ -0,0 +1,7 @@+import type { GoogleSyncStatus } from "@crm/db/enums";++export const SYNC_POLL_MS = 5_000;++export function isSyncing(status: GoogleSyncStatus | null): boolean {+ return status === "RUNNING";+}diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.tsindex a60162ca..b4c088ec 100644--- a/apps/app/lib/trpc/cache.ts+++ b/apps/app/lib/trpc/cache.ts@@ -23,6 +23,7 @@ export type CrmCache = {fieldCoverage(id?: string, options?: Options): Promise<void>;removed(record: RemovedRecord): Promise<void>;removedMany(records: RemovedRecords): Promise<void>;+ conversationRemoved(id: string): Promise<void>;activity(options?: Options): Promise<void>;google(options?: Options): Promise<void>;microsoft(options?: Options): Promise<void>;@@ -185,6 +186,22 @@ export function useCrmCache(): CrmCache {removedMany: ({ kind, ids }) => removeRecords(kind, ids),+ conversationRemoved: (id) => {+ for (const queryKey of [+ trpc.conversations.builderById.queryKey({ id }),+ trpc.conversations.events.queryKey({ id }),+ trpc.conversations.shareStatus.queryKey({ id }),+ ]) {+ void queryClient.invalidateQueries({+ queryKey,+ exact: true,+ refetchType: "none",+ });+ }++ return run([trpc.conversations.builderList.pathKey()], []);+ },+activity: (options) =>run(activityKeys(),diff --git a/apps/app/lib/trpc/query-client.ts b/apps/app/lib/trpc/query-client.tsindex 82a8cc50..af6f9eeb 100644--- a/apps/app/lib/trpc/query-client.ts+++ b/apps/app/lib/trpc/query-client.ts@@ -1,13 +1,36 @@-import { QueryClient } from "@tanstack/react-query";+import {+ defaultShouldDehydrateQuery,+ QueryClient,+} from "@tanstack/react-query";export function makeQueryClient(): QueryClient {return new QueryClient({defaultOptions: {- queries: { staleTime: 30_000 },+ queries: { staleTime: 30_000, retry: retryQuery },+ dehydrate: {+ shouldDehydrateQuery: (query) =>+ defaultShouldDehydrateQuery(query) ||+ query.state.status === "pending",+ },},});}+function retryQuery(failureCount: number, error: unknown): boolean {+ const data =+ error && typeof error === "object" && "data" in error ? error.data : null;+ const status =+ data && typeof data === "object" && "httpStatus" in data+ ? data.httpStatus+ : null;++ if (typeof status === "number" && status >= 400 && status < 500) {+ return false;+ }++ return failureCount < 1;+}+let browserQueryClient: QueryClient | undefined;export function getQueryClient(): QueryClient {diff --git a/apps/app/lib/trpc/server.ts b/apps/app/lib/trpc/server.tsindex 2fc69f69..35509a54 100644--- a/apps/app/lib/trpc/server.ts+++ b/apps/app/lib/trpc/server.ts@@ -12,8 +12,8 @@ import { makeQueryClient } from "./query-client";export const getServerQueryClient = cache(makeQueryClient);-export function getServerTrpc(): TRPCOptionsProxy<AppRouter> {- const client = createTRPCClient<AppRouter>({+export function getServerTrpcClient(): TRPCClient<AppRouter> {+ return createTRPCClient<AppRouter>({links: [httpBatchLink({url: `${API_URL}/api/trpc`,@@ -24,6 +24,10 @@ export function getServerTrpc(): TRPCOptionsProxy<AppRouter> {}),],});+}++export function getServerTrpc(): TRPCOptionsProxy<AppRouter> {+ const client = getServerTrpcClient();return createTRPCOptionsProxy<AppRouter>({client,diff --git a/apps/app/lib/use-hydrated.ts b/apps/app/lib/use-hydrated.tsnew file mode 100644index 00000000..06392591--- /dev/null+++ b/apps/app/lib/use-hydrated.ts@@ -0,0 +1,19 @@+"use client";++import { useSyncExternalStore } from "react";++export function useHydrated() {+ return useSyncExternalStore(subscribe, clientSnapshot, serverSnapshot);+}++function subscribe() {+ return () => undefined;+}++function clientSnapshot() {+ return true;+}++function serverSnapshot() {+ return false;+}diff --git a/apps/app/lib/workspace-label.ts b/apps/app/lib/workspace-label.tsnew file mode 100644index 00000000..8c913131--- /dev/null+++ b/apps/app/lib/workspace-label.ts@@ -0,0 +1,7 @@+export function workspaceLabel(name: string | undefined): string {+ const trimmed = name?.trim();++ if (!trimmed) return "CRM";++ return /\bcrm$/i.test(trimmed) ? trimmed : `${trimmed} CRM`;+}diff --git a/apps/app/test/workspace-label.spec.ts b/apps/app/test/workspace-label.spec.tsindex 22dcf4cf..f44d7bca 100644--- a/apps/app/test/workspace-label.spec.ts+++ b/apps/app/test/workspace-label.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "bun:test";import { DEFAULT_WORKSPACE_NAME } from "@crm/auth";-import { workspaceLabel } from "../components/app-header";+import { workspaceLabel } from "../lib/workspace-label";describe("what the header calls this install", () => {it("does not say CRM twice before anybody has named the workspace", () => {diff --git a/packages/ui/src/components/bubble.tsx b/packages/ui/src/components/bubble.tsxindex 95d03dc9..a177e0e9 100644--- a/packages/ui/src/components/bubble.tsx+++ b/packages/ui/src/components/bubble.tsx@@ -15,7 +15,7 @@ function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {}const bubbleVariants = cva(- "group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",+ "group/bubble relative flex w-fit max-w-full min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full sm:max-w-[80%]",{variants: {variant: {diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsxindex 3bef6b94..ebb661d1 100644--- a/packages/ui/src/components/button.tsx+++ b/packages/ui/src/components/button.tsx@@ -4,7 +4,7 @@ import { Slot } from "radix-ui";import type * as React from "react";const buttonVariants = cva(- "group/button inline-flex shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/button inline-flex shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,opacity,transform] outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {diff --git a/packages/ui/src/components/calendar.tsx b/packages/ui/src/components/calendar.tsxindex 41483184..3fccae86 100644--- a/packages/ui/src/components/calendar.tsx+++ b/packages/ui/src/components/calendar.tsx@@ -9,6 +9,7 @@ import {} from "react-day-picker"import { cn } from "@crm/ui/lib/utils"+import { toDay } from "@crm/ui/lib/format"import { Button, buttonVariants } from "@crm/ui/components/button"import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"@@ -199,7 +200,7 @@ function CalendarDayButton({ref={ref}variant="ghost"size="icon"- data-day={day.date.toLocaleDateString(locale?.code)}+ data-day={toDay(day.date)}data-selected-single={modifiers.selected &&!modifiers.range_start &&diff --git a/packages/ui/src/components/chart.tsx b/packages/ui/src/components/chart.tsxindex 3092964f..32310a9d 100644--- a/packages/ui/src/components/chart.tsx+++ b/packages/ui/src/components/chart.tsx@@ -56,9 +56,10 @@ function ChartContainer({}) {const uniqueId = React.useId();const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`;+ const context = React.useMemo(() => ({ config }), [config]);return (- <ChartContext.Provider value={{ config }}>+ <ChartContext.Provider value={context}><divdata-slot="chart"data-chart={chartId}@@ -146,11 +147,12 @@ function ChartTooltipContent({>) {const { config } = useChart();- const tooltipLabel = React.useMemo(() => {- if (hideLabel || !payload?.length) {- return null;- }+ if (!active || !payload?.length) {+ return null;+ }+ let tooltipLabel: React.ReactNode = null;+ if (!hideLabel) {const [item] = payload;const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`;const itemConfig = getPayloadConfigFromPayload(config, item, key);@@ -160,30 +162,16 @@ function ChartTooltipContent({: itemConfig?.label;if (labelFormatter) {- return (+ tooltipLabel = (<div className={cn("font-medium", labelClassName)}>{labelFormatter(value, payload)}</div>);+ } else if (value) {+ tooltipLabel = (+ <div className={cn("font-medium", labelClassName)}>{value}</div>+ );}-- if (!value) {- return null;- }-- return <div className={cn("font-medium", labelClassName)}>{value}</div>;- }, [- label,- labelFormatter,- payload,- hideLabel,- labelClassName,- config,- labelKey,- ]);-- if (!active || !payload?.length) {- return null;}const nestLabel = payload.length === 1 && indicator !== "dot";@@ -197,16 +185,16 @@ function ChartTooltipContent({>{!nestLabel ? tooltipLabel : null}<div className="grid gap-1.5">- {payload- .filter((item) => item.type !== "none")- .map((item, index) => {+ {payload.map((item, index) => {+ if (item.type === "none") return null;const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`;const itemConfig = getPayloadConfigFromPayload(config, item, key);const indicatorColor = color ?? item.payload?.fill ?? item.color;+ const itemKey = `${String(item.dataKey ?? item.name ?? "value")}:${String(item.type ?? "default")}:${index}`;return (<div- key={index}+ key={itemKey}className={cn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",indicator === "dot" && "items-center",@@ -300,15 +288,15 @@ function ChartLegendContent({className,)}>- {payload- .filter((item) => item.type !== "none")- .map((item, index) => {+ {payload.map((item, index) => {+ if (item.type === "none") return null;const key = `${nameKey ?? item.dataKey ?? "value"}`;const itemConfig = getPayloadConfigFromPayload(config, item, key);+ const itemKey = `${String(item.dataKey ?? item.value ?? "value")}:${String(item.type ?? "default")}:${index}`;return (<div- key={index}+ key={itemKey}className={cn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",)}diff --git a/packages/ui/src/components/entity-logo.tsx b/packages/ui/src/components/entity-logo.tsxindex 009b664f..a9d91a7d 100644--- a/packages/ui/src/components/entity-logo.tsx+++ b/packages/ui/src/components/entity-logo.tsx@@ -106,10 +106,13 @@ function Artwork({className,} as const;- return isOptimizable(src) ? (- <Image src={src} width={px} height={px} {...shared} />- ) : (- // biome-ignore lint/performance/noImgElement: the optimizer may not serve this — see `isOptimizable`.- <img src={src} {...shared} />+ return (+ <Image+ src={src}+ width={px}+ height={px}+ unoptimized={!isOptimizable(src)}+ {...shared}+ />);}diff --git a/packages/ui/src/components/field.tsx b/packages/ui/src/components/field.tsxindex 0f867d0b..0b29c35f 100644--- a/packages/ui/src/components/field.tsx+++ b/packages/ui/src/components/field.tsx@@ -201,8 +201,8 @@ function FieldError({return (<ul className="ml-4 flex list-disc flex-col gap-1">{uniqueErrors.map(- (error, index) =>- error?.message && <li key={index}>{error.message}</li>,+ (error) =>+ error?.message && <li key={error.message}>{error.message}</li>,)}</ul>);diff --git a/packages/ui/src/components/simple-table.tsx b/packages/ui/src/components/simple-table.tsxindex 7bc0a13b..96734093 100644--- a/packages/ui/src/components/simple-table.tsx+++ b/packages/ui/src/components/simple-table.tsx@@ -15,6 +15,7 @@ import { cn } from "@crm/ui/lib/utils";import type { ComponentProps, ReactNode } from "react";export type SimpleTableColumn = {+ id: string;header?: ReactNode;srLabel?: string;width?: string;@@ -74,9 +75,9 @@ export function SimpleTable({)}><TableRow className={cn("hover:bg-transparent", headerRowClassName)}>- {columns.map((column, index) => (+ {columns.map((column) => (<TableHead- key={index}+ key={column.id}aria-label={column.header ? undefined : column.srLabel}className={cn(headerHeight ?? "h-9",diff --git a/packages/ui/src/components/sourced-value.tsx b/packages/ui/src/components/sourced-value.tsxindex 84015286..4c92d1e0 100644--- a/packages/ui/src/components/sourced-value.tsx+++ b/packages/ui/src/components/sourced-value.tsx@@ -34,7 +34,7 @@ export function Provenance({}: {claim: string;reasons: string[];- observedAt?: string;+ observedAt?: React.ReactNode;sourceUrl?: string | null;}) {return (diff --git a/packages/ui/src/components/textarea.tsx b/packages/ui/src/components/textarea.tsxindex 74e4801a..27cc72ac 100644--- a/packages/ui/src/components/textarea.tsx+++ b/packages/ui/src/components/textarea.tsx@@ -6,14 +6,24 @@ const textareaVariants = cva("flex field-sizing-content w-full rounded-md border border-input bg-background px-2.5 py-2 text-xs transition-colors outline-none placeholder:text-muted-foreground hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-60 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/25 md:text-xs dark:bg-muted dark:shadow-[inset_0_1px_1px_rgb(0_0_0/0.30)] dark:disabled:bg-muted",{variants: {- size: { default: "min-h-16", sm: "min-h-8" },+ variant: {+ default: "",+ composer:+ "resize-none rounded-none border-transparent bg-transparent px-1 py-0 text-base leading-6 shadow-none ring-0 hover:border-transparent focus-visible:border-transparent focus-visible:ring-0 disabled:bg-transparent sm:text-[15px] dark:bg-transparent dark:shadow-none dark:disabled:bg-transparent",+ },+ size: {+ default: "min-h-16",+ sm: "min-h-8",+ composer: "max-h-40 min-h-6",+ },},- defaultVariants: { size: "default" },+ defaultVariants: { variant: "default", size: "default" },},);function Textarea({className,+ variant,size,...props}: Omit<React.ComponentProps<"textarea">, "size"> &@@ -21,7 +31,7 @@ function Textarea({return (<textareadata-slot="textarea"- className={cn(textareaVariants({ size }), className)}+ className={cn(textareaVariants({ variant, size }), className)}{...props}/>);diff --git a/packages/ui/src/components/thread-message.tsx b/packages/ui/src/components/thread-message.tsxindex 6150fa8e..c3011ee9 100644--- a/packages/ui/src/components/thread-message.tsx+++ b/packages/ui/src/components/thread-message.tsx@@ -16,7 +16,7 @@ function ThreadMessage({from: string;fromEmail: string;fromImageUrl?: string | null;- sentAt: string;+ sentAt: React.ReactNode;direction: "INBOUND" | "OUTBOUND";body: string | null;action?: React.ReactNode;diff --git a/packages/ui/src/components/toggle-group.tsx b/packages/ui/src/components/toggle-group.tsxindex a21fac66..2fa84fda 100644--- a/packages/ui/src/components/toggle-group.tsx+++ b/packages/ui/src/components/toggle-group.tsx@@ -31,6 +31,11 @@ function ToggleGroup({spacing?: number;orientation?: "horizontal" | "vertical";}) {+ const context = React.useMemo(+ () => ({ variant, size, spacing, orientation }),+ [variant, size, spacing, orientation],+ );+return (<ToggleGroupPrimitive.Rootdata-slot="toggle-group"@@ -40,14 +45,12 @@ function ToggleGroup({data-orientation={orientation}style={{ "--gap": spacing } as React.CSSProperties}className={cn(- "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-md data-[size=sm]:rounded-md data-vertical:flex-col data-vertical:items-stretch",+ "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-md data-[size=sm]:rounded-md data-vertical:w-full data-vertical:flex-col data-vertical:items-stretch",className,)}{...props}>- <ToggleGroupContext.Provider- value={{ variant, size, spacing, orientation }}- >+ <ToggleGroupContext.Provider value={context}>{children}</ToggleGroupContext.Provider></ToggleGroupPrimitive.Root>diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsxindex b9822f14..b7ef1b78 100644--- a/packages/ui/src/components/toggle.tsx+++ b/packages/ui/src/components/toggle.tsx@@ -11,7 +11,8 @@ const toggleVariants = cva(variants: {variant: {default: "bg-transparent",- outline: "border border-input bg-transparent hover:bg-muted",+ outline:+ "border border-input bg-transparent hover:bg-muted data-[state=on]:border-ring data-[state=on]:bg-background data-[state=on]:ring-1 data-[state=on]:ring-ring/30",},size: {default:diff --git a/packages/ui/src/hooks/use-search-input.ts b/packages/ui/src/hooks/use-search-input.tsindex c994e90b..2593b1a8 100644--- a/packages/ui/src/hooks/use-search-input.ts+++ b/packages/ui/src/hooks/use-search-input.ts@@ -7,23 +7,27 @@ export function useSearchInput(commit: (value: string) => void,delayMs = 250,) {- const [value, setValue] = useState(committed);+ const [state, setState] = useState({ committed, value: committed });+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ let value = state.value;- const commitRef = useRef(commit);- commitRef.current = commit;+ if (state.committed !== committed) {+ value = committed;+ setState({ committed, value: committed });+ }- const committedRef = useRef(committed);- committedRef.current = committed;+ useEffect(+ () => () => {+ if (timer.current) clearTimeout(timer.current);+ },+ [],+ );- useEffect(() => {- setValue(committed);- }, [committed]);+ const change = (next: string) => {+ setState({ committed, value: next });+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => commit(next), delayMs);+ };- useEffect(() => {- if (value === committedRef.current) return;- const timer = setTimeout(() => commitRef.current(value), delayMs);- return () => clearTimeout(timer);- }, [value, delayMs]);-- return [value, setValue] as const;+ return [value, change] as const;}diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.tsindex b58a5abc..de4a95c3 100644--- a/packages/ui/src/lib/format.ts+++ b/packages/ui/src/lib/format.ts@@ -7,6 +7,10 @@ export function formatCount(}const WELL_FORMED_CURRENCY_CODE = /^[A-Za-z]{3}$/;+const percentFormat = new Intl.NumberFormat("en-US", {+ style: "percent",+ maximumFractionDigits: 0,+});function displayCurrencyCode(currency: string): string {return WELL_FORMED_CURRENCY_CODE.test(currency)@@ -53,13 +57,10 @@ export function formatMoneyCompact(cents: number, currency = "usd"): string {}export function formatPercent(rate: number): string {- return new Intl.NumberFormat(undefined, {- style: "percent",- maximumFractionDigits: 0,- }).format(rate);+ return percentFormat.format(rate);}-const dayFormat = new Intl.DateTimeFormat(undefined, {+const dayFormat = new Intl.DateTimeFormat("en-US", {month: "short",day: "numeric",year: "numeric",@@ -86,33 +87,6 @@ export function formatDay(value: string | null | undefined): string {return date ? dayFormat.format(date) : (value ?? "—");}-export function relativeTimeFromIso(iso: string | null | undefined): string {- if (!iso) return "—";- const then = new Date(iso).getTime();- if (!Number.isFinite(then)) return "—";- const diff = Date.now() - then;- const abs = Math.abs(diff);- const min = 60_000;- const hour = 60 * min;- const day = 24 * hour;- if (abs < min) return "just now";- const distance =- abs < hour- ? `${Math.round(abs / min)}m`- : abs < day- ? `${Math.round(abs / hour)}h`- : abs < 30 * day- ? `${Math.round(abs / day)}d`- : null;- if (distance === null) {- return new Date(iso).toLocaleDateString(undefined, {- month: "short",- day: "numeric",- });- }- return diff < 0 ? `in ${distance}` : `${distance} ago`;-}-export function initialsFromName(name: string | null | undefined): string {const parts = (name ?? "").split(/\s+/).filter(Boolean);const first = parts[0];