Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat(app): adopt Neo design system and EvilCharts (#262)
grimee56599a09f2
diff --git a/apps/agent/agent/lib/builder-runtime.ts b/apps/agent/agent/lib/builder-runtime.tsindex e1dcfeda..109f84f2 100644--- a/apps/agent/agent/lib/builder-runtime.ts+++ b/apps/agent/agent/lib/builder-runtime.ts@@ -265,7 +265,7 @@ export async function saveBuilderDraft(backend: "eve-default",networkPolicy: "deny-all",credentials: "app-runtime-only",- summary: "Isolated sandbox · deny-all network · bounded CRM tools",+ summary: "Isolated sandbox with deny-all network and bounded CRM tools",};const files = artifactFiles(input, JSON.stringify(manifest, null, 2));for (const file of files) assertSafeArtifact(file.content);@@ -1009,5 +1009,5 @@ function scopeSummary((resource) => resource.kind !== "integration",);if (recordScope === "WORKSPACE") return "Workspace CRM records";- return records.map((resource) => resource.label).join(" · ");+ return records.map((resource) => resource.label).join(", ");}diff --git a/apps/agent/agent/tools/write_brief.ts b/apps/agent/agent/tools/write_brief.tsindex 4a1841dc..9fa8c902 100644--- a/apps/agent/agent/tools/write_brief.ts+++ b/apps/agent/agent/tools/write_brief.ts@@ -26,7 +26,7 @@ export default defineTool({currentRole: z.string().optional()- .describe('e.g. "CEO & Co-founder · Comp AI"'),+ .describe('e.g. "CEO and Co-founder at Comp AI"'),tenure: z.string().optional().describe('e.g. "2 yrs 3 mos"'),previousRoles: z.array(z.string()).optional(),seniority: z.string().optional().describe('e.g. "Founder / C-level"'),diff --git a/apps/api/package.json b/apps/api/package.jsonindex 0700434a..717f5df0 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -37,7 +37,7 @@"@nestjs/swagger": "^11.4.7","@thallesp/nestjs-better-auth": "^2.8.0","@trpc/server": "^11.18.0",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","cache-manager": "^7.2.9","class-transformer": "^0.5.1","class-validator": "^0.15.1",diff --git a/apps/api/src/activities/activities.contracts.ts b/apps/api/src/activities/activities.contracts.tsindex 2b633c38..e37865c2 100644--- a/apps/api/src/activities/activities.contracts.ts+++ b/apps/api/src/activities/activities.contracts.ts@@ -72,7 +72,7 @@ export const activityCreateInput = z.refine((input) => input.type !== ActivityType.TASK || Boolean(input.subject),{- message: "A task needs a subject — it is the thing to do.",+ message: "A task needs a subject. It is the thing to do.",path: ["subject"],},);@@ -82,7 +82,7 @@ export type ActivityCreateInput = z.infer<typeof activityCreateInput>;export const activityUpdateInput = z.object({id: z.string(),subject: z.string().trim().min(1, {- message: "A task needs a subject — it is the thing to do.",+ message: "A task needs a subject. It is the thing to do.",}),dueAt: taskDueDayInput.nullable(),});diff --git a/apps/api/src/backfill/backfill.service.ts b/apps/api/src/backfill/backfill.service.tsindex 04f0d817..49c2eae5 100644--- a/apps/api/src/backfill/backfill.service.ts+++ b/apps/api/src/backfill/backfill.service.ts@@ -155,7 +155,7 @@ export class BackfillService implements OnModuleInit {const brand = await this.agent.backfill({kind: "brand",- reason: "Backfill — this company has no logo or icon",+ reason: "Backfill: this company has no logo or icon",companyIds,budget: 2,priority: PRIORITY.brand,@@ -163,7 +163,7 @@ export class BackfillService implements OnModuleInit {const profile = await this.agent.backfill({kind: "company-profile",- reason: "Backfill — this company was never successfully looked up",+ reason: "Backfill: this company was never successfully looked up",companyIds: rows.map((row) => row.id),});@@ -196,7 +196,7 @@ export class BackfillService implements OnModuleInit {const photos = await this.agent.backfill({kind: "portrait",- reason: "Backfill — somewhere to look for a picture, and no picture",+ reason: "Backfill: somewhere to look for a picture, and no picture",contactIds: photoRows.map((row) => row.id),budget: 1,priority: PRIORITY.portrait,@@ -218,7 +218,7 @@ export class BackfillService implements OnModuleInit {const research = await this.agent.backfill({kind: "identify",- reason: "Backfill — this contact was never researched",+ reason: "Backfill: this contact was never researched",contactIds: researchRows.map((row) => row.id),});diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.tsindex d2107d8a..1d106cdd 100644--- a/apps/api/src/companies/companies.contracts.ts+++ b/apps/api/src/companies/companies.contracts.ts@@ -218,6 +218,12 @@ export const companyDetailOutput = z.object({primaryContactId: z.string().nullable(),primaryContact: companyDetailPrimaryContactOutput.nullable(),reportingCurrency: z.string(),+ openPipeline: z.object({+ count: z.number().int().nonnegative(),+ totalCents: z.number().nullable(),+ unconverted: z.number().int().nonnegative(),+ nextClose: z.string().nullable(),+ }),deals: z.array(companyDetailDealOutput),});diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex 5d896f5c..8dfcc6f9 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -161,6 +161,7 @@ export class CompaniesService {}async byId(id: string) {+ const reportingCurrency = await this.conversion.reportingCurrency();const company = await this.db.company.findUnique({where: { id },select: {@@ -226,6 +227,7 @@ export class CompaniesService {amount: true,currency: true,baseAmount: true,+ baseCurrency: true,expectedCloseDate: true,owner: { select: OWNER_SELECT },},@@ -237,6 +239,30 @@ export class CompaniesService {throw new NotFoundException(`No company with id ${id}.`);}+ const openWhere: Prisma.DealWhereInput = {+ companyId: id,+ archivedAt: null,+ stage: { in: [...OPEN_DEAL_STAGES] },+ };+ const [openDeals, openValue, unconverted] = await Promise.all([+ this.db.deal.aggregate({+ where: openWhere,+ _count: { _all: true },+ _min: { expectedCloseDate: true },+ }),+ this.db.deal.aggregate({+ where: {+ AND: [openWhere, this.conversion.countedWhere(reportingCurrency)],+ },+ _sum: { baseAmount: true },+ }),+ this.db.deal.count({+ where: {+ AND: [openWhere, this.conversion.pendingWhere(reportingCurrency)],+ },+ }),+ ]);+const {deals,primaryContact,@@ -255,13 +281,23 @@ export class CompaniesService {enrichedAt: enrichedAt?.toISOString() ?? null,primaryContactId: primaryContact?.id ?? null,primaryContact,- reportingCurrency: await this.conversion.reportingCurrency(),+ reportingCurrency,+ openPipeline: {+ count: openDeals._count._all,+ totalCents: toCents(openValue._sum.baseAmount),+ unconverted,+ nextClose: openDeals._min.expectedCloseDate?.toISOString() ?? null,+ },deals: deals.map((deal) => ({...deal,amount: undefined,baseAmount: undefined,+ baseCurrency: undefined,amountCents: toCents(deal.amount),- baseAmountCents: toCents(deal.baseAmount),+ baseAmountCents:+ deal.baseCurrency === reportingCurrency+ ? toCents(deal.baseAmount)+ : null,expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,})),};@@ -474,7 +510,7 @@ export class CompaniesService {const domain = normalizeDomain(input.domain);if (input.domain.trim() && !domain) {throw new BadRequestException(- `"${input.domain}" is not a domain — try something like "stripe.com".`,+ `"${input.domain}" is not a domain. Try something like "stripe.com".`,);}data.domain = domain;@@ -507,7 +543,7 @@ export class CompaniesService {if (data.enrichmentStatus === "PENDING") {await this.agent.companyCreated(id,- "Domain changed — anything we knew was about a different company",+ "Domain changed. Anything we knew was about a different company",);void this.favicon.backfill(id, updated.domain);}@@ -713,7 +749,7 @@ export class CompaniesService {if (!company.domain) {throw new BadRequestException(- "There is nothing to read without a domain — add one first.",+ "There is nothing to read without a domain. Add one first.",);}diff --git a/apps/api/src/companies/company-directory.service.ts b/apps/api/src/companies/company-directory.service.tsindex b60f09f1..15488c66 100644--- a/apps/api/src/companies/company-directory.service.ts+++ b/apps/api/src/companies/company-directory.service.ts@@ -47,7 +47,7 @@ export class CompanyDirectoryService {await this.agent.companyCreated(outcome.id,- `Created from an email domain (${domain}) — it has no name but the domain`,+ `Created from an email domain (${domain}). It has no name but the domain`,);this.logger.log({diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 043fd4b7..2968c983 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -684,7 +684,7 @@ export class ContactsService {const queued = await this.agent.contactCreated(id,contact.linkedinUrl && !contact.imageUrl- ? "A rep asked for a fresh look — they have a LinkedIn profile on file but no picture"+ ? "A rep asked for a fresh look. They have a LinkedIn profile on file but no picture": "A rep asked for a fresh look",true,);diff --git a/apps/api/src/crm/bulk.ts b/apps/api/src/crm/bulk.tsindex aa5474a0..1ae1c262 100644--- a/apps/api/src/crm/bulk.ts+++ b/apps/api/src/crm/bulk.ts@@ -8,7 +8,7 @@ export const bulkIdsInput = z.object({ids: z.array(z.string()).min(1, "Nothing was selected.")- .max(MAX_BULK_IDS, "Too many records at once — select a page at a time."),+ .max(MAX_BULK_IDS, "Too many records at once. Select a page at a time."),});export type BulkResult = {diff --git a/apps/api/src/currency/currency.service.ts b/apps/api/src/currency/currency.service.tsindex d0bfa973..0236e06e 100644--- a/apps/api/src/currency/currency.service.ts+++ b/apps/api/src/currency/currency.service.ts@@ -150,7 +150,7 @@ export class CurrencyService {if (quoteCurrency === baseCurrency) {throw new BadRequestException(- `${baseCurrency} is the reporting currency — its rate is always 1.`,+ `${baseCurrency} is the reporting currency. Its rate is always 1.`,);}diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.tsindex 4a4d01c8..ea8d4d74 100644--- a/apps/api/src/deals/deals.service.ts+++ b/apps/api/src/deals/deals.service.ts@@ -192,6 +192,7 @@ export class DealsService {}async byId(id: string) {+ const reportingCurrency = await this.conversion.reportingCurrency();const deal = await this.db.deal.findUnique({where: { id },select: {@@ -203,6 +204,7 @@ export class DealsService {amount: true,currency: true,baseAmount: true,+ baseCurrency: true,fxRate: true,fxRateAt: true,expectedCloseDate: true,@@ -227,6 +229,7 @@ export class DealsService {contacts,amount,baseAmount,+ baseCurrency,fxRate,fxRateAt,archivedAt,@@ -237,10 +240,17 @@ export class DealsService {...rest,fields: await this.fields.valuesFor("DEAL", id),amountCents: toCents(amount),- baseAmountCents: toCents(baseAmount),- reportingCurrency: await this.conversion.reportingCurrency(),- fxRate: fxRate?.toNumber() ?? null,- fxRateAt: fxRateAt?.toISOString() ?? null,+ baseAmountCents:+ baseCurrency === reportingCurrency ? toCents(baseAmount) : null,+ reportingCurrency,+ fxRate:+ baseCurrency === reportingCurrency+ ? (fxRate?.toNumber() ?? null)+ : null,+ fxRateAt:+ baseCurrency === reportingCurrency+ ? (fxRateAt?.toISOString() ?? null)+ : null,stageChangedAt: deal.stageChangedAt.toISOString(),expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,closedAt: deal.closedAt?.toISOString() ?? null,@@ -497,7 +507,7 @@ export class DealsService {}if (LOSING.has(input.stage) && !closedReason) {throw new BadRequestException(- "Say why it was lost — a closed-lost deal with no reason teaches nobody anything.",+ "Say why it was lost. A closed-lost deal with no reason teaches nobody anything.",);}@@ -701,7 +711,7 @@ export class DealsService {if (LOSING.has(input.stage) && !closedReason) {throw new BadRequestException(- "Say why they were lost — a closed-lost deal with no reason teaches nobody anything.",+ "Say why they were lost. A closed-lost deal with no reason teaches nobody anything.",);}diff --git a/apps/api/src/google/google-connection.service.ts b/apps/api/src/google/google-connection.service.tsindex d25e7d4d..406ed660 100644--- a/apps/api/src/google/google-connection.service.ts+++ b/apps/api/src/google/google-connection.service.ts@@ -187,7 +187,7 @@ export class GoogleConnectionService {const ours = await this.match.internalIdentity();if (ours.domains.has(normalised)) {throw new NotFoundException(- "That is our own domain — it is already excluded.",+ "That is our own domain. It is already excluded.",);}diff --git a/apps/api/src/mailbox/mailbox-token.service.ts b/apps/api/src/mailbox/mailbox-token.service.tsindex 7353d9a1..a8f8354a 100644--- a/apps/api/src/mailbox/mailbox-token.service.ts+++ b/apps/api/src/mailbox/mailbox-token.service.ts@@ -72,8 +72,12 @@ export class MailboxTokenService {source: SyncSource,): Promise<TokenResult> {const providerId = PROVIDER_FOR_SOURCE[source];+ const account = await this.db.account.findFirst({+ where: { userId, providerId },+ select: { id: true, scope: true },+ });- if (!(await this.isConnected(userId, source))) {+ if (!account || !parseScopes(account.scope).has(SCOPE_FOR_SOURCE[source])) {return {outcome: "not-connected",reason: `The ${source} scope has not been granted.`,@@ -82,7 +86,7 @@ export class MailboxTokenService {try {const { accessToken } = await auth.api.getAccessToken({- body: { providerId, userId },+ body: { accountId: account.id, userId },});if (!accessToken) {diff --git a/apps/api/src/search/search.service.ts b/apps/api/src/search/search.service.tsindex 7a435dca..b1c6ecfc 100644--- a/apps/api/src/search/search.service.ts+++ b/apps/api/src/search/search.service.ts@@ -1,4 +1,5 @@import type { Db } from "@crm/db";+import { QUICK_SEARCH } from "@crm/validation/search-config";import { Injectable } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";@@ -13,15 +14,13 @@ export type SearchHit = {imageUrl: string | null;};-const PER_KIND = 5;-@Injectable()export class SearchService {constructor(@InjectDatabase() private readonly db: Db) {}async quick(q: string): Promise<{ hits: SearchHit[] }> {const term = q.trim();- if (term.length < 2) return { hits: [] };+ if (term.length < QUICK_SEARCH.query.minLength) return { hits: [] };const [companies, contacts, deals] = await Promise.all([this.db.company.findMany({@@ -31,7 +30,7 @@ export class SearchService {{ domain: { contains: term, mode: "insensitive" } },],},- take: PER_KIND,+ take: QUICK_SEARCH.results.perKind,orderBy: { name: "asc" },select: {id: true,@@ -50,7 +49,7 @@ export class SearchService {{ email: { contains: term, mode: "insensitive" } },],},- take: PER_KIND,+ take: QUICK_SEARCH.results.perKind,orderBy: [{ lastName: "asc" }, { firstName: "asc" }],select: {id: true,@@ -63,7 +62,7 @@ export class SearchService {}),this.db.deal.findMany({where: { name: { contains: term, mode: "insensitive" } },- take: PER_KIND,+ take: QUICK_SEARCH.results.perKind,orderBy: [{ stage: "asc" }, { name: "asc" }],select: {id: true,diff --git a/apps/api/src/settings/settings.contracts.ts b/apps/api/src/settings/settings.contracts.tsindex aa8c91ff..4b17bbf1 100644--- a/apps/api/src/settings/settings.contracts.ts+++ b/apps/api/src/settings/settings.contracts.ts@@ -54,8 +54,8 @@ export const setResearchKeyInput = z.object({apiKey: z.string().trim()- .min(8, "That does not look like a Context API key — it is too short.")- .max(500, "That does not look like a Context API key — it is too long.")+ .min(8, "That does not look like a Context API key. It is too short.")+ .max(500, "That does not look like a Context API key. It is too long.").refine((value) => !/\s/.test(value),"An API key has no spaces in it. Paste the whole key on its own.",diff --git a/apps/api/src/tracking/tracking.service.ts b/apps/api/src/tracking/tracking.service.tsindex 58c4b84d..2a2c72ee 100644--- a/apps/api/src/tracking/tracking.service.ts+++ b/apps/api/src/tracking/tracking.service.ts@@ -231,7 +231,7 @@ export class TrackingService {if (!trackingReady(row?.trackingLimitToDomains ?? true, domains)) {throw new BadRequestException(- "Add the domain your website runs on first — there is no script to find yet.",+ "Add the domain your website runs on first. There is no script to find yet.",);}diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.tsindex 5cb97c7a..85ca5a0c 100644--- a/apps/api/test/currency-totals.integration.spec.ts+++ b/apps/api/test/currency-totals.integration.spec.ts@@ -2,7 +2,10 @@ import { afterAll, beforeAll, describe, expect, it } from "bun:test";import { DealStage, db, RateSource } from "@crm/db";import { normalizeCurrency } from "@crm/db/currency";import { SETTINGS_ID, writeReportingCurrency } from "@crm/db/settings";+import { AgentQueueService } from "../src/agent/agent-queue.service";import type { AgentTriggerService } from "../src/agent/agent-trigger.service";+import { CompaniesService } from "../src/companies/companies.service";+import { FaviconService } from "../src/companies/favicon.service";import { ActivityStampService } from "../src/crm/activity-stamp.service";import { ConversionService } from "../src/currency/conversion.service";import { DashboardService } from "../src/dashboard/dashboard.service";@@ -27,6 +30,15 @@ const deals = new DealsService(new FieldsService(db, { fieldBackfill: async () => undefined } as never),);const dashboard = new DashboardService(db, conversion);+const companies = new CompaniesService(+ db,+ agent,+ new AgentQueueService(db),+ new FaviconService(db),+ new ActivityStampService(db),+ conversion,+ new FieldsService(db, { fieldBackfill: async () => undefined } as never),+);let companyId: string;let previousReportingCurrency: string | null = null;@@ -518,3 +530,87 @@ describe("the dashboard only values what it can convert", () => {await db.deal.deleteMany({ where: { id: { in: [open.id, unvalued.id] } } });});});++describe("record sheet money", () => {+ it("excludes archived and stale amounts from a company's open pipeline", async () => {+ await writeReportingCurrency(db, "USD");+ const company = await db.company.create({+ data: { name: `Record money ${suffix}` },+ });++ try {+ const close = new Date("2027-02-01T00:00:00.000Z");+ await db.deal.createMany({+ data: [+ {+ companyId: company.id,+ name: "Current conversion",+ amount: 100,+ currency: "EUR",+ baseAmount: 110,+ baseCurrency: "USD",+ expectedCloseDate: close,+ },+ {+ companyId: company.id,+ name: "Stale conversion",+ amount: 100,+ currency: "EUR",+ baseAmount: 9000,+ baseCurrency: "JPY",+ },+ {+ companyId: company.id,+ name: "Unlabelled conversion",+ amount: 100,+ currency: "EUR",+ baseAmount: 110,+ },+ {+ companyId: company.id,+ name: "Archived conversion",+ amount: 1000,+ currency: "USD",+ baseAmount: 1000,+ baseCurrency: "USD",+ archivedAt: new Date(),+ expectedCloseDate: new Date("2026-01-01T00:00:00.000Z"),+ },+ {+ companyId: company.id,+ name: "Closed conversion",+ stage: DealStage.CLOSED_WON,+ amount: 2000,+ currency: "USD",+ baseAmount: 2000,+ baseCurrency: "USD",+ },+ ].map((deal) => ({ ...deal, ownerId: userId })),+ });++ const record = await companies.byId(company.id);+ expect(record.openPipeline).toEqual({+ count: 3,+ totalCents: 11000,+ unconverted: 2,+ nextClose: close.toISOString(),+ });++ const stale = record.deals.find(+ (deal) => deal.name === "Stale conversion",+ );+ expect(stale?.baseAmountCents).toBeNull();+ const staleDetail = await deals.byId(stale?.id ?? "missing");+ expect(staleDetail.baseAmountCents).toBeNull();+ expect(staleDetail.fxRate).toBeNull();++ await db.deal.deleteMany({ where: { companyId: company.id } });+ expect(+ (await companies.byId(company.id)).openPipeline.totalCents,+ ).toBeNull();+ } finally {+ await db.deal.deleteMany({ where: { companyId: company.id } });+ await db.company.delete({ where: { id: company.id } });+ }+ });+});diff --git a/apps/api/test/error-formatter.spec.ts b/apps/api/test/error-formatter.spec.tsindex f6126cdd..ed584c5d 100644--- a/apps/api/test/error-formatter.spec.ts+++ b/apps/api/test/error-formatter.spec.ts@@ -14,7 +14,7 @@ describe("what a rejected form says", () => {const cause = causeOf(setResearchKeyInput, { apiKey: "short" });expect(readableInputError("ignored", cause)).toBe(- "That does not look like a Context API key — it is too short.",+ "That does not look like a Context API key. It is too short.",);});diff --git a/apps/api/test/mailbox-token.spec.ts b/apps/api/test/mailbox-token.spec.tsnew file mode 100644index 00000000..d99ead33--- /dev/null+++ b/apps/api/test/mailbox-token.spec.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";+import { auth } from "@crm/auth/auth";+import { GOOGLE_PROVIDER_ID, SYNC_SCOPES } from "@crm/auth/scopes";+import { db } from "@crm/db";+import { MailboxTokenService } from "../src/mailbox/mailbox-token.service";++const userId = `mailbox-token-${crypto.randomUUID()}`;+const accountId = `mailbox-account-${crypto.randomUUID()}`;+const service = new MailboxTokenService(db);++const accessTokenSpy = () =>+ spyOn(auth.api, "getAccessToken").mockResolvedValue({+ accessToken: "test-mailbox-access-token",+ accessTokenExpiresAt: undefined,+ scopes: [...SYNC_SCOPES],+ idToken: undefined,+ });++let getAccessToken: ReturnType<typeof accessTokenSpy>;++beforeEach(async () => {+ await db.user.create({+ data: {+ id: userId,+ name: "Mailbox token test",+ email: `${userId}@example.test`,+ },+ });+ getAccessToken = accessTokenSpy();+});++afterEach(async () => {+ getAccessToken.mockRestore();+ await db.user.delete({ where: { id: userId } });+});++async function grant(scope: string) {+ await db.account.create({+ data: {+ id: accountId,+ userId,+ providerId: GOOGLE_PROVIDER_ID,+ accountId: "provider-subject-differs-from-local-account-id",+ scope,+ },+ });+}++describe("mailbox token account selection", () => {+ it("uses the local account ID for Better Auth token refresh", async () => {+ await grant(SYNC_SCOPES.join(" "));+ expect(await service.accessTokenFor(userId, "gmail")).toEqual({+ outcome: "ok",+ accessToken: "test-mailbox-access-token",+ });+ expect(getAccessToken).toHaveBeenCalledTimes(1);+ expect(getAccessToken).toHaveBeenCalledWith({+ body: { accountId, userId },+ });+ });++ it("does not request a token without an account", async () => {+ expect(await service.accessTokenFor(userId, "gmail")).toMatchObject({+ outcome: "not-connected",+ });+ expect(getAccessToken).not.toHaveBeenCalled();+ });++ it("does not request a token without the mailbox scope", async () => {+ await grant("openid email");+ expect(await service.accessTokenFor(userId, "gmail")).toMatchObject({+ outcome: "not-connected",+ });+ expect(getAccessToken).not.toHaveBeenCalled();+ });+});diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsxindex 1f5aa61c..19d5d30b 100644--- a/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx+++ b/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx@@ -1,8 +1,8 @@+import { PageShellFallback } from "@crm/ui/components/page-shell";import type { Metadata } from "next";import { notFound } from "next/navigation";import { Suspense } from "react";import { TeamAgentDetail } from "@/components/agent-builder/team-agent-detail";-import { PageShellFallback } from "@/components/page-shell";import { getServerTrpcClient } from "@/lib/trpc/server";import { nullIfMissing } from "../../missing-record";diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsxindex 8edbb7e7..32319d03 100644--- a/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx+++ b/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx@@ -1,6 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";-import { TeamAgentsIndex } from "@/components/agent-builder/team-agents-index";import {PageShell,PageShellContent,@@ -9,7 +6,10 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";+import { TeamAgentsIndex } from "@/components/agent-builder/team-agents-index";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -28,7 +28,7 @@ export default function AgentsPage() {</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="table" />}><PrefetchedTeamAgents /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsxindex fa038833..c266388b 100644--- a/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx+++ b/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx@@ -1,9 +1,5 @@import { Suspense } from "react";-import {- AgentBuilderShell,- AgentBuilderSidebarFallback,-} from "@/components/agent-builder/agent-builder-shell";-import { AgentBuilderSidebar } from "@/components/agent-builder/agent-builder-sidebar";+import { AgentBuilderShell } from "@/components/agent-builder/agent-builder-shell";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -11,39 +7,23 @@ export default function AgentBuilderLayout({children,}: Readonly<{ children: React.ReactNode }>) {return (- <AgentBuilderShell- sidebar={- <Suspense fallback={<AgentBuilderSidebarFallback />}>- <PrefetchedAgentBuilderSidebar />- </Suspense>- }- >+ <AgentBuilderShell>+ <Suspense fallback={null}>+ <PrefetchedAgentChatNav />+ </Suspense>{children}</AgentBuilderShell>);}-async function PrefetchedAgentBuilderSidebar() {+async function PrefetchedAgentChatNav() {const trpc = getServerTrpc();const queryClient = getServerQueryClient();- const conversationsQuery = trpc.conversations.builderList.queryOptions();- const agentsQuery = trpc.agents.list.queryOptions();- const [conversations, agents] = await Promise.all([- queryClient.fetchQuery(conversationsQuery),- queryClient.fetchQuery(agentsQuery),+ await Promise.all([+ queryClient.prefetchQuery(trpc.conversations.builderList.queryOptions()),+ queryClient.prefetchQuery(trpc.agents.list.queryOptions()),]);- const updatedAt = Math.min(- queryClient.getQueryState(conversationsQuery.queryKey)?.dataUpdatedAt ?? 0,- queryClient.getQueryState(agentsQuery.queryKey)?.dataUpdatedAt ?? 0,- );- return (- <HydrateClient>- <AgentBuilderSidebar- className="hidden w-[213px] flex-none border-r md:flex"- initialData={{ conversations, agents, updatedAt }}- />- </HydrateClient>- );+ return <HydrateClient>{null}</HydrateClient>;}diff --git a/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx b/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsxindex 3ac14002..b1770f73 100644--- a/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx+++ b/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx@@ -1,8 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";-import Renew from "@carbon/icons-react/es/Renew";-import Undo from "@carbon/icons-react/es/Undo";import {DropdownMenuGroup,DropdownMenuItem,@@ -10,6 +7,7 @@ import {} from "@crm/ui/components/dropdown-menu";import { formatCount } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";+import { ArchiveIcon, RefreshCwIcon, Undo2Icon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import {@@ -58,7 +56,8 @@ export function CompaniesBulkActions({await cache.company();reportBulk(result,- (count) => `Looking up ${companies(count)} — the table will update.`,+ (count) =>+ `Looking up ${companies(count)}. The table updates when complete.`,);onDone();},@@ -108,7 +107,7 @@ export function CompaniesBulkActions({<BulkActionsMenu pending={pending}><DropdownMenuGroup><DropdownMenuItem onSelect={() => restore.mutate({ ids })}>- <Undo />+ <Undo2Icon />Restore</DropdownMenuItem></DropdownMenuGroup>@@ -146,14 +145,14 @@ export function CompaniesBulkActions({/><DropdownMenuGroup><DropdownMenuItem onSelect={() => enrich.mutate({ ids })}>- <Renew />+ <RefreshCwIcon />Re-enrich</DropdownMenuItem></DropdownMenuGroup><DropdownMenuSeparator /><DropdownMenuGroup><DropdownMenuItem onSelect={() => archive.mutate({ ids })}>- <Archive />+ <ArchiveIcon />Archive</DropdownMenuItem></DropdownMenuGroup>diff --git a/apps/app/app/(app)/[slug]/companies/companies-table.tsx b/apps/app/app/(app)/[slug]/companies/companies-table.tsxindex b2356b13..a79cfdbd 100644--- a/apps/app/app/(app)/[slug]/companies/companies-table.tsx+++ b/apps/app/app/(app)/[slug]/companies/companies-table.tsx@@ -1,6 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";import { Button } from "@crm/ui/components/button";import {DataTable,@@ -14,6 +13,7 @@ import {} from "@crm/ui/components/entity-logo";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { useQuery } from "@tanstack/react-query";+import { ArchiveIcon } from "lucide-react";import { useMemo } from "react";import { EnrichmentIndicator } from "@/components/crm/enrichment-status";import { useFieldColumns } from "@/components/crm/fields/field-columns";@@ -21,6 +21,7 @@ import { useFieldFacets } from "@/components/crm/fields/field-facets";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 { ListEmpty } from "@/components/data-table/list-empty";import { ListSearch } from "@/components/data-table/list-search";import { SavedViewsMenu } from "@/components/data-table/saved-views-menu";import { useTableQuery } from "@/components/data-table/use-table-query";@@ -44,7 +45,6 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [header: "Company",sortable: true,hideable: false,- width: "w-[26%]",cell: (row) => (<span className="flex min-w-0 items-center gap-2.5"><EntityLogo@@ -62,11 +62,13 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [id: "domain",header: "Domain",sortable: true,- width: "w-[16%]",+ width: "40",hideBelow: "md",cell: (row) =>row.domain ? (- <span className="truncate text-muted-foreground">{row.domain}</span>+ <span className="block truncate text-muted-foreground">+ {row.domain}+ </span>) : (<EmptyCellValue />),@@ -75,11 +77,11 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [id: "industry",header: "Industry",sortable: true,- width: "w-[16%]",+ width: "40",hideBelow: "lg",cell: (row) =>row.industry ? (- <span className="truncate">{row.industry}</span>+ <span className="block truncate">{row.industry}</span>) : (<EmptyCellValue />),@@ -88,7 +90,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [id: "owner",header: "Owner",sortable: true,- width: "w-[16%]",+ width: "40",hideBelow: "md",cell: (row) => <OwnerCell owner={row.owner} />,},@@ -97,7 +99,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [header: "Contacts",sortable: true,align: "right",- width: "w-[9%]",+ width: "28",hideBelow: "lg",cell: (row) => <span className="tabular-nums">{row.contactCount}</span>,},@@ -106,7 +108,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [header: "Open deals",sortable: true,align: "right",- width: "w-[9%]",+ width: "28",cell: (row) => <span className="tabular-nums">{row.openDealCount}</span>,},{@@ -115,7 +117,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [label: "Created date",sortable: true,align: "right",- width: "w-[10%]",+ width: "28",defaultHidden: true,cell: (row) => (<span className="text-muted-foreground">@@ -128,7 +130,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [header: "Last activity",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",hideBelow: "sm",cell: (row) => (<span className="text-muted-foreground">@@ -145,7 +147,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [header: "Enrichment",label: "Enrichment status",defaultHidden: true,- width: "w-[14%]",+ width: "36",cell: (row) => (<EnrichmentIndicator status={row.enrichmentStatus} queued={row.queued} />),@@ -158,7 +160,7 @@ const ARCHIVED_COLUMN: DataTableColumn<CompanyRow> = {label: "Archived date",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",cell: (row) => (<span className="text-muted-foreground">{row.archivedAt ? (@@ -244,18 +246,19 @@ export function CompaniesTable() {return (<DataTable+ label="Companies"query={query}- search={<ListSearch placeholder="Search companies by name or domain…" />}+ search={<ListSearch placeholder="Search companies…" />}actions={<><SavedViewsMenu entity="COMPANY" table={table} /><Buttonvariant={input.archived ? "contrast" : "outline"}- size="sm"+ aria-pressed={input.archived}className="justify-start sm:justify-center"onClick={() => setArchived(!input.archived)}>- <Archive data-icon="inline-start" />+ <ArchiveIcon data-icon="inline-start" />Archived</Button></>@@ -279,11 +282,22 @@ export function CompaniesTable() {getRowId={(row) => row.id}loading={companies.isFetching}onRowHover={(row) => prefetchRecord({ kind: "company", id: row.id })}- onRowClick={(row) => openRecord({ kind: "company", id: row.id })}+ onRowClick={(row, orderedRows) =>+ openRecord(+ { kind: "company", id: row.id },+ orderedRows.map((entry) => ({ kind: "company", id: entry.id })),+ )+ }empty={- input.archived- ? "No archived companies."- : "No companies match this view."+ <ListEmpty+ query={query}+ noun="companies"+ archived={input.archived}+ blank={{+ title: "No companies yet",+ description: "Add a company or import a CSV to start the pipeline.",+ }}+ />}/>);diff --git a/apps/app/app/(app)/[slug]/companies/create-company-sheet.tsx b/apps/app/app/(app)/[slug]/companies/create-company-sheet.tsxindex 59405fad..7a422542 100644--- a/apps/app/app/(app)/[slug]/companies/create-company-sheet.tsx+++ b/apps/app/app/(app)/[slug]/companies/create-company-sheet.tsx@@ -1,13 +1,19 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";import {Field,FieldDescription,- FieldGroup,+ FieldError,FieldLabel,} from "@crm/ui/components/field";+import {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ useFormSheetValidation,+} from "@crm/ui/components/form-sheet";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";import {@@ -18,17 +24,14 @@ import {SelectValue,} from "@crm/ui/components/select";import {- Sheet,- SheetClose,- SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,SheetTrigger,} from "@crm/ui/components/sheet";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { parseAsBoolean, useQueryState } from "nuqs";import { type ComponentProps, Suspense, useId, useState } from "react";import { toast } from "sonner";@@ -42,7 +45,7 @@ const UNASSIGNED = "unassigned";function AddButton(props: ComponentProps<typeof Button>) {return (<Button {...props}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New company</Button>);@@ -58,6 +61,7 @@ export function CreateCompanySheet() {function CreateCompanyForm() {const openRecord = useOpenRecord();+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();@@ -80,21 +84,32 @@ function CreateCompanyForm() {await cache.company(company.id);toast.success(`${company.name} added.`);await setOpen(null);- setName("");- setDomain("");- setOwnerId(UNASSIGNED);+ reset();openRecord({ kind: "company", id: company.id });},onError: (error) => toast.error(error.message),}),);+ const reset = () => {+ validation.reset();+ setName("");+ setDomain("");+ setOwnerId(UNASSIGNED);+ };+return (- <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>+ <FormSheet+ dirty={name !== "" || domain !== "" || ownerId !== UNASSIGNED}+ pending={create.isPending}+ onDiscard={reset}+ open={open}+ onOpenChange={(next) => setOpen(next || null)}+ ><SheetTrigger asChild><AddButton /></SheetTrigger>- <SheetContent side="right">+ <FormSheetContent side="right"><SheetHeader><SheetTitle>New company</SheetTitle><SheetDescription>@@ -103,11 +118,13 @@ function CreateCompanyForm() {</SheetDescription></SheetHeader>- <form+ <FormSheetForm+ noValidate+ onInput={validation.onInput}id="create-company"- className="flex-1 overflow-y-auto px-4"onSubmit={(event) => {event.preventDefault();+ if (!validation.validate(event.currentTarget)) return;create.mutate({name,domain: domain || undefined,@@ -115,68 +132,77 @@ function CreateCompanyForm() {});}}>- <FieldGroup>- <Field>- <FieldLabel htmlFor={nameId}>Name</FieldLabel>- <Input- id={nameId}- value={name}- onChange={(event) => setName(event.target.value)}- placeholder="Stripe"- autoComplete="off"- required- />- </Field>+ <Field data-invalid={!!validation.errors[nameId]}>+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>+ <Input+ id={nameId}+ aria-invalid={!!validation.errors[nameId]}+ aria-describedby={+ validation.errors[nameId] ? `${nameId}-error` : undefined+ }+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder="Stripe"+ autoComplete="off"+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${nameId}-error`}>+ {validation.errors[nameId]}+ </FieldError>+ </Field>- <Field>- <FieldLabel htmlFor={domainId}>Domain</FieldLabel>- <Input- id={domainId}- value={domain}- onChange={(event) => setDomain(event.target.value)}- placeholder="stripe.com"- autoComplete="off"- inputMode="url"- />- <FieldDescription>- A full URL is fine — it is reduced to the bare host, which has- to be unique.- </FieldDescription>- </Field>+ <Field data-invalid={!!validation.errors[domainId]}>+ <FieldLabel htmlFor={domainId}>Domain</FieldLabel>+ <Input+ id={domainId}+ aria-invalid={!!validation.errors[domainId]}+ aria-describedby={+ validation.errors[domainId] ? `${domainId}-error` : undefined+ }+ value={domain}+ onChange={(event) => setDomain(event.target.value)}+ placeholder="stripe.com"+ autoComplete="off"+ inputMode="url"+ />+ <FieldError id={`${domainId}-error`}>+ {validation.errors[domainId]}+ </FieldError>+ <FieldDescription>+ A full URL works. The CRM uses the host, which has to be unique.+ </FieldDescription>+ </Field>- <Field>- <FieldLabel htmlFor="create-company-owner">Owner</FieldLabel>- <Select value={ownerId} onValueChange={setOwnerId}>- <SelectTrigger id="create-company-owner">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>- {(users.data ?? []).map((user) => (- <SelectItem key={user.id} value={user.id}>- {user.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>- </FieldGroup>- </form>+ <Field>+ <FieldLabel htmlFor="create-company-owner">Owner</FieldLabel>+ <Select value={ownerId} onValueChange={setOwnerId}>+ <SelectTrigger id="create-company-owner">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>+ {(users.data ?? []).map((user) => (+ <SelectItem key={user.id} value={user.id}>+ {user.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </FormSheetForm>- <SheetFooter>+ <FormSheetFooter><Buttontype="submit"form="create-company"- disabled={create.isPending || name.trim() === ""}+ disabled={create.isPending}>- {create.isPending ? <Spinner /> : null}+ {create.isPending ? <Spinner data-icon="inline-start" /> : null}Add company</Button>- <SheetClose asChild>- <Button variant="outline">Cancel</Button>- </SheetClose>- </SheetFooter>- </SheetContent>- </Sheet>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>);}diff --git a/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx b/apps/app/app/(app)/[slug]/companies/import-companies-link.tsxindex 56f492e4..687d2c99 100644--- a/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx+++ b/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx@@ -1,30 +1,51 @@-import Upload from "@carbon/icons-react/es/Upload";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";+import { UploadIcon } from "lucide-react";import Link from "next/link";import { workspaceUrl } from "@/lib/workspace-url";+const LABEL = "Import CSV";+export async function ImportCompaniesLink({params,}: {params: Promise<{ slug: string }>;}) {const { slug } = await params;+ const href = workspaceUrl(slug, "/companies/import");return (- <Button asChild variant="outline">- <Link href={workspaceUrl(slug, "/companies/import")}>- <Icon icon={Upload} data-icon="inline-start" />- Import CSV- </Link>- </Button>+ <>+ <Button asChild variant="outline" size="icon" className="sm:hidden">+ <Link href={href} aria-label={LABEL}>+ <Icon icon={UploadIcon} />+ </Link>+ </Button>+ <Button asChild variant="outline" className="max-sm:hidden">+ <Link href={href}>+ <Icon icon={UploadIcon} data-icon="inline-start" />+ {LABEL}+ </Link>+ </Button>+ </>);}export function ImportCompaniesLinkFallback() {return (- <Button variant="outline" disabled>- <Icon icon={Upload} data-icon="inline-start" />- Import CSV- </Button>+ <>+ <Button+ variant="outline"+ size="icon"+ className="sm:hidden"+ aria-label={LABEL}+ disabled+ >+ <Icon icon={UploadIcon} />+ </Button>+ <Button variant="outline" className="max-sm:hidden" disabled>+ <Icon icon={UploadIcon} data-icon="inline-start" />+ {LABEL}+ </Button>+ </>);}diff --git a/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx b/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsxindex cdcffd31..45efda74 100644--- a/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx+++ b/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx@@ -1,6 +1,5 @@"use client";-import Upload from "@carbon/icons-react/es/Upload";import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";import { Button } from "@crm/ui/components/button";import {@@ -40,6 +39,7 @@ import {} from "@crm/ui/components/table";import { COMPANY_IMPORT } from "@crm/validation/company-import";import { useMutation } from "@tanstack/react-query";+import { UploadIcon } from "lucide-react";import Link from "next/link";import { useId, useReducer, useState } from "react";import { useCrmCache } from "@/lib/trpc/cache";@@ -441,7 +441,7 @@ function ResultStep({<Link href={companiesUrl}>View companies</Link></Button><Button variant="outline" onClick={onRestart}>- <Icon icon={Upload} data-icon="inline-start" />+ <Icon icon={UploadIcon} data-icon="inline-start" />Import another file</Button></CardFooter>diff --git a/apps/app/app/(app)/[slug]/companies/import/page.tsx b/apps/app/app/(app)/[slug]/companies/import/page.tsxindex a56dfb0d..b14fd65d 100644--- a/apps/app/app/(app)/[slug]/companies/import/page.tsx+++ b/apps/app/app/(app)/[slug]/companies/import/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { workspaceUrl } from "@/lib/workspace-url";import { ImportWizard } from "./import-wizard";diff --git a/apps/app/app/(app)/[slug]/companies/page.tsx b/apps/app/app/(app)/[slug]/companies/page.tsxindex 943801e3..2c849075 100644--- a/apps/app/app/(app)/[slug]/companies/page.tsx+++ b/apps/app/app/(app)/[slug]/companies/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -9,7 +7,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -47,7 +47,7 @@ export default function CompaniesPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="table" />}><Companies searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsxindex 5fae7fb9..2e97d783 100644--- a/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx+++ b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx@@ -1,8 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";-import Renew from "@carbon/icons-react/es/Renew";-import Undo from "@carbon/icons-react/es/Undo";import {DropdownMenuGroup,DropdownMenuItem,@@ -13,6 +10,7 @@ import {} from "@crm/ui/components/dropdown-menu";import { formatCount } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";+import { ArchiveIcon, RefreshCwIcon, Undo2Icon } from "lucide-react";import { useRef, useState } from "react";import { toast } from "sonner";import {@@ -75,7 +73,8 @@ export function ContactsBulkActions({await cache.contact();reportBulk(result,- (count) => `Looking up ${contacts(count)} — the table will update.`,+ (count) =>+ `Looking up ${contacts(count)}. The table updates when complete.`,);onDone();},@@ -125,7 +124,7 @@ export function ContactsBulkActions({<BulkActionsMenu pending={pending}><DropdownMenuGroup><DropdownMenuItem onSelect={() => restore.mutate({ ids })}>- <Undo />+ <Undo2Icon />Restore</DropdownMenuItem></DropdownMenuGroup>@@ -190,14 +189,14 @@ export function ContactsBulkActions({</DropdownMenuSub><DropdownMenuGroup><DropdownMenuItem onSelect={() => enrich.mutate({ ids })}>- <Renew />+ <RefreshCwIcon />Re-enrich</DropdownMenuItem></DropdownMenuGroup><DropdownMenuSeparator /><DropdownMenuGroup><DropdownMenuItem onSelect={() => archive.mutate({ ids })}>- <Archive />+ <ArchiveIcon />Archive</DropdownMenuItem></DropdownMenuGroup>diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsxindex 1847de03..bc022be2 100644--- a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx+++ b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx@@ -1,6 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";import { Button } from "@crm/ui/components/button";import {DataTable,@@ -12,7 +11,8 @@ import { PersonAvatar } from "@crm/ui/components/person-avatar";import { useSearchInput } from "@crm/ui/hooks/use-search-input";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { useQuery } from "@tanstack/react-query";-import { useEffect, useMemo, useState } from "react";+import { ArchiveIcon } from "lucide-react";+import { useMemo, useState } from "react";import { CompanyCell } from "@/components/crm/company-cell";import { contactName } from "@/components/crm/contact-name";import { useFieldColumns } from "@/components/crm/fields/field-columns";@@ -20,6 +20,7 @@ import { useFieldFacets } from "@/components/crm/fields/field-facets";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 { ListEmpty } from "@/components/data-table/list-empty";import { ListSearch } from "@/components/data-table/list-search";import { SavedViewsMenu } from "@/components/data-table/saved-views-menu";import { useTableQuery } from "@/components/data-table/use-table-query";@@ -38,7 +39,6 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [header: "Name",sortable: true,hideable: false,- width: "w-[22%]",cell: (row) => (<span className="flex min-w-0 items-center gap-2"><PersonAvatar@@ -55,11 +55,11 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [id: "title",header: "Title",sortable: true,- width: "w-[20%]",+ width: "40",hideBelow: "lg",cell: (row) =>row.title ? (- <span className="truncate">{row.title}</span>+ <span className="block truncate">{row.title}</span>) : (<EmptyCellValue />),@@ -68,11 +68,13 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [id: "email",header: "Email",sortable: true,- width: "w-[24%]",+ width: "56",hideBelow: "md",cell: (row) =>row.email ? (- <span className="truncate text-muted-foreground">{row.email}</span>+ <span className="block truncate text-muted-foreground">+ {row.email}+ </span>) : (<EmptyCellValue />),@@ -81,14 +83,14 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [id: "company",header: "Company",sortable: true,- width: "w-[18%]",+ width: "40",cell: (row) => <CompanyCell company={row.company} />,},{id: "owner",header: "Owner",sortable: true,- width: "w-[16%]",+ width: "40",hideBelow: "md",cell: (row) => <OwnerCell owner={row.owner} />,},@@ -98,7 +100,7 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [label: "Created date",sortable: true,align: "right",- width: "w-[10%]",+ width: "28",defaultHidden: true,cell: (row) => (<span className="text-muted-foreground">@@ -111,7 +113,7 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [header: "Last activity",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",hideBelow: "sm",cell: (row) => (<span className="text-muted-foreground">@@ -131,7 +133,7 @@ const ARCHIVED_COLUMN: DataTableColumn<ContactRow> = {label: "Archived date",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",cell: (row) => (<span className="text-muted-foreground">{row.archivedAt ? (@@ -179,11 +181,6 @@ export function ContactsTable() {return selection.ids.filter((id) => matching.has(id));}, [rows, input.archived, selection.ids]);- // biome-ignore lint/correctness/useExhaustiveDependencies: clearing on archived-mode change is the entire purpose of this effect.- useEffect(() => {- selection.clear();- }, [input.archived]);-const toggleArchived = (next: boolean) => {selection.clear();if (!next && query.sort === "archivedAt") query.setSort("");@@ -265,18 +262,19 @@ export function ContactsTable() {return (<DataTable+ label="Contacts"query={query}- search={<ListSearch placeholder="Search by name, email or company…" />}+ search={<ListSearch placeholder="Search contacts…" />}actions={<><SavedViewsMenu entity="CONTACT" table={table} /><Buttonvariant={input.archived ? "contrast" : "outline"}- size="sm"+ aria-pressed={input.archived}className="justify-start sm:justify-center"onClick={() => toggleArchived(!input.archived)}>- <Archive data-icon="inline-start" />+ <ArchiveIcon data-icon="inline-start" />Archived</Button></>@@ -300,11 +298,23 @@ export function ContactsTable() {getRowId={(row) => row.id}loading={contacts.isFetching}onRowHover={(row) => prefetchRecord({ kind: "contact", id: row.id })}- onRowClick={(row) => openRecord({ kind: "contact", id: row.id })}+ onRowClick={(row, orderedRows) =>+ openRecord(+ { kind: "contact", id: row.id },+ orderedRows.map((entry) => ({ kind: "contact", id: entry.id })),+ )+ }empty={- input.archived- ? "No archived contacts."- : "No contacts match this view."+ <ListEmpty+ query={query}+ noun="contacts"+ archived={input.archived}+ blank={{+ title: "No contacts yet",+ description:+ "Add a contact to keep track of the people you sell to.",+ }}+ />}/>);diff --git a/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx b/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsxindex adbe905d..5e27462d 100644--- a/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx+++ b/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx@@ -1,8 +1,14 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";-import { Field, FieldGroup, FieldLabel } from "@crm/ui/components/field";+import { Field, FieldError, FieldLabel } from "@crm/ui/components/field";+import {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ useFormSheetValidation,+} from "@crm/ui/components/form-sheet";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";import {@@ -13,17 +19,14 @@ import {SelectValue,} from "@crm/ui/components/select";import {- Sheet,- SheetClose,- SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,SheetTrigger,} from "@crm/ui/components/sheet";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { parseAsBoolean, useQueryState } from "nuqs";import { type ComponentProps, Suspense, useId, useState } from "react";import { toast } from "sonner";@@ -38,7 +41,7 @@ const NONE = "none";function AddButton(props: ComponentProps<typeof Button>) {return (<Button {...props}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New contact</Button>);@@ -54,6 +57,7 @@ export function CreateContactSheet({ companyId }: { companyId?: string }) {function CreateContactForm({ companyId }: { companyId?: string }) {const openRecord = useOpenRecord();+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();@@ -83,22 +87,42 @@ function CreateContactForm({ companyId }: { companyId?: string }) {`${[contact.firstName, contact.lastName].filter(Boolean).join(" ")} added.`,);await setOpen(null);- setFirstName("");- setLastName("");- setEmail("");- setTitle("");+ reset();openRecord({ kind: "contact", id: contact.id });},onError: (error) => toast.error(error.message),}),);+ const reset = () => {+ validation.reset();+ setFirstName("");+ setLastName("");+ setEmail("");+ setTitle("");+ setCompany(companyId ?? NONE);+ setOwnerId(NONE);+ };+return (- <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>+ <FormSheet+ dirty={+ firstName !== "" ||+ lastName !== "" ||+ email !== "" ||+ title !== "" ||+ company !== (companyId ?? NONE) ||+ ownerId !== NONE+ }+ pending={create.isPending}+ onDiscard={reset}+ open={open}+ onOpenChange={(next) => setOpen(next || null)}+ ><SheetTrigger asChild><AddButton /></SheetTrigger>- <SheetContent side="right">+ <FormSheetContent side="right"><SheetHeader><SheetTitle>New contact</SheetTitle><SheetDescription>@@ -107,11 +131,13 @@ function CreateContactForm({ companyId }: { companyId?: string }) {</SheetDescription></SheetHeader>- <form+ <FormSheetForm+ noValidate+ onInput={validation.onInput}id="create-contact"- className="flex-1 overflow-y-auto px-4"onSubmit={(event) => {event.preventDefault();+ if (!validation.validate(event.currentTarget)) return;create.mutate({firstName,lastName: lastName || undefined,@@ -122,93 +148,121 @@ function CreateContactForm({ companyId }: { companyId?: string }) {});}}>- <FieldGroup>- <Field>- <FieldLabel htmlFor={firstNameId}>First name</FieldLabel>- <Input- id={firstNameId}- value={firstName}- onChange={(event) => setFirstName(event.target.value)}- autoComplete="off"- required- />- </Field>-- <Field>- <FieldLabel htmlFor={lastNameId}>Last name</FieldLabel>- <Input- id={lastNameId}- value={lastName}- onChange={(event) => setLastName(event.target.value)}- autoComplete="off"- />- </Field>-- <Field>- <FieldLabel htmlFor={emailId}>Email</FieldLabel>- <Input- id={emailId}- type="email"- value={email}- onChange={(event) => setEmail(event.target.value)}- autoComplete="off"- />- </Field>-- <Field>- <FieldLabel htmlFor={titleId}>Title</FieldLabel>- <Input- id={titleId}- value={title}- onChange={(event) => setTitle(event.target.value)}- placeholder="Head of Security"- autoComplete="off"- />- </Field>-- <Field>- <FieldLabel htmlFor="create-contact-company">Company</FieldLabel>- <CompanyPicker- id="create-contact-company"- value={company}- onValueChange={setCompany}- none={{ value: NONE, label: "No company" }}- />- </Field>-- <Field>- <FieldLabel htmlFor="create-contact-owner">Owner</FieldLabel>- <Select value={ownerId} onValueChange={setOwnerId}>- <SelectTrigger id="create-contact-owner">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value={NONE}>Unassigned</SelectItem>- {(users.data ?? []).map((user) => (- <SelectItem key={user.id} value={user.id}>- {user.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>- </FieldGroup>- </form>-- <SheetFooter>+ <Field data-invalid={!!validation.errors[firstNameId]}>+ <FieldLabel htmlFor={firstNameId}>First name</FieldLabel>+ <Input+ id={firstNameId}+ aria-invalid={!!validation.errors[firstNameId]}+ aria-describedby={+ validation.errors[firstNameId]+ ? `${firstNameId}-error`+ : undefined+ }+ value={firstName}+ onChange={(event) => setFirstName(event.target.value)}+ autoComplete="off"+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${firstNameId}-error`}>+ {validation.errors[firstNameId]}+ </FieldError>+ </Field>++ <Field data-invalid={!!validation.errors[lastNameId]}>+ <FieldLabel htmlFor={lastNameId}>Last name</FieldLabel>+ <Input+ id={lastNameId}+ aria-invalid={!!validation.errors[lastNameId]}+ aria-describedby={+ validation.errors[lastNameId]+ ? `${lastNameId}-error`+ : undefined+ }+ value={lastName}+ onChange={(event) => setLastName(event.target.value)}+ autoComplete="off"+ />+ <FieldError id={`${lastNameId}-error`}>+ {validation.errors[lastNameId]}+ </FieldError>+ </Field>++ <Field data-invalid={!!validation.errors[emailId]}>+ <FieldLabel htmlFor={emailId}>Email</FieldLabel>+ <Input+ id={emailId}+ aria-invalid={!!validation.errors[emailId]}+ aria-describedby={+ validation.errors[emailId] ? `${emailId}-error` : undefined+ }+ type="email"+ value={email}+ onChange={(event) => setEmail(event.target.value)}+ autoComplete="off"+ />+ <FieldError id={`${emailId}-error`}>+ {validation.errors[emailId]}+ </FieldError>+ </Field>++ <Field data-invalid={!!validation.errors[titleId]}>+ <FieldLabel htmlFor={titleId}>Title</FieldLabel>+ <Input+ id={titleId}+ aria-invalid={!!validation.errors[titleId]}+ aria-describedby={+ validation.errors[titleId] ? `${titleId}-error` : undefined+ }+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ placeholder="Head of Security"+ autoComplete="off"+ />+ <FieldError id={`${titleId}-error`}>+ {validation.errors[titleId]}+ </FieldError>+ </Field>++ <Field>+ <FieldLabel htmlFor="create-contact-company">Company</FieldLabel>+ <CompanyPicker+ id="create-contact-company"+ value={company}+ onValueChange={setCompany}+ none={{ value: NONE, label: "No company" }}+ />+ </Field>++ <Field>+ <FieldLabel htmlFor="create-contact-owner">Owner</FieldLabel>+ <Select value={ownerId} onValueChange={setOwnerId}>+ <SelectTrigger id="create-contact-owner">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={NONE}>Unassigned</SelectItem>+ {(users.data ?? []).map((user) => (+ <SelectItem key={user.id} value={user.id}>+ {user.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </FormSheetForm>++ <FormSheetFooter><Buttontype="submit"form="create-contact"- disabled={create.isPending || firstName.trim() === ""}+ disabled={create.isPending}>- {create.isPending ? <Spinner /> : null}+ {create.isPending ? <Spinner data-icon="inline-start" /> : null}Add contact</Button>- <SheetClose asChild>- <Button variant="outline">Cancel</Button>- </SheetClose>- </SheetFooter>- </SheetContent>- </Sheet>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>);}diff --git a/apps/app/app/(app)/[slug]/contacts/page.tsx b/apps/app/app/(app)/[slug]/contacts/page.tsxindex f5717e61..d9820d8a 100644--- a/apps/app/app/(app)/[slug]/contacts/page.tsx+++ b/apps/app/app/(app)/[slug]/contacts/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -9,7 +7,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -37,7 +37,7 @@ export default function ContactsPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="table" />}><Contacts searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/dashboard-summary.tsx b/apps/app/app/(app)/[slug]/dashboard-summary.tsxindex 08ae17d6..7fc1f4e5 100644--- a/apps/app/app/(app)/[slug]/dashboard-summary.tsx+++ b/apps/app/app/(app)/[slug]/dashboard-summary.tsx@@ -6,37 +6,37 @@ import {CardAction,CardDescription,CardHeader,- CardPanel,CardPanelEmpty,CardTitle,} from "@crm/ui/components/card";-import { CardTableEmpty } from "@crm/ui/components/card-table";import { Checkbox } from "@crm/ui/components/checkbox";+import { DashboardPanel } from "@crm/ui/components/dashboard";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import {EntityLogo,type EntityLogoTone,} from "@crm/ui/components/entity-logo";+import { PageShellLoading } from "@crm/ui/components/page-shell";import {SimpleTable,type SimpleTableColumn,SimpleTableRow,} from "@crm/ui/components/simple-table";-import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { TableCell } from "@crm/ui/components/table";+import { ValueMeter } from "@crm/ui/components/value-meter";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, ReactNode } from "react";+import type { ReactNode } from "react";import { toast } from "sonner";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 { LocalRelativeTime } from "@/components/local-date-time";import { activityLabel } from "@/lib/activity-presentation";-import { dealStageColor } from "@/lib/deal-stage";+import { dealStageChartColor } from "@/lib/deal-stage";import { SEARCH_PARAM } from "@/lib/search-param-keys";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -45,19 +45,24 @@ import { overviewParsers } from "./overview-search-params";import { SalesDashboard } from "./sales-dashboard";const CELL = "px-3 py-2.5 align-middle";+const STAGE_CELL = "hidden @lg/simple-table:table-cell";+const SHARE_CELL = "hidden @sm/simple-table:table-cell";+const COMPANY_CELL = "hidden @md/simple-table:table-cell";+const ACTIVITY_DEAL_CELL = "hidden @2xl/simple-table:table-cell";+const WHO_CELL = "hidden @lg/simple-table:table-cell";const OPEN_COLUMNS: SimpleTableColumn[] = [{ id: "deal", header: "Deal" },{id: "stage",header: "Stage",- width: "w-32",- className: "hidden lg:table-cell",+ width: "w-44",+ className: STAGE_CELL,},{id: "share",srLabel: "Share of the largest",width: "w-24",- className: "hidden sm:table-cell",+ className: SHARE_CELL,},{ id: "value", header: "Value", width: "w-20", align: "right" },];@@ -72,19 +77,19 @@ const ACTIVITY_COLUMNS: SimpleTableColumn[] = [id: "company",header: "Company",width: "w-44",- className: "hidden md:table-cell",+ className: COMPANY_CELL,},{id: "deal",header: "Deal",width: "w-48",- className: "hidden lg:table-cell",+ className: ACTIVITY_DEAL_CELL,},{id: "who",header: "Who",width: "w-32",- className: "hidden md:table-cell",+ className: WHO_CELL,},{ id: "when", header: "When", width: "w-20", align: "right" },];@@ -115,11 +120,7 @@ export function DashboardSummary() {const summary = summaryQuery.data;if (!summary) {- return (- <div className="flex flex-1 justify-center py-12">- <Spinner />- </div>- );+ return <PageShellLoading shape="dashboard" />;}const { biggestOpen, overdueTasks, recentActivity } = summary;@@ -139,12 +140,12 @@ export function DashboardSummary() {The largest open deals, and how long each has sat in its stage</CardDescription><CardAction>- <Button asChild variant="contrast" size="sm">+ <Button asChild variant="outline" size="sm"><Link href={workspaceUrl("/deals")}>Open deals</Link></Button></CardAction></CardHeader>- <CardPanel>+ <DashboardPanel>{biggestOpen.length === 0 ? (<CardPanelEmpty>Nothing open. Time to fill the pipeline.@@ -152,14 +153,22 @@ export function DashboardSummary() {) : (<SimpleTablevariant="panel"- surface="page"+ surface="card"columns={OPEN_COLUMNS}>{biggestOpen.map((deal) => (<SimpleTableRowkey={deal.id}clickable- onClick={() => openRecord({ kind: "deal", id: deal.id })}+ onClick={() =>+ openRecord(+ { kind: "deal", id: deal.id },+ biggestOpen.map((entry) => ({+ kind: "deal",+ id: entry.id,+ })),+ )+ }><TableCell className={CELL}><DealCell@@ -168,10 +177,10 @@ export function DashboardSummary() {meta={<LocalRelativeTime date={deal.stageChangedAt} />}/></TableCell>- <TableCell className={`${CELL} hidden lg:table-cell`}>+ <TableCell className={`${CELL} ${STAGE_CELL}`}><DealStageIndicator stage={deal.stage} /></TableCell>- <TableCell className={`${CELL} hidden sm:table-cell`}>+ <TableCell className={`${CELL} ${SHARE_CELL}`}><ValueMetershare={largestOpenCents > 0@@ -179,7 +188,7 @@ export function DashboardSummary() {100: 0}- color={dealStageColor(deal.stage)}+ color={dealStageChartColor(deal.stage)}/></TableCell><TableCell className={`${CELL} text-right tabular-nums`}>@@ -193,7 +202,7 @@ export function DashboardSummary() {))}</SimpleTable>)}- </CardPanel>+ </DashboardPanel></Card><Card className="min-w-0">@@ -205,18 +214,18 @@ export function DashboardSummary() {: `${formatCount(overdueTasks.length, "task")} past due`}</CardDescription><CardAction>- <Button asChild variant="contrast" size="sm">+ <Button asChild variant="outline" size="sm"><Link href={workspaceUrl("/tasks")}>Open tasks</Link></Button></CardAction></CardHeader>- <CardPanel>+ <DashboardPanel>{overdueTasks.length === 0 ? (<CardPanelEmpty>Nothing overdue. Good.</CardPanelEmpty>) : (<SimpleTablevariant="panel"- surface="page"+ surface="card"columns={TASK_COLUMNS}>{overdueTasks.map((task) => (@@ -263,7 +272,7 @@ export function DashboardSummary() {))}</SimpleTable>)}- </CardPanel>+ </DashboardPanel></Card></div>@@ -278,54 +287,60 @@ export function DashboardSummary() {: "Every note, task and stage change across the workspace"}</CardDescription><CardAction>- <Button asChild variant="contrast" size="sm">+ <Button asChild variant="outline" size="sm"><Link href={workspaceUrl("/companies")}>All companies</Link></Button></CardAction></CardHeader>- {recentActivity.length === 0 ? (- <CardTableEmpty>Nothing has happened yet.</CardTableEmpty>- ) : (- <SimpleTable columns={ACTIVITY_COLUMNS}>- {recentActivity.map((entry) => (- <SimpleTableRow key={entry.id}>- <TableCell className={CELL}>- <span className="truncate">- {entry.subject ?? activityLabel(entry.type)}- </span>- </TableCell>- <TableCell className={`${CELL} hidden md:table-cell`}>- {entry.company ? (- <RecordLink kind="company" id={entry.company.id}>- {entry.company.name}- </RecordLink>- ) : (- <EmptyCellValue />- )}- </TableCell>- <TableCell className={`${CELL} hidden lg:table-cell`}>- {entry.deal ? (- <RecordLink kind="deal" id={entry.deal.id}>- {entry.deal.name}- </RecordLink>- ) : (- <EmptyCellValue />- )}- </TableCell>- <TableCell- className={`${CELL} hidden truncate text-muted-foreground md:table-cell`}- >- {entry.createdBy.name}- </TableCell>- <TableCell- className={`${CELL} text-right text-muted-foreground`}- >- <LocalRelativeTime date={entry.createdAt} />- </TableCell>- </SimpleTableRow>- ))}- </SimpleTable>- )}+ <DashboardPanel>+ {recentActivity.length === 0 ? (+ <CardPanelEmpty>Nothing has happened yet.</CardPanelEmpty>+ ) : (+ <SimpleTable+ variant="panel"+ surface="card"+ columns={ACTIVITY_COLUMNS}+ >+ {recentActivity.map((entry) => (+ <SimpleTableRow key={entry.id}>+ <TableCell className={CELL}>+ <span className="truncate">+ {entry.subject ?? activityLabel(entry.type)}+ </span>+ </TableCell>+ <TableCell className={`${CELL} ${COMPANY_CELL}`}>+ {entry.company ? (+ <RecordLink kind="company" id={entry.company.id}>+ {entry.company.name}+ </RecordLink>+ ) : (+ <EmptyCellValue />+ )}+ </TableCell>+ <TableCell className={`${CELL} ${ACTIVITY_DEAL_CELL}`}>+ {entry.deal ? (+ <RecordLink kind="deal" id={entry.deal.id}>+ {entry.deal.name}+ </RecordLink>+ ) : (+ <EmptyCellValue />+ )}+ </TableCell>+ <TableCell+ className={`${CELL} ${WHO_CELL} truncate text-muted-foreground`}+ >+ {entry.createdBy.name}+ </TableCell>+ <TableCell+ className={`${CELL} text-right text-muted-foreground`}+ >+ <LocalRelativeTime date={entry.createdAt} />+ </TableCell>+ </SimpleTableRow>+ ))}+ </SimpleTable>+ )}+ </DashboardPanel></Card></div>);@@ -356,35 +371,11 @@ function DealCell({/><span className="flex min-w-0 flex-col"><span className="truncate font-medium">{name}</span>- <span className="truncate text-muted-foreground">- {meta ? (- <>- {company.name} · {meta}- </>- ) : (- company.name- )}+ <span className="flex min-w-0 items-baseline gap-x-3 text-muted-foreground">+ <span className="truncate">{company.name}</span>+ {meta ? <span className="shrink-0">{meta}</span> : null}</span></span></span>);}--function ValueMeter({ share, color }: { share: number; color: string }) {- return (- <span- className="bloom-low flex h-1.5 w-full overflow-hidden bg-muted"- style={{ "--bloom-color": color } as CSSProperties}- >- <span- className="h-full w-(--share)"- style={- {- backgroundColor: color,- "--share": `${Math.round(Math.max(Math.min(share, 100), 0))}%`,- } as CSSProperties- }- />- </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 fcdd96fe..2590fd28 100644--- a/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx+++ b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx@@ -1,15 +1,21 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { CURRENCIES } from "@crm/db/currency";import { Button } from "@crm/ui/components/button";import { DatePicker } from "@crm/ui/components/date-picker";import {Field,FieldDescription,- FieldGroup,+ FieldError,FieldLabel,} from "@crm/ui/components/field";+import {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ useFormSheetValidation,+} from "@crm/ui/components/form-sheet";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";import {@@ -20,17 +26,14 @@ import {SelectValue,} from "@crm/ui/components/select";import {- Sheet,- SheetClose,- SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,SheetTrigger,} from "@crm/ui/components/sheet";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { parseAsBoolean, useQueryState } from "nuqs";import { type ComponentProps, Suspense, useId, useState } from "react";import { toast } from "sonner";@@ -46,7 +49,7 @@ const UNSET = "";function AddButton(props: ComponentProps<typeof Button>) {return (<Button {...props}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New deal</Button>);@@ -62,6 +65,7 @@ export function CreateDealSheet({ companyId }: { companyId?: string }) {function CreateDealForm({ companyId }: { companyId?: string }) {const openRecord = useOpenRecord();+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();@@ -95,25 +99,44 @@ function CreateDealForm({ companyId }: { companyId?: string }) {await cache.deal(deal.id);toast.success(`${deal.name} added.`);await setOpen(null);- setName("");- setAmount("");- setCurrency("");- setCloseDate("");+ reset();openRecord({ kind: "deal", id: deal.id });},onError: (error) => toast.error(error.message),}),);- const ready =- name.trim() !== "" && company !== UNSET && resolvedOwner !== UNSET;+ const reset = () => {+ validation.reset();+ setName("");+ setCompany(companyId ?? UNSET);+ setOwnerId(UNSET);+ setStage("DEMO_BOOKED");+ setAmount("");+ setCurrency("");+ setCloseDate("");+ };return (- <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>+ <FormSheet+ dirty={+ name !== "" ||+ company !== (companyId ?? UNSET) ||+ (ownerId !== UNSET && ownerId !== me.data?.id) ||+ stage !== "DEMO_BOOKED" ||+ amount !== "" ||+ (currency !== "" && currency !== (workspaceCurrency || "USD")) ||+ closeDate !== ""+ }+ pending={create.isPending}+ onDiscard={reset}+ open={open}+ onOpenChange={(next) => setOpen(next || null)}+ ><SheetTrigger asChild><AddButton /></SheetTrigger>- <SheetContent side="right">+ <FormSheetContent side="right"><SheetHeader><SheetTitle>New deal</SheetTitle><SheetDescription>@@ -121,11 +144,18 @@ function CreateDealForm({ companyId }: { companyId?: string }) {</SheetDescription></SheetHeader>- <form+ <FormSheetForm+ noValidate+ onInput={validation.onInput}id="create-deal"- className="flex-1 overflow-y-auto px-4"onSubmit={(event) => {event.preventDefault();+ const errors: Record<string, string> = {};+ if (company === UNSET)+ errors["create-deal-company"] = "Choose a company.";+ if (resolvedOwner === UNSET)+ errors["create-deal-owner"] = "Choose an owner.";+ if (!validation.validate(event.currentTarget, errors)) return;const parsed = Number.parseFloat(amount);create.mutate({name,@@ -140,119 +170,151 @@ function CreateDealForm({ companyId }: { companyId?: string }) {});}}>- <FieldGroup>- <Field>- <FieldLabel htmlFor={nameId}>Name</FieldLabel>- <Input- id={nameId}- value={name}- onChange={(event) => setName(event.target.value)}- placeholder="Stripe — Comp AI"- autoComplete="off"- required- />- </Field>+ <Field data-invalid={!!validation.errors[nameId]}>+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>+ <Input+ id={nameId}+ aria-invalid={!!validation.errors[nameId]}+ aria-describedby={+ validation.errors[nameId] ? `${nameId}-error` : undefined+ }+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder="Stripe Comp AI"+ autoComplete="off"+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${nameId}-error`}>+ {validation.errors[nameId]}+ </FieldError>+ </Field>- <Field>- <FieldLabel htmlFor="create-deal-company">Company</FieldLabel>- <CompanyPicker- id="create-deal-company"- value={company}- onValueChange={setCompany}- />- </Field>+ <Field data-invalid={!!validation.errors["create-deal-company"]}>+ <FieldLabel htmlFor="create-deal-company">Company</FieldLabel>+ <CompanyPicker+ id="create-deal-company"+ aria-invalid={!!validation.errors["create-deal-company"]}+ aria-describedby={+ validation.errors["create-deal-company"]+ ? "create-deal-company-error"+ : undefined+ }+ value={company}+ onValueChange={(value) => {+ setCompany(value);+ validation.clearError("create-deal-company");+ }}+ />+ <FieldError id="create-deal-company-error">+ {validation.errors["create-deal-company"]}+ </FieldError>+ </Field>- <Field>- <FieldLabel htmlFor="create-deal-owner">Owner</FieldLabel>- <Select value={resolvedOwner} onValueChange={setOwnerId}>- <SelectTrigger id="create-deal-owner">- <SelectValue placeholder="Choose an owner" />- </SelectTrigger>- <SelectContent>- {(users.data ?? []).map((user) => (- <SelectItem key={user.id} value={user.id}>- {user.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>+ <Field data-invalid={!!validation.errors["create-deal-owner"]}>+ <FieldLabel htmlFor="create-deal-owner">Owner</FieldLabel>+ <Select+ value={resolvedOwner}+ onValueChange={(value) => {+ setOwnerId(value);+ validation.clearError("create-deal-owner");+ }}+ >+ <SelectTrigger+ id="create-deal-owner"+ aria-invalid={!!validation.errors["create-deal-owner"]}+ aria-describedby={+ validation.errors["create-deal-owner"]+ ? "create-deal-owner-error"+ : undefined+ }+ >+ <SelectValue placeholder="Choose an owner" />+ </SelectTrigger>+ <SelectContent>+ {(users.data ?? []).map((user) => (+ <SelectItem key={user.id} value={user.id}>+ {user.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError id="create-deal-owner-error">+ {validation.errors["create-deal-owner"]}+ </FieldError>+ </Field>- <Field>- <FieldLabel htmlFor="create-deal-stage">Stage</FieldLabel>- <Select value={stage} onValueChange={setStage}>- <SelectTrigger id="create-deal-stage">+ <Field>+ <FieldLabel htmlFor="create-deal-stage">Stage</FieldLabel>+ <Select value={stage} onValueChange={setStage}>+ <SelectTrigger id="create-deal-stage">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {OPEN_STAGES.map((value) => (+ <SelectItem key={value} value={value}>+ {dealStageLabel(value)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ A new deal starts open. Close it from the pipeline once there is+ an outcome to record.+ </FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[amountId]}>+ <FieldLabel htmlFor={amountId}>Amount</FieldLabel>+ <div className="flex gap-2">+ <Input+ id={amountId}+ aria-invalid={!!validation.errors[amountId]}+ aria-describedby={+ validation.errors[amountId] ? `${amountId}-error` : undefined+ }+ value={amount}+ onChange={(event) => setAmount(event.target.value)}+ placeholder="24000"+ inputMode="decimal"+ autoComplete="off"+ />+ <FieldError id={`${amountId}-error`}>+ {validation.errors[amountId]}+ </FieldError>+ <Select value={resolvedCurrency} onValueChange={setCurrency}>+ <SelectTrigger aria-label="Currency" className="w-28 shrink-0"><SelectValue /></SelectTrigger><SelectContent>- {OPEN_STAGES.map((value) => (- <SelectItem key={value} value={value}>- {dealStageLabel(value)}+ {CURRENCIES.map((entry) => (+ <SelectItem key={entry.code} value={entry.code}>+ {entry.code}</SelectItem>))}</SelectContent></Select>- <FieldDescription>- A new deal is an open deal — close it from the pipeline once- there is an outcome to record.- </FieldDescription>- </Field>+ </div>+ </Field>- <Field>- <FieldLabel htmlFor={amountId}>Amount</FieldLabel>- <div className="flex gap-2">- <Input- id={amountId}- value={amount}- onChange={(event) => setAmount(event.target.value)}- placeholder="24000"- inputMode="decimal"- autoComplete="off"- />- <Select value={resolvedCurrency} onValueChange={setCurrency}>- <SelectTrigger- aria-label="Currency"- className="w-28 shrink-0"- >- <SelectValue />- </SelectTrigger>- <SelectContent>- {CURRENCIES.map((entry) => (- <SelectItem key={entry.code} value={entry.code}>- {entry.code}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </Field>-- <Field>- <FieldLabel htmlFor={closeDateId}>Expected close date</FieldLabel>- <DatePicker- id={closeDateId}- value={closeDate}- onChange={setCloseDate}- placeholder="No date yet"- />- </Field>- </FieldGroup>- </form>+ <Field data-invalid={!!validation.errors[closeDateId]}>+ <FieldLabel htmlFor={closeDateId}>Expected close date</FieldLabel>+ <DatePicker+ id={closeDateId}+ value={closeDate}+ onChange={setCloseDate}+ placeholder="No date yet"+ />+ </Field>+ </FormSheetForm>- <SheetFooter>- <Button- type="submit"- form="create-deal"- disabled={create.isPending || !ready}- >- {create.isPending ? <Spinner /> : null}+ <FormSheetFooter>+ <Button type="submit" form="create-deal" disabled={create.isPending}>+ {create.isPending ? <Spinner data-icon="inline-start" /> : null}Add deal</Button>- <SheetClose asChild>- <Button variant="outline">Cancel</Button>- </SheetClose>- </SheetFooter>- </SheetContent>- </Sheet>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>);}diff --git a/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsxindex be440e9c..1ff6eeea 100644--- a/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx+++ b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx@@ -1,7 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";-import Undo from "@carbon/icons-react/es/Undo";import type { DealStage } from "@crm/db/enums";import { Button } from "@crm/ui/components/button";import {@@ -25,6 +23,7 @@ import { Spinner } from "@crm/ui/components/spinner";import { Textarea } from "@crm/ui/components/textarea";import { formatCount } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";+import { ArchiveIcon, Undo2Icon } from "lucide-react";import { useId, useState } from "react";import { toast } from "sonner";import {@@ -126,7 +125,7 @@ export function DealsBulkActions({<BulkActionsMenu pending={archivedPending}><DropdownMenuGroup><DropdownMenuItem onSelect={() => restore.mutate({ ids })}>- <Undo />+ <Undo2Icon />Restore</DropdownMenuItem></DropdownMenuGroup>@@ -145,7 +144,7 @@ export function DealsBulkActions({open={confirming}onOpenChange={setConfirming}title={`Delete ${deals(ids.length)} forever?`}- description="Everything filed against them — activity, notes, the amounts in your pipeline — goes too. This cannot be undone."+ description="This deletes their activity, notes and pipeline amounts. You cannot undo this."onConfirm={() => purge.mutate({ ids })}/></>@@ -188,7 +187,7 @@ export function DealsBulkActions({<DropdownMenuSeparator /><DropdownMenuGroup><DropdownMenuItem onSelect={() => archive.mutate({ ids })}>- <Archive />+ <ArchiveIcon />Archive</DropdownMenuItem></DropdownMenuGroup>diff --git a/apps/app/app/(app)/[slug]/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsxindex 0fb19ccb..e0247737 100644--- a/apps/app/app/(app)/[slug]/deals/deals-table.tsx+++ b/apps/app/app/(app)/[slug]/deals/deals-table.tsx@@ -1,6 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";import { Button } from "@crm/ui/components/button";import {DataTable,@@ -8,10 +7,12 @@ import {type DataTableFacet,} from "@crm/ui/components/data-table";import { EmptyCellValue } from "@crm/ui/components/empty-cell";+import { MetaRow } from "@crm/ui/components/meta-row";import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { formatMoney } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";-import { useEffect, useMemo } from "react";+import { ArchiveIcon } from "lucide-react";+import { useMemo } from "react";import { CLOSING_OPTIONS } from "@/components/crm/closing-window";import { CompanyCell } from "@/components/crm/company-cell";import { useFieldColumns } from "@/components/crm/fields/field-columns";@@ -20,6 +21,7 @@ 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 { DealStageMenu } from "@/components/crm/stage-change";+import { ListEmpty } from "@/components/data-table/list-empty";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";@@ -37,21 +39,22 @@ const COLUMNS: DataTableColumn<DealRow>[] = [header: "Deal",sortable: true,hideable: false,- width: "w-[24%]",- cell: (row) => <span className="truncate font-medium">{row.name}</span>,+ cell: (row) => (+ <span className="block truncate font-medium">{row.name}</span>+ ),},{id: "company",header: "Company",sortable: true,- width: "w-[18%]",+ width: { sm: "40" },cell: (row) => <CompanyCell company={row.company} />,},{id: "stage",header: "Stage",sortable: true,- width: "w-[18%]",+ width: { sm: "40" },cell: (row) => <DealStageMenu dealId={row.id} stage={row.stage} />,},{@@ -59,7 +62,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [header: "Amount",sortable: true,align: "right",- width: "w-[12%]",+ width: "36",hideBelow: "sm",cell: (row) =>row.amountCents === null ? (@@ -74,7 +77,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [id: "owner",header: "Owner",sortable: true,- width: "w-[14%]",+ width: "40",hideBelow: "md",cell: (row) => <OwnerCell owner={row.owner} />,},@@ -82,7 +85,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [id: "expectedCloseDate",header: "Close date",sortable: true,- width: "w-[12%]",+ width: "32",hideBelow: "lg",cell: (row) =>row.expectedCloseDate ? (@@ -99,7 +102,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [label: "Created date",sortable: true,align: "right",- width: "w-[10%]",+ width: "28",defaultHidden: true,cell: (row) => (<span className="text-muted-foreground">@@ -112,7 +115,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [header: "Last activity",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",hideBelow: "lg",cell: (row) => (<span className="text-muted-foreground">@@ -132,7 +135,7 @@ const ARCHIVED_COLUMN: DataTableColumn<DealRow> = {label: "Archived date",sortable: true,align: "right",- width: "w-[12%]",+ width: "32",cell: (row) => (<span className="text-muted-foreground">{row.archivedAt ? (@@ -169,11 +172,6 @@ export function DealsTable() {return selection.ids.filter((id) => matching.has(id));}, [rows, input.archived, selection.ids]);- // biome-ignore lint/correctness/useExhaustiveDependencies: clearing on archived-mode change is the entire purpose of this effect.- useEffect(() => {- selection.clear();- }, [input.archived]);-const toggleArchived = (next: boolean) => {selection.clear();if (!next && query.sort === "archivedAt") query.setSort("");@@ -229,16 +227,17 @@ export function DealsTable() {return (<DataTable+ label="Deals"query={query}- search={<ListSearch placeholder="Search deals by name or company…" />}+ search={<ListSearch placeholder="Search deals…" />}actions={<Buttonvariant={input.archived ? "contrast" : "outline"}- size="sm"+ aria-pressed={input.archived}className="justify-start sm:justify-center"onClick={() => toggleArchived(!input.archived)}>- <Archive data-icon="inline-start" />+ <ArchiveIcon data-icon="inline-start" />Archived</Button>}@@ -249,6 +248,7 @@ export function DealsTable() {facets={facets}tabs={{id: "status",+ label: "Status",allLabel: "All deals",options: [{ value: "open", label: "Open" },@@ -269,26 +269,40 @@ export function DealsTable() {getRowId={(row) => row.id}loading={deals.isFetching}onRowHover={(row) => prefetchRecord({ kind: "deal", id: row.id })}- onRowClick={(row) => openRecord({ kind: "deal", id: row.id })}+ onRowClick={(row, orderedRows) =>+ openRecord(+ { kind: "deal", id: row.id },+ orderedRows.map((entry) => ({ kind: "deal", id: entry.id })),+ )+ }empty={- input.archived ? "No archived deals." : "No deals match this view."+ <ListEmpty+ query={query}+ noun="deals"+ archived={input.archived}+ blank={{+ title: "No deals yet",+ description: "Add a deal to start tracking the pipeline.",+ }}+ />}meta={input.archived || openPipelineCents === null ? undefined : (- <span>- {deals.data?.total ?? 0} deals ·{" "}- <span className="tabular-nums">- {formatMoney(openPipelineCents, reportingCurrency)}- </span>{" "}- open pipeline+ <MetaRow>+ <span>{deals.data?.total ?? 0} deals</span>+ <span>+ <span className="tabular-nums">+ {formatMoney(openPipelineCents, reportingCurrency)}+ </span>{" "}+ open pipeline+ </span>{unconverted && unconverted.count > 0 ? (- <span className="text-muted-foreground">- {" "}- · {unconverted.count} not counted (no{" "}+ <span>+ {unconverted.count} not counted (no{" "}{unconverted.currencies.join(", ")} rate)</span>) : null}- </span>+ </MetaRow>)}/>diff --git a/apps/app/app/(app)/[slug]/deals/page.tsx b/apps/app/app/(app)/[slug]/deals/page.tsxindex f1d7ab44..65f816d2 100644--- a/apps/app/app/(app)/[slug]/deals/page.tsx+++ b/apps/app/app/(app)/[slug]/deals/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -9,7 +7,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -39,7 +39,7 @@ export default function DealsPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="table" />}><Deals searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/layout.tsx b/apps/app/app/(app)/[slug]/layout.tsxindex d562cd03..976da655 100644--- a/apps/app/app/(app)/[slug]/layout.tsx+++ b/apps/app/app/(app)/[slug]/layout.tsx@@ -1,12 +1,14 @@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";+import { AccountMenu, AccountMenuFallback } from "@/components/account-menu";import { QuickSwitcher } from "@/components/crm/quick-switcher";import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-host";import { RecordStackBoundary } from "@/components/crm/record-sheet/record-stack";+import { EnrichmentQueue } from "@/components/enrichment-queue";import { MobileNavProvider } from "@/components/mobile-nav";+import { WorkspaceNav, WorkspaceNavFallback } from "@/components/workspace-nav";+import { WorkspaceShell } from "@/components/workspace-shell";import { requireMailboxAccess } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -18,26 +20,28 @@ export default function AppLayout({return (<MobileNavProvider><RecordStackBoundary>- <div className="isolate flex h-svh flex-col">- <Suspense fallback={<AppHeaderFallback />}>- <WorkspaceHeader params={params} />- </Suspense>-- <div className="flex min-h-0 flex-1">- <Suspense fallback={<AppIconRailFallback />}>- <AppIconRail />+ <WorkspaceShell+ sidebar={+ <Suspense fallback={<WorkspaceNavFallback />}>+ <WorkspaceSidebar />+ </Suspense>+ }+ end={+ <Suspense fallback={<AccountMenuFallback />}>+ <WorkspaceAccount params={params} /></Suspense>- {children}- </div>+ }+ >+ {children}+ </WorkspaceShell>- <Suspense fallback={null}>- <RecordSheetHost />- </Suspense>+ <Suspense fallback={null}>+ <RecordSheetHost />+ </Suspense>- <Suspense fallback={null}>- <QuickSwitcher />- </Suspense>- </div>+ <Suspense fallback={null}>+ <QuickSwitcher />+ </Suspense></RecordStackBoundary></MobileNavProvider>);@@ -54,7 +58,14 @@ async function loadWorkspace() {}}-async function WorkspaceHeader({+async function WorkspaceSidebar() {+ await connection();+ const workspace = await loadWorkspace();++ return <WorkspaceNav initialWorkspace={workspace ?? undefined} />;+}++async function WorkspaceAccount({params,}: Pick<LayoutProps<"/[slug]">, "params">) {await connection();@@ -68,7 +79,8 @@ async function WorkspaceHeader({return (<HydrateClient>- <AppHeader+ <EnrichmentQueue />+ <AccountMenuuser={{name: user.name,email: user.email,diff --git a/apps/app/app/(app)/[slug]/overview-greeting.tsx b/apps/app/app/(app)/[slug]/overview-greeting.tsxindex ff92369e..215479a4 100644--- a/apps/app/app/(app)/[slug]/overview-greeting.tsx+++ b/apps/app/app/(app)/[slug]/overview-greeting.tsx@@ -1,7 +1,10 @@"use client";+import {+ PageShellDescription,+ PageShellTitle,+} from "@crm/ui/components/page-shell";import { useQueryState } from "nuqs";-import { PageShellDescription, PageShellTitle } from "@/components/page-shell";import { SEARCH_PARAM } from "@/lib/search-param-keys";import { overviewParsers } from "./overview-search-params";diff --git a/apps/app/app/(app)/[slug]/page.tsx b/apps/app/app/(app)/[slug]/page.tsxindex feaf6017..b7eff893 100644--- a/apps/app/app/(app)/[slug]/page.tsx+++ b/apps/app/app/(app)/[slug]/page.tsx@@ -1,4 +1,3 @@-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -6,7 +5,8 @@ import {PageShellHeader,PageShellHeading,PageShellLoading,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -38,7 +38,7 @@ export default function OverviewPage({ searchParams }: PageProps<"/[slug]">) {</PageShellHeader><PageShellContent>- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="dashboard" />}><Summary searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/sales-dashboard.tsx b/apps/app/app/(app)/[slug]/sales-dashboard.tsxindex d4a3162d..5857e660 100644--- a/apps/app/app/(app)/[slug]/sales-dashboard.tsx+++ b/apps/app/app/(app)/[slug]/sales-dashboard.tsx@@ -6,9 +6,15 @@ import {CardHeader,CardTitle,} from "@crm/ui/components/card";-import type { ChartConfig } from "@crm/ui/components/chart";-import { DashboardRow, StatGroup } from "@crm/ui/components/dashboard";+import { ChartSwatch } from "@crm/ui/components/chart-swatch";+import {+ DashboardPanel,+ DashboardRow,+ StatGroup,+} from "@crm/ui/components/dashboard";+import { MetaRow } from "@crm/ui/components/meta-row";import { StatCard, type StatDelta } from "@crm/ui/components/stat-card";+import { CHART_CONFIG } from "@crm/ui/lib/chart-config";import {formatCount,formatMoney,@@ -17,16 +23,20 @@ import {} from "@crm/ui/lib/format";import Link from "next/link";import type { ReactNode } from "react";-import { AreaTrend, DonutStat } from "@/components/dashboard-charts";-import { dealStageColor, dealStageLabel } from "@/lib/deal-stage";+import {+ AreaTrend,+ DonutStat,+ type SeriesConfig,+} from "@/components/dashboard-charts";+import { dealStageChartColor, dealStageLabel } from "@/lib/deal-stage";import type { RouterOutputs } from "@/lib/trpc/types";import { useWorkspaceUrl } from "@/lib/use-workspace-url";type Summary = RouterOutputs["dashboard"]["summary"];-const TREND_CONFIG: ChartConfig = {- won: { label: "Closed won", color: "var(--success)" },- created: { label: "New pipeline", color: "var(--chart-1)" },+const TREND_CONFIG: SeriesConfig = {+ won: { label: "Closed won", color: CHART_CONFIG.trend.won },+ created: { label: "New pipeline", color: CHART_CONFIG.trend.created },};function changeDelta(@@ -70,7 +80,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {key: stage.stage,label: dealStageLabel(stage.stage),value: stage.valueCents,- color: dealStageColor(stage.stage),+ color: dealStageChartColor(stage.stage),count: stage.count,},]@@ -88,31 +98,50 @@ export function SalesDashboard({ summary }: { summary: Summary }) {wonPrevMonth.valueCents,"vs. last month",)}- description={`${formatCount(wonThisMonth.count, "deal")} · ${money(wonPrevMonth.valueCents)} last month`}+ description={+ <MetaRow>+ <span>{formatCount(wonThisMonth.count, "deal")}</span>+ <span>{money(wonPrevMonth.valueCents)} last month</span>+ </MetaRow>+ }/><StatCardlabel="Open pipeline"value={money(pipeline.totalCents)}- description={`${formatCount(pipeline.totalDeals, "deal")} in progress · ${money(closingThisMonthTotal.valueCents)} due this month`}+ description={+ <MetaRow>+ <span>+ {formatCount(pipeline.totalDeals, "deal")} in progress+ </span>+ <span>+ {money(closingThisMonthTotal.valueCents)} due this month+ </span>+ </MetaRow>+ }/><StatCardlabel={`Win rate (${performance.windowDays}d)`}value={performance.winRate === null- ? "—"+ ? "None yet": formatPercent(performance.winRate)}description={- performance.wins + performance.losses === 0- ? "Nothing has closed yet"- : `${performance.wins} won · ${performance.losses} lost`+ performance.wins + performance.losses === 0 ? (+ "Nothing has closed yet"+ ) : (+ <MetaRow>+ <span>{performance.wins} won</span>+ <span>{performance.losses} lost</span>+ </MetaRow>+ )}/><StatCardlabel={`Average deal (${performance.windowDays}d)`}value={performance.avgDealCents === null- ? "—"+ ? "None yet": money(performance.avgDealCents)}description={@@ -128,7 +157,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {Every figure above is in {reportingCurrency}.{" "}{formatCount(unconverted.count, "deal")} in{" "}{unconverted.currencies.join(", ")}{" "}- {unconverted.count === 1 ? "is" : "are"} not included — there is no+ {unconverted.count === 1 ? "is" : "are"} not included. There is norate to convert {unconverted.currencies.length === 1 ? "it" : "them"}{" "}with.{" "}<Link@@ -152,11 +181,10 @@ export function SalesDashboard({ summary }: { summary: Summary }) {data={trend}config={TREND_CONFIG}xKey="month"- height={196}- variant="gradient"- bloom="high"+ height={CHART_CONFIG.height.dashboardTrend}showLegendformatValue={exact}+ label="Closed won and new pipeline by month"/></div>) : (@@ -172,10 +200,11 @@ export function SalesDashboard({ summary }: { summary: Summary }) {<div className="flex flex-1 flex-col justify-between gap-1 pt-4"><DonutStatdata={stageSlices}- height={168}+ height={CHART_CONFIG.height.dashboardDonut}centerValue={money(pipeline.totalCents)}centerLabel="open"formatValue={exact}+ label="Open pipeline value by stage"/><ul className="flex flex-col px-5 pb-1 md:px-6">{stageSlices.map((slice) => (@@ -184,11 +213,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {href={`${workspaceUrl("/deals")}?stage=${slice.key}`}className="flex items-center gap-2.5 py-2 text-xs hover:underline">- <span- aria-hidden- className="size-1.5 shrink-0"- style={{ backgroundColor: slice.color }}- />+ <ChartSwatch color={slice.color} size="sm" /><span className="min-w-0 flex-1 truncate">{slice.label}</span>@@ -227,7 +252,7 @@ function ChartPanel({<CardTitle>{title}</CardTitle>{description ? <CardDescription>{description}</CardDescription> : null}</CardHeader>- <div className="flex flex-1 flex-col border">{children}</div>+ <DashboardPanel>{children}</DashboardPanel></Card>);}diff --git a/apps/app/app/(app)/[slug]/settings/agent-model.tsx b/apps/app/app/(app)/[slug]/settings/agent-model.tsxindex 6584a94c..30afad4d 100644--- a/apps/app/app/(app)/[slug]/settings/agent-model.tsx+++ b/apps/app/app/(app)/[slug]/settings/agent-model.tsx@@ -1,14 +1,6 @@"use client";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";import { Button } from "@crm/ui/components/button";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";import {Command,CommandEmpty,@@ -17,13 +9,17 @@ import {CommandItem,CommandList,} from "@crm/ui/components/command";+import { Field, FieldDescription } from "@crm/ui/components/field";import { Icon } from "@crm/ui/components/icon";+import { MetaRow } from "@crm/ui/components/meta-row";import {Popover,PopoverContent,PopoverTrigger,} from "@crm/ui/components/popover";+import { SettingsCard } from "@crm/ui/components/settings-card";import { useMutation, useQuery } from "@tanstack/react-query";+import { ChevronDownIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";@@ -46,7 +42,7 @@ function perMillion(rate: number): string {function priceHint(model: CatalogModel): string | null {if (!model.pricing) return null;- return `${perMillion(model.pricing.input)} in · ${perMillion(model.pricing.output)} out per 1M`;+ return `${perMillion(model.pricing.input)} in, ${perMillion(model.pricing.output)} out per 1M`;}function contextHint(tokens: number): string {@@ -98,7 +94,7 @@ export function AgentModel() {const currentLabel = selectedId? effectiveName- : `Default — ${effectiveName}`;+ : `Default (${effectiveName})`;const choose = (id: string) => {setOpen(false);@@ -107,15 +103,12 @@ export function AgentModel() {};return (- <Card>- <CardHeader>- <CardTitle>Research agent</CardTitle>- <CardDescription>- The model the agent thinks with, routed through the Vercel AI Gateway.- </CardDescription>- </CardHeader>-- <CardContent>+ <SettingsCard+ title="Research agent"+ description="The model the agent thinks with, routed through the Vercel AI Gateway."+ hint="Changes save as you make them. The agent uses the new model from its next session."+ >+ <Field><Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button@@ -126,7 +119,7 @@ export function AgentModel() {disabled={save.isPending || catalog.isPending || unavailable}>{currentLabel}- <Icon icon={ChevronDown} data-icon="inline-end" />+ <Icon icon={ChevronDownIcon} data-icon="inline-end" /></Button></PopoverTrigger>@@ -142,7 +135,7 @@ export function AgentModel() {data-checked={current === FOLLOW_DEFAULT}onSelect={() => choose(FOLLOW_DEFAULT)}>- Default — {defaultModel?.name ?? defaultId}+ Default ({defaultModel?.name ?? defaultId})</CommandItem></CommandGroup>@@ -172,16 +165,23 @@ export function AgentModel() {</PopoverContent></Popover>- <p className="text-muted-foreground text-xs">- {unavailable- ? `Could not reach the AI Gateway to list models. The agent is still running ${effectiveId}.`- : effective- ? `${effectiveId} · ${contextHint(effective.contextWindowTokens)}${- priceHint(effective) ? ` · ${priceHint(effective)}` : ""- }`- : effectiveId}- </p>- </CardContent>- </Card>+ {unavailable ? (+ <FieldDescription>+ Could not reach the AI Gateway to list models. The agent is still+ running {effectiveId}.+ </FieldDescription>+ ) : (+ <MetaRow className="text-13">+ <span>{effectiveId}</span>+ {effective ? (+ <span>{contextHint(effective.contextWindowTokens)}</span>+ ) : null}+ {effective && priceHint(effective) ? (+ <span>{priceHint(effective)}</span>+ ) : null}+ </MetaRow>+ )}+ </Field>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/api-keys/api-keys-table.tsx b/apps/app/app/(app)/[slug]/settings/api-keys/api-keys-table.tsxindex a6737ee7..5db38b34 100644--- a/apps/app/app/(app)/[slug]/settings/api-keys/api-keys-table.tsx+++ b/apps/app/app/(app)/[slug]/settings/api-keys/api-keys-table.tsx@@ -1,6 +1,5 @@"use client";-import TrashCan from "@carbon/icons-react/es/TrashCan";import {AlertDialog,AlertDialogAction,@@ -17,6 +16,7 @@ import { Button } from "@crm/ui/components/button";import { DataTable, type DataTableColumn } from "@crm/ui/components/data-table";import { Icon } from "@crm/ui/components/icon";import { useMutation, useQuery } from "@tanstack/react-query";+import { Trash2Icon } from "lucide-react";import { toast } from "sonner";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";@@ -42,7 +42,6 @@ function columns(header: "Name",sortable: true,hideable: false,- width: "w-[28%]",cell: (row) => (<span className="truncate font-medium">{row.name ?? "Untitled key"}@@ -52,17 +51,17 @@ function columns({id: "start",header: "Key",- width: "w-[20%]",+ width: "36",hideBelow: "sm",cell: (row) => (- <Badge variant="mono">{row.start ? `${row.start}…` : "—"}</Badge>+ <Badge variant="mono">{row.start ? `${row.start}…` : ""}</Badge>),},{id: "createdAt",header: "Created",sortable: true,- width: "w-[16%]",+ width: "28",hideBelow: "md",cell: (row) => (<span className="text-muted-foreground">@@ -75,7 +74,7 @@ function columns(header: "Last used",label: "Last used date",sortable: true,- width: "w-[16%]",+ width: "28",hideBelow: "lg",cell: (row) => (<span className="text-muted-foreground">@@ -91,7 +90,7 @@ function columns(id: "expiresAt",header: "Expires",sortable: true,- width: "w-[14%]",+ width: "24",hideBelow: "lg",cell: (row) =>row.expiresAt ? (@@ -114,12 +113,12 @@ function columns(label: "Actions",hideable: false,align: "right",- width: "w-[6%]",+ width: "12",cell: (row) => (<AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" disabled={pending}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} /><span className="sr-only">Revoke {row.name ?? "this API key"}</span>@@ -178,8 +177,9 @@ export function ApiKeysTable() {return (<DataTable+ label="API keys"query={query}- search={<ListSearch placeholder="Search by name…" />}+ search={<ListSearch placeholder="Search API keys…" />}columns={columns((apiKey) => revoke.mutate({ id: apiKey.id }),revoke.isPending,diff --git a/apps/app/app/(app)/[slug]/settings/api-keys/create-api-key-sheet.tsx b/apps/app/app/(app)/[slug]/settings/api-keys/create-api-key-sheet.tsxindex 3d29ba2d..38f11ca9 100644--- a/apps/app/app/(app)/[slug]/settings/api-keys/create-api-key-sheet.tsx+++ b/apps/app/app/(app)/[slug]/settings/api-keys/create-api-key-sheet.tsx@@ -1,13 +1,19 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";import {Field,FieldDescription,- FieldGroup,+ FieldError,FieldLabel,} from "@crm/ui/components/field";+import {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ useFormSheetValidation,+} from "@crm/ui/components/form-sheet";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";import {@@ -18,19 +24,16 @@ import {SelectValue,} from "@crm/ui/components/select";import {- Sheet,- SheetClose,- SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,SheetTrigger,} from "@crm/ui/components/sheet";import { Spinner } from "@crm/ui/components/spinner";import { useMutation } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { parseAsBoolean, useQueryState } from "nuqs";-import { type ComponentProps, Suspense, useId, useState } from "react";+import { type ComponentProps, Suspense, useId, useRef, useState } from "react";import { toast } from "sonner";import { SEARCH_PARAM } from "@/lib/search-param-keys";import { useCrmCache } from "@/lib/trpc/cache";@@ -54,7 +57,7 @@ type CreatedApiKey = RouterOutputs["apiKeys"]["create"];function NewApiKeyButton(props: ComponentProps<typeof Button>) {return (<Button {...props}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New API key</Button>);@@ -69,11 +72,13 @@ export function CreateApiKeySheet() {}function CreateApiKeyForm() {+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();const nameId = useId();const expirationId = useId();+ const triggerRef = useRef<HTMLButtonElement>(null);const [open, setOpen] = useQueryState(SEARCH_PARAM.dialog.create,@@ -88,22 +93,33 @@ function CreateApiKeyForm() {onSuccess: async (apiKey) => {await cache.apiKeys();await setOpen(null);- setName("");- setExpiration("90");+ reset();setCreated(apiKey);},onError: (error) => toast.error(error.message),}),);+ const reset = () => {+ validation.reset();+ setName("");+ setExpiration("90");+ };+return (<>- <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>+ <FormSheet+ dirty={name !== "" || expiration !== "90"}+ pending={create.isPending}+ onDiscard={reset}+ open={open}+ onOpenChange={(next) => setOpen(next || null)}+ ><SheetTrigger asChild>- <NewApiKeyButton />+ <NewApiKeyButton ref={triggerRef} /></SheetTrigger>- <SheetContent side="right">+ <FormSheetContent side="right"><SheetHeader><SheetTitle>New API key</SheetTitle><SheetDescription>@@ -112,11 +128,13 @@ function CreateApiKeyForm() {</SheetDescription></SheetHeader>- <form+ <FormSheetForm+ noValidate+ onInput={validation.onInput}id={FORM}- className="flex-1 overflow-y-auto px-4"onSubmit={(event) => {event.preventDefault();+ if (!validation.validate(event.currentTarget)) return;create.mutate({name: name.trim(),expiresInDays:@@ -124,67 +142,70 @@ function CreateApiKeyForm() {});}}>- <FieldGroup>- <Field>- <FieldLabel htmlFor={nameId}>Name</FieldLabel>- <Input- id={nameId}- value={name}- onChange={(event) => setName(event.target.value)}- placeholder="CI pipeline"- maxLength={64}- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- required- />- <FieldDescription>- Something you will recognise later, like where it runs.- </FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={expirationId}>Expires</FieldLabel>- <Select- value={expiration}- onValueChange={(value) =>- setExpiration(value as ExpirationValue)- }- >- <SelectTrigger id={expirationId} className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {EXPIRATION_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>- </FieldGroup>- </form>-- <SheetFooter>- <Button- type="submit"- form={FORM}- disabled={!name.trim() || create.isPending}- >- {create.isPending ? <Spinner /> : null}+ <Field data-invalid={!!validation.errors[nameId]}>+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>+ <Input+ id={nameId}+ aria-invalid={!!validation.errors[nameId]}+ aria-describedby={+ validation.errors[nameId] ? `${nameId}-error` : undefined+ }+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder="CI pipeline"+ maxLength={64}+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${nameId}-error`}>+ {validation.errors[nameId]}+ </FieldError>+ <FieldDescription>+ Something you will recognise later, like where it runs.+ </FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[expirationId]}>+ <FieldLabel htmlFor={expirationId}>Expires</FieldLabel>+ <Select+ value={expiration}+ onValueChange={(value) =>+ setExpiration(value as ExpirationValue)+ }+ >+ <SelectTrigger id={expirationId} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EXPIRATION_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </FormSheetForm>++ <FormSheetFooter>+ <Button type="submit" form={FORM} disabled={create.isPending}>+ {create.isPending ? <Spinner data-icon="inline-start" /> : null}Create key</Button>- <SheetClose asChild>- <Button variant="outline">Cancel</Button>- </SheetClose>- </SheetFooter>- </SheetContent>- </Sheet>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet><CreatedApiKeyDialogapiKey={created}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ triggerRef.current?.focus();+ }}onOpenChange={(next) => {if (!next) setCreated(null);}}diff --git a/apps/app/app/(app)/[slug]/settings/api-keys/created-api-key-dialog.tsx b/apps/app/app/(app)/[slug]/settings/api-keys/created-api-key-dialog.tsxindex 1baa59c4..16632e61 100644--- a/apps/app/app/(app)/[slug]/settings/api-keys/created-api-key-dialog.tsx+++ b/apps/app/app/(app)/[slug]/settings/api-keys/created-api-key-dialog.tsx@@ -9,11 +9,13 @@ import {DialogHeader,DialogTitle,} from "@crm/ui/components/dialog";+import { useDiscardChanges } from "@crm/ui/components/discard-changes";import {InputGroup,InputGroupAddon,InputGroupInput,} from "@crm/ui/components/input-group";+import { type ComponentProps, useState } from "react";import type { RouterOutputs } from "@/lib/trpc/types";import { CopyValue } from "../copy-value";@@ -22,13 +24,41 @@ type CreatedApiKey = RouterOutputs["apiKeys"]["create"];export function CreatedApiKeyDialog({apiKey,onOpenChange,+ onCloseAutoFocus,}: {apiKey: CreatedApiKey | null;onOpenChange: (open: boolean) => void;+ onCloseAutoFocus?: ComponentProps<typeof DialogContent>["onCloseAutoFocus"];}) {+ const [copiedId, setCopiedId] = useState<string | null>(null);+ const guard = useDiscardChanges({+ open: apiKey !== null,+ dirty: apiKey !== null && copiedId !== apiKey.id,+ onOpenChange: (next) => {+ if (!next) setCopiedId(null);+ onOpenChange(next);+ },+ wording: {+ title: "Close without copying the key?",+ description:+ "This is the only time the key is shown. Copy it before you close.",+ confirmLabel: "Close anyway",+ keepLabel: "Go back to the key",+ },+ });+return (- <Dialog open={apiKey !== null} onOpenChange={onOpenChange}>- <DialogContent>+ <Dialog open={apiKey !== null} onOpenChange={guard.onOpenChange}>+ <DialogContent+ onPointerDownOutside={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => {+ if (apiKey !== null) {+ event.preventDefault();+ return;+ }+ onCloseAutoFocus?.(event);+ }}+ ><DialogHeader><DialogTitle>{apiKey?.name ?? "API key"} created</DialogTitle><DialogDescription>@@ -43,14 +73,19 @@ export function CreatedApiKeyDialog({className="font-mono"/><InputGroupAddon align="inline-end">- <CopyValue value={apiKey?.key ?? ""} label="API key" />+ <CopyValue+ value={apiKey?.key ?? ""}+ label="API key"+ onCopied={() => setCopiedId(apiKey?.id ?? null)}+ /></InputGroupAddon></InputGroup><DialogFooter>- <Button onClick={() => onOpenChange(false)}>Done</Button>+ <Button onClick={() => guard.onOpenChange(false)}>Done</Button></DialogFooter></DialogContent>+ {guard.dialog}</Dialog>);}diff --git a/apps/app/app/(app)/[slug]/settings/api-keys/page.tsx b/apps/app/app/(app)/[slug]/settings/api-keys/page.tsxindex 9503fda8..9ed386f2 100644--- a/apps/app/app/(app)/[slug]/settings/api-keys/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/api-keys/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -9,7 +7,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -25,13 +25,13 @@ export default function ApiKeysSettingsPage({searchParams,}: PageProps<"/[slug]/settings/api-keys">) {return (- <PageShell className="min-h-0">+ <PageShell width="narrow" className="min-h-0"><PageShellHeader><PageShellHeading><PageShellTitle>API Keys</PageShellTitle><PageShellDescription>- Personal keys for calling the CRM API. Each one acts as you —- anything it can read or change is exactly what you can.+ Personal keys for calling the CRM API. Each key has the same access+ as your account.</PageShellDescription></PageShellHeading>@@ -41,7 +41,7 @@ export default function ApiKeysSettingsPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><ApiKeys searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/settings/archive-retention.tsx b/apps/app/app/(app)/[slug]/settings/archive-retention.tsxindex d43eef32..17fe3dba 100644--- a/apps/app/app/(app)/[slug]/settings/archive-retention.tsx+++ b/apps/app/app/(app)/[slug]/settings/archive-retention.tsx@@ -1,24 +1,12 @@"use client";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,-} from "@crm/ui/components/field";+import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";-import { useEffect, useId, useState } from "react";+import { useId, useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -27,18 +15,15 @@ export function ArchiveRetention() {const trpc = useTRPC();const cache = useCrmCache();const daysId = useId();- const [draft, setDraft] = useState("");+ const [draft, setDraft] = useState<string | null>(null);const retention = useQuery(trpc.settings.archiveRetention.queryOptions());- useEffect(() => {- if (retention.data) setDraft(String(retention.data.days));- }, [retention.data]);-const save = useMutation(trpc.settings.setArchiveRetention.mutationOptions({onSuccess: async () => {await cache.settings();+ setDraft(null);toast.success("Archive retention saved.");},onError: (error) => toast.error(error.message),@@ -47,63 +32,55 @@ export function ArchiveRetention() {if (!retention.data) return null;- const days = Number.parseInt(draft, 10);+ const value = draft ?? String(retention.data.days);+ const days = Number.parseInt(value, 10);const unchanged = days === retention.data.days;return (- <Card>- <CardHeader>- <CardTitle>Archived records</CardTitle>- <CardDescription>- Deleted records are archived and hidden, then pruned for good.- </CardDescription>-- <CardAction>- <Button- type="submit"- form="archive-retention"- disabled={- save.isPending ||- unchanged ||- draft.trim() === "" ||- !Number.isFinite(days)- }- >- {save.isPending ? <Spinner data-icon="inline-start" /> : null}- Save- </Button>- </CardAction>- </CardHeader>-- <CardContent>- <form- id="archive-retention"- onSubmit={(event) => {- event.preventDefault();- if (!Number.isFinite(days)) {- toast.error("Enter a number of days.");- return;- }- save.mutate({ days });- }}+ <SettingsCard+ title="Archived records"+ description="Deleted records are archived and hidden, then pruned for good."+ hint="Days. 180 is the default."+ action={+ <Button+ type="submit"+ form="archive-retention"+ size="sm"+ disabled={+ save.isPending ||+ unchanged ||+ value.trim() === "" ||+ !Number.isFinite(days)+ }>- <FieldGroup>- <Field>- <FieldLabel htmlFor={daysId}>- Prune archived records after- </FieldLabel>- <Input- id={daysId}- inputMode="numeric"- value={draft}- disabled={save.isPending}- onChange={(event) => setDraft(event.target.value)}- />- <FieldDescription>Days. 180 is the default.</FieldDescription>- </Field>- </FieldGroup>- </form>- </CardContent>- </Card>+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ Save+ </Button>+ }+ control="compact"+ >+ <form+ id="archive-retention"+ onSubmit={(event) => {+ event.preventDefault();+ if (!Number.isFinite(days)) {+ toast.error("Enter a number of days.");+ return;+ }+ save.mutate({ days });+ }}+ >+ <Field>+ <FieldLabel htmlFor={daysId}>Prune archived records after</FieldLabel>+ <Input+ id={daysId}+ inputMode="numeric"+ value={value}+ disabled={save.isPending}+ onChange={(event) => setDraft(event.target.value)}+ />+ </Field>+ </form>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/connections/connection-page.tsx b/apps/app/app/(app)/[slug]/settings/connections/connection-page.tsxindex c6114d51..996ba64e 100644--- a/apps/app/app/(app)/[slug]/settings/connections/connection-page.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/connection-page.tsx@@ -1,4 +1,4 @@-import { Spinner } from "@crm/ui/components/spinner";+import { PageShell, PageShellFallback } from "@crm/ui/components/page-shell";import { cn } from "@crm/ui/lib/utils";export function ConnectionPage({@@ -11,24 +11,15 @@ export function ConnectionPage({children: React.ReactNode;}) {return (- <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto px-(--spacing-page-inline) pt-(--spacing-page-top) pb-(--spacing-page-bottom)">- <div- className={cn(- "mx-auto flex w-full max-w-(--container-page) flex-col gap-(--spacing-page-gap)",- centered && "flex-1 justify-center",- className,- )}- >- {children}- </div>- </main>+ <PageShell+ width="narrow"+ className={cn(centered && "justify-center", className)}+ >+ {children}+ </PageShell>);}export function ConnectionPageLoading() {- return (- <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center">- <Spinner size="lg" />- </main>- );+ return <PageShellFallback width="narrow" shape="settings" />;}diff --git a/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsxindex 20f3fca8..c9b3dc61 100644--- a/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx@@ -1,7 +1,5 @@"use client";-import Launch from "@carbon/icons-react/es/Launch";-import Warning from "@carbon/icons-react/es/Warning";import { authClient } from "@crm/auth/client";import { SYNC_SCOPES } from "@crm/auth/scopes";import {@@ -23,22 +21,20 @@ import {} from "@crm/ui/components/alert-dialog";import GoogleLogo from "@crm/ui/components/brand-logos/google";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";import { Icon } from "@crm/ui/components/icon";-import { Label } from "@crm/ui/components/label";+import {+ PageShellDescription,+ PageShellHeader,+ PageShellHeading,+ PageShellTitle,+} from "@crm/ui/components/page-shell";+import { SettingRow, SettingRows } from "@crm/ui/components/setting-rows";+import { SettingsCard, SettingsColumn } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import Link from "next/link";+import { CircleAlertIcon, ExternalLinkIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { LocalRelativeTime } from "@/components/local-date-time";@@ -104,28 +100,35 @@ function failureSignature(return failures.sort().join("|");}+function GoogleHeader() {+ return (+ <PageShellHeader>+ <PageShellHeading>+ <PageShellTitle>Google</PageShellTitle>+ <PageShellDescription>+ Read-only Gmail and Calendar. Only conversations with companies in the+ CRM are stored.+ </PageShellDescription>+ </PageShellHeading>+ </PageShellHeader>+ );+}+function GoogleUnavailable() {return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- <StatusIndicator size="sm" tone="neutral" label="Not configured" />- </div>- </CardTitle>- <CardDescription>- Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in the root .env file- and restart.- </CardDescription>- </CardHeader>- </Card>+ <SettingsCard+ title="Connection"+ status={+ <StatusIndicator size="sm" tone="neutral" label="Not configured" />+ }+ description="Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in the root .env file and restart."+ />);}const CONNECT_ERRORS = new Map([[- "email_doesn't_match",+ "email_does_not_match","That Google account has a different email address to the one you sign in with, so it cannot be attached to your account. Connect the Google account that matches your sign-in address.",],]);@@ -160,51 +163,41 @@ function ConnectGoogle({}return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- <StatusIndicator size="sm" tone="neutral" label="Not connected" />- </div>- </CardTitle>- <CardDescription>- Read-only Gmail and Calendar. Only conversations with companies in the- CRM are stored.- </CardDescription>-- <CardAction>- <Button- size="sm"- disabled={pending}- onClick={() => {- handleConnect().catch(() => fail());- }}- type="button"- >- {pending ? (- <Spinner data-icon="inline-start" />- ) : (- <GoogleLogo data-icon="inline-start" className="size-4" />- )}- Connect- </Button>- </CardAction>- </CardHeader>-+ <SettingsCard+ title="Connection"+ status={+ <StatusIndicator size="sm" tone="neutral" label="Not connected" />+ }+ description="Connect the Google account you sign in with."+ action={+ <Button+ size="sm"+ disabled={pending}+ onClick={() => {+ handleConnect().catch(() => fail());+ }}+ type="button"+ >+ {pending ? (+ <Spinner data-icon="inline-start" />+ ) : (+ <GoogleLogo data-icon="inline-start" className="size-4" />+ )}+ Connect+ </Button>+ }+ >{connectError ? (- <CardContent>- <Alert variant="destructive">- <Icon icon={Warning} />- <AlertTitle>Google did not finish connecting</AlertTitle>- <AlertDescription>- {CONNECT_ERRORS.get(connectError) ??- "Google returned an error before the connection was made. Try again."}- </AlertDescription>- </Alert>- </CardContent>+ <Alert variant="destructive">+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>Google did not finish connecting</AlertTitle>+ <AlertDescription>+ {CONNECT_ERRORS.get(connectError) ??+ "Google returned an error before the connection was made. Try again."}+ </AlertDescription>+ </Alert>) : null}- </Card>+ </SettingsCard>);}@@ -273,13 +266,27 @@ export function GoogleConnection({}),);- if (!status.data) return null;+ if (!status.data) return <GoogleHeader />;const { sources, hasRefreshToken, configured, linked, required } =status.data;- if (!configured) return <GoogleUnavailable />;- if (!linked) return <ConnectGoogle slug={slug} connectError={connectError} />;+ if (!configured) {+ return (+ <>+ <GoogleHeader />+ <GoogleUnavailable />+ </>+ );+ }+ if (!linked) {+ return (+ <>+ <GoogleHeader />+ <ConnectGoogle slug={slug} connectError={connectError} />+ </>+ );+ }const failing = sources.filter((source) => source.status === "NEEDS_RECONNECT" || source.lastError,@@ -293,131 +300,145 @@ export function GoogleConnection({const healthy = failing.length === 0 && hasRefreshToken;return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">+ <>+ <GoogleHeader />+ <SettingsColumn>+ <SettingsCard+ title="Connection"+ status={<StatusIndicatorsize="sm"tone={healthy ? "success" : "warning"}label={healthy ? "Connected" : "Needs attention"}/>- </div>- </CardTitle>- <CardDescription>- Meetings and email threads land on the matching company as they- happen.- </CardDescription>-- <CardAction>- <Button- variant="contrast"- size="sm"- disabled={syncNow.isPending}- onClick={() => syncNow.mutate()}- >- {syncNow.isPending ? "Checking…" : "Check now"}- </Button>- </CardAction>- </CardHeader>-- <CardContent>- {!hasRefreshToken ? (- <Alert variant="destructive" attention={insistence}>- <Icon icon={Warning} />- <AlertTitle>Google did not return a refresh token</AlertTitle>- <AlertDescription>Sign out and back in.</AlertDescription>- </Alert>- ) : failing.length > 0 ? (- failing.map((source) => {- const { summary, url } = explain(- source.lastError ?? "Google needs reconnecting.",- );-- return (- <Alert- key={source.source}- variant="destructive"- attention={insistence}- >- <Icon icon={Warning} />- <AlertTitle>- {SOURCES[source.source].label} sync failed- </AlertTitle>- <AlertDescription>{summary}</AlertDescription>-- {url ? (- <AlertAction>- <Button variant="contrast" size="xs" asChild>- <a href={url} target="_blank" rel="noreferrer">- Resolve- <Icon icon={Launch} data-icon="inline-end" />- </a>- </Button>- </AlertAction>- ) : null}- </Alert>- );- })- ) : (- <p className="text-muted-foreground text-xs">- {lastSyncedAt ? (+ }+ description="Meetings and email threads land on the matching company as they happen."+ hint={+ lastSyncedAt ? (<>Last checked <LocalRelativeTime date={lastSyncedAt} /></>) : ("Waiting for the first check"- )}- </p>- )}-- {sources.map((source) => {- const copy = SOURCES[source.source];-- return (- <div- key={source.source}- className="flex items-center justify-between gap-6"+ )+ }+ action={+ <Button+ variant="outline"+ size="sm"+ disabled={syncNow.isPending}+ onClick={() => syncNow.mutate()}>- <Label- htmlFor={`auto-create-${source.source}`}- className="flex flex-col items-start gap-1"- >- <span className="text-sm">{copy.label}</span>- <span className="font-normal text-muted-foreground text-xs">- {copy.autoCreate}- </span>- </Label>-- <Switch- id={`auto-create-${source.source}`}- checked={source.autoCreate}- disabled={setAutoCreate.isPending}- onCheckedChange={(enabled) =>- setAutoCreate.mutate({ source: source.source, enabled })- }- />+ {syncNow.isPending ? "Checking…" : "Check now"}+ </Button>+ }+ >+ {!hasRefreshToken ? (+ <Alert variant="destructive" attention={insistence}>+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>Google did not return a refresh token</AlertTitle>+ <AlertDescription>Sign out and back in.</AlertDescription>+ </Alert>+ ) : failing.length > 0 ? (+ <div className="flex flex-col gap-3">+ {failing.map((source) => {+ const { summary, url } = explain(+ source.lastError ?? "Google needs reconnecting.",+ );++ return (+ <Alert+ key={source.source}+ variant="destructive"+ attention={insistence}+ >+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>+ {SOURCES[source.source].label} sync failed+ </AlertTitle>+ <AlertDescription>{summary}</AlertDescription>++ {url ? (+ <AlertAction>+ <Button variant="contrast" size="xs" asChild>+ <a href={url} target="_blank" rel="noreferrer">+ Resolve+ <Icon+ icon={ExternalLinkIcon}+ data-icon="inline-end"+ />+ </a>+ </Button>+ </AlertAction>+ ) : null}+ </Alert>+ );+ })}</div>- );- })}-- <CardFooter>- <div className="-ml-2 flex flex-wrap items-center gap-1 text-muted-foreground">+ ) : null}+ </SettingsCard>++ <SettingsCard+ title="New companies and contacts"+ description="Add them to the CRM when someone new shows up in a synced source."+ hint="Changes save as you make them."+ >+ <SettingRows>+ {sources.map((source) => {+ const copy = SOURCES[source.source];++ return (+ <SettingRow+ key={source.source}+ title={copy.label}+ description={copy.autoCreate}+ control={(id, describedBy) => (+ <Switch+ id={id}+ aria-describedby={describedBy}+ checked={source.autoCreate}+ disabled={setAutoCreate.isPending}+ onCheckedChange={(enabled) =>+ setAutoCreate.mutate({+ source: source.source,+ enabled,+ })+ }+ />+ )}+ />+ );+ })}+ </SettingRows>+ </SettingsCard>++ <SettingsCard+ title="Google access"+ description="Stop new email and meetings from arriving."+ hint={+ <a+ href="https://myaccount.google.com/permissions"+ target="_blank"+ rel="noreferrer"+ >+ Manage in your Google account+ </a>+ }+ action={<AlertDialog><AlertDialogTrigger asChild>- <Button variant="ghost" size="xs" disabled={purge.isPending}>- Delete synced data+ <Button variant="outline" size="sm" disabled={revoke.isPending}>+ Revoke access</Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Delete synced data?</AlertDialogTitle>+ <AlertDialogTitle>Revoke Google access?</AlertDialogTitle><AlertDialogDescription>- Every email and meeting brought in from Google is removed- from the CRM. The next check starts from now, so nothing- deleted here comes back.+ {required+ ? "You will be signed out, and you cannot use the CRM again until you grant access."+ : "New email and meetings stop arriving. Everything already synced stays, and you can connect Google again from this page."}</AlertDialogDescription></AlertDialogHeader>@@ -425,28 +446,40 @@ export function GoogleConnection({<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActionvariant="destructive"- onClick={() => purge.mutate()}+ onClick={() => revoke.mutate()}>- Delete+ Revoke</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>-+ }+ />++ <SettingsCard+ tone="destructive"+ title="Delete synced data"+ description="Remove every email and meeting brought in from Google."+ hint="This can't be undone."+ action={<AlertDialog><AlertDialogTrigger asChild>- <Button variant="ghost" size="xs" disabled={revoke.isPending}>- Revoke Google access+ <Button+ variant="destructive"+ size="sm"+ disabled={purge.isPending}+ >+ Delete synced data</Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Revoke Google access?</AlertDialogTitle>+ <AlertDialogTitle>Delete synced data?</AlertDialogTitle><AlertDialogDescription>- {required- ? "You will be signed out, and you cannot use the CRM again until you grant access."- : "New email and meetings stop arriving. Everything already synced stays, and you can connect Google again from this page."}+ Every email and meeting brought in from Google is removed+ from the CRM. The next check starts from now, so nothing+ deleted here comes back.</AlertDialogDescription></AlertDialogHeader>@@ -454,26 +487,16 @@ export function GoogleConnection({<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActionvariant="destructive"- onClick={() => revoke.mutate()}+ onClick={() => purge.mutate()}>- Revoke+ Delete</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>-- <Button variant="ghost" size="xs" asChild>- <Link- href="https://myaccount.google.com/permissions"- target="_blank"- rel="noreferrer"- >- Manage in your Google account- </Link>- </Button>- </div>- </CardFooter>- </CardContent>- </Card>+ }+ />+ </SettingsColumn>+ </>);}diff --git a/apps/app/app/(app)/[slug]/settings/connections/mcp-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/mcp-connection.tsxindex 0804da1e..d893785f 100644--- a/apps/app/app/(app)/[slug]/settings/connections/mcp-connection.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/mcp-connection.tsx@@ -1,7 +1,5 @@"use client";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import Warning from "@carbon/icons-react/es/Warning";import {Accordion,AccordionContent,@@ -22,19 +20,12 @@ import {import { Badge } from "@crm/ui/components/badge";import { Button } from "@crm/ui/components/button";import {- Card,- CardAction,- CardContent,- CardDescription,- CardFooter,- CardHeader,CardPanel,CardPanelDetail,CardPanelGroup,CardPanelGroupContent,CardPanelGroupHeader,CardPanelScroll,- CardTitle,CardToolbar,} from "@crm/ui/components/card";import { CodeBlock } from "@crm/ui/components/code-block";@@ -45,18 +36,29 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@crm/ui/components/dropdown-menu";+import { FieldLegend, FieldSet } from "@crm/ui/components/field";import { Icon } from "@crm/ui/components/icon";import { InlineReferenceText } from "@crm/ui/components/inline-reference-text";+import { PageSection } from "@crm/ui/components/page-section";+import {+ PageShellActions,+ PageShellDescription,+ PageShellHeader,+ PageShellHeading,+ PageShellTitle,+} from "@crm/ui/components/page-shell";import { ProviderMark } from "@crm/ui/components/provider-mark";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";import type { ProviderBrand } from "@crm/ui/lib/provider-brand";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { CircleAlertIcon, EllipsisVerticalIcon } from "lucide-react";import Link from "next/link";import { useRouter } from "next/navigation";-import { useState } from "react";+import { useId, useState } from "react";import { toast } from "sonner";import { MCP_CONNECTION_STATUS } from "@/lib/mcp-connection-status";import { useTRPC } from "@/lib/trpc/client";@@ -157,6 +159,7 @@ export function McpConnection({);const [confirmingDisconnect, setConfirmingDisconnect] = useState(false);const [toolFilter, setToolFilter] = useState<ToolFilter>("all");+ const accessLegendId = useId();const start = useMutation(trpc.mcp.start.mutationOptions({onSuccess: ({ authorizationUrl }) => {@@ -201,48 +204,50 @@ export function McpConnection({return (<ConnectionPage centered={!connected}>{connecting ? <ConnectionPendingRefresh /> : null}- <div className="flex items-start justify-between gap-4">- <div className="flex min-w-0 flex-col gap-2">- <Button asChild variant="link" size="inline">- <Link href={`/${slug}/settings/connections`}>- Back to connections- </Link>- </Button>- <h1 className="flex items-center gap-3 font-medium text-2xl tracking-tight">- <ProviderMark- slug={entry.slug}- name={entry.name}- brand={brand}- className="size-6"- />- {entry.name}- </h1>- <p className="text-muted-foreground text-sm">- Deployed agents receive only reviewed tools.- </p>- </div>- {connected && canManage ? (- <div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-sm">- <Icon icon={OverflowMenuVertical} />- <span className="sr-only">More {entry.name} actions</span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuGroup>- <DropdownMenuItem- variant="destructive"- onSelect={() => setConfirmingDisconnect(true)}- >- Disconnect {entry.name}- </DropdownMenuItem>- </DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenu>- </div>- ) : null}+ <div className="flex flex-col gap-2">+ <Button asChild variant="link" size="inline" className="self-start">+ <Link href={`/${slug}/settings/connections`}>+ Back to connections+ </Link>+ </Button>+ <PageShellHeader>+ <PageShellHeading>+ <PageShellTitle className="flex items-center gap-3">+ <ProviderMark+ slug={entry.slug}+ name={entry.name}+ brand={brand}+ className="size-6"+ />+ {entry.name}+ </PageShellTitle>+ <PageShellDescription>+ Deployed agents receive only reviewed tools.+ </PageShellDescription>+ </PageShellHeading>+ {connected && canManage ? (+ <PageShellActions>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-sm">+ <Icon icon={EllipsisVerticalIcon} />+ <span className="sr-only">More {entry.name} actions</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuGroup>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirmingDisconnect(true)}+ >+ Disconnect {entry.name}+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ </PageShellActions>+ ) : null}+ </PageShellHeader></div>{presentation.overview ? (@@ -250,121 +255,127 @@ export function McpConnection({) : null}{connecting ? (- <Card>- <CardContent>+ <SettingsCard+ title="Access"+ status={<StatusIndicatorbusy+ size="sm"tone="primary"label={`Connecting to ${entry.name}`}/>- </CardContent>- </Card>+ }+ description={`Waiting for ${entry.name} to confirm the connection.`}+ />) : null}{!connected && !connecting ? (- <Card>- <CardHeader>- <CardTitle>Access</CardTitle>- <CardDescription>- Choose what deployed agents can do.- </CardDescription>- </CardHeader>-- {!configured ? (- <CardContent>- <Alert>- <Icon icon={Warning} />- <AlertTitle>MCP connections are not configured</AlertTitle>- <AlertDescription>- Set MCP_ENCRYPTION_KEY in the root .env file. Then restart the- API.- </AlertDescription>- </Alert>- </CardContent>- ) : null}-- {connection?.status === "error" ? (- <CardContent>- <Alert variant="destructive">- <Icon icon={Warning} />- <AlertTitle>{entry.name} needs authorization</AlertTitle>- <AlertDescription>- Reconnect {entry.name}. The stored access is no longer usable.- </AlertDescription>- </Alert>- </CardContent>- ) : null}-- {!connected && configured && canManage ? (- <CardContent>- <p className="font-medium text-sm">- What can agents do in {entry.name}?- </p>- <ToggleGroup- type="single"- variant="outline"- spacing={0}- value={mode}- onValueChange={(value) => {- if (value === "read_only" || value === "read_write")- setMode(value);- }}- >- <ToggleGroupItem value="read_only">Read only</ToggleGroupItem>- <ToggleGroupItem value="read_write">- Read and write- </ToggleGroupItem>- </ToggleGroup>- <p className="text-muted-foreground text-sm">- {mode === "read_only"- ? `Agents read ${entry.name} and change nothing.`- : `Agents read ${entry.name} and make approved changes.`}- </p>- </CardContent>- ) : null}-- <CardFooter align="end" divider="none">- {!connected && configured && canManage ? (- <Button disabled={start.isPending} onClick={connect}>+ <SettingsCard+ title="Access"+ description="Choose what deployed agents can do."+ hint={+ configured && canManage+ ? mode === "read_only"+ ? `Agents read ${entry.name} and change nothing.`+ : `Agents read ${entry.name} and make approved changes.`+ : configured+ ? `Only an owner or an admin can connect ${entry.name}.`+ : undefined+ }+ action={+ configured && canManage ? (+ <Button size="sm" disabled={start.isPending} onClick={connect}>{start.isPending ? <Spinner data-icon="inline-start" /> : null}Continue to {entry.name}</Button>- ) : null}- </CardFooter>- </Card>+ ) : undefined+ }+ >+ {!configured ||+ connection?.status === "error" ||+ (configured && canManage) ? (+ <div className="flex flex-col gap-4">+ {!configured ? (+ <Alert>+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>MCP connections are not configured</AlertTitle>+ <AlertDescription>+ Set MCP_ENCRYPTION_KEY in the root .env file. Then restart+ the API.+ </AlertDescription>+ </Alert>+ ) : null}++ {connection?.status === "error" ? (+ <Alert variant="destructive">+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>{entry.name} needs authorization</AlertTitle>+ <AlertDescription>+ Reconnect {entry.name}. The stored access is no longer+ usable.+ </AlertDescription>+ </Alert>+ ) : null}++ {configured && canManage ? (+ <FieldSet>+ <FieldLegend id={accessLegendId} variant="label">+ What can agents do in {entry.name}?+ </FieldLegend>+ <ToggleGroup+ aria-labelledby={accessLegendId}+ type="single"+ variant="outline"+ spacing={0}+ value={mode}+ onValueChange={(value) => {+ if (value === "read_only" || value === "read_write")+ setMode(value);+ }}+ >+ <ToggleGroupItem value="read_only">+ Read only+ </ToggleGroupItem>+ <ToggleGroupItem value="read_write">+ Read and write+ </ToggleGroupItem>+ </ToggleGroup>+ </FieldSet>+ ) : null}+ </div>+ ) : null}+ </SettingsCard>) : null}{connected ? (- <Card>- <CardHeader>- <CardTitle>Tool access</CardTitle>- <CardDescription>- {presentation.pendingReviewCount > 0- ? `${presentation.pendingReviewCount} tools need review. Open a tool to inspect it.`- : "All tools are reviewed. Open a tool to inspect it."}- </CardDescription>- {presentation.pendingReadTools.length > 0 && canManage ? (- <CardAction>- <Button- size="sm"- disabled={review.isPending}- onClick={() =>- review.mutate({- platformSlug: entry.slug,- tools: presentation.pendingReadTools,- })- }- >- {review.isPending ? (- <Spinner data-icon="inline-start" />- ) : null}- Review {presentation.pendingReadTools.length} read tools- </Button>- </CardAction>- ) : null}- </CardHeader>+ <PageSection+ title="Tool access"+ description={+ presentation.pendingReviewCount > 0+ ? `${presentation.pendingReviewCount} tools need review. Open a tool to inspect it.`+ : "All tools are reviewed. Open a tool to inspect it."+ }+ action={+ presentation.pendingReadTools.length > 0 && canManage ? (+ <Button+ size="sm"+ disabled={review.isPending}+ onClick={() =>+ review.mutate({+ platformSlug: entry.slug,+ tools: presentation.pendingReadTools,+ })+ }+ >+ {review.isPending ? <Spinner data-icon="inline-start" /> : null}+ Review {presentation.pendingReadTools.length} read tools+ </Button>+ ) : undefined+ }+ ><CardToolbar><ToggleGroup+ aria-label={`Filter ${entry.name} tools`}type="single"variant="outline"size="sm"@@ -473,7 +484,7 @@ export function McpConnection({))}</CardPanelScroll></CardPanel>- </Card>+ </PageSection>) : null}<AlertDialog@@ -535,7 +546,7 @@ function ConnectionDetails({<>{overview.failure ? (<Alert variant="destructive">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>{overview.failure.title}</AlertTitle><AlertDescription><Badge variant="mono">{overview.failure.code}</Badge>@@ -543,15 +554,14 @@ function ConnectionDetails({</Alert>) : null}{overview.scopeGroups.length > 0 ? (- <Card>- <CardHeader>- <CardTitle>Permissions</CardTitle>- <CardAction>- <span className="text-muted-foreground text-xs tabular-nums">- {overview.scopeCount} scopes- </span>- </CardAction>- </CardHeader>+ <PageSection+ title="Permissions"+ action={+ <span className="text-muted-foreground text-sm tabular-nums">+ {overview.scopeCount} scopes+ </span>+ }+ ><CardPanelrole="region"aria-label="Granted permissions"@@ -590,37 +600,32 @@ function ConnectionDetails({</CardPanelGroupContent></CardPanelScroll></CardPanel>- </Card>+ </PageSection>) : null}{overview.agents.length > 0 ? (- <Card>- <CardHeader>- <CardTitle>Used by</CardTitle>- </CardHeader>- <CardContent>- <div className="flex flex-col divide-y rounded-md border">- {overview.agents.map((agent) => (- <Link- className="flex items-center gap-3 px-3 py-2.5 hover:bg-muted/50"- href={`/${slug}/agents/${agent.id}`}- key={agent.id}- >- <span className="min-w-0 flex-1">- <span className="block truncate font-medium text-xs">- {agent.name}- </span>- {agent.description ? (- <span className="block truncate text-muted-foreground text-xs">- {agent.description}- </span>- ) : null}+ <PageSection title="Used by">+ <div className="flex flex-col divide-y rounded-md shadow-border">+ {overview.agents.map((agent) => (+ <Link+ className="flex items-center gap-3 px-4 py-3 outline-none hover:bg-muted/50 focus-visible:shadow-focus"+ href={`/${slug}/agents/${agent.id}`}+ key={agent.id}+ >+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium text-sm">+ {agent.name}</span>- <Badge variant="outline">{agent.statusLabel}</Badge>- </Link>- ))}- </div>- </CardContent>- </Card>+ {agent.description ? (+ <span className="block truncate text-13 text-muted-foreground">+ {agent.description}+ </span>+ ) : null}+ </span>+ <Badge variant="outline">{agent.statusLabel}</Badge>+ </Link>+ ))}+ </div>+ </PageSection>) : null}</>);diff --git a/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsxindex 6be4afa5..3513bd1d 100644--- a/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/microsoft-connection.tsx@@ -1,6 +1,5 @@"use client";-import Warning from "@carbon/icons-react/es/Warning";import { authClient } from "@crm/auth/client";import { MICROSOFT_SYNC_SCOPES } from "@crm/auth/scopes";import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";@@ -17,22 +16,20 @@ import {} from "@crm/ui/components/alert-dialog";import MicrosoftLogo from "@crm/ui/components/brand-logos/microsoft";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";import { Icon } from "@crm/ui/components/icon";-import { Label } from "@crm/ui/components/label";+import {+ PageShellDescription,+ PageShellHeader,+ PageShellHeading,+ PageShellTitle,+} from "@crm/ui/components/page-shell";+import { SettingRow, SettingRows } from "@crm/ui/components/setting-rows";+import { SettingsCard, SettingsColumn } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery } from "@tanstack/react-query";-import Link from "next/link";+import { CircleAlertIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { LocalRelativeTime } from "@/components/local-date-time";@@ -44,27 +41,34 @@ const AUTO_CREATE = "Add the company and contact when you reply to someone new";const CONNECT_ERRORS = new Map([[- "email_doesn't_match",+ "email_does_not_match","That Microsoft account has a different email address to the one you sign in with, so it cannot be attached to your account. Connect the Microsoft account that matches your sign-in address.",],]);+function MicrosoftHeader() {+ return (+ <PageShellHeader>+ <PageShellHeading>+ <PageShellTitle>Microsoft</PageShellTitle>+ <PageShellDescription>+ Read-only Outlook mail. Only conversations with companies in the CRM+ are stored.+ </PageShellDescription>+ </PageShellHeading>+ </PageShellHeader>+ );+}+function MicrosoftUnavailable() {return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- Microsoft- <StatusIndicator size="sm" tone="neutral" label="Not configured" />- </div>- </CardTitle>- <CardDescription>- Set MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET in the root .env- file and restart.- </CardDescription>- </CardHeader>- </Card>+ <SettingsCard+ title="Connection"+ status={+ <StatusIndicator size="sm" tone="neutral" label="Not configured" />+ }+ description="Set MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET in the root .env file and restart."+ />);}@@ -98,51 +102,41 @@ function ConnectMicrosoft({}return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- Microsoft- <StatusIndicator size="sm" tone="neutral" label="Not connected" />- </div>- </CardTitle>- <CardDescription>- Read-only Outlook mail. Only conversations with companies in the CRM- are stored.- </CardDescription>-- <CardAction>- <Button- size="sm"- disabled={pending}- onClick={() => {- handleConnect().catch(() => fail());- }}- type="button"- >- {pending ? (- <Spinner data-icon="inline-start" />- ) : (- <MicrosoftLogo data-icon="inline-start" className="size-4" />- )}- Connect- </Button>- </CardAction>- </CardHeader>-+ <SettingsCard+ title="Connection"+ status={+ <StatusIndicator size="sm" tone="neutral" label="Not connected" />+ }+ description="Connect the Microsoft account you sign in with."+ action={+ <Button+ size="sm"+ disabled={pending}+ onClick={() => {+ handleConnect().catch(() => fail());+ }}+ type="button"+ >+ {pending ? (+ <Spinner data-icon="inline-start" />+ ) : (+ <MicrosoftLogo data-icon="inline-start" className="size-4" />+ )}+ Connect+ </Button>+ }+ >{connectError ? (- <CardContent>- <Alert variant="destructive">- <Icon icon={Warning} />- <AlertTitle>Microsoft did not finish connecting</AlertTitle>- <AlertDescription>- {CONNECT_ERRORS.get(connectError) ??- "Microsoft returned an error before the connection was made. Try again."}- </AlertDescription>- </Alert>- </CardContent>+ <Alert variant="destructive">+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>Microsoft did not finish connecting</AlertTitle>+ <AlertDescription>+ {CONNECT_ERRORS.get(connectError) ??+ "Microsoft returned an error before the connection was made. Try again."}+ </AlertDescription>+ </Alert>) : null}- </Card>+ </SettingsCard>);}@@ -198,14 +192,26 @@ export function MicrosoftConnection({}),);- if (!status.data) return null;+ if (!status.data) return <MicrosoftHeader />;const { sources, hasRefreshToken, configured, linked, required } =status.data;- if (!configured) return <MicrosoftUnavailable />;+ if (!configured) {+ return (+ <>+ <MicrosoftHeader />+ <MicrosoftUnavailable />+ </>+ );+ }if (!linked) {- return <ConnectMicrosoft slug={slug} connectError={connectError} />;+ return (+ <>+ <MicrosoftHeader />+ <ConnectMicrosoft slug={slug} connectError={connectError} />+ </>+ );}const failing = sources.filter(@@ -220,105 +226,116 @@ export function MicrosoftConnection({const healthy = failing.length === 0 && hasRefreshToken;return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- Microsoft+ <>+ <MicrosoftHeader />+ <SettingsColumn>+ <SettingsCard+ title="Connection"+ status={<StatusIndicatorsize="sm"tone={healthy ? "success" : "warning"}label={healthy ? "Connected" : "Needs attention"}/>- </div>- </CardTitle>- <CardDescription>- Email threads land on the matching company as they happen.- </CardDescription>-- <CardAction>- <Button- variant="contrast"- size="sm"- disabled={syncNow.isPending}- onClick={() => syncNow.mutate()}- >- {syncNow.isPending ? "Checking…" : "Check now"}- </Button>- </CardAction>- </CardHeader>-- <CardContent>- {!hasRefreshToken ? (- <Alert variant="destructive">- <Icon icon={Warning} />- <AlertTitle>Microsoft did not return a refresh token</AlertTitle>- <AlertDescription>Sign out and back in.</AlertDescription>- </Alert>- ) : failing.length > 0 ? (- failing.map((source) => (- <Alert key={source.source} variant="destructive">- <Icon icon={Warning} />- <AlertTitle>Email sync failed</AlertTitle>- <AlertDescription>- {source.lastError ?? "Microsoft needs reconnecting."}- </AlertDescription>- </Alert>- ))- ) : (- <p className="text-muted-foreground text-xs">- {lastSyncedAt ? (+ }+ description="Email threads land on the matching company as they happen."+ hint={+ lastSyncedAt ? (<>Last checked <LocalRelativeTime date={lastSyncedAt} /></>) : ("Waiting for the first check"- )}- </p>- )}-- {sources.map((source) => (- <div- key={source.source}- className="flex items-center justify-between gap-6"- >- <Label- htmlFor={`auto-create-${source.source}`}- className="flex flex-col items-start gap-1"+ )+ }+ action={+ <Button+ variant="outline"+ size="sm"+ disabled={syncNow.isPending}+ onClick={() => syncNow.mutate()}>- <span className="text-sm">Email</span>- <span className="font-normal text-muted-foreground text-xs">- {AUTO_CREATE}- </span>- </Label>-- <Switch- id={`auto-create-${source.source}`}- checked={source.autoCreate}- disabled={setAutoCreate.isPending}- onCheckedChange={(enabled) =>- setAutoCreate.mutate({ source: source.source, enabled })- }- />- </div>- ))}-- <CardFooter>- <div className="-ml-2 flex flex-wrap items-center gap-1 text-muted-foreground">+ {syncNow.isPending ? "Checking…" : "Check now"}+ </Button>+ }+ >+ {!hasRefreshToken ? (+ <Alert variant="destructive">+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>Microsoft did not return a refresh token</AlertTitle>+ <AlertDescription>Sign out and back in.</AlertDescription>+ </Alert>+ ) : failing.length > 0 ? (+ <div className="flex flex-col gap-3">+ {failing.map((source) => (+ <Alert key={source.source} variant="destructive">+ <Icon icon={CircleAlertIcon} />+ <AlertTitle>Email sync failed</AlertTitle>+ <AlertDescription>+ {source.lastError ?? "Microsoft needs reconnecting."}+ </AlertDescription>+ </Alert>+ ))}+ </div>+ ) : null}+ </SettingsCard>++ <SettingsCard+ title="New companies and contacts"+ description="Add them to the CRM when someone new shows up in a synced source."+ hint="Changes save as you make them."+ >+ <SettingRows>+ {sources.map((source) => (+ <SettingRow+ key={source.source}+ title="Email"+ description={AUTO_CREATE}+ control={(id, describedBy) => (+ <Switch+ id={id}+ aria-describedby={describedBy}+ checked={source.autoCreate}+ disabled={setAutoCreate.isPending}+ onCheckedChange={(enabled) =>+ setAutoCreate.mutate({ source: source.source, enabled })+ }+ />+ )}+ />+ ))}+ </SettingRows>+ </SettingsCard>++ <SettingsCard+ title="Microsoft access"+ description="Stop new email from arriving."+ hint={+ <a+ href="https://myapplications.microsoft.com"+ target="_blank"+ rel="noreferrer"+ >+ Manage in your Microsoft account+ </a>+ }+ action={<AlertDialog><AlertDialogTrigger asChild>- <Button variant="ghost" size="xs" disabled={purge.isPending}>- Delete synced data+ <Button variant="outline" size="sm" disabled={revoke.isPending}>+ Disconnect Microsoft</Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Delete synced data?</AlertDialogTitle>+ <AlertDialogTitle>Disconnect Microsoft?</AlertDialogTitle><AlertDialogDescription>- Every email brought in from Outlook is removed from the CRM.- The next check starts from now, so nothing deleted here- comes back.+ {required+ ? "You will be signed out, and you cannot use the CRM again until you grant access."+ : "New email stops arriving. Everything already synced stays, and you can connect Microsoft again from this page."}{" "}+ Remove this app from your Microsoft account to withdraw+ consent.</AlertDialogDescription></AlertDialogHeader>@@ -326,30 +343,40 @@ export function MicrosoftConnection({<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActionvariant="destructive"- onClick={() => purge.mutate()}+ onClick={() => revoke.mutate()}>- Delete+ Disconnect</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>-+ }+ />++ <SettingsCard+ tone="destructive"+ title="Delete synced data"+ description="Remove every email brought in from Outlook."+ hint="This can't be undone."+ action={<AlertDialog><AlertDialogTrigger asChild>- <Button variant="ghost" size="xs" disabled={revoke.isPending}>- Disconnect Microsoft+ <Button+ variant="destructive"+ size="sm"+ disabled={purge.isPending}+ >+ Delete synced data</Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Disconnect Microsoft?</AlertDialogTitle>+ <AlertDialogTitle>Delete synced data?</AlertDialogTitle><AlertDialogDescription>- {required- ? "You will be signed out, and you cannot use the CRM again until you grant access."- : "New email stops arriving. Everything already synced stays, and you can connect Microsoft again from this page."}{" "}- Microsoft has no way for us to withdraw the consent itself —- remove this app from your Microsoft account to do that.+ Every email brought in from Outlook is removed from the CRM.+ The next check starts from now, so nothing deleted here+ comes back.</AlertDialogDescription></AlertDialogHeader>@@ -357,26 +384,16 @@ export function MicrosoftConnection({<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActionvariant="destructive"- onClick={() => revoke.mutate()}+ onClick={() => purge.mutate()}>- Disconnect+ Delete</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>-- <Button variant="ghost" size="xs" asChild>- <Link- href="https://myapplications.microsoft.com"- target="_blank"- rel="noreferrer"- >- Manage in your Microsoft account- </Link>- </Button>- </div>- </CardFooter>- </CardContent>- </Card>+ }+ />+ </SettingsColumn>+ </>);}diff --git a/apps/app/app/(app)/[slug]/settings/connections/page.tsx b/apps/app/app/(app)/[slug]/settings/connections/page.tsxindex 78c0df54..9ad51cd6 100644--- a/apps/app/app/(app)/[slug]/settings/connections/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/page.tsx@@ -4,7 +4,6 @@ import MicrosoftLogo from "@crm/ui/components/brand-logos/microsoft";import SlackLogo from "@crm/ui/components/brand-logos/slack";import { Button } from "@crm/ui/components/button";import { ProviderMark } from "@crm/ui/components/provider-mark";-import { Spinner } from "@crm/ui/components/spinner";import { providerBrand } from "@crm/ui/lib/provider-brand";import type { Metadata } from "next";import Link from "next/link";@@ -12,6 +11,7 @@ import { Suspense } from "react";import { requireSession } from "@/lib/session";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";import { AddConnectionDialog } from "./add-connection-dialog";+import { ConnectionPage, ConnectionPageLoading } from "./connection-page";export const metadata: Metadata = { title: "Connections" };@@ -108,9 +108,9 @@ async function ConnectionsSettingsPageContent({];return (- <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto px-(--spacing-page-inline) pt-(--spacing-page-top) pb-(--spacing-page-bottom)">+ <ConnectionPage centered={rows.length === 0}>{rows.length > 0 ? (- <div className="mx-auto flex w-full max-w-(--container-page) flex-col gap-(--spacing-page-gap)">+ <><header className="flex items-start justify-between gap-4 px-(--spacing-block-inline)"><div className="flex flex-col gap-2"><h1 className="font-medium text-2xl tracking-tight">@@ -132,9 +132,9 @@ async function ConnectionsSettingsPageContent({<ConnectionCard key={row.name} {...row} />))}</div>- </div>+ </>) : (- <div className="mx-auto flex w-full max-w-(--container-narrow) flex-1 flex-col justify-center gap-(--spacing-page-gap) text-center">+ <div className="mx-auto flex w-full max-w-(--container-narrow) flex-col gap-(--spacing-page-gap) text-center"><div className="flex flex-col gap-2 px-(--spacing-block-inline)"><h1 className="font-medium text-2xl tracking-tight">Nothing is connected yet@@ -189,16 +189,12 @@ async function ConnectionsSettingsPageContent({brand: providerBrand(vendor.slug, vendor.name),}))}/>- </main>+ </ConnectionPage>);}function ConnectionsFallback() {- return (- <main className="flex min-h-0 min-w-0 flex-1 items-center justify-center px-(--spacing-page-inline) pt-(--spacing-page-top) pb-(--spacing-page-bottom)">- <Spinner size="lg" />- </main>- );+ return <ConnectionPageLoading />;}function ConnectionCard({diff --git a/apps/app/app/(app)/[slug]/settings/connections/slack/page.tsx b/apps/app/app/(app)/[slug]/settings/connections/slack/page.tsxindex 7eff64f4..597044df 100644--- a/apps/app/app/(app)/[slug]/settings/connections/slack/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/slack/page.tsx@@ -1,5 +1,3 @@-import Close from "@carbon/icons-react/es/Close";-import Warning from "@carbon/icons-react/es/Warning";import {describeSlackScopes,SLACK_REQUESTED_SCOPES,@@ -17,6 +15,16 @@ import {import SlackLogo from "@crm/ui/components/brand-logos/slack";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";+import { PageSection } from "@crm/ui/components/page-section";+import {+ PageShellActions,+ PageShellDescription,+ PageShellHeader,+ PageShellHeading,+ PageShellTitle,+} from "@crm/ui/components/page-shell";+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { CircleAlertIcon, XIcon } from "lucide-react";import Link from "next/link";import { Suspense } from "react";import { NewAgentDialog } from "@/components/agent-builder/new-agent-dialog";@@ -76,21 +84,23 @@ async function SlackConnectionPageContent({return status.connected ? (<ConnectedSlack slug={slug} status={status} />) : (- <ConnectionPage centered className="max-w-(--container-page)">- <header className="flex flex-col gap-3 px-(--spacing-block-inline)">- <div className="flex items-center gap-3">- <SlackLogo className="size-6" />- <h1 className="font-medium text-xl">Slack</h1>- <span className="ml-auto text-muted-foreground text-sm">- Not connected- </span>- </div>- <p className="text-muted-foreground text-sm leading-relaxed">- Connecting Slack gives the CRM a way in and a way out. What it- actually does with that is up to you afterwards, one automation at a- time.- </p>- </header>+ <ConnectionPage centered>+ <PageShellHeader>+ <PageShellHeading>+ <PageShellTitle className="flex items-center gap-3">+ <SlackLogo className="size-6" />+ Slack+ </PageShellTitle>+ <PageShellDescription>+ Connecting Slack gives the CRM a way in and a way out. What it+ actually does with that is up to you afterwards, one automation at a+ time.+ </PageShellDescription>+ </PageShellHeading>+ <PageShellActions>+ <StatusIndicator size="sm" tone="neutral" label="Not connected" />+ </PageShellActions>+ </PageShellHeader><SlackScopeGroupsgroups={groupScopes([...SLACK_REQUESTED_SCOPES])}title="What you are handing over"@@ -99,41 +109,38 @@ async function SlackConnectionPageContent({<PlainListtitle="What it will never do"items={never}- icon={Close}+ icon={XIcon}tone="text-muted-foreground"/>- <div className="flex items-center gap-4 border-y px-(--spacing-block-inline) py-5">+ <div className="flex flex-wrap items-center gap-4 border-y py-5"><SlackConnectButtonslug={slug}configured={status.configured}connectError={connectErrorOf(query, "slack")}/>- <p className="text-muted-foreground text-xs">+ <p className="text-muted-foreground text-13">You approve the workspace in Slack. You can disconnect it here at anytime.</p></div>- <section className="flex flex-col gap-3 px-(--spacing-block-inline)">- <div>- <h2 className="font-medium text-sm">- Afterwards, most teams start with one of these- </h2>- <p className="text-muted-foreground text-xs">- Suggestions, not settings. None of them exist until you pick one and- switch it on.- </p>- </div>+ <PageSection+ title="Afterwards, most teams start with one of these"+ description="Suggestions, not settings. None of them exist until you pick one and switch it on."+ ><div className="grid gap-3 md:grid-cols-3">{suggestions.map(([name, description]) => (- <div className="rounded-lg border p-4" key={name}>+ <div+ className="flex flex-col gap-2 rounded-md p-4 shadow-border"+ key={name}+ ><h3 className="font-medium text-sm">{name}</h3>- <p className="mt-2 text-muted-foreground text-xs leading-relaxed">+ <p className="text-pretty text-13 text-muted-foreground">{description}</p></div>))}</div>- </section>+ </PageSection></ConnectionPage>);}@@ -183,24 +190,30 @@ function ConnectedSlack({: [...drift.missing, SLACK_USER_GRANT];return (<ConnectionPage>- <header className="flex flex-col gap-2 px-(--spacing-block-inline)">- <div className="flex items-center gap-3">- <SlackLogo className="size-6" />- <h1 className="font-medium text-xl">Slack</h1>- <span className="ml-auto text-muted-foreground text-sm">- {status.workspace ?? "Connected"}- </span>+ <PageShellHeader>+ <PageShellHeading>+ <PageShellTitle className="flex items-center gap-3">+ <SlackLogo className="size-6" />+ Slack+ </PageShellTitle>+ <PageShellDescription>+ {status.canManage+ ? "Here is what Slack gave us. Agents only post where their automation says."+ : "Here is what Slack gave us. Only an owner or an admin can disconnect it."}+ </PageShellDescription>+ </PageShellHeading>+ <PageShellActions>+ <StatusIndicator+ size="sm"+ tone="success"+ label={status.workspace ?? "Connected"}+ /><SlackDisconnectButtoncanManage={status.canManage}workspace={status.workspace}/>- </div>- <p className="text-muted-foreground text-sm">- {status.canManage- ? "Here is what Slack gave us. Agents only post where their automation says."- : "Here is what Slack gave us. Only an owner or an admin can disconnect it."}- </p>- </header>+ </PageShellActions>+ </PageShellHeader><MissingGrant missing={missing} slug={slug} /><SlackScopeGroupsgroups={groupScopes(status.scopes)}@@ -208,19 +221,16 @@ function ConnectedSlack({withheld={missing.map(toLine)}/><SlackChannels />- <section className="flex flex-col gap-3 border-y px-(--spacing-block-inline) py-5">- <div className="flex items-end justify-between gap-4">- <div>- <h2 className="font-medium text-sm">Agents that use Slack</h2>- <p className="text-muted-foreground text-xs">- Built in chat, not here. Open one to change it.- </p>- </div>+ <PageSection+ title="Agents that use Slack"+ description="Built in chat, not here. Open one to change it."+ action={<NewAgentDialog><Button size="sm">New agent</Button></NewAgentDialog>- </div>- <div className="flex flex-col divide-y rounded-lg border">+ }+ >+ <div className="flex flex-col divide-y rounded-md shadow-border">{agents.length === 0 ? (<p className="px-(--spacing-block-inline) py-4 text-muted-foreground text-sm">No deployed agents use Slack yet.@@ -240,11 +250,11 @@ function ConnectedSlack({><div className="min-w-0 flex-1"><h3 className="font-medium text-sm">{agent.name}</h3>- <p className="truncate text-muted-foreground text-xs">+ <p className="truncate text-muted-foreground text-13">{agent.description}</p></div>- <span className="flex w-19 shrink-0 items-center gap-2 text-xs">+ <span className="flex w-19 shrink-0 items-center gap-2 text-13"><spanclassName={`size-2 rounded-full ${agent.status === "LIVE" ? "bg-success" : "bg-muted-foreground"}`}/>@@ -260,8 +270,8 @@ function ConnectedSlack({Describe another agent in chat</Link></div>- </section>- <div className="flex items-center justify-between gap-4 px-(--spacing-block-inline)">+ </PageSection>+ <div className="flex items-center justify-between gap-4"><p className="text-sm">{status.people.reviewed === 0? "No workspace people have been reviewed yet."@@ -291,9 +301,9 @@ function MissingGrant({);return (- <div className="px-(--spacing-block-inline)">+ <div><Alert variant="warning">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>{privateChannels? "Comp AI cannot reach private channels"@@ -305,7 +315,7 @@ function MissingGrant({{missing.map((entry) => (<li className="flex items-start gap-2" key={entry.scope}><Icon- icon={Close}+ icon={XIcon}motion="none"className="mt-0.5 size-3.5 shrink-0"/>@@ -334,8 +344,7 @@ function PlainList({tone: string;}) {return (- <section className="flex flex-col gap-3 px-(--spacing-block-inline)">- <h2 className="font-medium text-sm">{title}</h2>+ <PageSection title={title}><div className="flex flex-col gap-2">{items.map((item) => (<div className="flex items-start gap-3 text-sm" key={item}>@@ -348,6 +357,6 @@ function PlainList({</div>))}</div>- </section>+ </PageSection>);}diff --git a/apps/app/app/(app)/[slug]/settings/connections/slack/people/page.tsx b/apps/app/app/(app)/[slug]/settings/connections/slack/people/page.tsxindex d50a2b85..76285201 100644--- a/apps/app/app/(app)/[slug]/settings/connections/slack/people/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/slack/people/page.tsx@@ -1,10 +1,9 @@import SlackLogo from "@crm/ui/components/brand-logos/slack";-import { Spinner } from "@crm/ui/components/spinner";import { redirect } from "next/navigation";import { Suspense } from "react";import { requireSession } from "@/lib/session";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";-import { ConnectionPage } from "../../connection-page";+import { ConnectionPage, ConnectionPageLoading } from "../../connection-page";import { SlackPeopleMatches } from "./slack-people-matches";type SlackPeoplePageProps = {@@ -13,13 +12,7 @@ type SlackPeoplePageProps = {export default function SlackPeoplePage(props: SlackPeoplePageProps) {return (- <Suspense- fallback={- <ConnectionPage centered>- <Spinner size="lg" />- </ConnectionPage>- }- >+ <Suspense fallback={<ConnectionPageLoading />}><SlackPeoplePageContent {...props} /></Suspense>);diff --git a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-channels.tsx b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-channels.tsxindex bbf9d9ff..e6c06b32 100644--- a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-channels.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-channels.tsx@@ -1,5 +1,5 @@"use client";-import Search from "@carbon/icons-react/es/Search";+import {AlertDialog,AlertDialogCancel,@@ -20,7 +20,9 @@ import {InputGroupAddon,InputGroupInput,} from "@crm/ui/components/input-group";+import { PageSection } from "@crm/ui/components/page-section";import { useMutation } from "@tanstack/react-query";+import { SearchIcon } from "lucide-react";import { useDeferredValue, useState } from "react";import { toast } from "sonner";import {@@ -72,14 +74,10 @@ export function SlackChannels() {const canInviteItself = channels.canInviteItself;return (- <section className="flex flex-col gap-3 px-(--spacing-block-inline)">- <div className="flex items-end justify-between gap-4">- <div>- <h2 className="font-medium text-sm">Channels Comp AI can reach</h2>- <p className="text-muted-foreground text-xs">- Agents pick from this list.- </p>- </div>+ <PageSection+ title="Channels Comp AI can reach"+ description="Agents pick from this list."+ action={<Buttondisabled={refreshing}onClick={() => refresh.mutate()}@@ -88,8 +86,8 @@ export function SlackChannels() {>{refreshing ? "Refreshing…" : "Refresh"}</Button>- </div>-+ }+ >{channels.stalled ? (<p className="text-warning text-xs">Comp AI is not reading Slack right now. The list can be out of date.@@ -99,9 +97,10 @@ export function SlackChannels() {{rows.length > 0 || query ? (<InputGroup><InputGroupAddon>- <Icon icon={Search} motion="none" className="size-4" />+ <Icon icon={SearchIcon} motion="none" className="size-4" /></InputGroupAddon><InputGroupInput+ aria-label="Search channels"onChange={(event) => setQuery(event.target.value)}placeholder="Search channels"value={query}@@ -144,7 +143,7 @@ export function SlackChannels() {onConfirm={() => asking && void joinAction.run(asking.id)}status={joinAction.status}/>- </section>+ </PageSection>);}diff --git a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-connect-button.tsx b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-connect-button.tsxindex 74b7fc38..5efb8231 100644--- a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-connect-button.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-connect-button.tsx@@ -15,7 +15,7 @@ const CONNECT_ERRORS = new Map(["That Slack installer is already linked to another CRM account.",],[- "email_doesn't_match",+ "email_does_not_match","The Slack installer's email must match the CRM account you are signed in with.",],[@@ -30,8 +30,8 @@ const CONNECT_ERRORS = new Map([async function startSlackOAuth(slug: string) {try {- const { error } = await authClient.oauth2.link({- providerId: "slack",+ const { error } = await authClient.linkSocial({+ provider: "slack",callbackURL: `${window.location.origin}/${slug}/settings/connections/slack/people`,errorCallbackURL: `${window.location.origin}/${slug}/settings/connections/slack?provider=slack`,});diff --git a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-scope-groups.tsx b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-scope-groups.tsxindex cd848f75..2e6c9d2c 100644--- a/apps/app/app/(app)/[slug]/settings/connections/slack/slack-scope-groups.tsx+++ b/apps/app/app/(app)/[slug]/settings/connections/slack/slack-scope-groups.tsx@@ -1,8 +1,5 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Close from "@carbon/icons-react/es/Close";-import Warning from "@carbon/icons-react/es/Warning";import {Accordion,AccordionContent,@@ -10,6 +7,8 @@ import {AccordionTrigger,} from "@crm/ui/components/accordion";import { Icon } from "@crm/ui/components/icon";+import { PageSection } from "@crm/ui/components/page-section";+import { CheckIcon, CircleAlertIcon, XIcon } from "lucide-react";export type ScopeLine = {scope: string;@@ -34,16 +33,11 @@ export function SlackScopeGroups({withheld: ScopeLine[];}) {return (- <section className="flex flex-col gap-3 px-(--spacing-block-inline)">- <div>- <h2 className="font-medium text-sm">{title}</h2>- <p className="text-muted-foreground text-xs">- Broad means the whole workspace, not one channel. Open a group to see- the details.- </p>- </div>-- <Accordion className="rounded-lg border px-4" type="multiple">+ <PageSection+ title={title}+ description="Broad means the whole workspace, not one channel. Open a group to see the details."+ >+ <Accordion className="rounded-md px-4 shadow-border" type="multiple">{groups.map((group) => {const broad = group.scopes.filter((entry) => entry.sensitive).length;@@ -67,7 +61,7 @@ export function SlackScopeGroups({<li className="flex items-start gap-2.5" key={entry.scope}><IconclassName={`mt-0.5 size-3.5 shrink-0 ${entry.sensitive ? "text-warning" : "text-success"}`}- icon={entry.sensitive ? Warning : Checkmark}+ icon={entry.sensitive ? CircleAlertIcon : CheckIcon}motion="none"/><span className="text-sm">{entry.grant}</span>@@ -88,7 +82,7 @@ export function SlackScopeGroups({<span className="flex items-center gap-2 font-medium text-muted-foreground text-sm"><IconclassName="size-3.5 shrink-0"- icon={Close}+ icon={XIcon}motion="none"/>{entry.grant}@@ -103,6 +97,6 @@ export function SlackScopeGroups({</div>))}</Accordion>- </section>+ </PageSection>);}diff --git a/apps/app/app/(app)/[slug]/settings/copy-value.tsx b/apps/app/app/(app)/[slug]/settings/copy-value.tsxindex 380191d3..bcfb99cb 100644--- a/apps/app/app/(app)/[slug]/settings/copy-value.tsx+++ b/apps/app/app/(app)/[slug]/settings/copy-value.tsx@@ -1,11 +1,19 @@"use client";-import Copy from "@carbon/icons-react/es/Copy";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";+import { CopyIcon } from "lucide-react";import { toast } from "sonner";-export function CopyValue({ value, label }: { value: string; label: string }) {+export function CopyValue({+ value,+ label,+ onCopied,+}: {+ value: string;+ label: string;+ onCopied?: () => void;+}) {const unavailable = () =>toast.error(`Could not copy the ${label.toLowerCase()}. Select it instead.`,@@ -26,11 +34,14 @@ export function CopyValue({ value, label }: { value: string; label: string }) {clipboard.writeText(value)- .then(() => toast.success(`${label} copied.`))+ .then(() => {+ toast.success(`${label} copied.`);+ onCopied?.();+ }).catch(unavailable);}}>- <Icon icon={Copy} />+ <Icon icon={CopyIcon} /><span className="sr-only">Copy {label.toLowerCase()}</span></Button>);diff --git a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsxindex 5d29edaa..433f0c1e 100644--- a/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx+++ b/apps/app/app/(app)/[slug]/settings/currencies/currency-settings.tsx@@ -1,18 +1,17 @@"use client";-import { CURRENCIES } from "@crm/db/currency";+import { CURRENCIES, isCurrencyCode } from "@crm/db/currency";+import { Badge } from "@crm/ui/components/badge";import { Button } from "@crm/ui/components/button";import {- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { CardTableEmpty } from "@crm/ui/components/card-table";-import { Field, FieldDescription, FieldLabel } from "@crm/ui/components/field";+ Field,+ FieldError,+ FieldGroup,+ FieldLabel,+} from "@crm/ui/components/field";+import { useFormSheetValidation } from "@crm/ui/components/form-sheet";import { Input } from "@crm/ui/components/input";+import { OptionLabel } from "@crm/ui/components/option-label";import {Select,SelectContent,@@ -20,6 +19,7 @@ import {SelectTrigger,SelectValue,} from "@crm/ui/components/select";+import { SettingsCard, SettingsColumn } from "@crm/ui/components/settings-card";import {SimpleTable,type SimpleTableColumn,@@ -53,6 +53,7 @@ const USAGE_COLUMNS: SimpleTableColumn[] = [];export function CurrencySettings() {+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();@@ -83,6 +84,7 @@ export function CurrencySettings() {trpc.currency.setManualRate.mutationOptions({onSuccess: async () => {await invalidate();+ validation.reset();setDraftCurrency("");setDraftRate("");toast.success("Rate saved.");@@ -130,135 +132,80 @@ export function CurrencySettings() {refresh.isPending;return (- <div className="flex flex-col gap-6">- <Card>- <CardHeader>- <CardTitle>Reporting currency</CardTitle>- <CardDescription>- Every total, chart and average in the CRM is expressed in this- currency. Each deal keeps the currency it was sold in.- </CardDescription>- </CardHeader>-- <CardContent>- <Field>- <FieldLabel htmlFor={baseId}>Report totals in</FieldLabel>- <Select- value={reportingCurrency}- disabled={busy}- onValueChange={(currency) => setBase.mutate({ currency })}- >- <SelectTrigger id={baseId} className="w-full max-w-sm">- <SelectValue />- </SelectTrigger>- <SelectContent>- {CURRENCIES.map((entry) => (- <SelectItem key={entry.code} value={entry.code}>- {entry.code} · {entry.name}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- {canManage- ? "Changing this re-converts every deal at today's rates. Figures already reported will move."- : "Only an owner or an admin can change how money is reported."}- </FieldDescription>- </Field>- </CardContent>- </Card>-- <Card>- <CardHeader>- <CardTitle>Exchange rates</CardTitle>- <CardDescription>- How many {reportingCurrency} one unit of each currency buys. Fetched- daily from open.er-api.com; a rate you enter here wins.- </CardDescription>- <CardAction>- <Button- variant="contrast"- size="sm"- disabled={busy}- onClick={() => refresh.mutate()}- >- {refresh.isPending ? <Spinner data-icon="inline-start" /> : null}- Refresh- </Button>- </CardAction>- </CardHeader>-- <CardContent>- <form- className="flex flex-wrap items-end gap-3"- onSubmit={(event) => {- event.preventDefault();- const rate = Number.parseFloat(draftRate);- if (!Number.isFinite(rate) || rate <= 0) {- toast.error("A rate has to be a number greater than zero.");- return;- }- setRate.mutate({ currency: draftCurrency, rate });- }}+ <SettingsColumn>+ <SettingsCard+ title="Reporting currency"+ description="Every total, chart and average in the CRM is expressed in this currency. Each deal keeps the currency it was sold in."+ hint={+ canManage+ ? "Changes save as you make them. Every deal is re-converted at today's rates, so figures already reported move."+ : "Only an owner or an admin can change how money is reported."+ }+ control="compact"+ >+ <Field>+ <FieldLabel htmlFor={baseId}>Report totals in</FieldLabel>+ <Select+ value={reportingCurrency}+ disabled={busy}+ onValueChange={(currency) => setBase.mutate({ currency })}>- <Field className="w-48">- <FieldLabel htmlFor={rateCurrencyId}>Currency</FieldLabel>- <Select- value={draftCurrency}- disabled={busy}- onValueChange={setDraftCurrency}- >- <SelectTrigger id={rateCurrencyId} className="w-full">- <SelectValue placeholder="Pick one" />- </SelectTrigger>- <SelectContent>- {CURRENCIES.filter(- (entry) => entry.code !== reportingCurrency,- ).map((entry) => (- <SelectItem key={entry.code} value={entry.code}>- {entry.code} · {entry.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>-- <Field className="w-48">- <FieldLabel htmlFor={rateValueId}>- 1 {draftCurrency || "unit"} = ? {reportingCurrency}- </FieldLabel>- <Input- id={rateValueId}- value={draftRate}- inputMode="decimal"- placeholder="1.09"- disabled={busy}- onChange={(event) => setDraftRate(event.target.value)}- />- </Field>-- <Button- type="submit"- disabled={busy || draftCurrency === "" || draftRate.trim() === ""}- >- {setRate.isPending ? <Spinner data-icon="inline-start" /> : null}- Save rate- </Button>- </form>- </CardContent>+ <SelectTrigger id={baseId} className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {CURRENCIES.map((entry) => (+ <SelectItem key={entry.code} value={entry.code}>+ <OptionLabel label={entry.code} detail={entry.name} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </SettingsCard>+ <SettingsCard+ title="Exchange rates"+ description={`How many ${reportingCurrency} one unit of each currency buys.`}+ hint={+ refreshedAt ? (+ <>+ Fetched daily from open.er-api.com. Last fetched{" "}+ <LocalRelativeTime date={refreshedAt} />.+ </>+ ) : (+ "Fetched daily from open.er-api.com."+ )+ }+ action={+ <Button+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() => refresh.mutate()}+ >+ {refresh.isPending ? <Spinner data-icon="inline-start" /> : null}+ Refresh rates+ </Button>+ }+ control={rates.length === 0 ? "full" : "table"}+ >{rates.length === 0 ? (- <CardTableEmpty>+ <p className="text-muted-foreground text-sm">No rates yet. Refresh to fetch them, or enter one by hand.- </CardTableEmpty>+ </p>) : (<SimpleTable columns={RATE_COLUMNS}>{rates.map((rate) => (<SimpleTableRow key={rate.currency}><TableCell className={CELL}>- <span className="font-medium">{rate.currency}</span>- <span className="text-muted-foreground">- {rate.name ? ` · ${rate.name}` : ""}+ <span className="flex min-w-0 flex-col">+ <span className="font-medium">{rate.currency}</span>+ {rate.name ? (+ <span className="truncate text-muted-foreground">+ {rate.name}+ </span>+ ) : null}</span></TableCell><TableCell className={`${CELL} text-right tabular-nums`}>@@ -294,41 +241,137 @@ export function CurrencySettings() {))}</SimpleTable>)}- </Card>+ </SettingsCard>- <Card>- <CardHeader>- <CardTitle>Currencies in use</CardTitle>- <CardDescription>- {unconverted.count === 0- ? "Every deal with an amount can be converted into the reporting currency."- : `${formatCount(unconverted.count, "deal")} cannot be converted, so ${unconverted.count === 1 ? "it is" : "they are"} left out of every total.`}- {refreshedAt ? (- <>- {" "}- Rates last fetched <LocalRelativeTime date={refreshedAt} />.- </>- ) : null}- </CardDescription>- </CardHeader>+ <SettingsCard+ title="Rate by hand"+ description="A rate you enter here wins over the fetched one."+ hint="Use a number greater than zero."+ control="compact"+ action={+ <Button type="submit" form="manual-rate" size="sm" disabled={busy}>+ {setRate.isPending ? <Spinner data-icon="inline-start" /> : null}+ Save rate+ </Button>+ }+ >+ <form+ id="manual-rate"+ noValidate+ onInput={validation.onInput}+ onSubmit={(event) => {+ event.preventDefault();+ if (busy) return;+ const rate = Number.parseFloat(draftRate);+ const errors: Record<string, string> = {};+ if (!isCurrencyCode(draftCurrency))+ errors[rateCurrencyId] = "Choose a currency.";+ else if (draftCurrency === reportingCurrency)+ errors[rateCurrencyId] =+ `${reportingCurrency} is the reporting currency. Its rate is always 1.`;+ if (!Number.isFinite(rate) || rate <= 0)+ errors[rateValueId] =+ "A rate has to be a number greater than zero.";+ if (!validation.validate(event.currentTarget, errors)) return;+ setRate.mutate({ currency: draftCurrency, rate });+ }}+ >+ <FieldGroup>+ <Field data-invalid={!!validation.errors[rateCurrencyId]}>+ <FieldLabel htmlFor={rateCurrencyId}>Currency</FieldLabel>+ <Select+ value={draftCurrency}+ disabled={busy}+ onValueChange={(currency) => {+ setDraftCurrency(currency);+ validation.clearError(rateCurrencyId);+ }}+ >+ <SelectTrigger+ id={rateCurrencyId}+ className="w-full"+ aria-invalid={!!validation.errors[rateCurrencyId]}+ aria-describedby={+ validation.errors[rateCurrencyId]+ ? `${rateCurrencyId}-error`+ : undefined+ }+ >+ <SelectValue placeholder="Pick one" />+ </SelectTrigger>+ <SelectContent>+ {CURRENCIES.filter(+ (entry) => entry.code !== reportingCurrency,+ ).map((entry) => (+ <SelectItem key={entry.code} value={entry.code}>+ <OptionLabel label={entry.code} detail={entry.name} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError id={`${rateCurrencyId}-error`}>+ {validation.errors[rateCurrencyId]}+ </FieldError>+ </Field>+ <Field data-invalid={!!validation.errors[rateValueId]}>+ <FieldLabel htmlFor={rateValueId}>+ 1 {draftCurrency || "unit"} = ? {reportingCurrency}+ </FieldLabel>+ <Input+ id={rateValueId}+ aria-invalid={!!validation.errors[rateValueId]}+ aria-describedby={+ validation.errors[rateValueId]+ ? `${rateValueId}-error`+ : undefined+ }+ required+ value={draftRate}+ inputMode="decimal"+ placeholder="1.09"+ disabled={busy}+ onChange={(event) => setDraftRate(event.target.value)}+ />+ <FieldError id={`${rateValueId}-error`}>+ {validation.errors[rateValueId]}+ </FieldError>+ </Field>+ </FieldGroup>+ </form>+ </SettingsCard>++ <SettingsCard+ title="Currencies in use"+ description={+ unconverted.count === 0+ ? "Every deal with an amount can be converted into the reporting currency."+ : `${formatCount(unconverted.count, "deal")} cannot be converted, so ${unconverted.count === 1 ? "it is" : "they are"} left out of every total.`+ }+ control={inUse.length === 0 ? "full" : "table"}+ >{inUse.length === 0 ? (- <CardTableEmpty>No deals have an amount yet.</CardTableEmpty>+ <p className="text-muted-foreground text-sm">+ No deals have an amount yet.+ </p>) : (<SimpleTable columns={USAGE_COLUMNS}>{inUse.map((row) => (<SimpleTableRow key={row.currency}><TableCell className={CELL}>- <span className="font-medium">{row.currency}</span>- <span className="text-muted-foreground">- {row.name ? ` · ${row.name}` : ""}- </span>- {row.currency === reportingCurrency ? (- <span className="text-muted-foreground">- {" "}- · reporting currency+ <span className="flex min-w-0 flex-col">+ <span className="flex items-center gap-2">+ <span className="font-medium">{row.currency}</span>+ {row.currency === reportingCurrency ? (+ <Badge variant="secondary">Reporting currency</Badge>+ ) : null}</span>- ) : null}+ {row.name ? (+ <span className="truncate text-muted-foreground">+ {row.name}+ </span>+ ) : null}+ </span></TableCell><TableCell className={`${CELL} text-right tabular-nums`}>{row.deals}@@ -344,7 +387,7 @@ export function CurrencySettings() {))}</SimpleTable>)}- </Card>- </div>+ </SettingsCard>+ </SettingsColumn>);}diff --git a/apps/app/app/(app)/[slug]/settings/currencies/page.tsx b/apps/app/app/(app)/[slug]/settings/currencies/page.tsxindex 3fdba12d..a065ab9e 100644--- a/apps/app/app/(app)/[slug]/settings/currencies/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/currencies/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -20,7 +20,7 @@ export const metadata: Metadata = {export default function CurrenciesSettingsPage() {return (- <PageShell>+ <PageShell width="narrow"><PageShellHeader><PageShellHeading><PageShellTitle>Currencies</PageShellTitle>@@ -32,7 +32,7 @@ export default function CurrenciesSettingsPage() {</PageShellHeader><PageShellContent>- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><Currencies /></Suspense></PageShellContent>@@ -50,9 +50,7 @@ async function Currencies() {return (<HydrateClient>- <div className="flex max-w-3xl flex-col gap-6">- <CurrencySettings />- </div>+ <CurrencySettings /></HydrateClient>);}diff --git a/apps/app/app/(app)/[slug]/settings/layout.tsx b/apps/app/app/(app)/[slug]/settings/layout.tsxindex de5b1fc6..74edf6ff 100644--- a/apps/app/app/(app)/[slug]/settings/layout.tsx+++ b/apps/app/app/(app)/[slug]/settings/layout.tsx@@ -1,17 +1,7 @@-import { Suspense } from "react";-import { SettingsSidebar, SettingsSidebarFallback } from "./settings-sidebar";-export default function SettingsLayout({children,}: Readonly<{children: React.ReactNode;}>) {- return (- <div className="flex min-h-0 min-w-0 flex-1 flex-col md:flex-row">- <Suspense fallback={<SettingsSidebarFallback />}>- <SettingsSidebar />- </Suspense>- {children}- </div>- );+ return <div className="flex min-h-0 min-w-0 flex-1 flex-col">{children}</div>;}diff --git a/apps/app/app/(app)/[slug]/settings/members/members-table.tsx b/apps/app/app/(app)/[slug]/settings/members/members-table.tsxindex 023bdfb0..efa5a3a5 100644--- a/apps/app/app/(app)/[slug]/settings/members/members-table.tsx+++ b/apps/app/app/(app)/[slug]/settings/members/members-table.tsx@@ -1,6 +1,5 @@"use client";-import OverflowMenuHorizontal from "@carbon/icons-react/es/OverflowMenuHorizontal";import { Button } from "@crm/ui/components/button";import {DataTable,@@ -16,6 +15,7 @@ import {import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";import { useMutation, useQuery } from "@tanstack/react-query";+import { EllipsisIcon } from "lucide-react";import { toast } from "sonner";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";@@ -46,7 +46,6 @@ function columns(header: "Name",sortable: true,hideable: false,- width: "w-[34%]",cell: (row) => (<span className="flex min-w-0 items-center gap-2"><PersonAvatar@@ -66,7 +65,7 @@ function columns(id: "email",header: "Email",sortable: true,- width: "w-[32%]",+ width: "56",hideBelow: "md",cell: (row) => (<span className="truncate text-muted-foreground">{row.email}</span>@@ -76,7 +75,7 @@ function columns(id: "role",header: "Role",sortable: true,- width: "w-[14%]",+ width: "28",cell: (row) => (<span className="text-muted-foreground">{ROLE_LABEL[row.role]}</span>),@@ -87,7 +86,7 @@ function columns(label: "Joined date",sortable: true,align: "right",- width: "w-[14%]",+ width: "28",hideBelow: "sm",cell: (row) => (<span className="text-muted-foreground">@@ -101,13 +100,13 @@ function columns(label: "Actions",hideable: false,align: "right",- width: "w-[6%]",+ width: "12",cell: (row) =>canChangeRoles ? (<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" disabled={pending}>- <Icon icon={OverflowMenuHorizontal} />+ <Icon icon={EllipsisIcon} /><span className="sr-only">Change {row.name}'s role</span></Button></DropdownMenuTrigger>@@ -169,8 +168,9 @@ export function MembersTable() {return (<DataTable+ label="Members"query={query}- search={<ListSearch placeholder="Search by name or email…" />}+ search={<ListSearch placeholder="Search members…" />}columns={columns(workspace.data?.canChangeRoles ?? false,(member, role) => setRole.mutate({ memberId: member.id, role }),diff --git a/apps/app/app/(app)/[slug]/settings/members/page.tsx b/apps/app/app/(app)/[slug]/settings/members/page.tsxindex b8bcfdd9..05401ca8 100644--- a/apps/app/app/(app)/[slug]/settings/members/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/members/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -23,7 +23,7 @@ export default function MembersSettingsPage({searchParams,}: PageProps<"/[slug]/settings/members">) {return (- <PageShell className="min-h-0">+ <PageShell width="narrow" className="min-h-0"><PageShellHeader><PageShellHeading><PageShellTitle>Members</PageShellTitle>@@ -34,7 +34,7 @@ export default function MembersSettingsPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><Members searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/settings/page.tsx b/apps/app/app/(app)/[slug]/settings/page.tsxindex 284c9f0e..7f2dba2b 100644--- a/apps/app/app/(app)/[slug]/settings/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,10 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import { SettingsColumn } from "@crm/ui/components/settings-card";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -23,7 +24,7 @@ export const metadata: Metadata = {export default function GeneralSettingsPage() {return (- <PageShell>+ <PageShell width="narrow"><PageShellHeader><PageShellHeading><PageShellTitle>General</PageShellTitle>@@ -34,7 +35,7 @@ export default function GeneralSettingsPage() {</PageShellHeader><PageShellContent>- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><Settings /></Suspense></PageShellContent>@@ -58,12 +59,12 @@ async function Settings() {return (<HydrateClient>- <div className="flex max-w-3xl flex-col gap-6">+ <SettingsColumn><WorkspaceForm /><ResearchKey /><ArchiveRetention /><AgentModel />- </div>+ </SettingsColumn></HydrateClient>);}diff --git a/apps/app/app/(app)/[slug]/settings/research-key.tsx b/apps/app/app/(app)/[slug]/settings/research-key.tsxindex 3c5dab1a..702f907e 100644--- a/apps/app/app/(app)/[slug]/settings/research-key.tsx+++ b/apps/app/app/(app)/[slug]/settings/research-key.tsx@@ -2,21 +2,9 @@import { CONTEXT_DEV_SIGNUP_URL } from "@crm/db/settings";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,-} from "@crm/ui/components/field";+import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { useMutation, useQuery } from "@tanstack/react-query";@@ -50,71 +38,60 @@ export function ResearchKey() {const { configured, hint } = key.data;return (- <Card>- <CardHeader>- <CardTitle>Company research</CardTitle>- <CardDescription>- Enter your Context API key so our agents can research every company in- the CRM.- </CardDescription>-- <CardAction>- <Button- type="submit"- form="research-key"- disabled={save.isPending || draft.trim() === ""}- >- {save.isPending ? <Spinner data-icon="inline-start" /> : null}- {configured ? "Replace key" : "Save key"}- </Button>- </CardAction>- </CardHeader>-- <CardContent>- <form- id="research-key"- onSubmit={(event) => {- event.preventDefault();- save.mutate({ apiKey: draft.trim() });- }}+ <SettingsCard+ title="Company research"+ description="Enter your Context API key so our agents can research every company in the CRM."+ status={+ <StatusIndicator+ size="sm"+ tone={configured ? "success" : "warning"}+ label={configured ? "Connected" : "Not connected"}+ />+ }+ hint={+ <>+ Don't have a Context API key?{" "}+ <a href={CONTEXT_DEV_SIGNUP_URL} target="_blank" rel="noreferrer">+ Sign up here+ </a>+ </>+ }+ action={+ <Button+ type="submit"+ form="research-key"+ size="sm"+ disabled={save.isPending || draft.trim() === ""}>- <FieldGroup>- <Field>- <div className="flex items-center justify-between gap-3">- <FieldLabel htmlFor={keyId}>Context API key</FieldLabel>- <StatusIndicator- size="sm"- tone={configured ? "success" : "warning"}- label={configured ? "Connected" : "Not connected"}- />- </div>- <Input- id={keyId}- type="password"- value={draft}- onChange={(event) => setDraft(event.target.value)}- placeholder={hint ?? "Paste the key"}- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- disabled={save.isPending}- />- <FieldDescription>- Don't have a Context API key?{" "}- <a- href={CONTEXT_DEV_SIGNUP_URL}- target="_blank"- rel="noreferrer"- className="underline underline-offset-4 hover:text-foreground"- >- Sign up here- </a>- </FieldDescription>- </Field>- </FieldGroup>- </form>- </CardContent>- </Card>+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ {configured ? "Replace key" : "Save key"}+ </Button>+ }+ control="compact"+ >+ <form+ id="research-key"+ onSubmit={(event) => {+ event.preventDefault();+ save.mutate({ apiKey: draft.trim() });+ }}+ >+ <Field>+ <FieldLabel htmlFor={keyId}>Context API key</FieldLabel>+ <Input+ id={keyId}+ type="password"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ placeholder={hint ?? "Paste the key"}+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ disabled={save.isPending}+ />+ </Field>+ </form>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsxdeleted file mode 100644index cdce91b4..00000000--- a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx+++ /dev/null@@ -1,148 +0,0 @@-"use client";--import { Button } from "@crm/ui/components/button";-import { cn } from "@crm/ui/lib/utils";-import Link from "next/link";-import { usePathname } from "next/navigation";-import { useMemo } from "react";-import { useWorkspaceUrl } from "@/lib/use-workspace-url";--type SettingsNavItem = {- title: string;- href: string;-};--const ROOT = "/settings";--const ITEMS: SettingsNavItem[] = [- { title: "General", href: ROOT },- { title: "Tracking & Analytics", href: `${ROOT}/tracking` },- { title: "Connections", href: `${ROOT}/connections` },- { title: "Currencies", href: `${ROOT}/currencies` },- { title: "Members", href: `${ROOT}/members` },- { title: "API Keys", href: `${ROOT}/api-keys` },- { title: "SSO", href: `${ROOT}/sso` },-];--function isActive(href: string, root: string, pathname: string): boolean {- return href === root ? pathname === href : pathname.startsWith(href);-}--function NavLink({- item,- active,- className,-}: {- item: SettingsNavItem;- active: boolean;- className: string;-}) {- return (- <Button- asChild- variant="ghost"- className={cn(- "justify-start font-normal text-muted-foreground",- active &&- "bg-muted text-foreground hover:bg-muted hover:text-foreground",- className,- )}- >- <Link- href={item.href}- prefetch- aria-current={active ? "page" : undefined}- transitionTypes={["nav-lateral"]}- >- {item.title}- </Link>- </Button>- );-}--export function SettingsSidebarFallback() {- return (- <>- <aside className="hidden w-56 shrink-0 border-r md:block [view-transition-name:settings-sidebar]">- <nav- aria-label="Workspace settings"- aria-busy="true"- className="flex flex-col gap-0.5 p-3"- >- {ITEMS.map((item) => (- <Button- key={item.href}- variant="ghost"- disabled- className="w-full justify-start px-3 font-normal text-muted-foreground"- >- {item.title}- </Button>- ))}- </nav>- </aside>-- <nav- aria-label="Workspace settings"- aria-busy="true"- className="flex gap-1 overflow-x-auto border-b p-2 md:hidden [view-transition-name:settings-sidebar]"- >- {ITEMS.map((item) => (- <Button- key={item.href}- variant="ghost"- disabled- className="shrink-0 justify-start px-3 font-normal text-muted-foreground"- >- {item.title}- </Button>- ))}- </nav>- </>- );-}--export function SettingsSidebar() {- const pathname = usePathname();- const workspaceUrl = useWorkspaceUrl();-- const root = workspaceUrl(ROOT);- const items = useMemo(- () => ITEMS.map((item) => ({ ...item, href: workspaceUrl(item.href) })),- [workspaceUrl],- );-- return (- <>- <aside className="hidden w-56 shrink-0 border-r md:block [view-transition-name:settings-sidebar]">- <nav- aria-label="Workspace settings"- className="flex flex-col gap-0.5 p-3"- >- {items.map((item) => (- <NavLink- key={item.href}- item={item}- active={isActive(item.href, root, pathname)}- className="w-full px-3"- />- ))}- </nav>- </aside>-- <nav- aria-label="Workspace settings"- className="flex gap-1 overflow-x-auto border-b p-2 md:hidden [view-transition-name:settings-sidebar]"- >- {items.map((item) => (- <NavLink- key={item.href}- item={item}- active={isActive(item.href, root, pathname)}- className="shrink-0 px-3"- />- ))}- </nav>- </>- );-}diff --git a/apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsx b/apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsxindex f16e4d4a..3544a14b 100644--- a/apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsx+++ b/apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsx@@ -1,13 +1,19 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";import {Field,FieldDescription,- FieldGroup,+ FieldError,FieldLabel,} from "@crm/ui/components/field";+import {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ useFormSheetValidation,+} from "@crm/ui/components/form-sheet";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";import {@@ -16,17 +22,14 @@ import {InputGroupInput,} from "@crm/ui/components/input-group";import {- Sheet,- SheetClose,- SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,SheetTrigger,} from "@crm/ui/components/sheet";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { parseAsBoolean, useQueryState } from "nuqs";import { type ComponentProps, Suspense, useId, useState } from "react";import { toast } from "sonner";@@ -48,7 +51,7 @@ const EMPTY = {function AddButton(props: ComponentProps<typeof Button>) {return (<Button {...props}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />Add provider</Button>);@@ -63,6 +66,7 @@ export function AddSsoProviderSheet() {}function AddSsoProviderForm() {+ const validation = useFormSheetValidation();const trpc = useTRPC();const cache = useCrmCache();@@ -87,7 +91,7 @@ function AddSsoProviderForm() {await cache.sso();toast.success(`${provider.name} saved.`);await setOpen(null);- setValues(EMPTY);+ reset();},onError: (error) => toast.error(error.message),}),@@ -102,15 +106,24 @@ function AddSsoProviderForm() {providerId || "…"}`;- const complete = Object.values(values).every((value) => value.trim() !== "");+ const reset = () => {+ validation.reset();+ setValues(EMPTY);+ };return (- <Sheet open={open} onOpenChange={(next) => setOpen(next || null)}>+ <FormSheet+ dirty={Object.values(values).some((value) => value !== "")}+ pending={register.isPending}+ onDiscard={reset}+ open={open}+ onOpenChange={(next) => setOpen(next || null)}+ ><SheetTrigger asChild><AddButton disabled={!settings.data?.canConfigure} /></SheetTrigger>- <SheetContent side="right">+ <FormSheetContent side="right"><SheetHeader><SheetTitle>Add an identity provider</SheetTitle><SheetDescription>@@ -118,11 +131,17 @@ function AddSsoProviderForm() {</SheetDescription></SheetHeader>- <form+ <FormSheetForm+ noValidate+ onInput={validation.onInput}id={FORM}- className="flex-1 overflow-y-auto px-4"onSubmit={(event) => {event.preventDefault();+ if (+ !settings.data?.canConfigure ||+ !validation.validate(event.currentTarget)+ )+ return;register.mutate({providerId,issuer: values.issuer.trim(),@@ -132,115 +151,161 @@ function AddSsoProviderForm() {});}}>- <FieldGroup>- <Field>- <FieldLabel htmlFor={providerIdId}>Name</FieldLabel>- <Input- id={providerIdId}- value={values.providerId}- onChange={(event) => edit({ providerId: event.target.value })}- placeholder="okta"- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- required- />- <FieldDescription>- Names the sign-in button. Cannot be changed later.- </FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={issuerId}>Issuer URL</FieldLabel>- <Input- id={issuerId}- type="url"- value={values.issuer}- onChange={(event) => edit({ issuer: event.target.value })}- placeholder="https://acme.okta.com"- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- inputMode="url"- required- />- <FieldDescription>Where discovery lives.</FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={domainId}>Email domain</FieldLabel>- <Input- id={domainId}- value={values.domain}- onChange={(event) => edit({ domain: event.target.value })}- placeholder="acme.com"- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- required- />- <FieldDescription>Comma-separate several.</FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={clientIdId}>Client ID</FieldLabel>- <Input- id={clientIdId}- value={values.clientId}- onChange={(event) => edit({ clientId: event.target.value })}- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- required- />- </Field>-- <Field>- <FieldLabel htmlFor={clientSecretId}>Client secret</FieldLabel>- <Input- id={clientSecretId}- type="password"- value={values.clientSecret}- onChange={(event) => edit({ clientSecret: event.target.value })}- autoComplete="off"- required- />- <FieldDescription>Never shown again.</FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={redirectId}>Redirect URI</FieldLabel>- <InputGroup>- <InputGroupInput id={redirectId} value={callbackURL} readOnly />- <InputGroupAddon align="inline-end">- <CopyValue value={callbackURL} label="Redirect URI" />- </InputGroupAddon>- </InputGroup>- <FieldDescription>- Add this at your provider before saving.- </FieldDescription>- </Field>- </FieldGroup>- </form>-- <SheetFooter>+ <Field data-invalid={!!validation.errors[providerIdId]}>+ <FieldLabel htmlFor={providerIdId}>Name</FieldLabel>+ <Input+ id={providerIdId}+ maxLength={64}+ aria-invalid={!!validation.errors[providerIdId]}+ aria-describedby={+ validation.errors[providerIdId]+ ? `${providerIdId}-error`+ : undefined+ }+ value={values.providerId}+ onChange={(event) => edit({ providerId: event.target.value })}+ placeholder="okta"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${providerIdId}-error`}>+ {validation.errors[providerIdId]}+ </FieldError>+ <FieldDescription>+ Names the sign-in button. Cannot be changed later.+ </FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[issuerId]}>+ <FieldLabel htmlFor={issuerId}>Issuer URL</FieldLabel>+ <Input+ id={issuerId}+ maxLength={512}+ aria-invalid={!!validation.errors[issuerId]}+ aria-describedby={+ validation.errors[issuerId] ? `${issuerId}-error` : undefined+ }+ type="url"+ value={values.issuer}+ onChange={(event) => edit({ issuer: event.target.value })}+ placeholder="https://acme.okta.com"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ inputMode="url"+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${issuerId}-error`}>+ {validation.errors[issuerId]}+ </FieldError>+ <FieldDescription>Where discovery lives.</FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[domainId]}>+ <FieldLabel htmlFor={domainId}>Email domain</FieldLabel>+ <Input+ id={domainId}+ maxLength={255}+ aria-invalid={!!validation.errors[domainId]}+ aria-describedby={+ validation.errors[domainId] ? `${domainId}-error` : undefined+ }+ value={values.domain}+ onChange={(event) => edit({ domain: event.target.value })}+ placeholder="acme.com"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${domainId}-error`}>+ {validation.errors[domainId]}+ </FieldError>+ <FieldDescription>Comma-separate several.</FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[clientIdId]}>+ <FieldLabel htmlFor={clientIdId}>Client ID</FieldLabel>+ <Input+ id={clientIdId}+ maxLength={512}+ aria-invalid={!!validation.errors[clientIdId]}+ aria-describedby={+ validation.errors[clientIdId]+ ? `${clientIdId}-error`+ : undefined+ }+ value={values.clientId}+ onChange={(event) => edit({ clientId: event.target.value })}+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${clientIdId}-error`}>+ {validation.errors[clientIdId]}+ </FieldError>+ </Field>++ <Field data-invalid={!!validation.errors[clientSecretId]}>+ <FieldLabel htmlFor={clientSecretId}>Client secret</FieldLabel>+ <Input+ id={clientSecretId}+ maxLength={1024}+ aria-invalid={!!validation.errors[clientSecretId]}+ aria-describedby={+ validation.errors[clientSecretId]+ ? `${clientSecretId}-error`+ : undefined+ }+ type="password"+ value={values.clientSecret}+ onChange={(event) => edit({ clientSecret: event.target.value })}+ autoComplete="off"+ pattern=".*\S.*"+ required+ />+ <FieldError id={`${clientSecretId}-error`}>+ {validation.errors[clientSecretId]}+ </FieldError>+ <FieldDescription>Never shown again.</FieldDescription>+ </Field>++ <Field data-invalid={!!validation.errors[redirectId]}>+ <FieldLabel htmlFor={redirectId}>Redirect URI</FieldLabel>+ <InputGroup>+ <InputGroupInput id={redirectId} value={callbackURL} readOnly />+ <InputGroupAddon align="inline-end">+ <CopyValue value={callbackURL} label="Redirect URI" />+ </InputGroupAddon>+ </InputGroup>+ <FieldDescription>+ Add this at your provider before saving.+ </FieldDescription>+ </Field>+ </FormSheetForm>++ <FormSheetFooter><Buttontype="submit"form={FORM}- disabled={!complete || register.isPending}+ disabled={!settings.data?.canConfigure || register.isPending}>- {register.isPending ? <Spinner /> : null}+ {register.isPending ? <Spinner data-icon="inline-start" /> : null}Add provider</Button>- <SheetClose asChild>- <Button variant="outline">Cancel</Button>- </SheetClose>- </SheetFooter>- </SheetContent>- </Sheet>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>);}diff --git a/apps/app/app/(app)/[slug]/settings/sso/page.tsx b/apps/app/app/(app)/[slug]/settings/sso/page.tsxindex 52b3d5c8..042c81f9 100644--- a/apps/app/app/(app)/[slug]/settings/sso/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/sso/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellActions,@@ -9,7 +7,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -25,7 +25,7 @@ export default function SsoSettingsPage({searchParams,}: PageProps<"/[slug]/settings/sso">) {return (- <PageShell className="min-h-0">+ <PageShell width="narrow" className="min-h-0"><PageShellHeader><PageShellHeading><PageShellTitle>SSO</PageShellTitle>@@ -41,7 +41,7 @@ export default function SsoSettingsPage({</PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><Providers searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/settings/sso/sso-table.tsx b/apps/app/app/(app)/[slug]/settings/sso/sso-table.tsxindex 010a7f5b..7b43423b 100644--- a/apps/app/app/(app)/[slug]/settings/sso/sso-table.tsx+++ b/apps/app/app/(app)/[slug]/settings/sso/sso-table.tsx@@ -1,6 +1,5 @@"use client";-import TrashCan from "@carbon/icons-react/es/TrashCan";import {AlertDialog,AlertDialogAction,@@ -16,6 +15,7 @@ import { Button } from "@crm/ui/components/button";import { DataTable, type DataTableColumn } from "@crm/ui/components/data-table";import { Icon } from "@crm/ui/components/icon";import { useMutation, useQuery } from "@tanstack/react-query";+import { Trash2Icon } from "lucide-react";import { toast } from "sonner";import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";@@ -38,13 +38,14 @@ function columns(header: "Provider",sortable: true,hideable: false,- width: "w-[30%]",cell: (row) => (<span className="flex min-w-0 flex-col"><span className="truncate font-medium">{row.name}</span>- <span className="truncate text-muted-foreground text-xs">- {row.type === "saml" ? "SAML" : "OpenID Connect"}- {row.clientIdLastFour ? ` · client …${row.clientIdLastFour}` : ""}+ <span className="flex min-w-0 flex-wrap gap-x-3 text-muted-foreground text-xs">+ <span>{row.type === "saml" ? "SAML" : "OpenID Connect"}</span>+ {row.clientIdLastFour ? (+ <span>Client …{row.clientIdLastFour}</span>+ ) : null}</span></span>),@@ -53,7 +54,7 @@ function columns(id: "domain",header: "Email domain",sortable: true,- width: "w-[22%]",+ width: "40",hideBelow: "sm",cell: (row) => (<span className="truncate text-muted-foreground">@@ -65,7 +66,7 @@ function columns(id: "issuer",header: "Issuer",sortable: true,- width: "w-[22%]",+ width: "40",hideBelow: "md",cell: (row) => (<span className="truncate text-muted-foreground">{row.issuer}</span>@@ -74,7 +75,7 @@ function columns({id: "callbackURL",header: "Redirect URI",- width: "w-[20%]",+ width: "36",hideBelow: "lg",cell: (row) => (<span className="flex min-w-0 items-center gap-1 text-muted-foreground">@@ -89,13 +90,13 @@ function columns(label: "Actions",hideable: false,align: "right",- width: "w-[6%]",+ width: "12",cell: (row) =>canConfigure ? (<AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" disabled={pending}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} /><span className="sr-only">Remove {row.name}</span></Button></AlertDialogTrigger>@@ -148,8 +149,9 @@ export function SsoTable() {return (<DataTable+ label="SSO providers"query={query}- search={<ListSearch placeholder="Search by name, domain or issuer…" />}+ search={<ListSearch placeholder="Search providers…" />}columns={columns(settings.data?.canConfigure ?? false,(provider) => remove.mutate({ providerId: provider.providerId }),@@ -159,7 +161,7 @@ export function SsoTable() {total={providers.data?.total ?? 0}getRowId={(row) => row.providerId}loading={providers.isFetching}- empty="No identity provider yet — everyone signs in with Google."+ empty="No identity provider yet. Everyone signs in with Google."/>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/allowed-domains.tsx b/apps/app/app/(app)/[slug]/settings/tracking/allowed-domains.tsxindex e69cc930..bb64361f 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/allowed-domains.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/allowed-domains.tsx@@ -1,15 +1,6 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { CardTableEmpty } from "@crm/ui/components/card-table";import { Field, FieldLabel } from "@crm/ui/components/field";import { Icon } from "@crm/ui/components/icon";import { Input } from "@crm/ui/components/input";@@ -25,6 +16,7 @@ import {SelectTrigger,SelectValue,} from "@crm/ui/components/select";+import { SettingsCard } from "@crm/ui/components/settings-card";import {SimpleTable,type SimpleTableColumn,@@ -33,6 +25,7 @@ import {import { Spinner } from "@crm/ui/components/spinner";import { TableCell } from "@crm/ui/components/table";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import { useId, useState } from "react";import { toast } from "sonner";import { LocalRelativeTime } from "@/components/local-date-time";@@ -75,22 +68,17 @@ export function AllowedDomains() {const { domains, canManage } = tracking.data;return (- <Card>- <CardHeader>- <CardTitle>Allowed domains</CardTitle>- <CardDescription>- The script records page views on these hosts only.- </CardDescription>-- <CardAction>- <AddDomain disabled={!canManage} />- </CardAction>- </CardHeader>-+ <SettingsCard+ title="Allowed domains"+ description="The script records page views on these hosts only."+ hint={canManage ? null : "Only an owner or an admin can change this."}+ action={<AddDomain disabled={!canManage} />}+ control={domains.length === 0 ? "full" : "table"}+ >{domains.length === 0 ? (- <CardTableEmpty>+ <p className="text-muted-foreground text-sm">Add the domain your website runs on to get your tracking script.- </CardTableEmpty>+ </p>) : (<SimpleTable columns={COLUMNS}>{domains.map((domain) => (@@ -108,7 +96,7 @@ export function AllowedDomains() {{domain.lastSeenAt ? (<LocalRelativeTime date={domain.lastSeenAt} />) : (- "—"+ "")}</TableCell><TableCell className={`${CELL} text-right`}>@@ -127,7 +115,7 @@ export function AllowedDomains() {))}</SimpleTable>)}- </Card>+ </SettingsCard>);}@@ -160,7 +148,7 @@ function AddDomain({ disabled }: { disabled: boolean }) {<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button size="sm" disabled={disabled}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />Add domain</Button></PopoverTrigger>diff --git a/apps/app/app/(app)/[slug]/settings/tracking/page.tsx b/apps/app/app/(app)/[slug]/settings/tracking/page.tsxindex 85abe837..4ecf9ff0 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/page.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,10 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import { SettingsColumn } from "@crm/ui/components/settings-card";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -20,7 +21,7 @@ export const metadata: Metadata = {export default function TrackingSettingsPage() {return (- <PageShell>+ <PageShell width="narrow"><PageShellHeader><PageShellHeading><PageShellTitle>Tracking & Analytics</PageShellTitle>@@ -32,7 +33,7 @@ export default function TrackingSettingsPage() {</PageShellHeader><PageShellContent>- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="settings" />}><Tracking /></Suspense></PageShellContent>@@ -56,9 +57,9 @@ async function Tracking() {return (<HydrateClient>- <div className="flex max-w-3xl flex-col gap-6">+ <SettingsColumn><TrackingSections />- </div>+ </SettingsColumn></HydrateClient>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/tracking-cookies.tsx b/apps/app/app/(app)/[slug]/settings/tracking/tracking-cookies.tsxindex 3b6b054e..9011ca7e 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/tracking-cookies.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/tracking-cookies.tsx@@ -1,14 +1,5 @@"use client";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { Field, FieldDescription, FieldLabel } from "@crm/ui/components/field";-import { Label } from "@crm/ui/components/label";import {Select,SelectContent,@@ -16,9 +7,10 @@ import {SelectTrigger,SelectValue,} from "@crm/ui/components/select";+import { SettingRow, SettingRows } from "@crm/ui/components/setting-rows";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery } from "@tanstack/react-query";-import { useId } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -44,7 +36,6 @@ const TOGGLES = [export function TrackingCookies() {const trpc = useTRPC();const cache = useCrmCache();- const lifetimeId = useId();const tracking = useQuery(trpc.tracking.settings.queryOptions());@@ -71,67 +62,56 @@ export function TrackingCookies() {const busy = !canManage || setFlag.isPending || setLifetime.isPending;return (- <Card>- <CardHeader>- <CardTitle>Cookies</CardTitle>- <CardDescription>- How a returning visitor is recognised.- </CardDescription>- </CardHeader>-- <CardContent>+ <SettingsCard+ title="Cookies"+ description="How a returning visitor is recognised."+ hint="Changes save as you make them."+ >+ <SettingRows>{TOGGLES.map((toggle) => (- <div+ <SettingRowkey={toggle.flag}- className="flex items-center justify-between gap-6"- >- <Label- htmlFor={`tracking-${toggle.flag}`}- className="flex flex-col items-start gap-1"- >- <span className="text-sm">{toggle.label}</span>- <span className="font-normal text-muted-foreground text-xs">- {toggle.hint}- </span>- </Label>+ title={toggle.label}+ description={toggle.hint}+ control={(id, describedBy) => (+ <Switch+ id={id}+ aria-describedby={describedBy}+ checked={tracking.data[toggle.flag]}+ disabled={busy}+ onCheckedChange={(enabled) =>+ setFlag.mutate({ flag: toggle.flag, enabled })+ }+ />+ )}+ />+ ))}- <Switch- id={`tracking-${toggle.flag}`}- checked={tracking.data[toggle.flag]}+ <SettingRow+ title="Cookie lifetime"+ description="After this a returning visitor counts as somebody new. Shorten it if your policy asks you to."+ control={(id, describedBy) => (+ <Select+ value={String(cookieDays)}disabled={busy}- onCheckedChange={(enabled) =>- setFlag.mutate({ flag: toggle.flag, enabled })+ onValueChange={(value) =>+ setLifetime.mutate({ days: Number(value) })}- />- </div>- ))}-- <Field>- <FieldLabel htmlFor={lifetimeId}>Cookie lifetime</FieldLabel>- <Select- value={String(cookieDays)}- disabled={busy}- onValueChange={(value) =>- setLifetime.mutate({ days: Number(value) })- }- >- <SelectTrigger id={lifetimeId} className="w-full max-w-sm">- <SelectValue />- </SelectTrigger>- <SelectContent>- {cookieLifetimes.map((lifetime) => (- <SelectItem key={lifetime.days} value={String(lifetime.days)}>- {lifetime.label}- </SelectItem>- ))}- </SelectContent>- </Select>- <FieldDescription>- After this a returning visitor counts as somebody new. Shorten it if- your policy asks you to.- </FieldDescription>- </Field>- </CardContent>- </Card>+ >+ <SelectTrigger id={id} aria-describedby={describedBy} size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {cookieLifetimes.map((lifetime) => (+ <SelectItem key={lifetime.days} value={String(lifetime.days)}>+ {lifetime.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </SettingRows>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/tracking-rules.tsx b/apps/app/app/(app)/[slug]/settings/tracking/tracking-rules.tsxindex 5fb85c70..5ac7b709 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/tracking-rules.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/tracking-rules.tsx@@ -1,13 +1,7 @@"use client";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { Label } from "@crm/ui/components/label";+import { SettingRow, SettingRows } from "@crm/ui/components/setting-rows";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";@@ -45,41 +39,31 @@ export function TrackingRules() {const { canManage } = tracking.data;return (- <Card>- <CardHeader>- <CardTitle>Tracking rules</CardTitle>- <CardDescription>- Where the script may run, and how it follows a visitor.- </CardDescription>- </CardHeader>-- <CardContent>+ <SettingsCard+ title="Tracking rules"+ description="Where the script may run, and how it follows a visitor."+ hint="Changes save as you make them."+ >+ <SettingRows>{RULES.map((rule) => (- <div+ <SettingRowkey={rule.flag}- className="flex items-center justify-between gap-6"- >- <Label- htmlFor={`tracking-${rule.flag}`}- className="flex flex-col items-start gap-1"- >- <span className="text-sm">{rule.label}</span>- <span className="font-normal text-muted-foreground text-xs">- {rule.hint}- </span>- </Label>-- <Switch- id={`tracking-${rule.flag}`}- checked={tracking.data[rule.flag]}- disabled={!canManage || setFlag.isPending}- onCheckedChange={(enabled) =>- setFlag.mutate({ flag: rule.flag, enabled })- }- />- </div>+ title={rule.label}+ description={rule.hint}+ control={(id, describedBy) => (+ <Switch+ id={id}+ aria-describedby={describedBy}+ checked={tracking.data[rule.flag]}+ disabled={!canManage || setFlag.isPending}+ onCheckedChange={(enabled) =>+ setFlag.mutate({ flag: rule.flag, enabled })+ }+ />+ )}+ />))}- </CardContent>- </Card>+ </SettingRows>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/tracking-script.tsx b/apps/app/app/(app)/[slug]/settings/tracking/tracking-script.tsxindex 4311e825..aca74322 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/tracking-script.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/tracking-script.tsx@@ -1,6 +1,5 @@"use client";-import Copy from "@carbon/icons-react/es/Copy";import {Accordion,AccordionContent,@@ -19,20 +18,13 @@ import {AlertDialogTrigger,} from "@crm/ui/components/alert-dialog";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";import { Icon } from "@crm/ui/components/icon";-import { Label } from "@crm/ui/components/label";+import { SettingRow, SettingRows } from "@crm/ui/components/setting-rows";+import { SettingsCard } from "@crm/ui/components/settings-card";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery } from "@tanstack/react-query";+import { CopyIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";@@ -95,29 +87,58 @@ export function TrackingScript() {};return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- Tracking script- <StatusIndicator- size="sm"- tone={paused ? "warning" : receivingSince ? "success" : "neutral"}- label={- paused- ? "Paused"- : receivingSince- ? "Receiving page views"- : "No page views yet"- }- />- </div>- </CardTitle>- <CardDescription>- One tag, 4 KB, in the head of every page you measure.- </CardDescription>-- <CardAction>+ <SettingsCard+ title="Tracking script"+ status={+ <StatusIndicator+ size="sm"+ tone={paused ? "warning" : receivingSince ? "success" : "neutral"}+ label={+ paused+ ? "Paused"+ : receivingSince+ ? "Receiving page views"+ : "No page views yet"+ }+ />+ }+ description="One tag, 4 KB, in the head of every page you measure."+ hint="Rotating the site ID stops every copy of the old script at once."+ action={+ <div className="flex flex-wrap items-center gap-2">+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ disabled={!canManage || rotate.isPending}+ >+ Rotate site ID+ </Button>+ </AlertDialogTrigger>++ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Rotate the site ID?</AlertDialogTitle>+ <AlertDialogDescription>+ Every copy of the old script stops recording at once,+ including any you have forgotten about. You will need to paste+ the new tag on every page that carries the old one. Nothing+ already collected is lost.+ </AlertDialogDescription>+ </AlertDialogHeader>++ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => rotate.mutate()}+ >+ Rotate+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog><Buttonsize="sm"onClick={() =>@@ -125,13 +146,13 @@ export function TrackingScript() {}type="button">- <Icon icon={Copy} data-icon="inline-start" />+ <Icon icon={CopyIcon} data-icon="inline-start" />Copy</Button>- </CardAction>- </CardHeader>-- <CardContent>+ </div>+ }+ >+ <div className="flex flex-col gap-5"><Accordiontype="single"collapsible@@ -150,11 +171,13 @@ export function TrackingScript() {{"\n async\n defer\n"}<span className="text-code-accent">{"></script>"}</span></pre>- <p className="text-muted-foreground text-xs/relaxed">- Site ID{" "}- <span className="font-mono text-foreground">{siteId}</span> ·- Rotating it stops every copy of the old script at once.- </p>+ <div className="flex flex-col gap-1 text-muted-foreground text-xs/relaxed">+ <p>+ Site ID{" "}+ <span className="font-mono text-foreground">{siteId}</span>+ </p>+ <p>Rotating it stops every copy of the old script at once.</p>+ </div></AccordionContent></AccordionItem>@@ -172,9 +195,7 @@ export function TrackingScript() {</pre><ol className="flex list-decimal flex-col gap-1 pl-4 text-muted-foreground text-xs/relaxed"><li>In Tag Manager, add a new Custom HTML tag.</li>- <li>- Paste this snippet — not the one above — as the tag's HTML.- </li>+ <li>Use this snippet as the tag's HTML.</li><li>Trigger it on All Pages, then publish the container. Keep{" "}<span className="font-mono text-foreground">{scriptUrl}</span>{" "}@@ -191,66 +212,24 @@ export function TrackingScript() {</AccordionItem></Accordion>- <div className="flex items-center justify-between gap-6">- <Label- htmlFor="tracking-paused"- className="flex flex-col items-start gap-1"- >- <span className="text-sm">Pause tracking</span>- <span className="font-normal text-muted-foreground text-xs">- The script keeps loading and records nothing. Your domains and- settings are kept- </span>- </Label>-- <Switch- id="tracking-paused"- checked={paused}- disabled={!canManage || setFlag.isPending}- onCheckedChange={(enabled) =>- setFlag.mutate({ flag: "paused", enabled })- }+ <SettingRows>+ <SettingRow+ title="Pause tracking"+ description="The script keeps loading and records nothing. Your domains and settings are kept."+ control={(id, describedBy) => (+ <Switch+ id={id}+ aria-describedby={describedBy}+ checked={paused}+ disabled={!canManage || setFlag.isPending}+ onCheckedChange={(enabled) =>+ setFlag.mutate({ flag: "paused", enabled })+ }+ />+ )}/>- </div>-- <CardFooter>- <div className="-ml-2 flex flex-wrap items-center gap-1 text-muted-foreground">- <AlertDialog>- <AlertDialogTrigger asChild>- <Button- variant="ghost"- size="xs"- disabled={!canManage || rotate.isPending}- >- Rotate site ID- </Button>- </AlertDialogTrigger>-- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Rotate the site ID?</AlertDialogTitle>- <AlertDialogDescription>- Every copy of the old script stops recording at once,- including any you have forgotten about. You will need to- paste the new tag on every page that carries the old one.- Nothing already collected is lost.- </AlertDialogDescription>- </AlertDialogHeader>-- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- variant="destructive"- onClick={() => rotate.mutate()}- >- Rotate- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- </div>- </CardFooter>- </CardContent>- </Card>+ </SettingRows>+ </div>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/traffic-sources.tsx b/apps/app/app/(app)/[slug]/settings/tracking/traffic-sources.tsxindex 164caef7..0c6ad288 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/traffic-sources.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/traffic-sources.tsx@@ -1,12 +1,6 @@"use client";-import {- Card,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { CardTableEmpty } from "@crm/ui/components/card-table";+import { SettingsCard } from "@crm/ui/components/settings-card";import {SimpleTable,type SimpleTableColumn,@@ -32,27 +26,23 @@ export function TrafficSources() {if (!sources.data) return null;return (- <Card>- <CardHeader>- <CardTitle>Traffic sources</CardTitle>- <CardDescription>- Where your visitors come from. Only people who have submitted a form- are attributed to a record.- </CardDescription>- </CardHeader>-+ <SettingsCard+ title="Traffic sources"+ description="Where your visitors come from. Only people who have submitted a form are attributed to a record."+ control={sources.data.length === 0 ? "full" : "table"}+ >{sources.data.length === 0 ? (- <CardTableEmpty>+ <p className="text-muted-foreground text-sm">No sources yet. They appear once the script records its first pageview.- </CardTableEmpty>+ </p>) : (<SimpleTable columns={COLUMNS}>{sources.data.map((row) => (<SimpleTableRow key={`${row.source}-${row.medium ?? ""}`}><TableCell className={CELL}>{row.source}</TableCell><TableCell className={`${CELL} text-muted-foreground`}>- {row.medium ?? "—"}+ {row.medium ?? ""}</TableCell><TableCell className={`${CELL} text-right tabular-nums`}>{row.views.toLocaleString()}@@ -64,6 +54,6 @@ export function TrafficSources() {))}</SimpleTable>)}- </Card>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/settings/tracking/verify-installation.tsx b/apps/app/app/(app)/[slug]/settings/tracking/verify-installation.tsxindex 5b10f21a..07ed1ca8 100644--- a/apps/app/app/(app)/[slug]/settings/tracking/verify-installation.tsx+++ b/apps/app/app/(app)/[slug]/settings/tracking/verify-installation.tsx@@ -1,18 +1,8 @@"use client";-import CheckmarkFilled from "@carbon/icons-react/es/CheckmarkFilled";-import Warning from "@carbon/icons-react/es/Warning";import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";-import { Field, FieldDescription, FieldLabel } from "@crm/ui/components/field";+import { Field, FieldLabel } from "@crm/ui/components/field";import { Icon } from "@crm/ui/components/icon";import {InputGroup,@@ -20,9 +10,11 @@ import {InputGroupInput,InputGroupText,} from "@crm/ui/components/input-group";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { useMutation, useQuery } from "@tanstack/react-query";+import { CircleAlertIcon, CircleCheckIcon } from "lucide-react";import { useId, useState } from "react";import { toast } from "sonner";import { useTRPC } from "@/lib/trpc/client";@@ -51,33 +43,24 @@ export function VerifyInstallation() {const { canManage, siteId } = tracking.data;return (- <Card>- <CardHeader>- <CardTitle>- <div className="flex items-center gap-2">- Verify installation- {result ? <Indicator result={result} /> : null}- </div>- </CardTitle>- <CardDescription>- We load one page and look for the script, then read your Tag Manager- container if it is not in the HTML.- </CardDescription>-- <CardAction>- <Button- size="sm"- type="submit"- form="verify-tracking"- disabled={!canManage || verify.isPending || url.trim() === ""}- >- {verify.isPending ? <Spinner data-icon="inline-start" /> : null}- Check now- </Button>- </CardAction>- </CardHeader>-- <CardContent>+ <SettingsCard+ title="Verify installation"+ status={result ? <Indicator result={result} /> : null}+ description="We load one page and look for the script, then read your Tag Manager container if it is not in the HTML."+ hint="The page has to be public. A page behind a login always fails this check."+ action={+ <Button+ size="sm"+ type="submit"+ form="verify-tracking"+ disabled={!canManage || verify.isPending || url.trim() === ""}+ >+ {verify.isPending ? <Spinner data-icon="inline-start" /> : null}+ Check now+ </Button>+ }+ >+ <div className="flex flex-col gap-4"><formid="verify-tracking"onSubmit={(event) => {@@ -108,16 +91,12 @@ export function VerifyInstallation() {disabled={!canManage || verify.isPending}/></InputGroup>- <FieldDescription>- The page has to be public. A page behind a login always fails this- check.- </FieldDescription></Field></form>{result && siteId ? <Outcome result={result} siteId={siteId} /> : null}- </CardContent>- </Card>+ </div>+ </SettingsCard>);}@@ -151,7 +130,7 @@ function Outcome({ result, siteId }: { result: Result; siteId: string }) {if (result.status === "unreachable") {return (<Alert variant="destructive">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>Could not open {result.host}</AlertTitle><AlertDescription>{result.detail} We only follow public pages, and we never follow a@@ -164,7 +143,7 @@ function Outcome({ result, siteId }: { result: Result; siteId: string }) {if (result.status === "missing") {return (<Alert variant="destructive">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>No script on {result.host}</AlertTitle><AlertDescription>The page answered in {result.responseMs} ms, but the tag was not in@@ -181,7 +160,7 @@ function Outcome({ result, siteId }: { result: Result; siteId: string }) {if (result.container && !result.container.carriesSiteId) {return (<Alert variant="destructive">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>Tag Manager will drop the site ID</AlertTitle><AlertDescription>Container {result.container.id} carries the tag, but the site ID is@@ -199,7 +178,7 @@ function Outcome({ result, siteId }: { result: Result; siteId: string }) {return (<Alert>- <Icon icon={CheckmarkFilled} className="text-success" />+ <Icon icon={CircleCheckIcon} className="text-success" /><AlertTitle>{result.container? `Script found in container ${result.container.id}`@@ -209,11 +188,11 @@ function Outcome({ result, siteId }: { result: Result; siteId: string }) {It answered in {result.responseMs} ms. Site ID {siteId} matched, andthis domain is {result.allowed ? "on" : "not on"} the allow list.{result.container- ? " The tag is not in the HTML, so it only runs once Tag Manager fires it — a page view is the proof."+ ? " Tag Manager runs the tag after page load. A recorded page view confirms the installation.": ""}{result.pageView? " A page view arrived in the last five minutes."- : " No page view has arrived yet — open the page in a browser to send one."}+ : " No page view has arrived yet. Open the page in a browser to send one."}</AlertDescription></Alert>);diff --git a/apps/app/app/(app)/[slug]/settings/workspace-form.tsx b/apps/app/app/(app)/[slug]/settings/workspace-form.tsxindex 9ced0371..5483d34e 100644--- a/apps/app/app/(app)/[slug]/settings/workspace-form.tsx+++ b/apps/app/app/(app)/[slug]/settings/workspace-form.tsx@@ -1,14 +1,6 @@"use client";import { Button } from "@crm/ui/components/button";-import {- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@crm/ui/components/card";import {Field,FieldDescription,@@ -22,6 +14,7 @@ import {InputGroupInput,InputGroupText,} from "@crm/ui/components/input-group";+import { SettingsCard } from "@crm/ui/components/settings-card";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";import { useRouter } from "next/navigation";@@ -73,89 +66,80 @@ export function WorkspaceForm() {setDraft({ ...values, ...patch });return (- <Card>- <CardHeader>- <CardTitle>Workspace</CardTitle>- <CardDescription>- The name and website of the company using this CRM.- </CardDescription>-- <CardAction>- <Button- type="submit"- form="workspace"- disabled={- !canRename ||- save.isPending ||- !dirty ||- values.name.trim() === "" ||- values.website.trim() === ""- }- >- {save.isPending ? <Spinner data-icon="inline-start" /> : null}- Save- </Button>- </CardAction>- </CardHeader>-- <CardContent>- <form- id="workspace"- onSubmit={(event) => {- event.preventDefault();- save.mutate({- name: values.name,- website: values.website.trim(),- });- }}+ <SettingsCard+ title="Workspace"+ description="The name and website of the company using this CRM."+ hint={+ canRename+ ? "Shown wherever the CRM refers to your own company."+ : "Only an owner or an admin can change this."+ }+ action={+ <Button+ type="submit"+ form="workspace"+ size="sm"+ disabled={+ !canRename ||+ save.isPending ||+ !dirty ||+ values.name.trim() === "" ||+ values.website.trim() === ""+ }>- <FieldGroup>- <Field>- <FieldLabel htmlFor={nameId}>Name</FieldLabel>- <Input- id={nameId}- value={values.name}- onChange={(event) => edit({ name: event.target.value })}- placeholder="Acme Inc."- autoComplete="organization"+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ Save+ </Button>+ }+ control="compact"+ >+ <form+ id="workspace"+ onSubmit={(event) => {+ event.preventDefault();+ save.mutate({+ name: values.name,+ website: values.website.trim(),+ });+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>+ <Input+ id={nameId}+ value={values.name}+ onChange={(event) => edit({ name: event.target.value })}+ placeholder="Acme Inc."+ autoComplete="organization"+ disabled={!canRename || save.isPending}+ required+ />+ </Field>++ <Field>+ <FieldLabel htmlFor={websiteId}>Website</FieldLabel>+ <InputGroup>+ <InputGroupAddon>+ <InputGroupText>https://</InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ id={websiteId}+ value={values.website}+ onChange={(event) => edit({ website: event.target.value })}+ placeholder="acme.com"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ inputMode="url"disabled={!canRename || save.isPending}- required/>- <FieldDescription>- Shown wherever the CRM refers to your own company.- </FieldDescription>- </Field>-- <Field>- <FieldLabel htmlFor={websiteId}>Website</FieldLabel>- <InputGroup>- <InputGroupAddon>- <InputGroupText>https://</InputGroupText>- </InputGroupAddon>- <InputGroupInput- id={websiteId}- value={values.website}- onChange={(event) => edit({ website: event.target.value })}- placeholder="acme.com"- autoComplete="off"- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- inputMode="url"- disabled={!canRename || save.isPending}- />- </InputGroup>- <FieldDescription>Your own company's website.</FieldDescription>- </Field>- </FieldGroup>- </form>-- {canRename ? null : (- <p className="text-muted-foreground text-xs">- Only an owner or an admin can change this.- </p>- )}- </CardContent>- </Card>+ </InputGroup>+ <FieldDescription>Your own company's website.</FieldDescription>+ </Field>+ </FieldGroup>+ </form>+ </SettingsCard>);}diff --git a/apps/app/app/(app)/[slug]/tasks/page.tsx b/apps/app/app/(app)/[slug]/tasks/page.tsxindex f08cadcc..680c1e0c 100644--- a/apps/app/app/(app)/[slug]/tasks/page.tsx+++ b/apps/app/app/(app)/[slug]/tasks/page.tsx@@ -1,5 +1,3 @@-import type { Metadata } from "next";-import { Suspense } from "react";import {PageShell,PageShellContent,@@ -8,7 +6,9 @@ import {PageShellHeading,PageShellLoading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import type { Metadata } from "next";+import { Suspense } from "react";import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";@@ -31,7 +31,7 @@ export default function TasksPage({</PageShellHeading></PageShellHeader><PageShellContent className="min-h-0">- <Suspense fallback={<PageShellLoading />}>+ <Suspense fallback={<PageShellLoading shape="table" />}><Tasks searchParams={searchParams} /></Suspense></PageShellContent>diff --git a/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx b/apps/app/app/(app)/[slug]/tasks/tasks-table.tsxindex 704616b5..3ba8332c 100644--- a/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx+++ b/apps/app/app/(app)/[slug]/tasks/tasks-table.tsx@@ -14,6 +14,7 @@ import { useRef, useState } from "react";import { toast } from "sonner";import { contactName } from "@/components/crm/contact-name";import { RecordLink } from "@/components/crm/record-sheet/record-link";+import { ListEmpty } from "@/components/data-table/list-empty";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";@@ -85,7 +86,7 @@ export function TasksTable() {label: "Status",sortable: true,hideable: false,- width: "w-12",+ width: "12",cell: (row) => (<Checkboxref={(element) => {@@ -104,12 +105,11 @@ export function TasksTable() {header: "Task",sortable: true,hideable: false,- width: "w-[34%]",cell: (row) =>row.subject ? (<spanclassName={cn(- "truncate font-medium",+ "block truncate font-medium",row.completedAt && "text-muted-foreground line-through",)}>@@ -123,7 +123,7 @@ export function TasksTable() {id: "company",header: "Related to",sortable: true,- width: "w-[24%]",+ width: { sm: "56" },cell: (row) => {if (row.deal) {return (@@ -154,7 +154,7 @@ export function TasksTable() {header: "Due",sortable: true,align: "right",- width: "w-32",+ width: { sm: "32" },cell: (row) =>row.dueAt ? (<span@@ -173,7 +173,7 @@ export function TasksTable() {id: "createdBy",header: "Created by",sortable: true,- width: "w-44",+ width: "44",hideBelow: "md",cell: (row) => (<span className="flex min-w-0 items-center gap-2">@@ -194,7 +194,7 @@ export function TasksTable() {header: "Created",sortable: true,align: "right",- width: "w-24",+ width: "28",defaultHidden: true,cell: (row) => (<span className="text-muted-foreground">@@ -228,6 +228,7 @@ export function TasksTable() {{announcement}</span><DataTable+ label="Tasks"query={query}search={<ListSearch inputRef={searchRef} placeholder="Search tasks…" />}columns={columns}@@ -237,6 +238,7 @@ export function TasksTable() {facets={facets}tabs={{id: "status",+ label: "Status",allLabel: "All tasks",options: [{ value: "open", label: "Open" },@@ -245,7 +247,17 @@ export function TasksTable() {}}getRowId={(row) => row.id}loading={tasks.isFetching}- empty="No tasks match this view."+ empty={+ <ListEmpty+ query={query}+ noun="tasks"+ blank={{+ title: "No tasks yet",+ description:+ "Tasks you add to a company, contact or deal show here.",+ }}+ />+ }/></>);diff --git a/apps/app/app/(landing)/grant-access/grant-access.tsx b/apps/app/app/(landing)/grant-access/grant-access.tsxindex 9f5ee1fa..f194eb65 100644--- a/apps/app/app/(landing)/grant-access/grant-access.tsx+++ b/apps/app/app/(landing)/grant-access/grant-access.tsx@@ -6,10 +6,10 @@ import {MICROSOFT_SYNC_SCOPES,SYNC_SCOPES,} from "@crm/auth/scopes";+import { AuthButton } from "@crm/ui/components/auth-button";import GoogleLogo from "@crm/ui/components/brand-logos/google";import MicrosoftLogo from "@crm/ui/components/brand-logos/microsoft";-import { Button } from "@crm/ui/components/button";-import { Spinner } from "@crm/ui/components/spinner";+import { LogoSpinner } from "@crm/ui/components/logo-spinner";import type { FC, SVGProps } from "react";import { useState } from "react";import { toast } from "sonner";@@ -69,7 +69,7 @@ export function GrantAccess({const { label, Logo } = PROVIDERS[provider];return (- <Button+ <AuthButtonkey={provider}className="w-full"disabled={pending !== null}@@ -79,16 +79,16 @@ export function GrantAccess({type="button">{pending === provider ? (- <Spinner data-icon="inline-start" />+ <LogoSpinner data-icon="inline-start" />) : (<Logo data-icon="inline-start" className="size-4" />)}{single ? "Grant access" : label}- </Button>+ </AuthButton>);})}- <Button+ <AuthButtonclassName="w-full"onClick={() => {signOutAndRedirect().catch(() => toast.error("Could not sign out."));@@ -97,7 +97,7 @@ export function GrantAccess({variant="ghost">Sign out- </Button>+ </AuthButton></div>);}diff --git a/apps/app/app/(landing)/grant-access/page.tsx b/apps/app/app/(landing)/grant-access/page.tsxindex 8edbe86e..b9732e95 100644--- a/apps/app/app/(landing)/grant-access/page.tsx+++ b/apps/app/app/(landing)/grant-access/page.tsx@@ -13,13 +13,13 @@ export const instant = false;const DESCRIPTION = {google:- "This CRM reads your Gmail and Calendar so meetings and email threads show up on the right company. It is read-only — nothing is ever sent on your behalf.",+ "This CRM reads your Gmail and Calendar so meetings and email threads show up on the right company. Access is read-only. The CRM sends nothing on your behalf.",microsoft:- "This CRM reads your Outlook mail so email threads show up on the right company. It is read-only — nothing is ever sent on your behalf.",+ "This CRM reads your Outlook mail so email threads show up on the right company. Access is read-only. The CRM sends nothing on your behalf.",} satisfies Record<MailboxProviderId, string>;const BOTH =- "This CRM reads your mail and calendar so meetings and email threads show up on the right company. It is read-only — nothing is ever sent on your behalf.";+ "This CRM reads your mail and calendar so meetings and email threads show up on the right company. Access is read-only. The CRM sends nothing on your behalf.";export default async function GrantAccessPage() {const { user } = await requireSession();diff --git a/apps/app/app/(landing)/onboarding/onboarding-form.tsx b/apps/app/app/(landing)/onboarding/onboarding-form.tsxindex 7f813dbb..8a5f8ca4 100644--- a/apps/app/app/(landing)/onboarding/onboarding-form.tsx+++ b/apps/app/app/(landing)/onboarding/onboarding-form.tsx@@ -1,21 +1,21 @@"use client";import { workspaceSlug } from "@crm/db/workspace";-import { Button } from "@crm/ui/components/button";+import { AuthButton } from "@crm/ui/components/auth-button";import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,-} from "@crm/ui/components/field";-import { Input } from "@crm/ui/components/input";+ AuthField,+ AuthFieldDescription,+ AuthFieldGroup,+ AuthFieldLabel,+} from "@crm/ui/components/auth-field";+import { AuthInput } from "@crm/ui/components/auth-input";import {- InputGroup,- InputGroupAddon,- InputGroupInput,- InputGroupText,-} from "@crm/ui/components/input-group";-import { Spinner } from "@crm/ui/components/spinner";+ AuthInputGroup,+ AuthInputGroupAddon,+ AuthInputGroupInput,+ AuthInputGroupText,+} from "@crm/ui/components/auth-input-group";+import { LogoSpinner } from "@crm/ui/components/logo-spinner";import { useMutation } from "@tanstack/react-query";import { useRouter } from "next/navigation";import { useId, useRef, useState } from "react";@@ -58,10 +58,10 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {}}className="flex flex-col gap-6">- <FieldGroup>- <Field>- <FieldLabel htmlFor={nameId}>Company name</FieldLabel>- <Input+ <AuthFieldGroup>+ <AuthField>+ <AuthFieldLabel htmlFor={nameId}>Company name</AuthFieldLabel>+ <AuthInputid={nameId}name="name"value={name}@@ -75,15 +75,15 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {autoFocusrequired/>- </Field>+ </AuthField>- <Field>- <FieldLabel htmlFor={slugId}>Workspace URL</FieldLabel>- <InputGroup>- <InputGroupAddon>- <InputGroupText>/</InputGroupText>- </InputGroupAddon>- <InputGroupInput+ <AuthField>+ <AuthFieldLabel htmlFor={slugId}>Workspace URL</AuthFieldLabel>+ <AuthInputGroup>+ <AuthInputGroupAddon>+ <AuthInputGroupText>/</AuthInputGroupText>+ </AuthInputGroupAddon>+ <AuthInputGroupInputid={slugId}name="slug"value={slug}@@ -101,19 +101,19 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {spellCheck={false}required/>- </InputGroup>- <FieldDescription>+ </AuthInputGroup>+ <AuthFieldDescription>Your team will use this address to open the CRM.- </FieldDescription>- </Field>+ </AuthFieldDescription>+ </AuthField>- <Field>- <FieldLabel htmlFor={websiteId}>Website</FieldLabel>- <InputGroup>- <InputGroupAddon>- <InputGroupText>https://</InputGroupText>- </InputGroupAddon>- <InputGroupInput+ <AuthField>+ <AuthFieldLabel htmlFor={websiteId}>Website</AuthFieldLabel>+ <AuthInputGroup>+ <AuthInputGroupAddon>+ <AuthInputGroupText>https://</AuthInputGroupText>+ </AuthInputGroupAddon>+ <AuthInputGroupInputid={websiteId}name="website"placeholder="acme.com"@@ -124,17 +124,17 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {inputMode="url"required/>- </InputGroup>- <FieldDescription>+ </AuthInputGroup>+ <AuthFieldDescription>Read once, so every answer afterwards knows what you sell.- </FieldDescription>- </Field>- </FieldGroup>+ </AuthFieldDescription>+ </AuthField>+ </AuthFieldGroup>- <Button type="submit" disabled={save.isPending}>- {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ <AuthButton type="submit" disabled={save.isPending}>+ {save.isPending ? <LogoSpinner data-icon="inline-start" /> : null}Continue- </Button>+ </AuthButton></form>);}diff --git a/apps/app/app/(landing)/onboarding/research/research-form.tsx b/apps/app/app/(landing)/onboarding/research/research-form.tsxindex 30887d2e..137ba2a6 100644--- a/apps/app/app/(landing)/onboarding/research/research-form.tsx+++ b/apps/app/app/(landing)/onboarding/research/research-form.tsx@@ -1,15 +1,15 @@"use client";import { CONTEXT_DEV_SIGNUP_URL } from "@crm/db/settings";-import { Button } from "@crm/ui/components/button";+import { AuthButton } from "@crm/ui/components/auth-button";import {- Field,- FieldDescription,- FieldGroup,- FieldLabel,-} from "@crm/ui/components/field";-import { Input } from "@crm/ui/components/input";-import { Spinner } from "@crm/ui/components/spinner";+ AuthField,+ AuthFieldDescription,+ AuthFieldGroup,+ AuthFieldLabel,+} from "@crm/ui/components/auth-field";+import { AuthInput } from "@crm/ui/components/auth-input";+import { LogoSpinner } from "@crm/ui/components/logo-spinner";import { useMutation } from "@tanstack/react-query";import { useRouter } from "next/navigation";import { useId } from "react";@@ -41,10 +41,10 @@ export function ResearchForm() {}}className="flex flex-col gap-6">- <FieldGroup>- <Field>- <FieldLabel htmlFor={keyId}>Context API key</FieldLabel>- <Input+ <AuthFieldGroup>+ <AuthField>+ <AuthFieldLabel htmlFor={keyId}>Context API key</AuthFieldLabel>+ <AuthInputid={keyId}name="apiKey"type="password"@@ -56,7 +56,7 @@ export function ResearchForm() {autoFocusrequired/>- <FieldDescription>+ <AuthFieldDescription>Don't have a Context API key?{" "}<ahref={CONTEXT_DEV_SIGNUP_URL}@@ -66,14 +66,14 @@ export function ResearchForm() {>Sign up here</a>- </FieldDescription>- </Field>- </FieldGroup>+ </AuthFieldDescription>+ </AuthField>+ </AuthFieldGroup>- <Button type="submit" disabled={save.isPending}>- {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ <AuthButton type="submit" disabled={save.isPending}>+ {save.isPending ? <LogoSpinner data-icon="inline-start" /> : null}Continue- </Button>+ </AuthButton></form>);}diff --git a/apps/app/app/(landing)/page.tsx b/apps/app/app/(landing)/page.tsxindex 8f27656d..53075df8 100644--- a/apps/app/app/(landing)/page.tsx+++ b/apps/app/app/(landing)/page.tsx@@ -11,7 +11,7 @@ import { ProductShot } from "@/components/landing/product-shot/product-shot";export const metadata: Metadata = {title: "The CRM for agents",description:- "The first agentic CRM experience — durable research agents that read your inbox, keep every record current and book their own follow-ups.",+ "The first agentic CRM experience. Durable research agents that read your inbox, keep every record current and book their own follow-ups.",};export default function Home() {diff --git a/apps/app/app/(landing)/sign-in/page.tsx b/apps/app/app/(landing)/sign-in/page.tsxindex 5b0e451a..039c4836 100644--- a/apps/app/app/(landing)/sign-in/page.tsx+++ b/apps/app/app/(landing)/sign-in/page.tsx@@ -90,12 +90,12 @@ async function SignIn({<><AuthHeadingtitle="No way in yet"- description="This CRM has no sign-in method configured, so nobody can get in — including you."+ description="This CRM has no sign-in method configured. Configure a provider to sign in."/><p className="text-center text-muted-foreground text-sm/5">- Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET — or MICROSOFT_CLIENT_ID- and MICROSOFT_CLIENT_SECRET — in the root .env file and restart. Your+ Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET, or MICROSOFT_CLIENT_ID+ and MICROSOFT_CLIENT_SECRET, in the root .env file and restart. Yourown identity provider can be added from Settings once somebody issigned in.</p>diff --git a/apps/app/app/(landing)/sign-in/social-sign-in.tsx b/apps/app/app/(landing)/sign-in/social-sign-in.tsxindex 882f89c1..9845409f 100644--- a/apps/app/app/(landing)/sign-in/social-sign-in.tsx+++ b/apps/app/app/(landing)/sign-in/social-sign-in.tsx@@ -2,10 +2,10 @@import { signIn } from "@crm/auth/client";import type { MailboxProviderId } from "@crm/auth/scopes";+import { AuthButton } from "@crm/ui/components/auth-button";import GoogleLogo from "@crm/ui/components/brand-logos/google";import MicrosoftLogo from "@crm/ui/components/brand-logos/microsoft";-import { Button } from "@crm/ui/components/button";-import { Spinner } from "@crm/ui/components/spinner";+import { LogoSpinner } from "@crm/ui/components/logo-spinner";import type { FC, SVGProps } from "react";import { useState } from "react";import { toast } from "sonner";@@ -45,7 +45,7 @@ export function SocialSignIn({ provider }: { provider: MailboxProviderId }) {}return (- <Button+ <AuthButtonclassName="w-full"disabled={pending}onClick={() => {@@ -55,11 +55,11 @@ export function SocialSignIn({ provider }: { provider: MailboxProviderId }) {variant="outline">{pending ? (- <Spinner data-icon="inline-start" />+ <LogoSpinner data-icon="inline-start" />) : (<Logo data-icon="inline-start" className="size-4" />)}{label}- </Button>+ </AuthButton>);}diff --git a/apps/app/app/(landing)/sign-in/sso-sign-in.tsx b/apps/app/app/(landing)/sign-in/sso-sign-in.tsxindex 62359276..93395559 100644--- a/apps/app/app/(landing)/sign-in/sso-sign-in.tsx+++ b/apps/app/app/(landing)/sign-in/sso-sign-in.tsx@@ -1,8 +1,8 @@"use client";import { signIn } from "@crm/auth/client";-import { Button } from "@crm/ui/components/button";-import { Spinner } from "@crm/ui/components/spinner";+import { AuthButton } from "@crm/ui/components/auth-button";+import { LogoSpinner } from "@crm/ui/components/logo-spinner";import { useState } from "react";import { toast } from "sonner";@@ -14,6 +14,11 @@ export type SsoProvider = {export function SsoSignIn({ providers }: { providers: SsoProvider[] }) {const [pending, setPending] = useState<string | null>(null);+ function fail(message?: string) {+ setPending(null);+ toast.error(message ?? "Could not reach the sign-in service.");+ }+async function handleClick(providerId: string) {setPending(providerId);@@ -25,28 +30,27 @@ export function SsoSignIn({ providers }: { providers: SsoProvider[] }) {errorCallbackURL: `${origin}/sign-in`,});- if (error) {- toast.error(error.message ?? "Could not reach the sign-in service.");- setPending(null);- }+ if (error) fail(error.message);}return (<>{providers.map((provider) => (- <Button+ <AuthButtonkey={provider.providerId}className="w-full"disabled={pending !== null}- onClick={() => handleClick(provider.providerId)}+ onClick={() => {+ handleClick(provider.providerId).catch(() => fail());+ }}type="button"variant="outline">{pending === provider.providerId ? (- <Spinner data-icon="inline-start" />+ <LogoSpinner data-icon="inline-start" />) : null}Continue with {provider.name}- </Button>+ </AuthButton>))}</>);diff --git a/apps/app/app/layout.tsx b/apps/app/app/layout.tsxindex d22ba155..4a4547c6 100644--- a/apps/app/app/layout.tsx+++ b/apps/app/app/layout.tsx@@ -1,10 +1,11 @@import "@crm/ui/globals.css";-import { Toaster } from "@crm/ui/components/sonner";import { TooltipProvider } from "@crm/ui/components/tooltip";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 { Suspense } from "react";+import { AppToaster } from "@/components/app-toaster";import { LocalDateTimeHydrator } from "@/components/local-date-time";import { ThemeProvider } from "@/components/theme-provider";import { TRPCReactProvider } from "@/lib/trpc/client";@@ -22,7 +23,7 @@ const fontMono = Geist_Mono({export const metadata: Metadata = {title: {default: "Comp AI - CRM",- template: "%s · Comp AI CRM",+ template: "Comp AI CRM: %s",},description: "Customer Relationship Management for Comp AI",icons: {@@ -51,7 +52,9 @@ export default function RootLayout({<TRPCReactProvider><ThemeProvider><TooltipProvider>{children}</TooltipProvider>- <Toaster richColors />+ <Suspense>+ <AppToaster />+ </Suspense></ThemeProvider></TRPCReactProvider></NuqsAdapter>diff --git a/apps/app/components/account-menu.tsx b/apps/app/components/account-menu.tsxnew file mode 100644index 00000000..decb3f51--- /dev/null+++ b/apps/app/components/account-menu.tsx@@ -0,0 +1,42 @@+"use client";++import { DropdownMenuItem } from "@crm/ui/components/dropdown-menu";+import { UserMenu, UserMenuSkeleton } from "@crm/ui/components/user-menu";+import { SettingsIcon } from "lucide-react";+import Link from "next/link";+import { useTheme } from "next-themes";+import { toast } from "sonner";+import { signOutAndRedirect } from "@/lib/sign-out";+import { useWorkspaceUrl } from "@/lib/use-workspace-url";++export type AccountUser = { name: string; email: string; image: string | null };++export function AccountMenu({ user }: { user: AccountUser }) {+ const { theme, setTheme } = useTheme();+ const workspaceUrl = useWorkspaceUrl();++ return (+ <UserMenu+ user={{ name: user.name, email: user.email, avatar: user.image }}+ theme={theme === "light" || theme === "dark" ? theme : "system"}+ onThemeChange={setTheme}+ onSignOut={() =>+ signOutAndRedirect().catch(() => {+ toast.error("Could not sign out.");+ })+ }+ actions={+ <DropdownMenuItem asChild>+ <Link href={workspaceUrl("/settings")}>+ <SettingsIcon aria-hidden />+ Settings+ </Link>+ </DropdownMenuItem>+ }+ />+ );+}++export function AccountMenuFallback() {+ return <UserMenuSkeleton />;+}diff --git a/apps/app/components/agent-builder/agent-builder-chat.tsx b/apps/app/components/agent-builder/agent-builder-chat.tsxindex e57bdf87..5d85dfbc 100644--- a/apps/app/components/agent-builder/agent-builder-chat.tsx+++ b/apps/app/components/agent-builder/agent-builder-chat.tsx@@ -1,20 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Application from "@carbon/icons-react/es/Application";-import ArrowRight from "@carbon/icons-react/es/ArrowRight";-import Building from "@carbon/icons-react/es/Building";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Copy from "@carbon/icons-react/es/Copy";-import Partnership from "@carbon/icons-react/es/Partnership";-import Play from "@carbon/icons-react/es/Play";-import Renew from "@carbon/icons-react/es/Renew";-import Reply from "@carbon/icons-react/es/Reply";-import Security from "@carbon/icons-react/es/Security";-import ThumbsDown from "@carbon/icons-react/es/ThumbsDown";-import ThumbsUp from "@carbon/icons-react/es/ThumbsUp";-import User from "@carbon/icons-react/es/User";-import WarningAlt from "@carbon/icons-react/es/WarningAlt";import {AsyncButtonContent,useAsyncAction,@@ -48,6 +33,23 @@ import {type UseEveAgentStatus,useEveAgent,} from "eve/react";+import {+ AppWindowIcon,+ ArrowRightIcon,+ Building2Icon,+ CheckIcon,+ CopyIcon,+ HandshakeIcon,+ PlayIcon,+ PlusIcon,+ RefreshCwIcon,+ ReplyIcon,+ ShieldIcon,+ ThumbsDownIcon,+ ThumbsUpIcon,+ TriangleAlertIcon,+ UserIcon,+} from "lucide-react";import Link from "next/link";import { Fragment, type ReactNode, useState } from "react";import { toast } from "sonner";@@ -935,7 +937,7 @@ function ChatHeader({{working ? (<span className="flex shrink-0 items-center gap-2 text-muted-foreground text-xs"><Icon- icon={Renew}+ icon={RefreshCwIcon}className="size-3.5 animate-spin text-ring"motion="none"/>@@ -948,7 +950,7 @@ function ChatHeader({</div><Button asChild variant="ghost" size="icon-sm"><Link href={workspaceUrl("/chat")} aria-label="Start a new chat">- <Icon icon={Add} />+ <Icon icon={PlusIcon} /></Link></Button><ShareChatDialog conversationId={conversation.id} title={title} />@@ -1015,13 +1017,13 @@ function UserSubmission({>{response ? (<div className="flex items-center gap-1.5 text-muted-foreground text-xs">- <Icon icon={Reply} className="size-3.5" />+ <Icon icon={ReplyIcon} className="size-3.5" /><span>Answer to follow-up</span></div>) : null}{submission.commandType === "CREATE_AGENT" ? (<div className="flex flex-wrap gap-1">- <ChatCommandChip label="Create agent" icon={Application} />+ <ChatCommandChip label="Create agent" icon={AppWindowIcon} /></div>) : null}<p className="wrap-break-word">{text}</p>@@ -1211,7 +1213,7 @@ function PermissionModeMenu({disabled={pending}aria-label={`Permission mode: ${selected?.label ?? "Manual"}`}>- <Icon icon={Security} data-icon="inline-start" />+ <Icon icon={ShieldIcon} data-icon="inline-start" />{selected?.label ?? "Manual"}</Button></DropdownMenuTrigger>@@ -1338,7 +1340,7 @@ function CopyResponseAction({ markdown }: { markdown: string }) {toast.success("Response copied as Markdown.");}}>- <Icon icon={Copy} />+ <Icon icon={CopyIcon} /></Button></div>);@@ -1381,7 +1383,7 @@ function ResponseActions({toast.success("Response copied as Markdown.");}}>- <Icon icon={Copy} />+ <Icon icon={CopyIcon} /></Button><Buttonvariant="ghost"@@ -1391,7 +1393,7 @@ function ResponseActions({className={cn(rating === "UP" && "bg-muted text-foreground")}onClick={() => choose("UP")}>- <Icon icon={ThumbsUp} />+ <Icon icon={ThumbsUpIcon} /></Button><Buttonvariant="ghost"@@ -1401,7 +1403,7 @@ function ResponseActions({className={cn(rating === "DOWN" && "bg-muted text-foreground")}onClick={() => choose("DOWN")}>- <Icon icon={ThumbsDown} />+ <Icon icon={ThumbsDownIcon} /></Button></div>);@@ -1457,7 +1459,7 @@ function BuildingAgentCard({)}>{done ? (- <Icon icon={Checkmark} className="size-3.5" />+ <Icon icon={CheckIcon} className="size-3.5" />) : active ? (<DotMatrix decorative />) : (@@ -1662,7 +1664,10 @@ function BuilderFailureCard({className="flex flex-col items-stretch gap-3 rounded-lg border border-destructive/30 bg-card px-4 py-3 sm:flex-row sm:items-start"><div className="flex min-w-0 flex-1 items-start gap-3">- <Icon icon={WarningAlt} className="mt-0.5 size-4 text-destructive" />+ <Icon+ icon={TriangleAlertIcon}+ className="mt-0.5 size-4 text-destructive"+ /><div className="min-w-0 flex-1"><p className="font-medium text-sm">{creatingAgent ? "Agent creation stopped" : "Response stopped"}@@ -1725,14 +1730,14 @@ function ReviewAgentCard({/></ReviewRow></div>- <AgentCardFooter note="Sandboxed · credentials never enter the sandbox">+ <AgentCardFooter note="Runs in a sandbox. Credentials never enter it."><Button asChild size="sm"><Linkhref={workspaceUrl(`/agents/${agent.id}`)}transitionTypes={["nav-forward"]}>View details- <Icon icon={ArrowRight} data-icon="inline-end" />+ <Icon icon={ArrowRightIcon} data-icon="inline-end" /></Link></Button></AgentCardFooter>@@ -1834,7 +1839,7 @@ function DeployedAgentCard({const nextRun =enabledTriggers.length === 1 ? enabledTriggers[0]?.nextRunAt : null;const triggerSummary =- enabledTriggers.map((trigger) => trigger.name).join(" · ") || "Manual only";+ enabledTriggers.map((trigger) => trigger.name).join(", ") || "Manual only";return (<div className="flex flex-col gap-[18px]">@@ -1865,8 +1870,9 @@ function DeployedAgentCard({)}/>- <ReviewRow label="Runs in" value="Eve runtime · isolated sandbox" />- <ReviewRow label="Owner" value={`Team · ${agent.createdBy.name}`} />+ <ReviewRow label="Runs in" value="Isolated Eve sandbox" />+ <ReviewRow label="Visibility" value="Team" />+ <ReviewRow label="Owner" value={agent.createdBy.name} /></div><AgentCardFooter note="The chat stays private. The agent is team-owned."><div className="flex items-center gap-2">@@ -1883,14 +1889,14 @@ function DeployedAgentCard({successLabel="Queued"errorLabel="Try again">- <Icon icon={Play} data-icon="inline-start" />+ <Icon icon={PlayIcon} data-icon="inline-start" />Run now</AsyncButtonContent></Button><Button asChild size="sm"><Link href={workspaceUrl(`/agents/${agent.id}`)}>Open agent- <Icon icon={ArrowRight} data-icon="inline-end" />+ <Icon icon={ArrowRightIcon} data-icon="inline-end" /></Link></Button></div>@@ -1911,7 +1917,10 @@ function DeployedAgentCard({<span className="min-w-0 flex-1 wrap-break-word text-sm">{suggestion}</span>- <Icon icon={ArrowRight} className="size-4 text-muted-foreground" />+ <Icon+ icon={ArrowRightIcon}+ className="size-4 text-muted-foreground"+ /></button>))}</div>@@ -1938,10 +1947,10 @@ function ChatUnavailable() {}const RESOURCE_ICONS = {- integration: Application,- company: Building,- contact: User,- deal: Partnership,+ integration: AppWindowIcon,+ company: Building2Icon,+ contact: UserIcon,+ deal: HandshakeIcon,} as const;function hasQueuedInputResponse(@@ -2018,7 +2027,7 @@ function manifestOf(manifest: AgentManifestSummary) {trigger.type === "EVENT" ? "On CRM event" : "On schedule",),)- .join(" · ") || "On demand",+ .join(", ") || "On demand",looksAt: textOf(manifest.dataScope.summary,"CRM records in the approved scope",diff --git a/apps/app/components/agent-builder/agent-builder-home.tsx b/apps/app/components/agent-builder/agent-builder-home.tsxindex 1217ca61..8b93cad8 100644--- a/apps/app/components/agent-builder/agent-builder-home.tsx+++ b/apps/app/components/agent-builder/agent-builder-home.tsx@@ -1,7 +1,6 @@"use client";-import ArrowRight from "@carbon/icons-react/es/ArrowRight";-import { Icon } from "@crm/ui/components/icon";+import { ChatSuggestions } from "@crm/ui/components/chat-thread";import { useMutation, useQueryClient } from "@tanstack/react-query";import { useState } from "react";import { toast } from "sonner";@@ -67,27 +66,13 @@ export function AgentBuilderHome({ name }: { name: string }) {it available to the whole team.</p>- <div className="pt-1">- <p className="flex h-7 items-center text-muted-foreground text-xs">- Suggested agents- </p>- {SUGGESTIONS.map((suggestion) => (- <button- key={suggestion}- type="button"- onClick={() => setInitialPrompt(`/Create agent ${suggestion}`)}- className="flex h-[42px] w-full items-center border-t text-left outline-none transition-colors hover:bg-muted/50 focus-visible:bg-muted/50"- >- <span className="min-w-0 flex-1 font-medium text-sm">- {suggestion}- </span>- <Icon- icon={ArrowRight}- className="size-4 text-muted-foreground"- />- </button>- ))}- </div>+ <ChatSuggestions+ label="Suggested agents"+ suggestions={SUGGESTIONS}+ onSelect={(suggestion) =>+ setInitialPrompt(`/Create agent ${suggestion}`)+ }+ /></div></main>);diff --git a/apps/app/components/agent-builder/agent-builder-shell.tsx b/apps/app/components/agent-builder/agent-builder-shell.tsxindex d0d9a000..2b2b5f93 100644--- a/apps/app/components/agent-builder/agent-builder-shell.tsx+++ b/apps/app/components/agent-builder/agent-builder-shell.tsx@@ -1,37 +1,3 @@-import { Skeleton } from "@crm/ui/components/skeleton";--export function AgentBuilderShell({- children,- sidebar,-}: {- children: React.ReactNode;- sidebar: React.ReactNode;-}) {- return (- <div className="flex min-h-0 min-w-0 flex-1">- {sidebar}- <div className="flex min-w-0 flex-1 flex-col">{children}</div>- </div>- );-}--export function AgentBuilderSidebarFallback() {- return (- <aside- className="hidden w-[213px] flex-none flex-col border-r p-4 md:flex"- aria-busy="true"- >- <div className="flex h-7 items-center pl-2 font-medium text-xs">- Chats- </div>- <div className="mt-3 space-y-2 px-2" aria-hidden="true">- <Skeleton className="h-2.5 w-16" />- <Skeleton className="h-7 w-full" />- <Skeleton className="h-7 w-full" />- </div>- <span role="status" className="sr-only">- Loading agent navigation…- </span>- </aside>- );+export function AgentBuilderShell({ children }: { children: React.ReactNode }) {+ return <div className="flex min-h-0 min-w-0 flex-1 flex-col">{children}</div>;}diff --git a/apps/app/components/agent-builder/agent-builder-sidebar.tsx b/apps/app/components/agent-builder/agent-builder-sidebar.tsxindex 7b58eba0..1ebad37c 100644--- a/apps/app/components/agent-builder/agent-builder-sidebar.tsx+++ b/apps/app/components/agent-builder/agent-builder-sidebar.tsx@@ -1,14 +1,19 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Bot from "@carbon/icons-react/es/Bot";-import CheckmarkFilled from "@carbon/icons-react/es/CheckmarkFilled";-import CircleFilled from "@carbon/icons-react/es/CircleFilled";-import Renew from "@carbon/icons-react/es/Renew";-import { Button } from "@crm/ui/components/button";-import { Icon } from "@crm/ui/components/icon";-import { cn } from "@crm/ui/lib/utils";+import { useAppShellNav } from "@crm/ui/components/app-shell";+import {+ AppSidebarGroup,+ AppSidebarItem,+ AppSidebarSection,+ AppSidebarSkeleton,+} from "@crm/ui/components/app-sidebar";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ BotIcon,+ CircleCheckIcon,+ LoaderCircleIcon,+ PlusIcon,+} from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";import { type ChatDateGroup, chatDateGroup } from "@/lib/chat-date-group";@@ -19,31 +24,16 @@ import { useWorkspaceUrl } from "@/lib/use-workspace-url";import { DeleteChatAction } from "./delete-chat-action";type Conversation = RouterOutputs["conversations"]["builderList"][number];-type TeamAgent = RouterOutputs["agents"]["list"][number];-type SidebarData = {- conversations: Conversation[];- agents: TeamAgent[];- updatedAt: number;-};--export function AgentBuilderSidebar({- className,- onNavigate,- initialData,-}: {- className?: string;- onNavigate?: () => void;- initialData?: SidebarData;-}) {++export function AgentChatNav() {const pathname = usePathname();const workspaceUrl = useWorkspaceUrl();const trpc = useTRPC();const queryClient = useQueryClient();const hydrated = useHydrated();+ const nav = useAppShellNav();const conversations = useQuery({...trpc.conversations.builderList.queryOptions(),- initialData: initialData?.conversations,- initialDataUpdatedAt: initialData?.updatedAt,refetchInterval: (query) =>query.state.data?.some((conversation) => conversation.state === "working")? 2500@@ -51,8 +41,6 @@ export function AgentBuilderSidebar({});const agents = useQuery({...trpc.agents.list.queryOptions(),- initialData: initialData?.agents,- initialDataUpdatedAt: initialData?.updatedAt,refetchInterval: 60_000,});const markRead = useMutation(@@ -64,167 +52,115 @@ export function AgentBuilderSidebar({}),);- const showData = Boolean(initialData) || hydrated;- const groupNow =- initialData && !hydrated- ? initialData.updatedAt- : conversations.dataUpdatedAt;- const groups = groupConversations(- showData ? (conversations.data ?? []) : [],- showData ? groupNow : 0,- );- const teamAgents = showData ? (agents.data ?? []) : [];+ const newChatHref = workspaceUrl("/chat");+ const agentsHref = workspaceUrl("/agents");+ const loading = !hydrated || conversations.isPending || agents.isPending;+ const groups = loading+ ? []+ : groupConversations(conversations.data ?? [], conversations.dataUpdatedAt);+ const teamAgents = loading ? [] : (agents.data ?? []);return (- <aside className={cn("min-h-0 min-w-0 flex-col p-4 font-sans", className)}>- <div className="flex h-7 shrink-0 items-center justify-between pl-2">- <span className="font-medium text-xs">Chats</span>- <Button asChild variant="ghost" size="icon-xs">- <Link- href={workspaceUrl("/chat")}- aria-label="New agent chat"- onClick={onNavigate}- >- <Icon icon={Add} />- </Link>- </Button>- </div>-- <nav aria-label="Agent chats" className="min-h-0 flex-1 overflow-y-auto">- {groups.map((group) => (- <div key={group.label}>- <div className="flex h-8 items-end pb-1 pl-2 font-medium text-[11px] text-muted-foreground uppercase tracking-[0.08em]">- {group.label}- </div>- {group.items.map((conversation) => {- const href = workspaceUrl(`/chat/${conversation.id}`);- const active = pathname === href;- const title = conversation.title ?? "Untitled chat";- return (- <div- key={conversation.id}- className="group relative flex h-7 min-w-0 items-center"- >- <Link- href={href}- aria-current={active ? "page" : undefined}- onClick={() => {- if (conversation.unread) {- markRead.mutate({ id: conversation.id });- }- onNavigate?.();- }}- className={cn(- "flex h-7 min-w-0 flex-1 items-center gap-3 rounded-sm pr-8 pl-2 text-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/60",- active && "bg-muted font-medium",- !active &&- conversation.state === "idle" &&- "text-muted-foreground",- )}- >- <ConversationState state={conversation.state} />- <span className="min-w-0 flex-1 truncate">{title}</span>- </Link>+ <AppSidebarSection+ label="Chat"+ back={<Link href={workspaceUrl()} transitionTypes={["nav-back"]} />}+ >+ <AppSidebarGroup>+ <AppSidebarItem+ icon={PlusIcon}+ label="New chat"+ active={pathname === newChatHref}+ >+ <Link href={newChatHref} />+ </AppSidebarItem>+ </AppSidebarGroup>++ {loading ? <AppSidebarSkeleton rows={3} /> : null}++ {groups.map((group) => (+ <AppSidebarGroup key={group.label} label={group.label} stacked>+ {group.items.map((conversation) => {+ const href = workspaceUrl(`/chat/${conversation.id}`);+ const active = pathname === href;+ const title = conversation.title ?? "Untitled chat";+ return (+ <AppSidebarItem+ key={conversation.id}+ label={title}+ active={active}+ indicator={<ConversationState state={conversation.state} />}+ action={<DeleteChatActionconversationId={conversation.id}title={title}trigger="close"returnToChatList={active}- onDeleted={active ? onNavigate : undefined}- className="absolute right-1 opacity-100 transition-opacity duration-150 [@media(hover:hover)]:pointer-events-none [@media(hover:hover)]:translate-x-1 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within:pointer-events-auto [@media(hover:hover)]:group-focus-within:translate-x-0 [@media(hover:hover)]:group-focus-within:opacity-100 [@media(hover:hover)]:group-hover:pointer-events-auto [@media(hover:hover)]:group-hover:translate-x-0 [@media(hover:hover)]:group-hover:opacity-100 motion-safe:transition-[opacity,translate] motion-reduce:translate-x-0"+ onDeleted={active ? nav.close : undefined}/>- </div>- );- })}- </div>- ))}-- {groups.length === 0 ? (- <p className="px-2 py-3 text-muted-foreground text-xs">- No chats in the last 7 days.- </p>- ) : null}-- <TeamAgents- agents={teamAgents}- pathname={pathname}- onNavigate={onNavigate}- />- </nav>- </aside>- );-}--function TeamAgents({- agents,- pathname,- onNavigate,-}: {- agents: TeamAgent[];- pathname: string;- onNavigate?: () => void;-}) {- const workspaceUrl = useWorkspaceUrl();-- return (- <div className="mt-3 border-t pt-1">- <Link- href={workspaceUrl("/agents")}- transitionTypes={["nav-lateral"]}- onClick={onNavigate}- className="flex h-8 items-end gap-2 rounded-sm px-2 pb-1 font-medium text-[11px] text-muted-foreground uppercase tracking-[0.08em] outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"- >- <span className="min-w-0 flex-1">Team agents</span>- <span className="shrink-0 font-mono">{agents.length}</span>- </Link>- {agents.map((agent) => {- const href = workspaceUrl(`/agents/${agent.id}`);- const active = pathname === href;- return (- <Link- key={agent.id}- href={href}- aria-current={active ? "page" : undefined}- onClick={onNavigate}- className={cn(- "flex h-7 items-center gap-3 rounded-sm px-2 text-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/60",- active ? "bg-muted font-medium" : "text-muted-foreground",- )}- >- <span className="flex size-5 shrink-0 items-center justify-center">- <Icon icon={Bot} className="size-3.5" />- </span>- <span className="min-w-0 flex-1 truncate">{agent.name}</span>- </Link>- );- })}- </div>+ }+ onClick={() => {+ if (conversation.unread) {+ markRead.mutate({ id: conversation.id });+ }+ }}+ >+ <Link href={href} />+ </AppSidebarItem>+ );+ })}+ </AppSidebarGroup>+ ))}++ {!loading && groups.length === 0 ? (+ <p className="px-4.5 py-2 text-13 text-muted-foreground">+ No chats in the last 7 days.+ </p>+ ) : null}++ <AppSidebarGroup label="Team agents">+ <AppSidebarItem+ icon={BotIcon}+ label="All agents"+ active={pathname === agentsHref}+ indicator={loading ? null : <span>{teamAgents.length}</span>}+ >+ <Link href={agentsHref} transitionTypes={["nav-lateral"]} />+ </AppSidebarItem>+ {teamAgents.map((agent) => {+ const href = workspaceUrl(`/agents/${agent.id}`);+ return (+ <AppSidebarItem+ key={agent.id}+ label={agent.name}+ active={pathname === href}+ inset+ >+ <Link href={href} />+ </AppSidebarItem>+ );+ })}+ </AppSidebarGroup>+ </AppSidebarSection>);}function ConversationState({ state }: { state: Conversation["state"] }) {if (state === "working") {- return (- <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">- <Icon icon={Renew} className="size-3.5 animate-spin" motion="none" />- </span>- );+ return <LoaderCircleIcon aria-label="Working" className="animate-spin" />;}if (state === "unread") {return (- <span className="flex size-5 shrink-0 items-center justify-center text-ring">- <Icon icon={CircleFilled} className="size-3.5" motion="none" />- </span>+ <span+ role="img"+ aria-label="Unread"+ className="mx-1 size-1.5 rounded-full bg-brand"+ />);}if (state === "deployed") {- return (- <span className="flex size-5 shrink-0 items-center justify-center text-ring">- <Icon icon={CheckmarkFilled} className="size-3.5" motion="none" />- </span>- );+ return <CircleCheckIcon aria-label="Deployed" className="text-brand" />;}return null;diff --git a/apps/app/components/agent-builder/agent-capabilities.tsx b/apps/app/components/agent-builder/agent-capabilities.tsxindex 36903761..59cef46f 100644--- a/apps/app/components/agent-builder/agent-capabilities.tsx+++ b/apps/app/components/agent-builder/agent-capabilities.tsx@@ -1,8 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Close from "@carbon/icons-react/es/Close";-import Warning from "@carbon/icons-react/es/Warning";import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";@@ -14,6 +11,7 @@ import {import { SaveBar } from "@crm/ui/components/save-bar";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { CircleAlertIcon, PlusIcon, XIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import {@@ -92,7 +90,7 @@ export function AgentCapabilities({if (!capabilities.readable) {return (<Alert variant="warning">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /><AlertTitle>This version's manifest cannot be read</AlertTitle><AlertDescription>{capabilities.problem ?? "The manifest is not in a shape we know."}@@ -235,8 +233,9 @@ export function AgentCapabilities({><div className="min-w-0 flex-1"><p className="text-sm">{tool.summary}</p>- <p className="font-mono text-muted-foreground text-xs">- {grant.platformSlug} · {tool.name}+ <p className="flex flex-wrap gap-x-3 font-mono text-muted-foreground text-xs">+ <span>{grant.platformSlug}</span>+ <span>{tool.name}</span></p></div><span className="rounded-md border px-2 py-1 text-xs">@@ -286,7 +285,7 @@ export function AgentCapabilities({}type="button">- <Icon className="size-3" icon={Close} motion="none" />+ <Icon className="size-3" icon={XIcon} motion="none" /></button>) : null}</span>@@ -362,7 +361,7 @@ function ResourcePicker({ onPick }: { onPick: (resource: Resource) => void }) {className="flex h-7 items-center gap-1.5 rounded-md border border-dashed px-2.5 text-muted-foreground text-sm hover:text-foreground"type="button">- <Icon className="size-3" icon={Add} motion="none" />+ <Icon className="size-3" icon={PlusIcon} motion="none" />Add a record type</button></PopoverTrigger>diff --git a/apps/app/components/agent-builder/agent-code-workspace.tsx b/apps/app/components/agent-builder/agent-code-workspace.tsxindex 5200bae6..04c34c87 100644--- a/apps/app/components/agent-builder/agent-code-workspace.tsx+++ b/apps/app/components/agent-builder/agent-code-workspace.tsx@@ -1,7 +1,5 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Renew from "@carbon/icons-react/es/Renew";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import { File, MultiFileDiff } from "@pierre/diffs/react";@@ -10,6 +8,7 @@ import {useFileTree,useFileTreeSelection,} from "@pierre/trees/react";+import { CheckIcon, RefreshCwIcon } from "lucide-react";import { useTheme } from "next-themes";import { useState } from "react";import { latestBuilderArtifacts } from "@/lib/agent-builder-state";@@ -114,7 +113,7 @@ function AgentCodeWorkspaceSurface({role={working ? "status" : undefined}><Icon- icon={working ? Renew : Checkmark}+ icon={working ? RefreshCwIcon : CheckIcon}className={working ? "size-3.5 animate-spin text-ring" : "size-3.5 text-ring"}diff --git a/apps/app/components/agent-builder/agent-composer.tsx b/apps/app/components/agent-builder/agent-composer.tsxindex bb4b289a..cda59ead 100644--- a/apps/app/components/agent-builder/agent-composer.tsx+++ b/apps/app/components/agent-builder/agent-composer.tsx@@ -1,23 +1,12 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Application from "@carbon/icons-react/es/Application";-import ArrowUp from "@carbon/icons-react/es/ArrowUp";-import AttachmentIcon from "@carbon/icons-react/es/Attachment";-import Building from "@carbon/icons-react/es/Building";-import Calendar from "@carbon/icons-react/es/Calendar";-import Email from "@carbon/icons-react/es/Email";-import Partnership from "@carbon/icons-react/es/Partnership";-import Search from "@carbon/icons-react/es/Search";-import StopFilled from "@carbon/icons-react/es/StopFilled";-import User from "@carbon/icons-react/es/User";import {AsyncButtonContent,useAsyncAction,} from "@crm/ui/components/async-action";import { Button } from "@crm/ui/components/button";import { CHAT_COMPOSER_SURFACE_CLASS_NAME } from "@crm/ui/components/chat-composer";-import { type CarbonIcon, Icon } from "@crm/ui/components/icon";+import { Icon, type IconComponent } from "@crm/ui/components/icon";import {InputGroup,InputGroupAddon,@@ -33,6 +22,19 @@ import { SkeletonSwap } from "@crm/ui/components/skeleton-swap";import { TokenField, TokenFieldEditable } from "@crm/ui/components/token-field";import { cn } from "@crm/ui/lib/utils";import { useQuery } from "@tanstack/react-query";+import {+ AppWindowIcon,+ ArrowUpIcon,+ Building2Icon,+ CalendarIcon,+ HandshakeIcon,+ MailIcon,+ PaperclipIcon,+ PlusIcon,+ SearchIcon,+ SquareIcon,+ UserIcon,+} from "lucide-react";import { type ReactNode, useReducer, useRef } from "react";import { flushSync } from "react-dom";import { toast } from "sonner";@@ -561,7 +563,12 @@ export function AgentComposer({successLabel={<span className="sr-only">Stopping</span>}errorLabel={<span className="sr-only">Stop failed</span>}>- <Icon icon={StopFilled} motion="none" />+ <Icon+ icon={SquareIcon}+ motion="none"+ size="xs"+ className="fill-current"+ /></AsyncButtonContent></Button>) : (@@ -592,7 +599,7 @@ export function AgentComposer({successLabel={<span className="sr-only">Sent</span>}errorLabel={<span className="sr-only">Send failed</span>}>- <Icon icon={ArrowUp} />+ <Icon icon={ArrowUpIcon} size="md" /></AsyncButtonContent></Button>)}@@ -818,7 +825,7 @@ function ComposerContextToken({content = (<ChatCommandChiplabel={state.command.label}- icon={Application}+ icon={AppWindowIcon}variant="composer"onRemove={remove}/>@@ -858,7 +865,7 @@ function ComposerContextToken({contentEditable={false}data-composer-token-key={anchor.key}data-composer-token-order={anchor.order}- className="inline-flex align-middle"+ className="inline-flex max-w-full align-middle">{content}</span>@@ -1299,7 +1306,7 @@ function ResourcePicker({aria-label="Tag CRM records and integrations"disabled={disabled}>- <Icon icon={Add} />+ <Icon icon={PlusIcon} /></Button></PopoverTrigger><PopoverContent size="fit" align="start" side="top" className="w-80">@@ -1318,7 +1325,7 @@ function ResourcePicker({disabled={disabled}/><InputGroupAddon>- <Icon icon={Search} className="size-3.5" />+ <Icon icon={SearchIcon} className="size-3.5" /></InputGroupAddon></InputGroup></div>@@ -1329,7 +1336,7 @@ function ResourcePicker({return (<ResourceButtonkey={source.source}- icon={calendar ? Calendar : Email}+ icon={calendar ? CalendarIcon : MailIcon}label={label}disabled={disabled}onSelect={() =>@@ -1427,7 +1434,7 @@ function AttachmentPicker({disabled={disabled}onClick={() => input.current?.click()}>- <Icon icon={AttachmentIcon} />+ <Icon icon={PaperclipIcon} /></Button></>);@@ -1477,7 +1484,7 @@ function CommandPicker({className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none hover:bg-muted focus-visible:bg-muted"disabled={disabled}>- <Icon icon={Application} className="size-4 text-muted-foreground" />+ <Icon icon={AppWindowIcon} className="size-4 text-muted-foreground" /><span className="font-medium text-xs">/{CREATE_AGENT_COMMAND.label}</span>@@ -1501,11 +1508,11 @@ function ResourceResultsSkeleton() {}const RESOURCE_ICONS = {- integration: Application,- company: Building,- contact: User,- deal: Partnership,-} satisfies Record<BuilderResource["kind"], CarbonIcon>;+ integration: AppWindowIcon,+ company: Building2Icon,+ contact: UserIcon,+ deal: HandshakeIcon,+} satisfies Record<BuilderResource["kind"], IconComponent>;function ResourceButton({icon,@@ -1514,7 +1521,7 @@ function ResourceButton({disabled,onSelect,}: {- icon: CarbonIcon;+ icon: IconComponent;label: string;imageUrl?: string | null;disabled: boolean;diff --git a/apps/app/components/agent-builder/agent-history.tsx b/apps/app/components/agent-builder/agent-history.tsxindex 7df33a1e..0d33b61e 100644--- a/apps/app/components/agent-builder/agent-history.tsx+++ b/apps/app/components/agent-builder/agent-history.tsx@@ -1,10 +1,5 @@"use client";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";-import ChevronUp from "@carbon/icons-react/es/ChevronUp";-import Download from "@carbon/icons-react/es/Download";-import Renew from "@carbon/icons-react/es/Renew";-import WarningAlt from "@carbon/icons-react/es/WarningAlt";import {AlertDialog,AlertDialogAction,@@ -18,6 +13,13 @@ import {import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import { cn } from "@crm/ui/lib/utils";+import {+ ChevronDownIcon,+ ChevronUpIcon,+ DownloadIcon,+ RefreshCwIcon,+ TriangleAlertIcon,+} from "lucide-react";import { useState } from "react";import { z } from "zod";import { runFailureReason } from "@/lib/agent-run-failure";@@ -133,14 +135,15 @@ export function AgentRuns({{humanStatus(run.status)}</span></span>- <span className="mt-1 block wrap-break-word font-mono text-muted-foreground text-xs leading-5 sm:mt-0">- {humanStatus(run.triggerType)} · {formatDate(run.createdAt)} ·- Version {run.version.number}+ <span className="mt-1 flex flex-wrap gap-x-3 font-mono text-muted-foreground text-xs leading-5 sm:mt-0">+ <span>{humanStatus(run.triggerType)}</span>+ <span>{formatDate(run.createdAt)}</span>+ <span>Version {run.version.number}</span></span>{run.status === "FAILED" || run.status === "CANCELLED" ? (<span className="mt-1.5 flex min-w-0 items-start gap-2 rounded-md bg-destructive/10 px-2.5 py-1.5"><Icon- icon={WarningAlt}+ icon={TriangleAlertIcon}className="mt-px size-3.5 shrink-0 text-destructive"/><span className="min-w-0 wrap-break-word text-destructive text-xs leading-5">@@ -156,7 +159,7 @@ export function AgentRuns({{run.actions.length === 1 ? "action" : "actions"}</span><Icon- icon={expanded === run.id ? ChevronUp : ChevronDown}+ icon={expanded === run.id ? ChevronUpIcon : ChevronDownIcon}className="size-3.5"/></span>@@ -170,7 +173,7 @@ export function AgentRuns({disabled={retryingRunId === run.id}onClick={() => onRetry(run.id)}>- <Icon icon={Renew} data-icon="inline-start" />+ <Icon icon={RefreshCwIcon} data-icon="inline-start" />Retry</Button></span>@@ -203,8 +206,8 @@ export function AgentRuns({<AlertDialogTitle>Stop this run?</AlertDialogTitle><AlertDialogDescription>The agent stops where it is and the run is recorded as cancelled.- Anything it has already done — a note, a task, a Slack message —- stays done.+ Anything it has already done, including notes, tasks and Slack+ messages, stays done.</AlertDialogDescription></AlertDialogHeader>@@ -288,11 +291,12 @@ function ExpandedRun({ run }: { run: RunRow }) {<span className="block wrap-break-word text-sm">{entry.action.summary}</span>- <span className="block wrap-break-word text-muted-foreground text-xs">- {entry.action.provider} · {humanStatus(entry.action.status)}- {entry.action.targetLabel- ? ` · ${entry.action.targetLabel}`- : ""}+ <span className="flex flex-wrap gap-x-3 wrap-break-word text-muted-foreground text-xs">+ <span>{entry.action.provider}</span>+ <span>{humanStatus(entry.action.status)}</span>+ {entry.action.targetLabel ? (+ <span>{entry.action.targetLabel}</span>+ ) : null}</span></span><span className="col-start-2 min-w-0 wrap-break-word font-mono text-muted-foreground text-xs sm:col-auto sm:shrink-0">@@ -358,7 +362,7 @@ export function AgentActivity({ activity }: { activity: Activity }) {size="sm"onClick={() => exportJson("agent-activity.json", visible)}>- <Icon icon={Download} data-icon="inline-start" />+ <Icon icon={DownloadIcon} data-icon="inline-start" />Export</Button></div>@@ -388,13 +392,13 @@ export function AgentActivity({ activity }: { activity: Activity }) {</span>) : null}</span>- <span className="min-w-0 wrap-break-word text-xs sm:w-[140px] sm:shrink-0 sm:text-sm">- <span className="text-muted-foreground sm:hidden">Actor · </span>+ <span className="flex min-w-0 flex-col wrap-break-word text-xs sm:block sm:w-[140px] sm:shrink-0 sm:text-sm">+ <span className="text-muted-foreground sm:hidden">Actor</span>{event.actorUser?.name ?? event.actorId ?? event.actorType}</span>- <span className="min-w-0 wrap-break-word font-mono text-muted-foreground text-xs sm:w-[118px] sm:shrink-0 sm:text-right">- <span className="font-sans sm:hidden">Request · </span>- {event.requestId?.slice(0, 12) ?? "—"}+ <span className="flex min-w-0 flex-col wrap-break-word font-mono text-muted-foreground text-xs sm:block sm:w-[118px] sm:shrink-0 sm:text-right">+ <span className="font-sans sm:hidden">Request</span>+ {event.requestId?.slice(0, 12) ?? ""}</span></div>))}@@ -424,7 +428,7 @@ function formatTime(value: string): string {}function duration(startedAt: string | null, finishedAt: string | null): string {- if (!startedAt) return "—";+ if (!startedAt) return "";if (!finishedAt) return "In progress";const milliseconds =diff --git a/apps/app/components/agent-builder/chat-chips.tsx b/apps/app/components/agent-builder/chat-chips.tsxindex e583f120..6b414317 100644--- a/apps/app/components/agent-builder/chat-chips.tsx+++ b/apps/app/components/agent-builder/chat-chips.tsx@@ -1,5 +1,3 @@-import Close from "@carbon/icons-react/es/Close";-import Document from "@carbon/icons-react/es/Document";import {Attachment,AttachmentAction,@@ -9,12 +7,13 @@ import {AttachmentTitle,} from "@crm/ui/components/attachment";import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";-import { type CarbonIcon, Icon } from "@crm/ui/components/icon";+import { Icon, type IconComponent } from "@crm/ui/components/icon";import {TokenFieldAction,TokenFieldItem,} from "@crm/ui/components/token-field";import { cn } from "@crm/ui/lib/utils";+import { FileTextIcon, XIcon } from "lucide-react";import Image from "next/image";type ChatChipVariant = "default" | "composer";@@ -43,7 +42,7 @@ export function ChatReferenceChip({variant = "default",}: {resource: ChatChipResource;- icon: CarbonIcon;+ icon: IconComponent;onRemove?: () => void;variant?: ChatChipVariant;}) {@@ -65,7 +64,7 @@ export function ChatReferenceChip({aria-label={`Remove ${resource.label}`}onClick={onRemove}>- <Icon icon={Close} className="size-3" />+ <Icon icon={XIcon} className="size-3" /></TokenFieldAction>) : null}</TokenFieldItem>@@ -82,7 +81,7 @@ export function ChatReferenceChip({onClick={onRemove}className="flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60">- <Icon icon={Close} className="size-3" />+ <Icon icon={XIcon} className="size-3" /></button>) : null}</span>@@ -96,7 +95,7 @@ export function ChatReferenceIdentity({compact = false,}: {resource: ChatChipResource;- icon: CarbonIcon;+ icon: IconComponent;showDetail?: boolean;compact?: boolean;}) {@@ -133,7 +132,6 @@ export function ChatAttachmentChip({onRemove?: () => void;variant?: ChatChipVariant;}) {- const label = `${attachment.name} · ${formatBytes(attachment.size)}`;const image = isPreviewableImage(attachment.type)? (attachment.previewUrl ??(attachment.contentBase64@@ -157,11 +155,16 @@ export function ChatAttachmentChip({className="size-full object-cover"/>) : (- <Icon icon={Document} />+ <Icon icon={FileTextIcon} />)}</AttachmentMedia>- <AttachmentContent>- <AttachmentTitle title={label}>{label}</AttachmentTitle>+ <AttachmentContent className="flex items-baseline gap-1.5">+ <AttachmentTitle title={attachment.name}>+ {attachment.name}+ </AttachmentTitle>+ <span className="shrink-0 text-muted-foreground tabular-nums">+ {formatBytes(attachment.size)}+ </span></AttachmentContent>{onRemove ? (<AttachmentActions>@@ -170,7 +173,7 @@ export function ChatAttachmentChip({aria-label={`Remove ${attachment.name}`}onClick={onRemove}>- <Icon icon={Close} />+ <Icon icon={XIcon} /></AttachmentAction></AttachmentActions>) : null}@@ -185,7 +188,7 @@ export function ChatCommandChip({variant = "default",}: {label: string;- icon: CarbonIcon;+ icon: IconComponent;onRemove?: () => void;variant?: ChatChipVariant;}) {@@ -196,7 +199,7 @@ export function ChatCommandChip({<span className="font-medium">{label}</span>{onRemove ? (<TokenFieldAction aria-label={`Remove ${label}`} onClick={onRemove}>- <Icon icon={Close} className="size-3" />+ <Icon icon={XIcon} className="size-3" /></TokenFieldAction>) : null}</TokenFieldItem>@@ -214,7 +217,7 @@ export function ChatCommandChip({onClick={onRemove}className="-mr-1 flex size-5 items-center justify-center rounded-sm outline-none hover:bg-primary-foreground/15 focus-visible:ring-2 focus-visible:ring-primary-foreground/60">- <Icon icon={Close} className="size-3" />+ <Icon icon={XIcon} className="size-3" /></button>) : null}</span>diff --git a/apps/app/components/agent-builder/deal-list-result.tsx b/apps/app/components/agent-builder/deal-list-result.tsxindex cd14ecec..a961f823 100644--- a/apps/app/components/agent-builder/deal-list-result.tsx+++ b/apps/app/components/agent-builder/deal-list-result.tsx@@ -62,7 +62,15 @@ export function DealListResultTable({ result }: { result: DealListResult }) {<SimpleTableRowkey={deal.id}clickable- onClick={() => openRecord(record)}+ onClick={() =>+ openRecord(+ record,+ result.deals.map((entry) => ({+ kind: "deal",+ id: entry.id,+ })),+ )+ }onFocus={() => prefetchRecord(record)}onMouseEnter={() => prefetchRecord(record)}>@@ -117,7 +125,11 @@ export function DealListResultTable({ result }: { result: DealListResult }) {)}</SimpleTable><div className="flex flex-wrap items-center justify-between gap-3 text-muted-foreground text-xs">- <span>{tableMeta(result)}</span>+ <span className="flex flex-wrap gap-x-3">+ {tableMeta(result).map((detail) => (+ <span key={detail}>{detail}</span>+ ))}+ </span><span>As of <LocalDay date={result.asOf} /></span>@@ -147,7 +159,7 @@ function tableTitle(result: DealListResult): string {: `${count} ${stale}${status}deal${count === 1 ? "" : "s"}`;}-function tableMeta(result: DealListResult): string {+function tableMeta(result: DealListResult): string[] {const details = [`${result.deals.length} deal${result.deals.length === 1 ? "" : "s"}`,pipelineTotal(result.deals),@@ -157,7 +169,7 @@ function tableMeta(result: DealListResult): string {result.hasMore ? "More results available" : null,].filter((detail): detail is string => Boolean(detail));- return details.join(" · ");+ return details;}function humaniseStage(stage: string): string {diff --git a/apps/app/components/agent-builder/delete-chat-action.tsx b/apps/app/components/agent-builder/delete-chat-action.tsxindex 1af2ddb6..03ee2104 100644--- a/apps/app/components/agent-builder/delete-chat-action.tsx+++ b/apps/app/components/agent-builder/delete-chat-action.tsx@@ -1,8 +1,5 @@"use client";-import Close from "@carbon/icons-react/es/Close";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import TrashCan from "@carbon/icons-react/es/TrashCan";import {AlertDialog,AlertDialogCancel,@@ -25,6 +22,7 @@ import {} from "@crm/ui/components/dropdown-menu";import { Icon } from "@crm/ui/components/icon";import { useMutation } from "@tanstack/react-query";+import { EllipsisVerticalIcon, Trash2Icon, XIcon } from "lucide-react";import { useRouter } from "next/navigation";import { useState } from "react";import { toast } from "sonner";@@ -82,7 +80,7 @@ export function DeleteChatAction({aria-label={`Delete ${title}`}onClick={() => setConfirming(true)}>- <Icon icon={Close} />+ <Icon icon={XIcon} /></Button>) : (<DropdownMenu>@@ -92,7 +90,7 @@ export function DeleteChatAction({size="icon-sm"disabled={removeAction.pending}>- <Icon icon={OverflowMenuVertical} />+ <Icon icon={EllipsisVerticalIcon} /><span className="sr-only">More chat actions</span></Button></DropdownMenuTrigger>@@ -101,7 +99,7 @@ export function DeleteChatAction({variant="destructive"onSelect={() => setConfirming(true)}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} />Delete chat</DropdownMenuItem></DropdownMenuContent>diff --git a/apps/app/components/agent-builder/new-agent-dialog.tsx b/apps/app/components/agent-builder/new-agent-dialog.tsxindex 22c6bc59..58d7b464 100644--- a/apps/app/components/agent-builder/new-agent-dialog.tsx+++ b/apps/app/components/agent-builder/new-agent-dialog.tsx@@ -1,6 +1,5 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";import { Button } from "@crm/ui/components/button";import {Dialog,@@ -24,6 +23,7 @@ import {import { Textarea } from "@crm/ui/components/textarea";import { InvalidInput, type Permission, parse, schemas } from "@crm/validation";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { CheckIcon } from "lucide-react";import { useRouter } from "next/navigation";import { useState } from "react";import { toast } from "sonner";@@ -181,7 +181,7 @@ export function NewAgentDialog({ children }: { children: React.ReactNode }) {{on ? (<IconclassName="size-3.5 text-primary"- icon={Checkmark}+ icon={CheckIcon}motion="none"/>) : null}diff --git a/apps/app/components/agent-builder/share-chat-dialog.tsx b/apps/app/components/agent-builder/share-chat-dialog.tsxindex 53a2cddd..b61c0510 100644--- a/apps/app/components/agent-builder/share-chat-dialog.tsx+++ b/apps/app/components/agent-builder/share-chat-dialog.tsx@@ -1,7 +1,5 @@"use client";-import Close from "@carbon/icons-react/es/Close";-import Copy from "@carbon/icons-react/es/Copy";import {AsyncButtonContent,useAsyncAction,@@ -20,6 +18,7 @@ import {import { Icon } from "@crm/ui/components/icon";import { cn } from "@crm/ui/lib/utils";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { CopyIcon, XIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { useTRPC } from "@/lib/trpc/client";@@ -127,7 +126,7 @@ export function ShareChatDialog({size="icon-sm"className="absolute top-4 right-4">- <Icon icon={Close} />+ <Icon icon={XIcon} /><span className="sr-only">Close</span></Button></DialogClose>@@ -211,7 +210,7 @@ export function ShareChatDialog({errorLabel="Try again">{shareToken ? (- <Icon icon={Copy} data-icon="inline-start" />+ <Icon icon={CopyIcon} data-icon="inline-start" />) : null}{shareToken ? "Copy link" : "Replace link"}</AsyncButtonContent>diff --git a/apps/app/components/agent-builder/team-agent-detail.tsx b/apps/app/components/agent-builder/team-agent-detail.tsxindex fa4c0e3e..62e2fa0d 100644--- a/apps/app/components/agent-builder/team-agent-detail.tsx+++ b/apps/app/components/agent-builder/team-agent-detail.tsx@@ -1,9 +1,5 @@"use client";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import Pause from "@carbon/icons-react/es/Pause";-import Play from "@carbon/icons-react/es/Play";-import TrashCan from "@carbon/icons-react/es/TrashCan";import {AlertDialog,AlertDialogCancel,@@ -25,12 +21,6 @@ import {DropdownMenuTrigger,} from "@crm/ui/components/dropdown-menu";import { Icon } from "@crm/ui/components/icon";-import { SaveBarViewport } from "@crm/ui/components/save-bar";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import Link from "next/link";-import { useRouter } from "next/navigation";-import { type ReactNode, useState } from "react";-import { toast } from "sonner";import {PageShell,PageShellActions,@@ -39,7 +29,19 @@ import {PageShellHeader,PageShellHeading,PageShellTitle,-} from "@/components/page-shell";+} from "@crm/ui/components/page-shell";+import { SaveBarViewport } from "@crm/ui/components/save-bar";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ EllipsisVerticalIcon,+ PauseIcon,+ PlayIcon,+ Trash2Icon,+} from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { type ReactNode, useState } from "react";+import { toast } from "sonner";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { useWorkspaceUrl } from "@/lib/use-workspace-url";@@ -200,7 +202,7 @@ export function TeamAgentDetail({const nextRun =enabledTriggers.length === 1 ? enabledTriggers[0]?.nextRunAt : null;const triggerSummary =- enabledTriggers.map((trigger) => trigger.name).join(" · ") || "Manual only";+ enabledTriggers.map((trigger) => trigger.name).join(", ") || "Manual only";return (<PageShell className="min-h-0" contained>@@ -211,10 +213,10 @@ export function TeamAgentDetail({</PageShellTitle><PageShellDescription className="wrap-break-word leading-6"><span className="block">{displayedDescription}</span>- <span className="mt-2 block text-xs">- Created by {data.createdBy.name} ·{" "}- {isDraft ? "Private draft" : "Team agent"} · Version{" "}- {displayedVersionNumber ?? "—"}+ <span className="mt-2 flex flex-wrap gap-x-3 text-xs">+ <span>Created by {data.createdBy.name}</span>+ <span>{isDraft ? "Private draft" : "Team agent"}</span>+ <span>Version {displayedVersionNumber ?? ""}</span></span></PageShellDescription></PageShellHeading>@@ -259,7 +261,7 @@ export function TeamAgentDetail({successLabel="Queued"errorLabel="Try again">- <Icon icon={Play} data-icon="inline-start" />+ <Icon icon={PlayIcon} data-icon="inline-start" />Run now</AsyncButtonContent></Button>@@ -277,7 +279,7 @@ export function TeamAgentDetail({successLabel="Paused"errorLabel="Try again">- <Icon icon={Pause} data-icon="inline-start" />+ <Icon icon={PauseIcon} data-icon="inline-start" />Pause</AsyncButtonContent></Button>@@ -295,7 +297,7 @@ export function TeamAgentDetail({successLabel="Resumed"errorLabel="Try again">- <Icon icon={Play} data-icon="inline-start" />+ <Icon icon={PlayIcon} data-icon="inline-start" />Resume</AsyncButtonContent></Button>@@ -464,7 +466,7 @@ function DeleteAgentAction({size="icon-sm"disabled={removeAction.pending}>- <Icon icon={OverflowMenuVertical} />+ <Icon icon={EllipsisVerticalIcon} /><span className="sr-only">More agent actions</span></Button></DropdownMenuTrigger>@@ -473,7 +475,7 @@ function DeleteAgentAction({variant="destructive"onSelect={() => setConfirming(true)}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} />Delete agent</DropdownMenuItem></DropdownMenuContent>diff --git a/apps/app/components/agent-builder/team-agents-index.tsx b/apps/app/components/agent-builder/team-agents-index.tsxindex 4d4b5bf5..2306edb8 100644--- a/apps/app/components/agent-builder/team-agents-index.tsx+++ b/apps/app/components/agent-builder/team-agents-index.tsx@@ -1,9 +1,9 @@"use client";-import ArrowRight from "@carbon/icons-react/es/ArrowRight";-import Bot from "@carbon/icons-react/es/Bot";import { Icon } from "@crm/ui/components/icon";+import Bot from "@crm/ui/components/icons/bot";import { useQuery } from "@tanstack/react-query";+import { ArrowRightIcon } from "lucide-react";import Link from "next/link";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -54,7 +54,7 @@ export function TeamAgentsIndex({ initialAgents }: { initialAgents: Agents }) {{agent.runCount} runs</span><Icon- icon={ArrowRight}+ icon={ArrowRightIcon}className="size-4 text-muted-foreground"/></Link>diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsxdeleted file mode 100644index 807d15be..00000000--- a/apps/app/components/app-header.tsx+++ /dev/null@@ -1,161 +0,0 @@-"use client";--import Asleep from "@carbon/icons-react/es/Asleep";-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 { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";-import { Button } from "@crm/ui/components/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@crm/ui/components/dropdown-menu";-import Logo from "@crm/ui/components/logo";-import { Separator } from "@crm/ui/components/separator";-import { Skeleton } from "@crm/ui/components/skeleton";-import { useQuery } from "@tanstack/react-query";-import Link from "next/link";-import { useTheme } from "next-themes";-import { toast } from "sonner";-import { EnrichmentQueue } from "@/components/enrichment-queue";-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 };--export function AppHeader({ user }: { user: User }) {- const { setOpen: setMobileNavOpen } = useMobileNav();- const trpc = useTRPC();- const workspaceUrl = useWorkspaceUrl();- const workspace = useQuery(trpc.workspace.get.queryOptions());- const label = workspaceLabel(workspace.data?.name);-- 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">- <Button- variant="ghost"- size="icon"- className="md:hidden"- aria-label="Open navigation"- onClick={() => setMobileNavOpen(true)}- >- <Menu />- </Button>- <Link- href={workspaceUrl()}- aria-label="Homepage"- className="hidden size-8 items-center justify-center text-foreground md:flex"- >- <Logo className="size-5" />- </Link>- <Separator orientation="vertical" className="mx-1 h-5 bg-transparent" />- <span className="min-w-0 truncate font-medium text-sm">{label}</span>- </div>-- <div className="ml-auto flex shrink-0 items-center gap-1.5">- <EnrichmentQueue />- <UserMenu- user={user}- onSignOut={() => {- signOutAndRedirect().catch(() =>- toast.error("Could not sign out."),- );- }}- />- </div>- </header>- );-}--export function AppHeaderFallback() {- return (- <header- className="flex h-12 shrink-0 items-center gap-2 border-b px-3 [view-transition-name:app-header]"- aria-busy="true"- >- <div className="flex shrink-0 items-center gap-1">- <span className="hidden size-8 items-center justify-center text-foreground md:flex">- <Logo className="size-5" />- </span>- <Separator orientation="vertical" className="mx-1 h-5 bg-transparent" />- <Skeleton className="h-4 w-24" />- </div>-- <div className="ml-auto flex shrink-0 items-center gap-1.5">- <Avatar className="size-7">- <AvatarFallback />- </Avatar>- </div>- <span role="status" className="sr-only">- Loading workspace header…- </span>- </header>- );-}--function UserMenu({ user, onSignOut }: { user: User; onSignOut: () => void }) {- const { resolvedTheme, setTheme } = useTheme();- const isDark = resolvedTheme === "dark";-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="ghost"- size="icon"- aria-label="Account menu"- className="hover:bg-transparent aria-expanded:bg-transparent dark:hover:bg-transparent"- >- <Avatar className="size-7">- {user.image && <AvatarImage alt={user.name} src={user.image} />}- <AvatarFallback className="text-xs">- {initials(user.name)}- </AvatarFallback>- </Avatar>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="min-w-56">- <DropdownMenuLabel className="flex items-center gap-2">- <UserAvatar />- <span className="min-w-0 truncate">{user.email}</span>- </DropdownMenuLabel>- <DropdownMenuSeparator />- <DropdownMenuItem- onSelect={(event) => {- event.preventDefault();- setTheme(isDark ? "light" : "dark");- }}- >- {isDark ? <Light /> : <Asleep />}- {isDark ? "Light mode" : "Dark mode"}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={onSignOut}>- <Logout />- Sign out- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}--function initials(name: string): string {- return (- name- .split(" ")- .map((part) => part[0])- .filter(Boolean)- .slice(0, 2)- .join("")- .toUpperCase() || "?"- );-}diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsxdeleted file mode 100644index 62e42503..00000000--- a/apps/app/components/app-icon-rail.tsx+++ /dev/null@@ -1,310 +0,0 @@-"use client";--import Building from "@carbon/icons-react/es/Building";-import Close from "@carbon/icons-react/es/Close";-import Dashboard from "@carbon/icons-react/es/Dashboard";-import Partnership from "@carbon/icons-react/es/Partnership";-import Settings from "@carbon/icons-react/es/Settings";-import Task from "@carbon/icons-react/es/Task";-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";-import Bot from "@crm/ui/components/icons/bot";-import {- Sheet,- SheetContent,- SheetHeader,- SheetTitle,-} from "@crm/ui/components/sheet";-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@crm/ui/components/tooltip";-import { cn } from "@crm/ui/lib/utils";-import Link from "next/link";-import { usePathname } from "next/navigation";-import { useMemo } from "react";-import { AgentBuilderSidebar } from "@/components/agent-builder/agent-builder-sidebar";-import { usePrefetchSection } from "@/components/crm/section-prefetch";-import { useMobileNav } from "@/components/mobile-nav";-import { useWorkspaceUrl } from "@/lib/use-workspace-url";--type RailItem = {- title: string;- href: string;- icon: CarbonIcon;- iconClassName?: string;- match: "exact" | "prefix";- related?: string[];-};--const ITEMS: RailItem[] = [- { title: "Overview", href: "/", icon: Dashboard, match: "exact" },- {- title: "Chat",- href: "/chat",- icon: Bot,- iconClassName: "size-5",- match: "prefix",- related: ["/agents"],- },- { title: "Companies", href: "/companies", icon: Building, match: "prefix" },- {- title: "Contacts",- href: "/contacts",- icon: UserMultiple,- match: "prefix",- },- { title: "Deals", href: "/deals", icon: Partnership, match: "prefix" },- { title: "Tasks", href: "/tasks", icon: Task, match: "prefix" },- { title: "Settings", href: "/settings", icon: Settings, match: "prefix" },-];--function isActive(item: RailItem, pathname: string): boolean {- return (- pathname === item.href ||- (item.match === "prefix" && pathname.startsWith(item.href)) ||- Boolean(item.related?.some((prefix) => pathname.startsWith(prefix)))- );-}--function RailLink({- item,- active,- onPrefetch,-}: {- item: RailItem;- active: boolean;- onPrefetch: () => void;-}) {- return (- <Tooltip>- <TooltipTrigger asChild>- <Button- asChild- variant="ghost"- size="icon"- className={cn(- "text-muted-foreground",- active &&- "bg-muted text-foreground hover:bg-muted hover:text-foreground",- )}- >- <Link- href={item.href}- prefetch- onMouseEnter={onPrefetch}- onFocus={onPrefetch}- aria-current={active ? "page" : undefined}- transitionTypes={["nav-lateral"]}- >- <Icon icon={item.icon} className={item.iconClassName} />- <span className="sr-only">{item.title}</span>- </Link>- </Button>- </TooltipTrigger>- <TooltipContent side="right">{item.title}</TooltipContent>- </Tooltip>- );-}--function MobileRailLink({- item,- active,- onNavigate,- onPrefetch,-}: {- item: RailItem;- active: boolean;- onNavigate: () => void;- onPrefetch: () => void;-}) {- return (- <Button- asChild- variant="ghost"- className={cn(- "justify-start gap-3 text-muted-foreground",- active &&- "bg-muted text-foreground hover:bg-muted hover:text-foreground",- )}- >- <Link- href={item.href}- prefetch- onMouseEnter={onPrefetch}- onFocus={onPrefetch}- aria-current={active ? "page" : undefined}- onClick={onNavigate}- transitionTypes={[- item.title === "Chat" ? "nav-forward" : "nav-lateral",- ]}- >- <Icon icon={item.icon} className={item.iconClassName} />- <span>{item.title}</span>- </Link>- </Button>- );-}--function MobileRailIconLink({- item,- active,- onNavigate,- onPrefetch,-}: {- item: RailItem;- active: boolean;- onNavigate: () => void;- onPrefetch: () => void;-}) {- return (- <Button- asChild- variant="ghost"- size="icon"- className={cn(- "text-muted-foreground",- active &&- "bg-muted text-foreground hover:bg-muted hover:text-foreground",- )}- >- <Link- href={item.href}- prefetch- onMouseEnter={onPrefetch}- onFocus={onPrefetch}- aria-current={active ? "page" : undefined}- onClick={onNavigate}- >- <Icon icon={item.icon} className={item.iconClassName} />- <span className="sr-only">{item.title}</span>- </Link>- </Button>- );-}--export function AppIconRailFallback() {- return (- <nav- aria-label="Primary"- aria-busy="true"- className="hidden w-14 shrink-0 flex-col items-center gap-1 border-r py-3 md:flex [view-transition-name:app-rail]"- >- {ITEMS.map((item) => (- <Button- key={item.href}- variant="ghost"- size="icon"- disabled- className="text-muted-foreground"- >- <Icon icon={item.icon} className={item.iconClassName} />- <span className="sr-only">{item.title}</span>- </Button>- ))}- </nav>- );-}--export function AppIconRail() {- const pathname = usePathname();- const workspaceUrl = useWorkspaceUrl();- const { open, setOpen } = useMobileNav();- const prefetchSection = usePrefetchSection();-- const items = useMemo(- () =>- ITEMS.map((item) => ({- ...item,- section: item.href,- href: workspaceUrl(item.href),- related: item.related?.map((path) => workspaceUrl(path)),- })),- [workspaceUrl],- );- const inChat = items.some(- (item) => item.title === "Chat" && isActive(item, pathname),- );-- return (- <>- <nav- aria-label="Primary"- className="hidden w-14 shrink-0 flex-col items-center gap-1 border-r py-3 md:flex [view-transition-name:app-rail]"- >- {items.map((item) => (- <RailLink- key={item.href}- item={item}- active={isActive(item, pathname)}- onPrefetch={() => prefetchSection(item.section)}- />- ))}- </nav>-- <Sheet open={open} onOpenChange={setOpen}>- {inChat ? (- <SheetContent- side="left"- showCloseButton={false}- className="w-5/6 max-w-sm flex-row gap-0 p-0"- >- <SheetHeader className="sr-only">- <SheetTitle>Navigation and agent chats</SheetTitle>- </SheetHeader>- <nav- aria-label="Primary"- className="flex w-14 shrink-0 flex-col items-center gap-1 border-r py-3"- >- <Button- variant="ghost"- size="icon"- aria-label="Close navigation"- onClick={() => setOpen(false)}- >- <Icon icon={Close} />- </Button>- <div className="my-1 h-px w-5 bg-border" />- {items.map((item) => (- <MobileRailIconLink- key={item.href}- item={item}- active={isActive(item, pathname)}- onNavigate={() => setOpen(false)}- onPrefetch={() => prefetchSection(item.section)}- />- ))}- </nav>- <AgentBuilderSidebar- className="flex flex-1"- onNavigate={() => setOpen(false)}- />- </SheetContent>- ) : (- <SheetContent side="left" className="w-64 gap-0 p-0">- <SheetHeader>- <SheetTitle>Navigation</SheetTitle>- </SheetHeader>- <nav- aria-label="Primary"- className="flex flex-1 flex-col gap-1 p-2"- >- {items.map((item) => (- <MobileRailLink- key={item.href}- item={item}- active={isActive(item, pathname)}- onNavigate={() => setOpen(false)}- onPrefetch={() => prefetchSection(item.section)}- />- ))}- </nav>- </SheetContent>- )}- </Sheet>- </>- );-}diff --git a/apps/app/components/app-toaster.tsx b/apps/app/components/app-toaster.tsxnew file mode 100644index 00000000..6dd82a74--- /dev/null+++ b/apps/app/components/app-toaster.tsx@@ -0,0 +1,18 @@+"use client";++import { Toaster } from "@crm/ui/components/sonner";+import { usePathname } from "next/navigation";++const CLASSIC_TOAST_ROUTES = new Set([+ "/sign-in",+ "/grant-access",+ "/onboarding",+ "/onboarding/research",+]);++export function AppToaster() {+ const pathname = usePathname();+ const variant = CLASSIC_TOAST_ROUTES.has(pathname) ? "classic" : "default";++ return <Toaster richColors variant={variant} />;+}diff --git a/apps/app/components/auth-shell.tsx b/apps/app/components/auth-shell.tsxindex 72a49386..85679819 100644--- a/apps/app/components/auth-shell.tsx+++ b/apps/app/components/auth-shell.tsx@@ -5,7 +5,7 @@ import { AuthShader } from "@/components/auth-shader";export function AuthShell({ children }: { children: ReactNode }) {return (- <main className="dark grid min-h-svh bg-background text-foreground lg:grid-cols-[minmax(0,1fr)_minmax(420px,520px)]">+ <main className="dark theme-classic grid min-h-svh bg-background text-foreground lg:grid-cols-[minmax(0,1fr)_minmax(420px,520px)]"><section className="relative hidden min-h-svh overflow-hidden bg-muted p-8 lg:flex lg:flex-col lg:justify-between xl:p-12"><AuthShader />diff --git a/apps/app/components/crm/agent-conversations.tsx b/apps/app/components/crm/agent-conversations.tsxindex f2079dd1..2d266ecf 100644--- a/apps/app/components/crm/agent-conversations.tsx+++ b/apps/app/components/crm/agent-conversations.tsx@@ -1,8 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";-import TrashCan from "@carbon/icons-react/es/TrashCan";import { Button } from "@crm/ui/components/button";import {DropdownMenu,@@ -13,6 +10,7 @@ import {} from "@crm/ui/components/dropdown-menu";import { Icon } from "@crm/ui/components/icon";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { ChevronDownIcon, PlusIcon, Trash2Icon } from "lucide-react";import { toast } from "sonner";import { LocalDateTime } from "@/components/local-date-time";import { useTRPC } from "@/lib/trpc/client";@@ -43,16 +41,16 @@ export function ConversationPicker({const label = current?.title ?? "New conversation";return (- <div className="flex min-w-0 items-center gap-2 border-b px-4 py-2 sm:px-5">+ <div className="flex min-w-0 items-center gap-2 border-b py-2"><DropdownMenu><DropdownMenuTrigger asChild><Buttonvariant="ghost"- size="sm"- className="min-w-0 flex-1 justify-start px-2 font-normal"+ size="sm-flush"+ className="min-w-0 flex-1 justify-start font-normal"><span className="truncate">{label}</span>- <Icon icon={ChevronDown} data-icon="inline-end" />+ <Icon icon={ChevronDownIcon} data-icon="inline-end" /></Button></DropdownMenuTrigger>@@ -80,7 +78,7 @@ export function ConversationPicker({<DropdownMenuSeparator /><DropdownMenuItem onSelect={onNew}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New conversation</DropdownMenuItem></DropdownMenuContent>@@ -123,7 +121,7 @@ function Forget({disabled={busy || remove.isPending}onClick={() => remove.mutate({ id: conversation.id })}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} /><span className="sr-only">Delete this conversation</span></Button>);diff --git a/apps/app/components/crm/agent-panel.tsx b/apps/app/components/crm/agent-panel.tsxindex 1df9c32e..71708d9f 100644--- a/apps/app/components/crm/agent-panel.tsx+++ b/apps/app/components/crm/agent-panel.tsx@@ -1,12 +1,5 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import CircleDash from "@carbon/icons-react/es/CircleDash";-import Document from "@carbon/icons-react/es/Document";-import LogoGithub from "@carbon/icons-react/es/LogoGithub";-import LogoLinkedin from "@carbon/icons-react/es/LogoLinkedin";-import Send from "@carbon/icons-react/es/Send";-import Warning from "@carbon/icons-react/es/Warning";import {Attachment,AttachmentContent,@@ -15,18 +8,16 @@ import {AttachmentTitle,AttachmentTrigger,} from "@crm/ui/components/attachment";+import GitHubLogo from "@crm/ui/components/brand-logos/github";+import LinkedInLogo from "@crm/ui/components/brand-logos/linkedin";import { Bubble, BubbleContent } from "@crm/ui/components/bubble";import { Button } from "@crm/ui/components/button";+import { ChatComposer } from "@crm/ui/components/chat-composer";import {- Empty,- EmptyContent,- EmptyDescription,- EmptyHeader,- EmptyMedia,- EmptyTitle,-} from "@crm/ui/components/empty";-import { type CarbonIcon, Icon } from "@crm/ui/components/icon";-import { Input } from "@crm/ui/components/input";+ ChatEmptyState,+ ChatSuggestions,+} from "@crm/ui/components/chat-thread";+import { Icon, type IconComponent } from "@crm/ui/components/icon";import Logo from "@crm/ui/components/logo";import { Markdown } from "@crm/ui/components/markdown";import { Marker, MarkerContent, MarkerIcon } from "@crm/ui/components/marker";@@ -43,10 +34,19 @@ import {MessageScrollerProvider,MessageScrollerViewport,} from "@crm/ui/components/message-scroller";+import { SkeletonField, SkeletonLine } from "@crm/ui/components/skeleton-lines";import { Spinner } from "@crm/ui/components/spinner";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { SKELETON, skeletonRows } from "@crm/ui/lib/skeleton-config";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useEveAgent } from "eve/react";-import { useEffect, useEffectEvent, useRef, useState } from "react";+import {+ CheckIcon,+ CircleAlertIcon,+ CircleDashedIcon,+ FileTextIcon,+} from "lucide-react";+import { useRef, useState } from "react";import { AgentClarificationComposer } from "@/components/agent-clarification-composer";import {type Conversation,@@ -75,6 +75,7 @@ import {type TranscriptItem,toTranscript,} from "@/lib/agent-transcript";+import { claimCursor, conversationCursor } from "@/lib/conversation-cursor";import { useTRPC } from "@/lib/trpc/client";import { useRecordSheetView } from "./record-sheet/record-stack";@@ -185,8 +186,18 @@ function ThreadWithHistory({function Loading() {return (- <div className="flex flex-1 items-center justify-center">- <Spinner />+ <div aria-busy className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-1 flex-col gap-3 py-4">+ {skeletonRows(SKELETON.rows.messages).map((row) => (+ <div key={row} className="flex flex-col gap-2">+ <SkeletonLine width="two-thirds" />+ <SkeletonLine width="40" />+ </div>+ ))}+ </div>+ <div className="border-t py-3">+ <SkeletonField />+ </div></div>);}@@ -213,14 +224,6 @@ function Thread({const opening = useRef<string | null>(conversation?.title ?? null);- useSavedConversation({- record: recordFilter(record),- conversation,- opening,- session: agent.session ?? null,- messages: agent.data.messages.length,- });-const busy = agent.status === "submitted" || agent.status === "streaming";const messages = toTranscript(agent.data.messages);const question = pendingQuestion(agent.data.messages);@@ -236,44 +239,53 @@ function Thread({return (<div className="flex min-h-0 flex-1 flex-col">- <MessageScrollerProvider autoScroll defaultScrollPosition="end">- <MessageScroller className="flex-1">- <MessageScrollerViewport>- <MessageScrollerContent className="gap-3 px-4 py-4 sm:px-5">- {messages.length === 0 && !busy ? (- <Idle kind={record.kind} onAsk={ask} />- ) : null}-- {messages.map((message) => (- <MessageScrollerItem key={message.id} messageId={message.id}>- <div className="space-y-3">- {message.items.map((item) =>- item.kind === "asked" &&- item.question.requestId === question?.requestId ? null : (- <Item key={item.id} item={item} />- ),- )}- </div>- </MessageScrollerItem>- ))}- </MessageScrollerContent>- </MessageScrollerViewport>-- <MessageScrollerButton />- </MessageScroller>- </MessageScrollerProvider>+ <SavedConversation+ record={recordFilter(record)}+ conversation={conversation}+ opening={opening}+ session={agent.session ?? null}+ messages={agent.data.messages.length}+ />++ {messages.length === 0 && !busy ? (+ <Idle kind={record.kind} onAsk={ask} />+ ) : (+ <MessageScrollerProvider autoScroll defaultScrollPosition="end">+ <MessageScroller className="flex-1">+ <MessageScrollerViewport>+ <MessageScrollerContent className="gap-3 py-4">+ {messages.map((message) => (+ <MessageScrollerItem key={message.id} messageId={message.id}>+ <div className="space-y-3">+ {message.items.map((item) =>+ item.kind === "asked" &&+ item.question.requestId ===+ question?.requestId ? null : (+ <Item key={item.id} item={item} />+ ),+ )}+ </div>+ </MessageScrollerItem>+ ))}+ </MessageScrollerContent>+ </MessageScrollerViewport>++ <MessageScrollerButton />+ </MessageScroller>+ </MessageScrollerProvider>+ )}{agent.error ? <Failure message={agent.error.message} /> : null}{thread?.status === "working" && !busy ? (- <p className="border-t px-4 py-2 text-pretty text-muted-foreground text-xs sm:px-5">+ <p className="border-t py-2 text-pretty text-muted-foreground text-xs">Still working on the last question. Your next one can go in when itfinishes.</p>) : null}{ended ? (- <div className="flex flex-col items-start gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-2">+ <div className="flex flex-col items-start gap-3 border-t py-3 sm:flex-row sm:items-center sm:justify-between sm:py-2"><p className="text-pretty text-muted-foreground text-xs">This conversation has ended.</p>@@ -283,7 +295,7 @@ function Thread({</div>) : null}- <div className="border-t px-4 py-3 sm:px-5">+ <div className="border-t py-3">{question ? (<AgentClarificationComposerkey={question.requestId}@@ -292,29 +304,16 @@ function Thread({onSubmit={(response) => agent.respond([response])}/>) : (- <form- className="flex min-w-0 items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- ask(draft);- }}- >- <Input- value={draft}- onChange={(event) => setDraft(event.target.value)}- placeholder={copy.placeholder}- disabled={locked}- />- <Button- type="submit"- size="icon-sm"- variant="outline"- disabled={locked}- >- {busy ? <Spinner /> : <Icon icon={Send} />}- <span className="sr-only">Ask</span>- </Button>- </form>+ <ChatComposer+ busy={busy}+ disabled={locked}+ onSubmit={ask}+ onValueChange={setDraft}+ placeholder={copy.placeholder}+ sendLabel="Ask"+ size="panel"+ value={draft}+ />)}</div></div>@@ -331,30 +330,14 @@ function Idle({const copy = recordCopy(kind);return (- <Empty width="wide">- <EmptyHeader>- <EmptyMedia>- <span className="flex size-8 items-center justify-center bg-foreground text-background">- <Logo className="size-4" />- </span>- </EmptyMedia>- <EmptyTitle>{copy.title}</EmptyTitle>- <EmptyDescription>{copy.blurb}</EmptyDescription>- </EmptyHeader>-- <EmptyContent layout="row">- {copy.suggestions.map((suggestion) => (- <Button- key={suggestion}- variant="outline"- size="sm"- onClick={() => onAsk(suggestion)}- >- {suggestion}- </Button>- ))}- </EmptyContent>- </Empty>+ <div className="flex min-h-0 flex-1 flex-col justify-center gap-5 overflow-y-auto py-4">+ <ChatEmptyState+ size="panel"+ title={copy.title}+ description={copy.blurb}+ />+ <ChatSuggestions suggestions={copy.suggestions} onSelect={onAsk} />+ </div>);}@@ -366,7 +349,7 @@ function Failure({ message }: { message: string }) {: null;return (- <div className="border-t px-4 py-3 text-xs sm:px-5">+ <div className="border-t py-3 text-xs"><p className="wrap-break-word text-destructive">{message}</p>{hint ? (<p className="wrap-break-word text-muted-foreground text-xs">{hint}</p>@@ -376,16 +359,16 @@ function Failure({ message }: { message: string }) {}const TONE_ICONS = {- neutral: CircleDash,- success: Checkmark,- warning: Warning,-} satisfies Record<Tone, CarbonIcon>;+ neutral: CircleDashedIcon,+ success: CheckIcon,+ warning: CircleAlertIcon,+} satisfies Record<Tone, IconComponent>;const SOURCE_ICONS = {- linkedin: LogoLinkedin,- github: LogoGithub,- web: Document,-} satisfies Record<Source["network"], CarbonIcon>;+ linkedin: LinkedInLogo,+ github: GitHubLogo,+ web: FileTextIcon,+} satisfies Record<Source["network"], IconComponent>;function Item({ item }: { item: TranscriptItem }) {if (item.kind === "said") {@@ -471,7 +454,7 @@ function AgentAvatar() {);}-function useSavedConversation({+function SavedConversation({record,conversation,opening,@@ -491,16 +474,19 @@ function useSavedConversation({const trpc = useTRPC();const queryClient = useQueryClient();const save = useMutation(trpc.conversations.save.mutationOptions({}));+ const written = useRef<string | null>(null);const sessionId = session?.sessionId ?? null;const token = session?.continuationToken ?? null;const streamIndex = session?.streamIndex ?? 0;- const { contactId, companyId, dealId } = record;+ const cursor = conversationCursor({ sessionId, token, messages });+ if (!cursor) return null;+ const { contactId, companyId, dealId } = record;const isNew = conversation === null || conversation.sessionId !== sessionId;- const written = useRef<string | null>(null);- const persist = useEffectEvent(() => {+ const persist = () => {+ if (!claimCursor(written, cursor)) return;save.mutate({contactId: contactId || undefined,@@ -521,14 +507,12 @@ function useSavedConversation({},},);- });+ };- useEffect(() => {- if (!sessionId) return;+ return <SaveCursor key={cursor} onMount={persist} />;+}- const cursor = `${sessionId}:${token ?? ""}:${messages}`;- if (written.current === cursor) return;- written.current = cursor;- persist();- }, [sessionId, token, messages]);+function SaveCursor({ onMount }: { onMount: () => void }) {+ useMountEffect(onMount);+ return null;}diff --git a/apps/app/components/crm/bulk-actions.tsx b/apps/app/components/crm/bulk-actions.tsxindex 7c15c899..225072fc 100644--- a/apps/app/components/crm/bulk-actions.tsx+++ b/apps/app/components/crm/bulk-actions.tsx@@ -1,6 +1,5 @@"use client";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";import {AlertDialog,AlertDialogAction,@@ -24,6 +23,7 @@ import {DropdownMenuTrigger,} from "@crm/ui/components/dropdown-menu";import { Spinner } from "@crm/ui/components/spinner";+import { ChevronDownIcon } from "lucide-react";import type { ReactNode } from "react";import { toast } from "sonner";@@ -47,7 +47,7 @@ export function reportBulk(toast.error(`${done(result.succeeded)} ${result.failed} ${result.failed === 1 ? "was" : "were"- } left alone${result.message ? ` — ${result.message}` : "."}`,+ } left alone${result.message ? `. ${result.message}` : "."}`,);return;}@@ -70,9 +70,12 @@ export function BulkActionsMenu({<DropdownMenu open={open} onOpenChange={onOpenChange}><DropdownMenuTrigger asChild><Button variant="outline" size="sm" disabled={pending}>- {pending ? <Spinner /> : null}Actions- <ChevronDown data-icon="inline-end" className="opacity-60" />+ {pending ? (+ <Spinner data-icon="inline-end" />+ ) : (+ <ChevronDownIcon data-icon="inline-end" className="opacity-60" />+ )}</Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="min-w-52">diff --git a/apps/app/components/crm/company-picker.tsx b/apps/app/components/crm/company-picker.tsxindex 8847a9a1..96fa010e 100644--- a/apps/app/components/crm/company-picker.tsx+++ b/apps/app/components/crm/company-picker.tsx@@ -13,7 +13,7 @@ import { Spinner } from "@crm/ui/components/spinner";import { useSearchInput } from "@crm/ui/hooks/use-search-input";import { cn } from "@crm/ui/lib/utils";import { useQuery } from "@tanstack/react-query";-import { type Ref, useId, useState } from "react";+import { type AriaAttributes, type Ref, useId, useState } from "react";import { PROPERTY_LABEL, PROPERTY_ROW } from "@/components/detail-sheet";import { useTRPC } from "@/lib/trpc/client";@@ -27,6 +27,8 @@ export function CompanyPicker({disabled,variant,className,+ "aria-invalid": ariaInvalid,+ "aria-describedby": ariaDescribedBy,}: {id?: string;value: string;@@ -37,6 +39,8 @@ export function CompanyPicker({disabled?: boolean;variant?: "default" | "ghost";className?: string;+ "aria-invalid"?: AriaAttributes["aria-invalid"];+ "aria-describedby"?: string;}) {const trpc = useTRPC();@@ -69,6 +73,8 @@ export function CompanyPicker({return (<Comboboxid={id}+ aria-invalid={ariaInvalid}+ aria-describedby={ariaDescribedBy}value={value}onValueChange={(next) => {setChosen(options.find((option) => option.value === next) ?? null);diff --git a/apps/app/components/crm/enrichment-actions.tsx b/apps/app/components/crm/enrichment-actions.tsxindex f7d10d30..6a70b4df 100644--- a/apps/app/components/crm/enrichment-actions.tsx+++ b/apps/app/components/crm/enrichment-actions.tsx@@ -1,11 +1,10 @@"use client";-import MagicWand from "@carbon/icons-react/es/MagicWand";-import Renew from "@carbon/icons-react/es/Renew";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import { Spinner } from "@crm/ui/components/spinner";import { useMutation } from "@tanstack/react-query";+import { RefreshCwIcon, WandSparklesIcon } from "lucide-react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -26,7 +25,7 @@ export function EnrichmentActions({await cache.company(companyId);toast.success(result.queued- ? "Looking it up — this page will update when it finishes."+ ? "Looking it up. This page updates when it finishes.": "Already running.",);},@@ -40,7 +39,7 @@ export function EnrichmentActions({await cache.activity();toast.success(result.queued- ? "Researching — the brief lands on the timeline when it finishes."+ ? "Researching. The brief appears on the timeline when it finishes.": "Already researching.",);},@@ -59,7 +58,7 @@ export function EnrichmentActions({{enrich.isPending ? (<Spinner />) : (- <Icon icon={Renew} data-icon="inline-start" />+ <Icon icon={RefreshCwIcon} data-icon="inline-start" />)}<span className="hidden sm:inline">Re-enrich</span></Button>@@ -72,7 +71,7 @@ export function EnrichmentActions({{research.isPending ? (<Spinner />) : (- <Icon icon={MagicWand} data-icon="inline-start" />+ <Icon icon={WandSparklesIcon} data-icon="inline-start" />)}<span className="hidden sm:inline">Research</span></Button>@@ -90,7 +89,7 @@ export function ContactEnrichmentAction({ contactId }: { contactId: string }) {await cache.contact(contactId);toast.success(result.queued- ? "Taking another look — this page will update when it finishes."+ ? "Taking another look. This page updates when it finishes.": "Already running.",);},@@ -108,7 +107,7 @@ export function ContactEnrichmentAction({ contactId }: { contactId: string }) {{enrich.isPending ? (<Spinner />) : (- <Icon icon={Renew} data-icon="inline-start" />+ <Icon icon={RefreshCwIcon} data-icon="inline-start" />)}<span className="hidden sm:inline">Re-enrich</span></Button>diff --git a/apps/app/components/crm/facts.tsx b/apps/app/components/crm/facts.tsxindex 97c802bc..0528e089 100644--- a/apps/app/components/crm/facts.tsx+++ b/apps/app/components/crm/facts.tsx@@ -41,7 +41,7 @@ export function FactSuggestion({toast.success(result.applied? "Added to the record."- : "Dismissed — it won't be suggested again.",+ : "Dismissed. This suggestion stays hidden.",);return cache.contact(contactId, { settle: "record" });},@@ -52,7 +52,11 @@ export function FactSuggestion({return (<Suggestionvalue={fact.value}- rationale={fact.evidence.map((item) => item.detail).join(" · ")}+ rationale={fact.evidence.map((item) => (+ <span key={item.detail} className="block">+ {item.detail}+ </span>+ ))}pending={decide.isPending}onAccept={() => decide.mutate({ factId: fact.id, decision: "accept" })}onDismiss={() => decide.mutate({ factId: fact.id, decision: "dismiss" })}diff --git a/apps/app/components/crm/fields/field-columns.tsx b/apps/app/components/crm/fields/field-columns.tsxindex f46b2797..5ed52592 100644--- a/apps/app/components/crm/fields/field-columns.tsx+++ b/apps/app/components/crm/fields/field-columns.tsx@@ -56,10 +56,10 @@ export function useFieldColumns<Row extends WithFields>(.map((field) => ({id: `field:${field.key}`,header: field.label,- width: "w-[12%]",+ width: "36" as const,hideBelow: "lg" as const,cell: (row: Row) => (- <span className="truncate">+ <span className="block truncate">{render(field.type, row.fields[field.key] ?? null, byId)}</span>),diff --git a/apps/app/components/crm/fields/field-editor.tsx b/apps/app/components/crm/fields/field-editor.tsxindex ab0e5ef9..eb46e6ab 100644--- a/apps/app/components/crm/fields/field-editor.tsx+++ b/apps/app/components/crm/fields/field-editor.tsx@@ -1,7 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Close from "@carbon/icons-react/es/Close";import {FIELD_TYPES,fieldKeyFromLabel,@@ -39,6 +37,7 @@ import { StatusIndicator } from "@crm/ui/components/status-indicator";import { Switch } from "@crm/ui/components/switch";import { Textarea } from "@crm/ui/components/textarea";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon, XIcon } from "lucide-react";import { useId, useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";@@ -88,16 +87,16 @@ type Draft = {};const TYPE_HINTS = {- TEXT: "Text — a short line",- LONG_TEXT: "Long text — a paragraph",+ TEXT: "Text: a short line",+ LONG_TEXT: "Long text: a paragraph",NUMBER: "Number",DATE: "Date",- CHECKBOX: "Checkbox — yes or no",- SELECT: "Select — one of a fixed list",+ CHECKBOX: "Checkbox: yes or no",+ SELECT: "Select: one of a fixed list",URL: "URL",EMAIL: "Email",PHONE: "Phone",- USER: "User — someone in the workspace",+ USER: "User: someone in the workspace",} satisfies Record<(typeof FIELD_TYPES)[number], string>;function optionId(option: { id?: string }, index: number): string {@@ -262,7 +261,7 @@ export function FieldEditor({<div className="flex items-baseline justify-between gap-2"><FieldTitle>{KEY_LABEL}</FieldTitle><span className="font-mono text-muted-foreground text-xs">- {key || "—"}+ {key || ""}</span></div><FieldDescription>{KEY_HELP}</FieldDescription>@@ -364,7 +363,7 @@ export function FieldEditor({})}>- <Icon icon={Close} />+ <Icon icon={XIcon} /><span className="sr-only">Remove {optionLabel(index)}</span>@@ -381,7 +380,7 @@ export function FieldEditor({patch({ options: [...draft.options, { label: "" }] })}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />{ADD_OPTION}</Button></Field>diff --git a/apps/app/components/crm/fields/fields-copy.ts b/apps/app/components/crm/fields/fields-copy.tsindex 7f209b58..bbee1bab 100644--- a/apps/app/components/crm/fields/fields-copy.ts+++ b/apps/app/components/crm/fields/fields-copy.ts@@ -40,7 +40,7 @@ export const RETRY = "Try again";export const LABEL_LABEL = "Label";export const KEY_LABEL = "Key";export const KEY_HELP =- "What the API and your agents call it. Set from the label, fixed once saved — renaming the label later never breaks a caller.";+ "What the API and your agents call it. Set from the label, fixed once saved. Renaming the label never breaks a caller.";export const AGENT_LABEL = "Let your agents fill this";export const AGENT_HELP ="They propose a value with a source, and never overwrite yours.";diff --git a/apps/app/components/crm/fields/fields-list.tsx b/apps/app/components/crm/fields/fields-list.tsxindex 83521701..025150d8 100644--- a/apps/app/components/crm/fields/fields-list.tsx+++ b/apps/app/components/crm/fields/fields-list.tsx@@ -1,10 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import ChevronRight from "@carbon/icons-react/es/ChevronRight";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import Renew from "@carbon/icons-react/es/Renew";-import Warning from "@carbon/icons-react/es/Warning";import { fieldKeyFromLabel, typeLabel } from "@crm/db/fields-shape";import { Badge } from "@crm/ui/components/badge";import { Button } from "@crm/ui/components/button";@@ -29,10 +24,19 @@ import {EmptyTitle,} from "@crm/ui/components/empty";import { Icon } from "@crm/ui/components/icon";+import { Skeleton } from "@crm/ui/components/skeleton";+import { SkeletonLine } from "@crm/ui/components/skeleton-lines";import { SortableItem, SortableList } from "@crm/ui/components/sortable-list";-import { Spinner } from "@crm/ui/components/spinner";+import { SKELETON, skeletonRows } from "@crm/ui/lib/skeleton-config";import { FIELD_TEMPLATES } from "@crm/validation/field-templates";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ ChevronRightIcon,+ CircleAlertIcon,+ EllipsisVerticalIcon,+ PlusIcon,+ RefreshCwIcon,+} from "lucide-react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -65,7 +69,7 @@ type Field = RouterOutputs["fields"]["list"][number];const ROW = "flex items-center gap-2.5 border-b px-5 py-2";-function summaryOf(field: Field): string {+function summaryOf(field: Field): string[] {const parts: string[] = [];if (field.agentFilled) {@@ -83,7 +87,7 @@ function summaryOf(field: Field): string {if (field.showOnTable) parts.push(TABLE_NOTE);if (field.showOnFilter) parts.push(FILTER_NOTE);- return parts.join(" · ");+ return parts;}function reordered(fields: Field[], ids: string[]): Field[] {@@ -102,10 +106,12 @@ function reordered(fields: Field[], ids: string[]): Field[] {function DisclosureRow({title,+ count,note,children,}: {title: string;+ count: number;note: string;children: React.ReactNode;}) {@@ -117,13 +123,16 @@ function DisclosureRow({className="flex w-full items-center gap-2 border-b px-5 py-2.5 text-left"><Icon- icon={ChevronRight}+ icon={ChevronRightIcon}className="shrink-0 text-muted-foreground"/><span className="flex-1 font-medium text-foreground text-xs">{title}</span>- <span className="shrink-0 text-muted-foreground text-xs">{note}</span>+ <span className="flex shrink-0 items-baseline gap-3 text-muted-foreground text-xs">+ <span className="tabular-nums">{count}</span>+ <span>{note}</span>+ </span></button></CollapsibleTrigger><CollapsibleContent>{children}</CollapsibleContent>@@ -206,7 +215,8 @@ export function FieldsList({<div className="flex min-h-0 flex-1 flex-col overflow-y-auto"><DisclosureRowtitle={STANDARD_ROW}- note={`${standard.length} · ${STANDARD_NOTE}`}+ count={standard.length}+ note={STANDARD_NOTE}><ul className="border-b bg-muted/40 py-1">{standard.map((field) => (@@ -223,7 +233,8 @@ export function FieldsList({{suggestions.length > 0 && (<DisclosureRowtitle={SUGGESTED_ROW}- note={`${suggestions.length} · ${SUGGESTED_NOTE}`}+ count={suggestions.length}+ note={SUGGESTED_NOTE}><ul className="border-b bg-muted/40 py-1">{suggestions.map((template) => (@@ -232,10 +243,14 @@ export function FieldsList({className="flex items-center gap-2.5 px-5 py-1.5"><span className="flex-1 truncate text-muted-foreground text-xs">- {template.label}- {template.options && template.options.length > 0- ? ` · ${template.options.join(", ")}`- : ` · ${typeLabel(template.type)}`}+ <span className="block truncate text-foreground">+ {template.label}+ </span>+ <span className="block truncate">+ {template.options && template.options.length > 0+ ? template.options.join(", ")+ : typeLabel(template.type)}+ </span></span><Buttonvariant="outline"@@ -259,7 +274,7 @@ export function FieldsList({})}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />{ADD}</Button></li>@@ -269,14 +284,22 @@ export function FieldsList({)}{query.isPending ? (- <div className="flex flex-1 items-center justify-center">- <Spinner />- </div>+ <ul aria-busy className="flex flex-col pt-3.5">+ {skeletonRows(SKELETON.rows.fields).map((row) => (+ <li key={row} className={ROW}>+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <SkeletonLine width="40" />+ <SkeletonLine width="24" />+ </div>+ <Skeleton className="h-5 w-18 shrink-0" />+ </li>+ ))}+ </ul>) : query.isError ? (<Empty className="flex-1"><EmptyHeader><EmptyMedia variant="icon">- <Icon icon={Warning} />+ <Icon icon={CircleAlertIcon} /></EmptyMedia><EmptyTitle>{ERROR_TITLE}</EmptyTitle><EmptyDescription>{ERROR_BODY}</EmptyDescription>@@ -287,7 +310,7 @@ export function FieldsList({disabled={query.isFetching}onClick={() => query.refetch()}>- <Icon icon={Renew} data-icon="inline-start" />+ <Icon icon={RefreshCwIcon} data-icon="inline-start" />{RETRY}</Button></EmptyContent>@@ -298,14 +321,14 @@ export function FieldsList({<Empty className="flex-1"><EmptyHeader><EmptyMedia variant="icon">- <Icon icon={Add} />+ <Icon icon={PlusIcon} /></EmptyMedia><EmptyTitle>{EMPTY_TITLE}</EmptyTitle><EmptyDescription>{EMPTY_BODY}</EmptyDescription></EmptyHeader><EmptyContent><Button onClick={onNew}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />{NEW_FIELD}</Button></EmptyContent>@@ -340,8 +363,10 @@ export function FieldsList({<span className="w-full truncate font-medium text-foreground text-xs">{field.label}</span>- <span className="w-full truncate text-muted-foreground text-xs">- {summaryOf(field)}+ <span className="flex w-full min-w-0 flex-wrap gap-x-3 text-muted-foreground text-xs">+ {summaryOf(field).map((part) => (+ <span key={part}>{part}</span>+ ))}</span></button>@@ -355,7 +380,7 @@ export function FieldsList({<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon-xs">- <Icon icon={OverflowMenuVertical} />+ <Icon icon={EllipsisVerticalIcon} /><span className="sr-only">More for {field.label}</span>@@ -382,7 +407,8 @@ export function FieldsList({{archived.length > 0 ? (<DisclosureRowtitle={ARCHIVED_ROW}- note={`${archived.length} · ${ARCHIVED_NOTE}`}+ count={archived.length}+ note={ARCHIVED_NOTE}><ul className="border-b">{archived.map((field) => (@@ -412,7 +438,7 @@ export function FieldsList({{live.length > 0 ? (<div className="flex shrink-0 items-center justify-between gap-3 border-t px-5 py-3"><Button onClick={onNew}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />{NEW_FIELD}</Button><span className="text-right text-muted-foreground text-xs">diff --git a/apps/app/components/crm/fields/fields-sheet.tsx b/apps/app/components/crm/fields/fields-sheet.tsxindex 5db37477..cf23d342 100644--- a/apps/app/components/crm/fields/fields-sheet.tsx+++ b/apps/app/components/crm/fields/fields-sheet.tsx@@ -1,7 +1,8 @@"use client";-import { Spinner } from "@crm/ui/components/spinner";+import { SkeletonField, SkeletonLine } from "@crm/ui/components/skeleton-lines";import { Tabs, TabsList, TabsTrigger } from "@crm/ui/components/tabs";+import { SKELETON, skeletonRows } from "@crm/ui/lib/skeleton-config";import { useQuery } from "@tanstack/react-query";import {type RecordKind,@@ -58,16 +59,31 @@ function FieldsSheetBody({<DetailSheetHeadertitle={editing?.label ?? (editingKey ? "" : NEW_FIELD)}description={- filled- ? `${entityLabel} · ${filled.filled} of ${filled.total} filled`- : entityLabel+ filled ? (+ <span className="flex flex-wrap gap-x-3">+ <span>{entityLabel}</span>+ <span>+ {filled.filled} of {filled.total} filled+ </span>+ </span>+ ) : (+ entityLabel+ )}onBack={() => onEdit(null)}onClose={onClose}/>{editingKey && query.isPending ? (- <div className="flex min-h-0 flex-1 items-center justify-center">- <Spinner />+ <div+ aria-busy+ className="flex min-h-0 flex-1 flex-col gap-6 px-5 py-4"+ >+ {skeletonRows(SKELETON.rows.editor).map((row) => (+ <div key={row} className="flex flex-col gap-2">+ <SkeletonLine width="24" />+ <SkeletonField />+ </div>+ ))}</div>) : (<FieldEditordiff --git a/apps/app/components/crm/fields/record-fields.tsx b/apps/app/components/crm/fields/record-fields.tsxindex a5cea083..b94cd506 100644--- a/apps/app/components/crm/fields/record-fields.tsx+++ b/apps/app/components/crm/fields/record-fields.tsx@@ -1,6 +1,5 @@"use client";-import Settings from "@carbon/icons-react/es/Settings";import type { FieldValueJson } from "@crm/db/fields";import { Button } from "@crm/ui/components/button";import { Checkbox } from "@crm/ui/components/checkbox";@@ -11,6 +10,7 @@ import {TooltipTrigger,} from "@crm/ui/components/tooltip";import { useQuery } from "@tanstack/react-query";+import { SettingsIcon } from "lucide-react";import {InlineDateField,InlineField,@@ -49,7 +49,7 @@ export function FieldsCog({ kind }: { kind: RecordKind }) {<Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon-sm" onClick={() => open(kind)}>- <Icon icon={Settings} />+ <Icon icon={SettingsIcon} /><span className="sr-only">Fields</span></Button></TooltipTrigger>diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsxindex 2673fb95..159e9b19 100644--- a/apps/app/components/crm/inline-field.tsx+++ b/apps/app/components/crm/inline-field.tsx@@ -22,10 +22,7 @@ const ROW = cn(PROPERTY_ROW, "items-center");const LABEL = PROPERTY_LABEL;const CONTROL ="h-8 w-full justify-start px-2 font-normal hover:border-input hover:bg-muted/40 border border-transparent";-const BLOCK_CONTROL = cn(- CONTROL,- "h-auto min-h-16 items-start whitespace-pre-wrap py-2 text-left leading-5",-);+const BLOCK_CONTROL = "hover:border-input hover:bg-muted/40";export function savingValue(update: {isPending: boolean;@@ -240,6 +237,7 @@ export function InlineTextArea({if (editing) {return (<Textarea+ variant="flush"aria-label={label}autoFocusvalue={draft}@@ -265,7 +263,7 @@ export function InlineTextArea({return (<Buttonvariant="ghost"- size="sm"+ size="block-flush"aria-label={label}className={BLOCK_CONTROL}disabled={saving}@@ -291,7 +289,7 @@ export function InlineDateField({value,onSave,saving = false,- placeholder = "—",+ placeholder = "Add value",}: {label: string;value: string | null;diff --git a/apps/app/components/crm/owner-cell.tsx b/apps/app/components/crm/owner-cell.tsxindex 3996f6cd..942f9475 100644--- a/apps/app/components/crm/owner-cell.tsx+++ b/apps/app/components/crm/owner-cell.tsx@@ -1,11 +1,10 @@-import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";import { EmptyCellValue } from "@crm/ui/components/empty-cell";+import { PersonAvatar } from "@crm/ui/components/person-avatar";import {Tooltip,TooltipContent,TooltipTrigger,} from "@crm/ui/components/tooltip";-import { initialsFromName } from "@crm/ui/lib/format";export type Owner = {id: string;@@ -24,10 +23,12 @@ export function OwnerCell({if (!owner) return compact ? null : <EmptyCellValue />;const avatar = (- <Avatar size="sm">- {owner.image ? <AvatarImage src={owner.image} alt="" /> : null}- <AvatarFallback>{initialsFromName(owner.name)}</AvatarFallback>- </Avatar>+ <PersonAvatar+ src={owner.image}+ name={owner.name}+ email={owner.email}+ size="sm"+ />);if (compact) {diff --git a/apps/app/components/crm/quick-switcher.tsx b/apps/app/components/crm/quick-switcher.tsxindex 2fb31bc2..20b71f57 100644--- a/apps/app/components/crm/quick-switcher.tsx+++ b/apps/app/components/crm/quick-switcher.tsx@@ -1,132 +1,402 @@"use client";import {- Command,- CommandDialog,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "@crm/ui/components/command";-import {- EntityLogo,- type EntityLogoTone,-} from "@crm/ui/components/entity-logo";+ CommandSearch,+ type CommandSearchItem,+} from "@crm/ui/components/command-search";+import { EntityLogo } from "@crm/ui/components/entity-logo";import { PersonAvatar } from "@crm/ui/components/person-avatar";-import { useQuery } from "@tanstack/react-query";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import {+ Building2Icon,+ HandshakeIcon,+ LayoutDashboardIcon,+ ListChecksIcon,+ type LucideIcon,+ MessagesSquareIcon,+ PlusIcon,+ SearchIcon,+ SettingsIcon,+ UsersIcon,+} from "lucide-react";+import { useRouter } from "next/navigation";import { parseAsBoolean, useQueryState } from "nuqs";-import { useEffect, useState } from "react";+import { useRef, useState } from "react";+import { toast } from "sonner";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";+import { COMMAND_SEARCH } from "@/lib/command-search-config";+import {+ entityLogoTone,+ forgetRecentRecord,+ type RecentRecord,+ readRecentRecords,+ recoverRecentRecords,+ resolveRecentRecord,+ useRecentRecordsRaw,+} from "@/lib/recent-records";import { SEARCH_PARAM } from "@/lib/search-param-keys";import { useTRPC } from "@/lib/trpc/client";+import { useWorkspaceSlug, useWorkspaceUrl } from "@/lib/use-workspace-url";++type RecordKind = RecentRecord["kind"];++const KINDS = {+ company: { group: "Companies", noun: "companies", list: "/companies" },+ contact: { group: "Contacts", noun: "contacts", list: "/contacts" },+ deal: { group: "Deals", noun: "deals", list: "/deals" },+} as const satisfies Record<+ RecordKind,+ { group: string; noun: string; list: string }+>;-const GROUP_LABEL = {- company: "Companies",- contact: "Contacts",- deal: "Deals",-} as const;+const KIND_ORDER = ["company", "contact", "deal"] as const;-const KINDS = ["company", "contact", "deal"] as const;+type Destination = {+ id: string;+ label: string;+ href: string;+ icon?: LucideIcon;+ keywords?: string[];+};++const PAGES: Destination[] = [+ {+ id: "overview",+ label: "Overview",+ href: "/",+ icon: LayoutDashboardIcon,+ keywords: ["home", "dashboard", "pipeline"],+ },+ {+ id: "chat",+ label: "Chat",+ href: "/chat",+ icon: MessagesSquareIcon,+ keywords: ["agent", "ask", "agents"],+ },+ {+ id: "companies",+ label: "Companies",+ href: "/companies",+ icon: Building2Icon,+ keywords: ["accounts", "organizations"],+ },+ {+ id: "contacts",+ label: "Contacts",+ href: "/contacts",+ icon: UsersIcon,+ keywords: ["people", "leads"],+ },+ {+ id: "deals",+ label: "Deals",+ href: "/deals",+ icon: HandshakeIcon,+ keywords: ["opportunities", "pipeline", "revenue"],+ },+ {+ id: "tasks",+ label: "Tasks",+ href: "/tasks",+ icon: ListChecksIcon,+ keywords: ["todo", "follow up"],+ },+ {+ id: "settings",+ label: "Settings",+ href: "/settings",+ icon: SettingsIcon,+ },+];++const CREATE: Destination[] = [+ {+ id: "new-company",+ label: "New company",+ href: `/companies?${SEARCH_PARAM.dialog.create}=true`,+ icon: PlusIcon,+ keywords: ["add", "create", "account"],+ },+ {+ id: "new-contact",+ label: "New contact",+ href: `/contacts?${SEARCH_PARAM.dialog.create}=true`,+ icon: PlusIcon,+ keywords: ["add", "create", "person"],+ },+ {+ id: "new-deal",+ label: "New deal",+ href: `/deals?${SEARCH_PARAM.dialog.create}=true`,+ icon: PlusIcon,+ keywords: ["add", "create", "opportunity"],+ },+];++const SETTINGS: Destination[] = [+ {+ id: "settings-general",+ label: "General",+ href: "/settings",+ keywords: ["workspace", "name", "agent model"],+ },+ {+ id: "settings-tracking",+ label: "Tracking & Analytics",+ href: "/settings/tracking",+ keywords: ["script", "website", "forms"],+ },+ {+ id: "settings-connections",+ label: "Connections",+ href: "/settings/connections",+ keywords: ["integrations", "slack", "gmail", "mcp"],+ },+ {+ id: "settings-currencies",+ label: "Currencies",+ href: "/settings/currencies",+ keywords: ["exchange rates", "money"],+ },+ {+ id: "settings-members",+ label: "Members",+ href: "/settings/members",+ keywords: ["team", "people", "invite", "roles"],+ },+ {+ id: "settings-api-keys",+ label: "API Keys",+ href: "/settings/api-keys",+ keywords: ["tokens", "developers"],+ },+ {+ id: "settings-sso",+ label: "SSO",+ href: "/settings/sso",+ keywords: ["single sign-on", "saml", "okta", "identity provider"],+ },+];++function recordMedia(record: RecentRecord) {+ return record.kind === "contact" ? (+ <PersonAvatar src={record.imageUrl} name={record.label} size="sm" />+ ) : (+ <EntityLogo+ src={record.iconUrl}+ darkSrc={record.iconDarkUrl}+ tone={record.iconTone}+ name={record.label}+ size="sm"+ />+ );+}++function RecentRecordsRecovery({+ slug,+ raw,+}: {+ slug: string;+ raw: string | null;+}) {+ useMountEffect(() => recoverRecentRecords(slug, raw));+ return null;+}export function QuickSwitcher() {+ const router = useRouter();const openRecord = useOpenRecord();const trpc = useTRPC();+ const queryClient = useQueryClient();+ const slug = useWorkspaceSlug();+ const workspaceUrl = useWorkspaceUrl();+ const recents = readRecentRecords(useRecentRecordsRaw(slug));const [open, setOpen] = useQueryState(SEARCH_PARAM.dialog.switcher,parseAsBoolean.withDefault(false),);const [query, setQuery] = useState("");+ const [requested, setRequested] = useState("");+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- if (event.key === "k" && (event.metaKey || event.ctrlKey)) {- event.preventDefault();- void setOpen((current) => (current ? null : true));- }- };-- document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [setOpen]);-- const results = useQuery({- ...trpc.search.quick.queryOptions({ q: query }),- enabled: open && query.trim().length >= 2,- placeholderData: (previous) => previous,+ useMountEffect(() => () => {+ if (timer.current) clearTimeout(timer.current);});- const hits = results.data?.hits ?? [];+ const current = query.trim().slice(0, COMMAND_SEARCH.query.maxLength);+ const ready = current === requested;+ const searchable = current.length >= COMMAND_SEARCH.query.minLength;++ const workspace = useQuery({+ ...trpc.workspace.get.queryOptions(),+ enabled: open,+ });++ const search = useQuery({+ ...trpc.search.quick.queryOptions({ q: requested }),+ enabled: open && requested.length >= COMMAND_SEARCH.query.minLength,+ });- const go = (kind: (typeof KINDS)[number], id: string) => {- setQuery("");- void setOpen(null);- openRecord({ kind, id });+ const hits = ready && searchable ? (search.data?.hits ?? []) : [];++ const go = (href: string) => {+ void setOpen(null).then(() => router.push(workspaceUrl(href)));+ };++ const choose = (record: RecentRecord) => {+ openRecord({ kind: record.kind, id: record.id });+ };++ const chooseRecent = async (record: RecentRecord) => {+ try {+ const exists = await resolveRecentRecord(+ () => {+ switch (record.kind) {+ case "company":+ return queryClient.fetchQuery({+ ...trpc.companies.byId.queryOptions({ id: record.id }),+ staleTime: 0,+ });+ case "contact":+ return queryClient.fetchQuery({+ ...trpc.contacts.byId.queryOptions({ id: record.id }),+ staleTime: 0,+ });+ case "deal":+ return queryClient.fetchQuery({+ ...trpc.deals.byId.queryOptions({ id: record.id }),+ staleTime: 0,+ });+ }+ },+ () => forgetRecentRecord(slug, record),+ );+ if (exists) choose(record);+ else+ toast.error(+ "This record no longer exists. It is removed from recent records.",+ );+ } catch {+ toast.error("This record cannot be opened. Try again.");+ }+ };++ const destination = (group: string, path?: string[]) => {+ return (entry: Destination): CommandSearchItem => ({+ id: entry.id,+ label: entry.label,+ group,+ icon: entry.icon,+ path,+ keywords: entry.keywords,+ onSelect: () => go(entry.href),+ });};+ const results: CommandSearchItem[] = KIND_ORDER.flatMap((kind) => {+ const group = hits.filter((hit) => hit.kind === kind);+ const records = group.map((hit): CommandSearchItem => {+ const tone = entityLogoTone.safeParse(hit.iconTone);+ const record: RecentRecord = {+ kind: hit.kind,+ id: hit.id,+ label: hit.label,+ detail: hit.detail,+ iconUrl: hit.iconUrl,+ iconDarkUrl: hit.iconDarkUrl,+ iconTone: tone.success ? tone.data : null,+ imageUrl: hit.imageUrl,+ };++ return {+ id: `${hit.kind}:${hit.id}`,+ label: hit.label,+ group: KINDS[kind].group,+ media: recordMedia(record),+ snippet: hit.detail ?? undefined,+ onSelect: () => choose(record),+ };+ });++ if (group.length < COMMAND_SEARCH.results.perKind) return records;++ const params = new URLSearchParams({ [SEARCH_PARAM.list.q]: current });++ return [+ ...records,+ {+ id: `all:${kind}`,+ label: `All ${KINDS[kind].noun} matching “${current}”`,+ group: KINDS[kind].group,+ icon: SearchIcon,+ onSelect: () => go(`${KINDS[kind].list}?${params}`),+ },+ ];+ });++ const items: CommandSearchItem[] = [+ ...(query.trim() || recents.status === "invalid"+ ? []+ : recents.records.map(+ (record): CommandSearchItem => ({+ id: `recent:${record.kind}:${record.id}`,+ label: record.label,+ group: "Recent",+ media: recordMedia(record),+ snippet: record.detail ?? undefined,+ onSelect: () => void chooseRecent(record),+ }),+ )),+ ...PAGES.map(destination("Pages")),+ ...CREATE.map(destination("Create")),+ ...SETTINGS.map(destination("Settings", ["Settings", "Workspace"])),+ ];+return (- <CommandDialog- open={open}- onOpenChange={(next) => setOpen(next || null)}- title="Search"- description="Jump to a company, contact or deal"- >- <Command shouldFilter={false}>- <CommandInput- placeholder="Search companies, contacts and deals…"- value={query}- onValueChange={setQuery}+ <>+ {recents.status === "invalid" ? (+ <RecentRecordsRecovery+ key={recents.raw}+ slug={slug}+ raw={recents.raw}/>- <CommandList>- <CommandEmpty>- {query.trim().length < 2- ? "Type at least two characters."- : "Nothing matches."}- </CommandEmpty>-- {KINDS.map((kind) => {- const group = hits.filter((hit) => hit.kind === kind);- if (group.length === 0) return null;-- return (- <CommandGroup key={kind} heading={GROUP_LABEL[kind]}>- {group.map((hit) => (- <CommandItem- key={`${hit.kind}:${hit.id}`}- value={`${hit.kind}:${hit.id}`}- onSelect={() => go(kind, hit.id)}- >- {hit.kind === "contact" ? (- <PersonAvatar- src={hit.imageUrl}- name={hit.label}- size="sm"- />- ) : (- <EntityLogo- src={hit.iconUrl}- darkSrc={hit.iconDarkUrl}- tone={hit.iconTone as EntityLogoTone | null | undefined}- name={hit.label}- size="sm"- />- )}- <span className="flex min-w-0 flex-col">- <span className="truncate">{hit.label}</span>- {hit.detail ? (- <span className="truncate text-muted-foreground text-xs">- {hit.detail}- </span>- ) : null}- </span>- </CommandItem>- ))}- </CommandGroup>+ ) : null}+ <CommandSearch+ open={open}+ onOpenChange={(next) => void setOpen(next || null)}+ items={items}+ results={results}+ workspaceName={workspace.data?.name.trim() || undefined}+ placeholder="Search companies, contacts, deals and pages…"+ description="Jump to a company, contact, deal, page or setting."+ onQueryChange={(value) => {+ setQuery(value);++ if (timer.current) clearTimeout(timer.current);+ const normalized = value+ .trim()+ .slice(0, COMMAND_SEARCH.query.maxLength);++ if (normalized.length < COMMAND_SEARCH.query.minLength) {+ setRequested("");+ } else {+ timer.current = setTimeout(+ () => setRequested(normalized),+ COMMAND_SEARCH.query.debounceMs,);- })}- </CommandList>- </Command>- </CommandDialog>+ }+ }}+ loading={searchable && (!ready || search.isPending)}+ searchError={+ ready && search.error+ ? "Search failed. Pages still match."+ : undefined+ }+ onRetry={() => void search.refetch()}+ />+ </>);}diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 90d89214..31bd65e9 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -1,10 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Partnership from "@carbon/icons-react/es/Partnership";-import Star from "@carbon/icons-react/es/Star";-import StarFilled from "@carbon/icons-react/es/StarFilled";-import UserMultiple from "@carbon/icons-react/es/UserMultiple";import type { FieldValueJson } from "@crm/db/fields";import { Button } from "@crm/ui/components/button";import { EmptyCellValue } from "@crm/ui/components/empty-cell";@@ -14,6 +9,11 @@ import {} from "@crm/ui/components/entity-logo";import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";+import {+ RecordFigure,+ RecordSection,+ type RecordSheetTab,+} from "@crm/ui/components/record-sheet";import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";import { TableCell } from "@crm/ui/components/table";import {@@ -23,6 +23,7 @@ import {} from "@crm/ui/components/tooltip";import { formatMoney } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";+import { HandshakeIcon, PlusIcon, StarIcon, UsersIcon } from "lucide-react";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import { EnrichmentActions } from "@/components/crm/enrichment-actions";@@ -39,23 +40,17 @@ import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import { WebsiteActivity } from "@/components/crm/website-activity";import {- DetailSheetBody,DetailSheetEmpty,- DetailSheetMain,+ DetailSheetLoaded,DetailSheetPending,DetailSheetProperties,DetailSheetProse,- DetailSheetRail,DetailSheetSection,- DetailSheetSplit,- DetailSheetStat,- 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 { entityLogoTone } from "@/lib/recent-records";import { hasCompanyLinks } from "@/lib/social-links";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -72,7 +67,6 @@ import {import { useOpenRecord, useRecordSheetView } from "./record-stack";type Company = RouterOutputs["companies"]["byId"];-type CompanyDeal = Company["deals"][number];const UNASSIGNED = "unassigned";@@ -102,7 +96,7 @@ function companyConsequence(company: Company): string {}const CONTACT_COLUMNS = [- { id: "primary", srLabel: "Primary", width: "w-10", className: "pl-5" },+ { id: "primary", srLabel: "Primary", width: "w-10", className: "pl-0" },{ id: "name", header: "Name", width: "w-[28%]" },{ id: "title", header: "Title", width: "w-[24%]" },{ id: "email", header: "Email", width: "w-[26%]" },@@ -110,7 +104,7 @@ const CONTACT_COLUMNS = [];const DEAL_COLUMNS = [- { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-5" },+ { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-0" },{ id: "stage", header: "Stage", width: "w-[24%]" },{id: "amount",@@ -122,14 +116,6 @@ const DEAL_COLUMNS = [{ id: "owner", header: "Owner", width: "w-[14%]" },];-function nextClose(deals: CompanyDeal[]): string | null {- const dates = deals- .map((deal) => deal.expectedCloseDate)- .filter((date): date is string => date !== null)- .sort();- return dates[0] ?? null;-}-export function CompanySheet({ companyId }: { companyId: string }) {const trpc = useTRPC();const {@@ -157,147 +143,188 @@ export function CompanySheet({ companyId }: { companyId: string }) {.join(", "): null;- const openDeals =- company?.deals.filter((deal) => OPEN_STAGES.includes(deal.stage)) ?? [];- const openValueCents = openDeals.reduce(- (total, deal) => total + (deal.baseAmountCents ?? 0),- 0,- );- const openUncounted = openDeals.filter(- (deal) => deal.amountCents !== null && deal.baseAmountCents === null,- ).length;- const closing = nextClose(openDeals);-- const tabs: DetailSheetTab[] = company- ? [- {- value: "overview",- label: "Overview",- content: <CompanyOverview company={company} />,- },- {- value: "contacts",- label: "Contacts",- count: company.contacts.length,- content: (- <CompanyContacts- company={company}- adding={adding === "contact"}- onAdd={() => setAdding("contact")}- onDone={() => setAdding(null)}- />- ),- },- {- value: "deals",- label: "Deals",- count: company.deals.length,- content: (- <CompanyDeals- company={company}- adding={adding === "deal"}- onAdd={() => setAdding("deal")}- onDone={() => setAdding(null)}- />- ),- },- {- value: "activity",- label: "Activity",- content: <Timeline anchor={{ companyId: company.id }} />,- },- {- value: "agent",- label: "Agent",- content: <AgentPanel record={{ kind: "company", id: company.id }} />,- keepMounted: true,- },- ]- : [];+ const tabs: RecordSheetTab[] = [+ {+ value: "overview",+ label: "Overview",+ content: company ? <CompanyOverview company={company} /> : null,+ },+ {+ value: "contacts",+ label: "Contacts",+ count: company?.contacts.length,+ fills: true,+ content: company ? (+ <CompanyContacts+ company={company}+ adding={adding === "contact"}+ onAdd={() => setAdding("contact")}+ onDone={() => setAdding(null)}+ />+ ) : null,+ },+ {+ value: "deals",+ label: "Deals",+ count: company?.deals.length,+ fills: true,+ content: company ? (+ <CompanyDeals+ company={company}+ adding={adding === "deal"}+ onAdd={() => setAdding("deal")}+ onDone={() => setAdding(null)}+ />+ ) : null,+ },+ {+ value: "activity",+ label: "Activity",+ fills: true,+ content: company ? <Timeline anchor={{ companyId: company.id }} /> : null,+ },+ {+ value: "agent",+ label: "Agent",+ fills: true,+ content: company ? (+ <AgentPanel record={{ kind: "company", id: company.id }} />+ ) : null,+ keepMounted: true,+ },+ ];return (- <RecordSheetFrame- loading={query.isPending}- error={query.error?.message ?? null}- title={company?.name ?? "Company"}- description={- company ? (- <MetaLine- lead={- <DomainLink domain={company.domain} website={company.website} />+ <DetailSheetLoaded+ record={+ company+ ? {+ kind: "company",+ id: company.id,+ label: company.name,+ detail: company.domain,+ iconUrl: company.iconUrl ?? company.logoUrl,+ iconDarkUrl: company.iconDarkUrl,+ iconTone: entityLogoTone.nullable().parse(company.iconTone),+ imageUrl: null,}- parts={[location, company.industry]}- />- ) : undefined- }- note={- company && company.enrichmentStatus !== "COMPLETE" ? (- <EnrichmentIndicator- status={company.enrichmentStatus}- queued={company.queued}- title={company.enrichmentError}- />- ) : null- }- media={- <EntityLogo- src={company?.iconUrl ?? company?.logoUrl}- darkSrc={company?.iconDarkUrl}- tone={company?.iconTone as EntityLogoTone | null | undefined}- name={company?.name ?? "?"}- size="lg"- />+ : null}- actions={- company ? (- <>- <EnrichmentActions- companyId={company.id}- hasDomain={company.domain !== null}- />- <RecordActions- record={{ kind: "company", id: company.id }}+ >+ <RecordSheetFrame+ kind="company"+ loading={query.isPending}+ error={query.error?.message ?? null}+ title={company?.name ?? "Company"}+ media={+ company ? (+ <EntityLogo+ src={company.iconUrl ?? company.logoUrl}+ darkSrc={company.iconDarkUrl}+ tone={company.iconTone as EntityLogoTone | null | undefined}name={company.name}- consequence={companyConsequence(company)}- archivedAt={company.archivedAt}+ size="sm"/>- </>- ) : null- }- stats={- company ? (- <DetailSheetStats>- <DetailSheetStat label="Open pipeline">- <span className="tabular-nums">- {formatMoney(openValueCents, company.reportingCurrency)}- </span>- {openUncounted > 0 ? (- <span className="text-muted-foreground">- {" "}- +{openUncounted} unconverted- </span>+ ) : null+ }+ pills={+ company ? (+ <>+ <MetaLine+ lead={+ <DomainLink+ domain={company.domain}+ website={company.website}+ />+ }+ parts={[location, company.industry]}+ />+ {company.enrichmentStatus !== "COMPLETE" ? (+ <EnrichmentIndicator+ status={company.enrichmentStatus}+ queued={company.queued}+ title={company.enrichmentError}+ />) : null}- </DetailSheetStat>- <DetailSheetStat label="Open deals">- <span className="tabular-nums">{openDeals.length}</span>- </DetailSheetStat>- <DetailSheetStat label="Next close">- {closing ? <LocalDay date={closing} /> : <EmptyCellValue />}- </DetailSheetStat>- <DetailSheetStat label="Owner">- <OwnerCell owner={company.owner} />- </DetailSheetStat>- </DetailSheetStats>- ) : null- }- tabs={tabs}- tab={tab}- onTabChange={setTab}- />+ </>+ ) : null+ }+ actions={+ company ? (+ <>+ <EnrichmentActions+ companyId={company.id}+ hasDomain={company.domain !== null}+ />+ <RecordActions+ record={{ kind: "company", id: company.id }}+ name={company.name}+ consequence={companyConsequence(company)}+ archivedAt={company.archivedAt}+ />+ </>+ ) : null+ }+ rail={company ? <CompanyRail company={company} /> : null}+ tabs={tabs}+ tab={tab}+ onTabChange={setTab}+ />+ </DetailSheetLoaded>);}function CompanyOverview({ company }: { company: Company }) {+ const {+ count: openDeals,+ totalCents: openValueCents,+ unconverted: openUncounted,+ nextClose: closing,+ } = company.openPipeline;+ return (+ <>+ <RecordSection label="Open pipeline">+ <RecordFigure+ value={+ openValueCents === null+ ? "None yet"+ : formatMoney(openValueCents, company.reportingCurrency)+ }+ >+ <span>+ {openDeals === 0+ ? "No open deals"+ : openDeals === 1+ ? "1 open deal"+ : `${openDeals} open deals`}+ </span>+ {closing ? (+ <span>+ Next close <LocalDay date={closing} />+ </span>+ ) : null}+ {openUncounted > 0 ? (+ <span>+ {openUncounted === 1+ ? "1 deal has no rate and is left out"+ : `${openUncounted} deals have no rate and are left out`}+ </span>+ ) : null}+ </RecordFigure>+ </RecordSection>++ {company.description ? (+ <DetailSheetSection title="About">+ <DetailSheetProse>{company.description}</DetailSheetProse>+ </DetailSheetSection>+ ) : null}++ <WebsiteActivity companyId={company.id} />+ </>+ );+}++function CompanyRail({ company }: { company: Company }) {const trpc = useTRPC();const cache = useCrmCache();@@ -320,107 +347,90 @@ function CompanyOverview({ company }: { company: Company }) {const isSavingField = savingValue(update);return (- <DetailSheetBody>- <DetailSheetSplit>- <DetailSheetMain>- {company.description ? (- <DetailSheetSection title="About">- <DetailSheetProse>{company.description}</DetailSheetProse>- </DetailSheetSection>- ) : null}-- <WebsiteActivity companyId={company.id} />- </DetailSheetMain>-- <DetailSheetRail>- <DetailSheetSection- title="Details"- action={<FieldsCog kind="company" />}- >- <DetailSheetProperties columns={1}>- <InlineField- label="Name"- value={company.name}- saving={isSaving("name")}- onSave={(name) => name && save({ name })}- />- <InlineField- label="Domain"- value={company.domain}- type="url"- placeholder="stripe.com"- saving={isSaving("domain")}- onSave={(domain) => save({ domain })}- />- <InlineField- label="Website"- value={company.website}- type="url"- placeholder="https://stripe.com"- saving={isSaving("website")}- onSave={(website) => save({ website })}- />- <InlineField- label="Phone"- value={company.phone}- type="tel"- saving={isSaving("phone")}- onSave={(phone) => save({ phone })}- />- <InlineField- label="Email"- value={company.email}- type="email"- saving={isSaving("email")}- onSave={(email) => save({ email })}- />- <InlineField- label="City"- value={company.city}- saving={isSaving("city")}- onSave={(city) => save({ city })}- />- <InlineField- label="Country"- value={company.country}- saving={isSaving("country")}- onSave={(country) => save({ country })}- />- <InlineSelectField- label="Owner"- value={company.owner?.id ?? UNASSIGNED}- options={[- { value: UNASSIGNED, label: "Unassigned" },- ...(users.data ?? []).map((user) => ({- value: user.id,- label: user.name,- })),- ]}- onSave={(ownerId) =>- save({ ownerId: ownerId === UNASSIGNED ? null : ownerId })- }- />- <RecordFields- fields={company.fields}- saving={isSavingField}- onSave={saveFields}- />- </DetailSheetProperties>- </DetailSheetSection>-- <DetailSheetPending- fields={pendingFields(company)}- running={isEnriching(company.enrichmentStatus, company.queued)}+ <>+ <DetailSheetSection title="Details" action={<FieldsCog kind="company" />}>+ <DetailSheetProperties columns={1}>+ <InlineField+ label="Name"+ value={company.name}+ saving={isSaving("name")}+ onSave={(name) => name && save({ name })}/>-- {hasCompanyLinks(company) ? (- <DetailSheetSection title="Links">- <CompanySocials company={company} />- </DetailSheetSection>- ) : null}- </DetailSheetRail>- </DetailSheetSplit>- </DetailSheetBody>+ <InlineField+ label="Domain"+ value={company.domain}+ type="url"+ placeholder="stripe.com"+ saving={isSaving("domain")}+ onSave={(domain) => save({ domain })}+ />+ <InlineField+ label="Website"+ value={company.website}+ type="url"+ placeholder="https://stripe.com"+ saving={isSaving("website")}+ onSave={(website) => save({ website })}+ />+ <InlineField+ label="Phone"+ value={company.phone}+ type="tel"+ saving={isSaving("phone")}+ onSave={(phone) => save({ phone })}+ />+ <InlineField+ label="Email"+ value={company.email}+ type="email"+ saving={isSaving("email")}+ onSave={(email) => save({ email })}+ />+ <InlineField+ label="City"+ value={company.city}+ saving={isSaving("city")}+ onSave={(city) => save({ city })}+ />+ <InlineField+ label="Country"+ value={company.country}+ saving={isSaving("country")}+ onSave={(country) => save({ country })}+ />+ <InlineSelectField+ label="Owner"+ value={company.owner?.id ?? UNASSIGNED}+ options={[+ { value: UNASSIGNED, label: "Unassigned" },+ ...(users.data ?? []).map((user) => ({+ value: user.id,+ label: user.name,+ })),+ ]}+ onSave={(ownerId) =>+ save({ ownerId: ownerId === UNASSIGNED ? null : ownerId })+ }+ />+ <RecordFields+ fields={company.fields}+ saving={isSavingField}+ onSave={saveFields}+ />+ </DetailSheetProperties>+ </DetailSheetSection>++ <DetailSheetPending+ fields={pendingFields(company)}+ running={isEnriching(company.enrichmentStatus, company.queued)}+ />++ {hasCompanyLinks(company) ? (+ <DetailSheetSection title="Links">+ <CompanySocials company={company} />+ </DetailSheetSection>+ ) : null}+ </>);}@@ -460,12 +470,12 @@ function CompanyContacts({{form}{adding ? null : (<DetailSheetEmpty- icon={UserMultiple}+ icon={UsersIcon}title="No contacts yet"- description={`Everyone you talk to at ${company.name} lives here — add the first person and their calls, emails and notes hang off them.`}+ description={`Everyone you talk to at ${company.name} lives here. Add the first person, and their calls, emails and notes hang off them.`}action={<Button variant="outline" size="sm" onClick={onAdd}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />Add contact</Button>}@@ -485,9 +495,17 @@ function CompanyContacts({<SimpleTableRowkey={contact.id}clickable- onClick={() => openRecord({ kind: "contact", id: contact.id })}+ onClick={() =>+ openRecord(+ { kind: "contact", id: contact.id },+ company.contacts.map((entry) => ({+ kind: "contact",+ id: entry.id,+ })),+ )+ }>- <TableCell className="w-10 py-2.5 pl-5">+ <TableCell className="w-10 py-2.5 pl-0"><Tooltip><TooltipTrigger asChild><Button@@ -503,7 +521,10 @@ function CompanyContacts({});}}>- <Icon icon={isPrimary ? StarFilled : Star} />+ <Icon+ icon={StarIcon}+ className={isPrimary ? "fill-current" : undefined}+ /><span className="sr-only">{isPrimary ? "Primary contact" : "Make primary"}</span>@@ -582,12 +603,12 @@ function CompanyDeals({{form}{adding ? null : (<DetailSheetEmpty- icon={Partnership}+ icon={HandshakeIcon}title="No deals yet"description={`Nothing is being sold to ${company.name} right now. Open one and it joins the pipeline and the forecast.`}action={<Button variant="outline" size="sm" onClick={onAdd}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />New deal</Button>}@@ -605,9 +626,14 @@ function CompanyDeals({<SimpleTableRowkey={deal.id}clickable- onClick={() => openRecord({ kind: "deal", id: deal.id })}+ onClick={() =>+ openRecord(+ { kind: "deal", id: deal.id },+ company.deals.map((entry) => ({ kind: "deal", id: entry.id })),+ )+ }>- <TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">+ <TableCell className="truncate py-2.5 pr-3 pl-0 font-medium">{deal.name}</TableCell><TableCell className="px-3 py-2.5">diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 1eb78e1a..830e8634 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -1,8 +1,5 @@"use client";-import Email from "@carbon/icons-react/es/Email";-import Partnership from "@carbon/icons-react/es/Partnership";-import Star from "@carbon/icons-react/es/Star";import type { FieldValueJson } from "@crm/db/fields";import {Accordion,@@ -18,10 +15,16 @@ import {} from "@crm/ui/components/entity-logo";import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";+import {+ RecordEmpty,+ RecordSection,+ type RecordSheetTab,+} from "@crm/ui/components/record-sheet";import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { TableCell } from "@crm/ui/components/table";import { useMutation, useQuery } from "@tanstack/react-query";+import { HandshakeIcon, MailIcon, StarIcon } from "lucide-react";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import { InlineCompanyField } from "@/components/crm/company-picker";@@ -41,15 +44,12 @@ import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import { WebsiteActivity } from "@/components/crm/website-activity";import {- DetailSheetBody,DetailSheetEmpty,+ DetailSheetLoaded,DetailSheetProperties,DetailSheetProperty,DetailSheetProse,DetailSheetSection,- DetailSheetStat,- DetailSheetStats,- type DetailSheetTab,} from "@/components/detail-sheet";import { LocalDateTime, LocalRelativeDate } from "@/components/local-date-time";import { factsByField } from "@/lib/contact-facts";@@ -60,7 +60,7 @@ import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { RecordActions } from "./record-actions";-import { DealAmount, MetaLine, RecordSheetFrame } from "./record-parts";+import { DealAmount, RecordSheetFrame } from "./record-parts";import { useOpenRecord, useRecordSheetView } from "./record-stack";type Contact = RouterOutputs["contacts"]["byId"];@@ -74,7 +74,7 @@ const DATE_OPTIONS: Intl.DateTimeFormatOptions = {};const DEAL_COLUMNS = [- { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-5" },+ { id: "deal", header: "Deal", width: "w-[32%]", className: "pl-0" },{ id: "role", header: "Role", width: "w-[16%]" },{ id: "stage", header: "Stage", width: "w-[22%]" },{@@ -112,155 +112,137 @@ export function ContactSheet({ contactId }: { contactId: string }) {}),);- const tabs: DetailSheetTab[] = contact- ? [- {- value: "overview",- label: "Overview",- content: <ContactOverview contact={contact} />,- },- {- value: "deals",- label: "Deals",- count: contact.deals.length,- content: <ContactDeals contact={contact} />,- },- {- value: "activity",- label: "Activity",- content: <Timeline anchor={{ contactId: contact.id }} />,- },- {- value: "agent",- label: "Agent",- content: <AgentPanel record={{ kind: "contact", id: contact.id }} />,- keepMounted: true,- },- ]- : [];+ const tabs: RecordSheetTab[] = [+ {+ value: "overview",+ label: "Overview",+ content: contact ? <ContactOverview contact={contact} /> : null,+ },+ {+ value: "deals",+ label: "Deals",+ count: contact?.deals.length,+ fills: true,+ content: contact ? <ContactDeals contact={contact} /> : null,+ },+ {+ value: "activity",+ label: "Activity",+ fills: true,+ content: contact ? <Timeline anchor={{ contactId: contact.id }} /> : null,+ },+ {+ value: "agent",+ label: "Agent",+ fills: true,+ content: contact ? (+ <AgentPanel record={{ kind: "contact", id: contact.id }} />+ ) : null,+ keepMounted: true,+ },+ ];return (- <RecordSheetFrame- loading={query.isPending}- error={query.error?.message ?? null}- title={contact ? contactName(contact) : "Contact"}- description={- contact ? (- <MetaLine parts={[contact.title, contact.company?.name]} />- ) : undefined- }- note={- contact ? (- <>- {contact.isPrimaryContact ? (- <StatusIndicator- tone="success"- label={`Primary contact at ${contact.company?.name ?? "this company"}`}- />- ) : null}- {contact.enrichmentStatus !== "COMPLETE" ? (- <EnrichmentIndicator- status={contact.enrichmentStatus}- queued={contact.queued}- title={contact.enrichmentError}- />- ) : null}- </>- ) : null- }- media={- <PersonAvatar- src={contact?.imageUrl}- name={contact ? contactName(contact) : "?"}- email={contact?.email}- size="lg"- />+ <DetailSheetLoaded+ record={+ contact+ ? {+ kind: "contact",+ id: contact.id,+ label: contactName(contact),+ detail: contact.company?.name ?? contact.email,+ iconUrl: null,+ iconDarkUrl: null,+ iconTone: null,+ imageUrl: contact.imageUrl,+ }+ : null}- actions={- contact ? (- <>- <ContactEnrichmentAction contactId={contact.id} />- {contact.email ? (- <Button asChild variant="outline" size="sm">- <a href={`mailto:${contact.email}`}>- <Icon icon={Email} data-icon="inline-start" />- <span className="hidden sm:inline">Email</span>- </a>- </Button>- ) : null}- {contact.company && !contact.isPrimaryContact ? (- <Button- variant="outline"- size="sm"- disabled={setPrimary.isPending}- onClick={() =>- setPrimary.mutate({- companyId: contact.company?.id ?? "",- contactId: contact.id,- })- }- >- <Icon icon={Star} data-icon="inline-start" />- <span className="hidden sm:inline">Make primary</span>- </Button>- ) : null}- <RecordActions- record={{ kind: "contact", id: contact.id }}+ >+ <RecordSheetFrame+ kind="contact"+ loading={query.isPending}+ error={query.error?.message ?? null}+ title={contact ? contactName(contact) : "Contact"}+ media={+ contact ? (+ <PersonAvatar+ src={contact.imageUrl}name={contactName(contact)}- consequence={`Their notes, agent conversations and everything the agent found go too; emails and meetings stay filed against the company.${contact.email ? ` The sync will not bring ${contact.email} back — only adding them yourself will.` : ""}`}- archivedAt={contact.archivedAt}+ email={contact.email}+ size="sm"/>- </>- ) : null- }- stats={- contact ? (- <DetailSheetStats>- <DetailSheetStat label="Company">+ ) : null+ }+ pills={+ contact ? (+ <>+ {contact.title ? (+ <span className="text-foreground">{contact.title}</span>+ ) : null}{contact.company ? (- <CompanyStat company={contact.company} />- ) : (- <EmptyCellValue />- )}- </DetailSheetStat>- <DetailSheetStat label="Email">+ <CompanyLink company={contact.company} />+ ) : null}+ {contact.isPrimaryContact ? (+ <StatusIndicator tone="success" label="Primary contact" />+ ) : null}+ {contact.enrichmentStatus !== "COMPLETE" ? (+ <EnrichmentIndicator+ status={contact.enrichmentStatus}+ queued={contact.queued}+ title={contact.enrichmentError}+ />+ ) : null}+ </>+ ) : null+ }+ actions={+ contact ? (+ <>+ <ContactEnrichmentAction contactId={contact.id} />{contact.email ? (- <a- href={`mailto:${contact.email}`}- className="underline-offset-2 hover:underline"- >- {contact.email}- </a>- ) : (- <EmptyCellValue />- )}- </DetailSheetStat>- <DetailSheetStat label="Phone">- {contact.phone ? (- <a- href={`tel:${contact.phone}`}- className="underline-offset-2 hover:underline"+ <Button asChild variant="outline" size="sm">+ <a href={`mailto:${contact.email}`}>+ <Icon icon={MailIcon} data-icon="inline-start" />+ <span className="hidden sm:inline">Email</span>+ </a>+ </Button>+ ) : null}+ {contact.company && !contact.isPrimaryContact ? (+ <Button+ variant="outline"+ size="sm"+ disabled={setPrimary.isPending}+ onClick={() =>+ setPrimary.mutate({+ companyId: contact.company?.id ?? "",+ contactId: contact.id,+ })+ }>- {contact.phone}- </a>- ) : (- <EmptyCellValue />- )}- </DetailSheetStat>- <DetailSheetStat label="Owner">- <OwnerCell owner={contact.owner} />- </DetailSheetStat>- </DetailSheetStats>- ) : null- }- tabs={tabs}- tab={tab}- onTabChange={setTab}- />+ <Icon icon={StarIcon} data-icon="inline-start" />+ <span className="hidden sm:inline">Make primary</span>+ </Button>+ ) : null}+ <RecordActions+ record={{ kind: "contact", id: contact.id }}+ name={contactName(contact)}+ consequence={`Their notes, agent conversations and everything the agent found go too. Emails and meetings stay filed against the company.${contact.email ? ` The sync will not bring ${contact.email} back. Only adding them yourself will.` : ""}`}+ archivedAt={contact.archivedAt}+ />+ </>+ ) : null+ }+ rail={contact ? <ContactRail contact={contact} /> : null}+ tabs={tabs}+ tab={tab}+ onTabChange={setTab}+ />+ </DetailSheetLoaded>);}-function CompanyStat({+function CompanyLink({company,}: {company: NonNullable<Contact["company"]>;@@ -271,7 +253,7 @@ function CompanyStat({<buttontype="button"onClick={() => openRecord({ kind: "company", id: company.id })}- className="flex min-w-0 items-center gap-2 underline-offset-2 hover:underline"+ className="flex min-w-0 items-center gap-1.5 rounded-sm text-muted-foreground underline-offset-2 outline-none hover:text-foreground hover:underline focus-visible:shadow-focus"><EntityLogosrc={company.iconUrl}@@ -286,6 +268,35 @@ function CompanyStat({}function ContactOverview({ contact }: { contact: Contact }) {+ const hasRelationship =+ contact.relationship.emails > 0 ||+ contact.relationship.meetings > 0 ||+ contact.relationship.colleagues.length > 0;++ return (+ <>+ {contact.brief ? (+ <Background brief={contact.brief} />+ ) : hasRelationship ? null : (+ <RecordSection label="Background">+ <RecordEmpty>+ Nothing is known about {contactName(contact)} yet. Research, emails+ and meetings show here as they arrive.+ </RecordEmpty>+ </RecordSection>+ )}++ <WeKnowThem+ relationship={contact.relationship}+ contactName={contactName(contact)}+ />++ <WebsiteActivity contactId={contact.id} />+ </>+ );+}++function ContactRail({ contact }: { contact: Contact }) {const trpc = useTRPC();const cache = useCrmCache();@@ -322,9 +333,9 @@ function ContactOverview({ contact }: { contact: Contact }) {const isSaving = savingField(update);return (- <DetailSheetBody>+ <><DetailSheetSection title="Details" action={<FieldsCog kind="contact" />}>- <DetailSheetProperties>+ <DetailSheetProperties columns={1}><InlineFieldlabel="First name"value={contact.firstName}@@ -414,21 +425,12 @@ function ContactOverview({ contact }: { contact: Contact }) {</DetailSheetProperties></DetailSheetSection>- {contact.brief ? <Background brief={contact.brief} /> : null}-- <WeKnowThem- relationship={contact.relationship}- contactName={contactName(contact)}- />-{hasContactLinks(contact) ? (<DetailSheetSection title="Links"><ContactSocials contact={contact} /></DetailSheetSection>) : null}-- <WebsiteActivity contactId={contact.id} />- </DetailSheetBody>+ </>);}@@ -448,7 +450,7 @@ function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {<DetailSheetSectiontitle="Background"action={- <span className="text-muted-foreground text-xs">+ <span className="flex items-baseline gap-x-3 text-13 text-muted-foreground">{brief.sourceUrl ? (<ahref={brief.sourceUrl}@@ -459,7 +461,6 @@ function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {Source</a>) : null}- {brief.sourceUrl ? " · " : null}<LocalDateTime date={brief.refreshedAt} options={DATE_OPTIONS} /></span>}@@ -522,16 +523,18 @@ function WeKnowThem({{emails > 0 ? (<DetailSheetProperty label="Emails"><span className="tabular-nums">{emails}</span>- <span className="text-muted-foreground">- {" · "}- {lastReplyAt ? (- <>- last reply <LocalRelativeDate date={lastReplyAt} />- </>- ) : (- `${first} has never replied`- )}- </span>+ </DetailSheetProperty>+ ) : null}++ {emails > 0 ? (+ <DetailSheetProperty label="Last reply">+ {lastReplyAt ? (+ <LocalRelativeDate date={lastReplyAt} />+ ) : (+ <span className="text-muted-foreground">+ {first} has never replied+ </span>+ )}</DetailSheetProperty>) : null}@@ -543,13 +546,14 @@ function WeKnowThem({{nextMeeting ? (<DetailSheetProperty label="Next meeting" wide>- {nextMeeting.title ?? "Meeting"}- <span className="text-muted-foreground">- {" · "}- <LocalDateTime- date={nextMeeting.startsAt}- options={DATE_OPTIONS}- />+ <span className="flex min-w-0 flex-col">+ <span>{nextMeeting.title ?? "Meeting"}</span>+ <span className="text-muted-foreground">+ <LocalDateTime+ date={nextMeeting.startsAt}+ options={DATE_OPTIONS}+ />+ </span></span></DetailSheetProperty>) : null}@@ -577,7 +581,12 @@ function Colleagues({<buttonkey={colleague.id}type="button"- onClick={() => openRecord({ kind: "contact", id: colleague.id })}+ onClick={() =>+ openRecord(+ { kind: "contact", id: colleague.id },+ colleagues.map((entry) => ({ kind: "contact", id: entry.id })),+ )+ }className="min-w-0 truncate underline-offset-2 hover:underline">{colleague.name}@@ -596,7 +605,7 @@ function ContactDeals({ contact }: { contact: Contact }) {if (contact.deals.length === 0) {return (<DetailSheetEmpty- icon={Partnership}+ icon={HandshakeIcon}title="Not on any deals"description={`${contactName(contact)} is not attached to anything being sold yet. Deals are opened on the company, then people are added to them.`}/>@@ -609,9 +618,14 @@ function ContactDeals({ contact }: { contact: Contact }) {<SimpleTableRowkey={deal.id}clickable- onClick={() => openRecord({ kind: "deal", id: deal.id })}+ onClick={() =>+ openRecord(+ { kind: "deal", id: deal.id },+ contact.deals.map((entry) => ({ kind: "deal", id: entry.id })),+ )+ }>- <TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">+ <TableCell className="truncate py-2.5 pr-3 pl-0 font-medium">{deal.name}</TableCell><TableCell className="truncate px-3 py-2.5 text-muted-foreground">diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsxindex 681a15ec..522667e7 100644--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx@@ -1,8 +1,5 @@"use client";-import Add from "@carbon/icons-react/es/Add";-import Close from "@carbon/icons-react/es/Close";-import UserMultiple from "@carbon/icons-react/es/UserMultiple";import { CURRENCIES, normalizeCurrency } from "@crm/db/currency";import type { FieldValueJson } from "@crm/db/fields";import { Button } from "@crm/ui/components/button";@@ -13,6 +10,11 @@ import {} from "@crm/ui/components/entity-logo";import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";+import {+ RecordFigure,+ RecordSection,+ type RecordSheetTab,+} from "@crm/ui/components/record-sheet";import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";import { TableCell } from "@crm/ui/components/table";import {@@ -22,6 +24,7 @@ import {} from "@crm/ui/components/tooltip";import { formatMoney } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";+import { PlusIcon, UsersIcon, XIcon } from "lucide-react";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import { InlineCompanyField } from "@/components/crm/company-picker";@@ -35,19 +38,15 @@ import {InlineTextCell,savingValue,} from "@/components/crm/inline-field";-import { OwnerCell } from "@/components/crm/owner-cell";import { DealStageMenu } from "@/components/crm/stage-change";import { StageStepper } from "@/components/crm/stage-stepper";import { Timeline } from "@/components/crm/timeline/timeline";import {- DetailSheetBody,DetailSheetEmpty,+ DetailSheetLoaded,DetailSheetProperties,DetailSheetProperty,DetailSheetSection,- DetailSheetStat,- DetailSheetStats,- type DetailSheetTab,} from "@/components/detail-sheet";import {LocalDateTime,@@ -55,6 +54,7 @@ import {LocalRelativeTime,} from "@/components/local-date-time";import { savingField } from "@/lib/pending-field";+import { entityLogoTone } from "@/lib/recent-records";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";@@ -67,7 +67,7 @@ type Deal = RouterOutputs["deals"]["byId"];const CURRENCY_OPTIONS = CURRENCIES.map((entry) => ({value: entry.code,- label: `${entry.code} · ${entry.name}`,+ label: `${entry.code} (${entry.name})`,}));function dealCurrency(currency: string) {@@ -80,7 +80,7 @@ function currencyOptions(currency: string) {}return [- { value: currency, label: `${currency} — no longer supported` },+ { value: currency, label: `${currency} (no longer supported)` },...CURRENCY_OPTIONS,];}@@ -95,7 +95,7 @@ function ReportedValue({ deal }: { deal: Deal }) {<DetailSheetProperty label={`In ${deal.reportingCurrency}`}>{deal.baseAmountCents === null ? (<span className="text-muted-foreground">- No {currency} rate — left out of totals+ No {currency} rate, so it is left out of totals</span>) : (<span className="tabular-nums text-muted-foreground">@@ -107,7 +107,7 @@ function ReportedValue({ deal }: { deal: Deal }) {}const CONTACT_COLUMNS = [- { id: "name", header: "Name", width: "w-[28%]", className: "pl-5" },+ { id: "name", header: "Name", width: "w-[28%]", className: "pl-0" },{ id: "role", header: "Role", width: "w-[20%]" },{ id: "title", header: "Title", width: "w-[22%]" },{ id: "email", header: "Email", width: "w-[22%]" },@@ -133,116 +133,153 @@ export function DealSheet({ dealId }: { dealId: string }) {const query = useQuery(trpc.deals.byId.queryOptions({ id: dealId }));const deal = query.data;- const tabs: DetailSheetTab[] = deal- ? [- {- value: "overview",- label: "Overview",- content: <DealOverview deal={deal} />,- },- {- value: "contacts",- label: "Contacts",- count: deal.contacts.length,- content: (- <DealContacts- deal={deal}- adding={adding === "contact"}- onAdd={() => setAdding("contact")}- onDone={() => setAdding(null)}- />- ),- },- {- value: "activity",- label: "Activity",- content: <Timeline anchor={{ dealId: deal.id }} />,- },- {- value: "agent",- label: "Agent",- content: <AgentPanel record={{ kind: "deal", id: deal.id }} />,- keepMounted: true,- },- ]- : [];+ const tabs: RecordSheetTab[] = [+ {+ value: "overview",+ label: "Overview",+ content: deal ? <DealOverview deal={deal} /> : null,+ },+ {+ value: "contacts",+ label: "Contacts",+ count: deal?.contacts.length,+ fills: true,+ content: deal ? (+ <DealContacts+ deal={deal}+ adding={adding === "contact"}+ onAdd={() => setAdding("contact")}+ onDone={() => setAdding(null)}+ />+ ) : null,+ },+ {+ value: "activity",+ label: "Activity",+ fills: true,+ content: deal ? <Timeline anchor={{ dealId: deal.id }} /> : null,+ },+ {+ value: "agent",+ label: "Agent",+ fills: true,+ content: deal ? (+ <AgentPanel record={{ kind: "deal", id: deal.id }} />+ ) : null,+ keepMounted: true,+ },+ ];return (- <RecordSheetFrame- loading={query.isPending}- error={query.error?.message ?? null}- title={deal?.name ?? "Deal"}- description={- deal ? (- <button- type="button"- onClick={() => openRecord({ kind: "company", id: deal.company.id })}- className="text-foreground underline-offset-2 hover:underline"- >- {deal.company.name}- </button>- ) : undefined- }- media={- deal ? (- <EntityLogo- src={deal.company.iconUrl}- darkSrc={deal.company.iconDarkUrl}- tone={deal.company.iconTone as EntityLogoTone | null | undefined}- name={deal.company.name}- size="lg"- />- ) : null+ <DetailSheetLoaded+ record={+ deal+ ? {+ kind: "deal",+ id: deal.id,+ label: deal.name,+ detail: deal.company.name,+ iconUrl: deal.company.iconUrl,+ iconDarkUrl: deal.company.iconDarkUrl,+ iconTone: entityLogoTone.nullable().parse(deal.company.iconTone),+ imageUrl: null,+ }+ : null}- actions={- deal ? (- <>- <DealStageMenu- dealId={deal.id}- stage={deal.stage}- variant="control"- />- <RecordActions- record={{ kind: "deal", id: deal.id }}- name={deal.name}- consequence={`Its stage history, notes and agent conversations go too. ${deal.company.name} and the ${deal.contacts.length === 1 ? "person" : "people"} on it stay in the CRM.`}- archivedAt={deal.archivedAt}+ >+ <RecordSheetFrame+ kind="deal"+ loading={query.isPending}+ error={query.error?.message ?? null}+ title={deal?.name ?? "Deal"}+ media={+ deal ? (+ <EntityLogo+ src={deal.company.iconUrl}+ darkSrc={deal.company.iconDarkUrl}+ tone={deal.company.iconTone as EntityLogoTone | null | undefined}+ name={deal.company.name}+ size="sm"/>- </>- ) : null- }- stats={- deal ? (- <DetailSheetStats>- <DetailSheetStat label="Amount">- {deal.amountCents === null ? (- <EmptyCellValue />- ) : (- <span className="tabular-nums">- {formatMoney(deal.amountCents, dealCurrency(deal.currency))}- </span>- )}- </DetailSheetStat>- <DetailSheetStat label="Expected close">+ ) : null+ }+ pills={+ deal ? (+ <>+ <button+ type="button"+ onClick={() =>+ openRecord({ kind: "company", id: deal.company.id })+ }+ className="rounded-sm text-foreground underline-offset-2 outline-none hover:underline focus-visible:shadow-focus"+ >+ {deal.company.name}+ </button>{deal.expectedCloseDate ? (- <LocalDay date={deal.expectedCloseDate} />- ) : (- <EmptyCellValue />- )}- </DetailSheetStat>- <DetailSheetStat label="In stage">- <LocalRelativeTime date={deal.stageChangedAt} />- </DetailSheetStat>- <DetailSheetStat label="Owner">- <OwnerCell owner={deal.owner} />- </DetailSheetStat>- </DetailSheetStats>- ) : null- }- tabs={tabs}- tab={tab}- onTabChange={setTab}- />+ <span className="text-muted-foreground">+ Closes <LocalDay date={deal.expectedCloseDate} />+ </span>+ ) : null}+ </>+ ) : null+ }+ actions={+ deal ? (+ <>+ <DealStageMenu+ dealId={deal.id}+ stage={deal.stage}+ variant="control"+ />+ <RecordActions+ record={{ kind: "deal", id: deal.id }}+ name={deal.name}+ consequence={`Its stage history, notes and agent conversations go too. ${deal.company.name} and the ${deal.contacts.length === 1 ? "person" : "people"} on it stay in the CRM.`}+ archivedAt={deal.archivedAt}+ />+ </>+ ) : null+ }+ rail={deal ? <DealRail deal={deal} /> : null}+ tabs={tabs}+ tab={tab}+ onTabChange={setTab}+ />+ </DetailSheetLoaded>+ );+}++function DealValue({ deal }: { deal: Deal }) {+ const currency = dealCurrency(deal.currency);+ const converted =+ currency !== deal.reportingCurrency && deal.amountCents !== null;++ return (+ <RecordSection label="Value">+ <RecordFigure+ value={+ deal.amountCents === null ? (+ <span className="text-muted-foreground">No amount</span>+ ) : (+ formatMoney(deal.amountCents, currency)+ )+ }+ >+ {converted ? (+ deal.baseAmountCents === null ? (+ <span>No {currency} rate, so it is left out of totals</span>+ ) : (+ <span className="tabular-nums">+ About {formatMoney(deal.baseAmountCents, deal.reportingCurrency)}{" "}+ in {deal.reportingCurrency}+ </span>+ )+ ) : null}+ <span>+ Stage changed <LocalRelativeTime date={deal.stageChangedAt} />+ </span>+ </RecordFigure>+ </RecordSection>);}@@ -250,8 +287,6 @@ function DealOverview({ deal }: { deal: Deal }) {const trpc = useTRPC();const cache = useCrmCache();- const users = useQuery(trpc.users.list.queryOptions());-const update = useMutation(trpc.deals.update.mutationOptions({onSuccess: () => cache.deal(deal.id, { settle: "record" }),@@ -259,101 +294,14 @@ function DealOverview({ deal }: { deal: Deal }) {}),);- const saveFields = (fields: Record<string, FieldValueJson>) =>- update.mutate({ id: deal.id, data: { fields } });-- const isSavingField = savingValue(update);-- const save = (data: Parameters<typeof update.mutate>[0]["data"]) =>- update.mutate({ id: deal.id, data });-- const currency = dealCurrency(deal.currency);-const isSaving = savingField(update);return (- <DetailSheetBody>+ <>+ <DealValue deal={deal} />+<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" />}>- <DetailSheetProperties>- <InlineField- label="Name"- value={deal.name}- saving={isSaving("name")}- onSave={(name) => name && save({ name })}- />- <InlineField- label="Amount"- value={- deal.amountCents === null ? null : String(deal.amountCents / 100)- }- placeholder="24000"- saving={isSaving("amountCents")}- onSave={(next) => {- if (next === "") return save({ amountCents: null });- const parsed = Number.parseFloat(next);- if (!Number.isFinite(parsed) || parsed < 0) {- toast.error("Amount has to be a number.");- return;- }- save({ amountCents: Math.round(parsed * 100) });- }}- render={(value) =>- formatMoney(Math.round(Number(value) * 100), currency)- }- />- <InlineSelectField- label="Currency"- value={currency}- options={currencyOptions(currency)}- onSave={(currency) => save({ currency })}- />- <ReportedValue deal={deal} />- <InlineDateField- label="Close date"- value={deal.expectedCloseDate}- saving={isSaving("expectedCloseDate")}- onSave={(next) => save({ expectedCloseDate: next || null })}- />- <InlineCompanyField- value={deal.company.id}- company={deal.company}- saving={isSaving("companyId")}- onSave={(companyId) => save({ companyId })}- />- <InlineSelectField- label="Owner"- value={deal.owner.id}- options={(users.data ?? []).map((user) => ({- value: user.id,- label: user.name,- }))}- onSave={(ownerId) => save({ ownerId })}- />- <RecordFields- fields={deal.fields}- saving={isSavingField}- onSave={saveFields}- />- </DetailSheetProperties></DetailSheetSection><DetailSheetSection title="Description">@@ -362,12 +310,106 @@ function DealOverview({ deal }: { deal: Deal }) {value={deal.description}placeholder={`What ${deal.company.name} is buying, why now, and what stands in the way.`}saving={isSaving("description")}- onSave={(description) => save({ description })}+ onSave={(description) =>+ update.mutate({ id: deal.id, data: { description } })+ }/></DetailSheetSection><WhereItStands deal={deal} />- </DetailSheetBody>+ </>+ );+}++function DealRail({ deal }: { deal: Deal }) {+ const trpc = useTRPC();+ const cache = useCrmCache();++ const users = useQuery(trpc.users.list.queryOptions());++ const update = useMutation(+ trpc.deals.update.mutationOptions({+ onSuccess: () => cache.deal(deal.id, { settle: "record" }),+ onError: (error) => toast.error(error.message),+ }),+ );++ const saveFields = (fields: Record<string, FieldValueJson>) =>+ update.mutate({ id: deal.id, data: { fields } });++ const isSavingField = savingValue(update);++ const save = (data: Parameters<typeof update.mutate>[0]["data"]) =>+ update.mutate({ id: deal.id, data });++ const currency = dealCurrency(deal.currency);++ const isSaving = savingField(update);++ return (+ <DetailSheetSection title="Details" action={<FieldsCog kind="deal" />}>+ <DetailSheetProperties columns={1}>+ <InlineField+ label="Name"+ value={deal.name}+ saving={isSaving("name")}+ onSave={(name) => name && save({ name })}+ />+ <InlineField+ label="Amount"+ value={+ deal.amountCents === null ? null : String(deal.amountCents / 100)+ }+ placeholder="24000"+ saving={isSaving("amountCents")}+ onSave={(next) => {+ if (next === "") return save({ amountCents: null });+ const parsed = Number.parseFloat(next);+ if (!Number.isFinite(parsed) || parsed < 0) {+ toast.error("Amount has to be a number.");+ return;+ }+ save({ amountCents: Math.round(parsed * 100) });+ }}+ render={(value) =>+ formatMoney(Math.round(Number(value) * 100), currency)+ }+ />+ <InlineSelectField+ label="Currency"+ value={currency}+ options={currencyOptions(currency)}+ onSave={(currency) => save({ currency })}+ />+ <ReportedValue deal={deal} />+ <InlineDateField+ label="Close date"+ value={deal.expectedCloseDate}+ saving={isSaving("expectedCloseDate")}+ onSave={(next) => save({ expectedCloseDate: next || null })}+ />+ <InlineCompanyField+ value={deal.company.id}+ company={deal.company}+ saving={isSaving("companyId")}+ onSave={(companyId) => save({ companyId })}+ />+ <InlineSelectField+ label="Owner"+ value={deal.owner.id}+ options={(users.data ?? []).map((user) => ({+ value: user.id,+ label: user.name,+ }))}+ onSave={(ownerId) => save({ ownerId })}+ />+ <RecordFields+ fields={deal.fields}+ saving={isSavingField}+ onSave={saveFields}+ />+ </DetailSheetProperties>+ </DetailSheetSection>);}@@ -473,12 +515,12 @@ function DealContacts({{form}{adding ? null : (<DetailSheetEmpty- icon={UserMultiple}+ icon={UsersIcon}title="No contacts on this deal"description={`Nobody from ${deal.company.name} is attached yet. Bring the people you are selling to onto the deal and it says who to chase.`}action={<Button variant="outline" size="sm" onClick={onAdd}>- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />Add contact</Button>}@@ -496,9 +538,17 @@ function DealContacts({<SimpleTableRowkey={contact.id}clickable- onClick={() => openRecord({ kind: "contact", id: contact.id })}+ onClick={() =>+ openRecord(+ { kind: "contact", id: contact.id },+ deal.contacts.map((entry) => ({+ kind: "contact",+ id: entry.id,+ })),+ )+ }>- <TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">+ <TableCell className="truncate py-2.5 pr-3 pl-0 font-medium"><span className="flex min-w-0 items-center gap-2"><PersonAvatarsrc={contact.imageUrl}@@ -548,7 +598,7 @@ function DealContacts({});}}>- <Icon icon={Close} />+ <Icon icon={XIcon} /><span className="sr-only">Take {contactName(contact)} off this deal</span>diff --git a/apps/app/components/crm/record-sheet/quick-add.tsx b/apps/app/components/crm/record-sheet/quick-add.tsxindex 957f714f..27d1fc13 100644--- a/apps/app/components/crm/record-sheet/quick-add.tsx+++ b/apps/app/components/crm/record-sheet/quick-add.tsx@@ -4,6 +4,7 @@ import { Button } from "@crm/ui/components/button";import { DatePicker } from "@crm/ui/components/date-picker";import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";+import { OptionLabel } from "@crm/ui/components/option-label";import {Select,SelectContent,@@ -36,7 +37,7 @@ function QuickAddForm({}) {return (<form- className="flex shrink-0 flex-col gap-4 border-b px-5 py-4"+ className="flex shrink-0 flex-col gap-4 border-b pb-4"action={onSubmit}><div className="grid gap-4 sm:grid-cols-2">{children}</div>@@ -218,8 +219,10 @@ export function AttachDealContact({<SelectContent>{candidates.map((candidate) => (<SelectItem key={candidate.id} value={candidate.id}>- {contactName(candidate)}- {candidate.title ? ` · ${candidate.title}` : ""}+ <OptionLabel+ label={contactName(candidate)}+ detail={candidate.title}+ /></SelectItem>))}</SelectContent>@@ -315,7 +318,7 @@ export function QuickAddDeal({autoFocusvalue={name}onChange={(event) => setName(event.target.value)}- placeholder={`${companyName} — Comp AI`}+ placeholder={`${companyName} Comp AI`}autoComplete="off"/></Field>diff --git a/apps/app/components/crm/record-sheet/record-actions.tsx b/apps/app/components/crm/record-sheet/record-actions.tsxindex a82a43cf..8af07c50 100644--- a/apps/app/components/crm/record-sheet/record-actions.tsx+++ b/apps/app/components/crm/record-sheet/record-actions.tsx@@ -1,9 +1,5 @@"use client";-import Archive from "@carbon/icons-react/es/Archive";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import TrashCan from "@carbon/icons-react/es/TrashCan";-import Undo from "@carbon/icons-react/es/Undo";import {AlertDialog,AlertDialogAction,@@ -23,6 +19,12 @@ import {} from "@crm/ui/components/dropdown-menu";import { Icon } from "@crm/ui/components/icon";import { useMutation } from "@tanstack/react-query";+import {+ ArchiveIcon,+ EllipsisVerticalIcon,+ Trash2Icon,+ Undo2Icon,+} from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";@@ -127,7 +129,7 @@ export function RecordActions({<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon-sm" disabled={pending}>- <Icon icon={OverflowMenuVertical} />+ <Icon icon={EllipsisVerticalIcon} /><span className="sr-only">More actions</span></Button></DropdownMenuTrigger>@@ -137,14 +139,14 @@ export function RecordActions({<DropdownMenuItemonSelect={() => restore.mutate({ id: record.id })}>- <Icon icon={Undo} />+ <Icon icon={Undo2Icon} />Restore {NOUN[record.kind]}</DropdownMenuItem><DropdownMenuItemvariant="destructive"onSelect={() => setConfirming(true)}>- <Icon icon={TrashCan} />+ <Icon icon={Trash2Icon} />Delete {NOUN[record.kind]} forever</DropdownMenuItem></>@@ -152,7 +154,7 @@ export function RecordActions({<DropdownMenuItemonSelect={() => archive.mutate({ id: record.id })}>- <Icon icon={Archive} />+ <Icon icon={ArchiveIcon} />Archive {NOUN[record.kind]}</DropdownMenuItem>)}diff --git a/apps/app/components/crm/record-sheet/record-navigation.ts b/apps/app/components/crm/record-sheet/record-navigation.tsnew file mode 100644index 00000000..0cc2ced5--- /dev/null+++ b/apps/app/components/crm/record-sheet/record-navigation.ts@@ -0,0 +1,116 @@+import type { RecordRef } from "./record-stack";++export type RecordQueueContext = {+ stack: readonly RecordRef[];+ orderedRecordRefs: readonly RecordRef[];+};++type RecordNavigationChange = {+ stack: RecordRef[];+ queues: RecordQueueContext[];+ history: "push" | "replace";+};++function sameRecord(left: RecordRef, right: RecordRef) {+ return left.kind === right.kind && left.id === right.id;+}++function isStackPrefix(+ prefix: readonly RecordRef[],+ stack: readonly RecordRef[],+) {+ return (+ prefix.length <= stack.length &&+ prefix.every((ref, index) => {+ const entry = stack[index];+ return entry !== undefined && sameRecord(ref, entry);+ })+ );+}++function findRecordQueue(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+) {+ return queues.find(+ (queue) =>+ queue.stack.length === stack.length && isStackPrefix(queue.stack, stack),+ );+}++function captureRecordQueue(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+ orderedRecordRefs?: readonly RecordRef[],+) {+ const next = queues.filter(+ (queue) =>+ queue.stack.length < stack.length && isStackPrefix(queue.stack, stack),+ );+ const top = stack.at(-1);+ if (top && orderedRecordRefs?.some((ref) => sameRecord(ref, top))) {+ next.push({+ stack: [...stack],+ orderedRecordRefs: [...orderedRecordRefs],+ });+ }+ return next;+}++export function getRecordNavigation(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+) {+ const queue = findRecordQueue(stack, queues);+ const top = stack.at(-1);+ if (!queue || !top) return null;+ const index = queue.orderedRecordRefs.findIndex((ref) =>+ sameRecord(ref, top),+ );+ return index < 0 ? null : { index, total: queue.orderedRecordRefs.length };+}++export function openRecordNavigation(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+ ref: RecordRef,+ orderedRecordRefs?: readonly RecordRef[],+): RecordNavigationChange {+ const next = [...stack.filter((entry) => !sameRecord(entry, ref)), ref];+ return {+ stack: next,+ queues: captureRecordQueue(next, queues, orderedRecordRefs),+ history: stack.length === 0 ? "push" : "replace",+ };+}++export function closeRecordNavigation(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+ all = false,+): RecordNavigationChange {+ const next = all ? [] : stack.slice(0, -1);+ return {+ stack: next,+ queues: queues.filter((queue) => isStackPrefix(queue.stack, next)),+ history: "replace",+ };+}++export function moveRecordNavigation(+ stack: readonly RecordRef[],+ queues: readonly RecordQueueContext[],+ direction: -1 | 1,+): RecordNavigationChange | null {+ const queue = findRecordQueue(stack, queues);+ const position = getRecordNavigation(stack, queues);+ if (!queue || !position) return null;+ const ref = queue.orderedRecordRefs[position.index + direction];+ if (!ref) return null;+ const next = [...stack.slice(0, -1), ref];+ return {+ stack: next,+ queues: captureRecordQueue(next, queues, queue.orderedRecordRefs),+ history: "replace",+ };+}diff --git a/apps/app/components/crm/record-sheet/record-parts.tsx b/apps/app/components/crm/record-sheet/record-parts.tsxindex eaf1c15a..2a1715f2 100644--- a/apps/app/components/crm/record-sheet/record-parts.tsx+++ b/apps/app/components/crm/record-sheet/record-parts.tsx@@ -1,78 +1,127 @@"use client";-import Add from "@carbon/icons-react/es/Add";import { Button } from "@crm/ui/components/button";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import { Icon } from "@crm/ui/components/icon";+import {+ RecordSheetBar,+ RecordSheetBody,+ RecordSheetHeader,+ RecordSheetLoading,+ type RecordSheetTab,+} from "@crm/ui/components/record-sheet";import { SimpleTableRow } from "@crm/ui/components/simple-table";-import { Spinner } from "@crm/ui/components/spinner";import { TableCell } from "@crm/ui/components/table";import { formatMoney } from "@crm/ui/lib/format";+import { useQueryClient } from "@tanstack/react-query";+import { PlusIcon } from "lucide-react";import type { ReactNode } from "react";+import { contactName } from "@/components/crm/contact-name";+import { useTRPC } from "@/lib/trpc/client";import {- DetailSheetHeader,- type DetailSheetTab,- DetailSheetTabs,-} from "@/components/detail-sheet";-import { useRecordStack } from "./record-stack";+ type RecordKind,+ type RecordRef,+ useRecordStack,+} from "./record-stack";++const KIND_LABEL = {+ company: "Company",+ contact: "Contact",+ deal: "Deal",+} satisfies Record<RecordKind, string>;++function useRecordName(ref: RecordRef | undefined): string | null {+ const trpc = useTRPC();+ const client = useQueryClient();++ if (!ref) return null;++ if (ref.kind === "company") {+ return (+ client.getQueryData(trpc.companies.byId.queryKey({ id: ref.id }))?.name ??+ null+ );+ }++ if (ref.kind === "contact") {+ const contact = client.getQueryData(+ trpc.contacts.byId.queryKey({ id: ref.id }),+ );+ return contact ? contactName(contact) : null;+ }++ return (+ client.getQueryData(trpc.deals.byId.queryKey({ id: ref.id }))?.name ?? null+ );+}export function RecordSheetFrame({+ kind,loading,error,title,- description,- note,media,+ pills,actions,- stats,tabs,tab,onTabChange,+ rail,}: {+ kind: RecordKind;loading: boolean;error: string | null;title: string;- description?: ReactNode;- note?: ReactNode;media?: ReactNode;+ pills?: ReactNode;actions?: ReactNode;- stats?: ReactNode;- tabs: DetailSheetTab[];+ tabs: RecordSheetTab[];tab: string;onTabChange: (tab: string) => void;+ rail?: ReactNode;}) {- const { stack, close, closeAll } = useRecordStack();+ const { stack, close, closeAll, navigation } = useRecordStack();+ const previous = stack.length > 1 ? stack.at(-2) : undefined;+ const previousName = useRecordName(previous);return (<>- <DetailSheetHeader+ <RecordSheetBar+ label={KIND_LABEL[kind]}+ navigation={navigation}+ back={+ previous+ ? {+ label: previousName ? `Back to ${previousName}` : "Back",+ onBack: close,+ }+ : undefined+ }+ onClose={closeAll}+ />++ <RecordSheetHeader+ title={loading || error ? KIND_LABEL[kind] : title}+ loading={loading}media={media}- title={title}- description={description}- note={note}+ pills={pills}actions={actions}- onBack={stack.length > 1 ? close : undefined}- onClose={closeAll}/>{loading ? (- <div className="flex min-h-0 flex-1 items-center justify-center">- <Spinner />- </div>+ <RecordSheetLoading tabs={tabs.length} />) : error ? (<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 p-6 text-center"><p className="font-medium text-sm">This record could not be loaded</p>- <p className="text-muted-foreground text-xs">{error}</p>+ <p className="text-muted-foreground text-sm">{error}</p></div>) : (- <>- {stats}- <DetailSheetTabs- tabs={tabs}- value={tab}- onValueChange={onTabChange}- />- </>+ <RecordSheetBody+ tabs={tabs}+ value={tab}+ onValueChange={onTabChange}+ rail={rail}+ />)}</>);@@ -94,9 +143,9 @@ export function AddRow({variant="ghost"size="sm"onClick={onClick}- className="h-9 w-full justify-start px-5 font-normal text-muted-foreground"+ className="h-9 w-full justify-start px-0 font-normal text-muted-foreground hover:bg-transparent hover:text-foreground">- <Icon icon={Add} data-icon="inline-start" />+ <Icon icon={PlusIcon} data-icon="inline-start" />{label}</Button></TableCell>@@ -139,15 +188,12 @@ export function MetaLine({}return (- <>+ <span className="flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-0.5">{lead}- {rest.map((part, index) => (- <span key={part}>- {index === 0 && !lead ? null : " · "}- {part}- </span>+ {rest.map((part) => (+ <span key={part}>{part}</span>))}- </>+ </span>);}diff --git a/apps/app/components/crm/record-sheet/record-sheet-host.tsx b/apps/app/components/crm/record-sheet/record-sheet-host.tsxindex 0b06c5dd..5b710d93 100644--- a/apps/app/components/crm/record-sheet/record-sheet-host.tsx+++ b/apps/app/components/crm/record-sheet/record-sheet-host.tsx@@ -1,16 +1,19 @@"use client";-import { useState } from "react";+import { focusRecordTitle } from "@crm/ui/components/record-sheet";+import { Sheet, SheetContent } from "@crm/ui/components/sheet";+import { useRef, useState } from "react";import { FieldsSheetHost } from "@/components/crm/fields/fields-sheet";import { CloseReasonDialog } from "@/components/crm/stage-change";-import { DetailSheet } from "@/components/detail-sheet";import { CompanySheet } from "./company-sheet";import { ContactSheet } from "./contact-sheet";import { DealSheet } from "./deal-sheet";import { type RecordRef, recordKey, useRecordStack } from "./record-stack";export function RecordSheetHost() {- const { stack, top, closeAll } = useRecordStack();+ const { stack, top, closeAll, restoreFocus } = useRecordStack();++ const content = useRef<HTMLDivElement>(null);const [shown, setShown] = useState<RecordRef | null>(top);if (top && (!shown || recordKey(shown) !== recordKey(top))) {@@ -19,24 +22,41 @@ export function RecordSheetHost() {return (<>- <DetailSheet+ <Sheetopen={stack.length > 0}onOpenChange={(next) => {if (!next) closeAll();}}>- {shown?.kind === "company" ? (- <CompanySheet key={recordKey(shown)} companyId={shown.id} />- ) : null}-- {shown?.kind === "contact" ? (- <ContactSheet key={recordKey(shown)} contactId={shown.id} />- ) : null}-- {shown?.kind === "deal" ? (- <DealSheet key={recordKey(shown)} dealId={shown.id} />- ) : null}- </DetailSheet>+ <SheetContent+ ref={content}+ side="right"+ size="record"+ showCloseButton={false}+ tabIndex={-1}+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ focusRecordTitle(content.current);+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ restoreFocus();+ }}+ className="gap-0 p-0"+ >+ {shown?.kind === "company" ? (+ <CompanySheet key={recordKey(shown)} companyId={shown.id} />+ ) : null}++ {shown?.kind === "contact" ? (+ <ContactSheet key={recordKey(shown)} contactId={shown.id} />+ ) : null}++ {shown?.kind === "deal" ? (+ <DealSheet key={recordKey(shown)} dealId={shown.id} />+ ) : null}+ </SheetContent>+ </Sheet><FieldsSheetHost />diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.tsindex d4cddea0..56301866 100644--- a/apps/app/components/crm/record-sheet/record-stack.ts+++ b/apps/app/components/crm/record-sheet/record-stack.ts@@ -1,5 +1,6 @@"use client";+import { usePathname } from "next/navigation";import {parseAsArrayOf,parseAsString,@@ -15,9 +16,17 @@ import {useContext,useMemo,useRef,+ useState,} from "react";import { timelineTabParser } from "@/components/crm/timeline/timeline-search-params";import { SEARCH_PARAM } from "@/lib/search-param-keys";+import {+ closeRecordNavigation,+ getRecordNavigation,+ moveRecordNavigation,+ openRecordNavigation,+ type RecordQueueContext,+} from "./record-navigation";const RECORD_KINDS = ["company", "contact", "deal"] as const;@@ -61,8 +70,14 @@ function parseRef(raw: string): RecordRef | null {function useRecordStackState() {const [values, setParams] = useQueryStates(params);+ const pathname = usePathname();const record = values[SEARCH_PARAM.record.stack];const returnFocus = useRef<HTMLElement | null>(null);+ const [session, setSession] = useState<{+ pathname: string;+ queues: RecordQueueContext[];+ }>({ pathname, queues: [] });+ const queues = session.pathname === pathname ? session.queues : [];const stack = useMemo(() => record.map(parseRef).filter((ref): ref is RecordRef => ref !== null),@@ -89,32 +104,40 @@ function useRecordStackState() {);const open = useCallback(- (ref: RecordRef) => {+ (ref: RecordRef, orderedRecordRefs?: readonly RecordRef[]) => {if (stack.length === 0 && document.activeElement instanceof HTMLElement) {returnFocus.current = document.activeElement;}- const key = recordKey(ref);- void write(- [...stack.filter((entry) => recordKey(entry) !== key), ref],- stack.length === 0 ? "push" : "replace",- );+ const next = openRecordNavigation(stack, queues, ref, orderedRecordRefs);+ setSession({ pathname, queues: next.queues });+ void write(next.stack, next.history);},- [stack, write],+ [stack, queues, pathname, write],);const close = useCallback(() => {- const next = stack.slice(0, -1);- void write(next, "replace").then(() => {- if (next.length > 0) return;- requestAnimationFrame(() => returnFocus.current?.focus());- });- }, [stack, write]);+ const next = closeRecordNavigation(stack, queues);+ setSession({ pathname, queues: next.queues });+ void write(next.stack, next.history);+ }, [stack, queues, pathname, write]);const closeAll = useCallback(() => {- void write([], "replace").then(() => {- requestAnimationFrame(() => returnFocus.current?.focus());- });- }, [write]);+ setSession({ pathname, queues: [] });+ void write([], "replace");+ }, [pathname, write]);++ const restoreFocus = useCallback(() => returnFocus.current?.focus(), []);++ const move = useCallback(+ (direction: -1 | 1) => {+ const next = moveRecordNavigation(stack, queues, direction);+ if (!next) return;+ setSession({ pathname, queues: next.queues });+ void write(next.stack, next.history);+ },+ [stack, queues, pathname, write],+ );+ const position = getRecordNavigation(stack, queues);return {stack,@@ -122,6 +145,14 @@ function useRecordStackState() {open,close,closeAll,+ restoreFocus,+ navigation: position+ ? {+ ...position,+ onPrevious: () => move(-1),+ onNext: () => move(1),+ }+ : undefined,};}@@ -135,6 +166,8 @@ const EMPTY_RECORD_STACK: RecordStackState = {open: () => undefined,close: () => undefined,closeAll: () => undefined,+ restoreFocus: () => undefined,+ navigation: undefined,};function RecordStackFallbackProvider({ children }: { children: ReactNode }) {diff --git a/apps/app/components/crm/social-links.tsx b/apps/app/components/crm/social-links.tsxindex a43a1845..bf09c82f 100644--- a/apps/app/components/crm/social-links.tsx+++ b/apps/app/components/crm/social-links.tsx@@ -1,5 +1,5 @@import { Button } from "@crm/ui/components/button";-import type { CarbonIcon } from "@crm/ui/components/icon";+import type { IconComponent } from "@crm/ui/components/icon";import { Icon } from "@crm/ui/components/icon";import {type CompanyLinks,@@ -14,7 +14,7 @@ function SocialLinks({rows: Array<{key: PropertyKey;label: string;- icon: CarbonIcon;+ icon: IconComponent;href: string;}>;}) {diff --git a/apps/app/components/crm/stage-change.tsx b/apps/app/components/crm/stage-change.tsxindex 4c4dc590..4e07c7c6 100644--- a/apps/app/components/crm/stage-change.tsx+++ b/apps/app/components/crm/stage-change.tsx@@ -1,6 +1,5 @@"use client";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";import type { DealStage } from "@crm/db/enums";import { Button } from "@crm/ui/components/button";import {@@ -23,6 +22,7 @@ import { Icon } from "@crm/ui/components/icon";import { Spinner } from "@crm/ui/components/spinner";import { Textarea } from "@crm/ui/components/textarea";import { useMutation } from "@tanstack/react-query";+import { ChevronDownIcon } from "lucide-react";import { parseAsString, useQueryStates } from "nuqs";import { useId, useState } from "react";import { toast } from "sonner";@@ -75,14 +75,14 @@ export function DealStageMenu({onClick={(event) => event.stopPropagation()}><DealStageIndicator stage={stage} className="text-foreground" />- <Icon icon={ChevronDown} className="text-muted-foreground" />+ <Icon icon={ChevronDownIcon} className="text-muted-foreground" /></Button>) : (<buttontype="button"onClick={(event) => event.stopPropagation()}disabled={setStage.isPending}- className="flex min-w-0 items-center text-left hover:text-foreground disabled:opacity-50"+ className="flex max-w-full min-w-0 items-center text-left hover:text-foreground disabled:opacity-50"><DealStageIndicator stage={stage} /></button>diff --git a/apps/app/components/crm/stage-stepper.tsx b/apps/app/components/crm/stage-stepper.tsxindex 541d7e2d..4aa10d09 100644--- a/apps/app/components/crm/stage-stepper.tsx+++ b/apps/app/components/crm/stage-stepper.tsx@@ -1,11 +1,16 @@"use client";import { DealStage } from "@crm/db/enums";+import { IndicatorDot } from "@crm/ui/components/status-indicator";import { cn } from "@crm/ui/lib/utils";import { useMutation } from "@tanstack/react-query";import { toast } from "sonner";-import { DealStageIndicator } from "@/components/crm/deal-stage";-import { dealStageLabel, isClosedStage, OPEN_STAGES } from "@/lib/deal-stage";+import {+ dealStageLabel,+ dealStagePresentation,+ isClosedStage,+ OPEN_STAGES,+} from "@/lib/deal-stage";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -48,16 +53,25 @@ export function StageStepper({disabled={setStage.isPending}onClick={() => setStage.mutate({ id: dealId, stage: option })}className={cn(- "min-w-0 flex-1 border-t-2 pt-2 text-left text-xs transition-colors disabled:pointer-events-none disabled:opacity-50",+ "group/step flex min-w-0 flex-1 flex-col gap-2 rounded-xs text-left text-xs outline-none transition-colors focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50",reached- ? "border-foreground text-foreground"- : "border-border text-muted-foreground hover:border-muted-foreground hover:text-foreground",+ ? "text-foreground"+ : "text-muted-foreground hover:text-foreground",current && "font-medium",)}>- <span className="block truncate">+ <span+ aria-hidden+ className={cn(+ "h-1.5 rounded-full transition-colors",+ reached+ ? "bg-foreground"+ : "bg-foreground/10 group-hover/step:bg-foreground/30",+ )}+ />+ <span className="text-pretty wrap-break-word leading-4">{current && option === DealStage.CLOSED_WON ? (- <DealStageIndicator stage={stage} className="text-xs" />+ <StageOutcome stage={stage} />) : (dealStageLabel(option))}@@ -69,11 +83,22 @@ export function StageStepper({{exited ? (<li className="flex min-w-0 flex-1">- <div className="min-w-0 flex-1 border-foreground border-t-2 pt-2">- <DealStageIndicator stage={stage} className="text-xs" />+ <div className="flex min-w-0 flex-1 flex-col gap-2 text-xs leading-4">+ <span aria-hidden className="h-1.5 rounded-full bg-foreground" />+ <StageOutcome stage={stage} /></div></li>) : null}</ol>);}++function StageOutcome({ stage }: { stage: DealStage }) {+ const { label, tone } = dealStagePresentation(stage);+ return (+ <span className="flex min-w-0 items-baseline gap-1.5">+ <IndicatorDot tone={tone} aria-hidden="true" className="translate-y-px" />+ <span className="text-pretty wrap-break-word">{label}</span>+ </span>+ );+}diff --git a/apps/app/components/crm/timeline/activity-composer.tsx b/apps/app/components/crm/timeline/activity-composer.tsxindex a17ce9d0..4da0fdc7 100644--- a/apps/app/components/crm/timeline/activity-composer.tsx+++ b/apps/app/components/crm/timeline/activity-composer.tsx@@ -1,6 +1,5 @@"use client";-import Calendar from "@carbon/icons-react/es/Calendar";import { Calendar as DayPicker } from "@crm/ui/components/calendar";import { Icon } from "@crm/ui/components/icon";import {@@ -18,6 +17,7 @@ import { Spinner } from "@crm/ui/components/spinner";import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";import { toDay } from "@crm/ui/lib/format";import { useMutation } from "@tanstack/react-query";+import { CalendarIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { activityLabel } from "@/lib/activity-presentation";@@ -126,7 +126,7 @@ export function ActivityComposer({ anchor }: { anchor: TimelineAnchor }) {<Popover><PopoverTrigger asChild><InputGroupButton variant="ghost" size="xs">- <Icon icon={Calendar} data-icon="inline-start" />+ <Icon icon={CalendarIcon} data-icon="inline-start" />{dueAt ? dueFormat.format(dueAt) : "Due date"}</InputGroupButton></PopoverTrigger>diff --git a/apps/app/components/crm/timeline/due-date-button.tsx b/apps/app/components/crm/timeline/due-date-button.tsxindex 8d4582ee..83d1101d 100644--- a/apps/app/components/crm/timeline/due-date-button.tsx+++ b/apps/app/components/crm/timeline/due-date-button.tsx@@ -1,6 +1,5 @@"use client";-import CalendarGlyph from "@carbon/icons-react/es/Calendar";import { Button } from "@crm/ui/components/button";import { Calendar } from "@crm/ui/components/calendar";import { Icon } from "@crm/ui/components/icon";@@ -11,6 +10,7 @@ import {PopoverTrigger,} from "@crm/ui/components/popover";import { formatDay, fromDay, toDay } from "@crm/ui/lib/format";+import { CalendarIcon } from "lucide-react";import { useState } from "react";export function DueDateButton({@@ -33,7 +33,7 @@ export function DueDateButton({<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><InputGroupButton variant="ghost" size="xs" disabled={disabled}>- <Icon icon={CalendarGlyph} data-icon="inline-start" />+ <Icon icon={CalendarIcon} data-icon="inline-start" />{selected ? formatDay(value) : "Due date"}</InputGroupButton></PopoverTrigger>diff --git a/apps/app/components/crm/timeline/meeting-entry.tsx b/apps/app/components/crm/timeline/meeting-entry.tsxindex f95e39e6..85dd5b03 100644--- a/apps/app/components/crm/timeline/meeting-entry.tsx+++ b/apps/app/components/crm/timeline/meeting-entry.tsx@@ -46,9 +46,10 @@ export function MeetingEntry({<div className="flex flex-wrap items-center gap-x-4 gap-y-2"><span className="text-muted-foreground text-xs">{isAllDay ? (- <>- <LocalDateTime date={startsAt} options={DAY_OPTIONS} /> · All day- </>+ <span className="flex gap-x-3">+ <LocalDateTime date={startsAt} options={DAY_OPTIONS} />+ <span>All day</span>+ </span>) : (<LocalDateTimeRangestart={startsAt}diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsxindex 615b5da5..d5520b0d 100644--- a/apps/app/components/crm/timeline/timeline-entry.tsx+++ b/apps/app/components/crm/timeline/timeline-entry.tsx@@ -1,6 +1,5 @@"use client";-import Edit from "@carbon/icons-react/es/Edit";import { DealStage } from "@crm/db/enums";import { Button } from "@crm/ui/components/button";import { Checkbox } from "@crm/ui/components/checkbox";@@ -8,6 +7,7 @@ import { Icon } from "@crm/ui/components/icon";import { StatusIndicator } from "@crm/ui/components/status-indicator";import { cn } from "@crm/ui/lib/utils";import { useMutation } from "@tanstack/react-query";+import { PencilIcon } from "lucide-react";import { useRef, useState } from "react";import { toast } from "sonner";import { z } from "zod";@@ -162,8 +162,8 @@ export function TimelineEntry({) : null}</div>- <span className="shrink-0 text-muted-foreground">- <span className="hidden sm:inline">{author} · </span>+ <span className="flex shrink-0 gap-x-3 text-muted-foreground">+ <span className="hidden sm:inline">{author}</span><span className="tabular-nums"><LocalDateTime date={when} options={TIME_OPTIONS} /></span>@@ -178,7 +178,7 @@ export function TimelineEntry({disabled={complete.isPending}onClick={() => setEditing(true)}>- <Icon icon={Edit} />+ <Icon icon={PencilIcon} /><span className="sr-only">Edit task</span></Button>) : null}diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsxindex a19a11eb..62e17ab9 100644--- a/apps/app/components/crm/timeline/timeline.tsx+++ b/apps/app/components/crm/timeline/timeline.tsx@@ -1,17 +1,21 @@"use client";-import Chat from "@carbon/icons-react/es/Chat";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Email from "@carbon/icons-react/es/Email";-import Events from "@carbon/icons-react/es/Events";-import Task from "@carbon/icons-react/es/Task";-import Time from "@carbon/icons-react/es/Time";import { Button } from "@crm/ui/components/button";-import type { CarbonIcon } from "@crm/ui/components/icon";+import type { IconComponent } from "@crm/ui/components/icon";+import { Skeleton } from "@crm/ui/components/skeleton";import { Spinner } from "@crm/ui/components/spinner";import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";+import { SKELETON, skeletonRows } from "@crm/ui/lib/skeleton-config";import { cn } from "@crm/ui/lib/utils";import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import {+ CalendarDaysIcon,+ CheckIcon,+ Clock3Icon,+ MailIcon,+ MessageSquareIcon,+ SquareCheckIcon,+} from "lucide-react";import { useQueryState } from "nuqs";import { DetailSheetEmpty, SECTION_TITLE } from "@/components/detail-sheet";import { SEARCH_PARAM } from "@/lib/search-param-keys";@@ -49,7 +53,7 @@ const EMPTY_STATES = {notes: {title: "No notes",description:- "Notes are what you write down for the next person to read — what they care about, who else is involved, what you promised.",+ "Notes are what you write down for the next person to read: what they care about, who else is involved, what you promised.",},email: {title: "No email",@@ -73,13 +77,13 @@ const EMPTY_STATES = {} satisfies Record<TimelineTab, { title: string; description: string }>;const EMPTY_ICONS = {- all: Time,- notes: Chat,- email: Email,- meetings: Events,- upcoming: Task,- done: Checkmark,-} satisfies Record<TimelineTab, CarbonIcon>;+ all: Clock3Icon,+ notes: MessageSquareIcon,+ email: MailIcon,+ meetings: CalendarDaysIcon,+ upcoming: SquareCheckIcon,+ done: CheckIcon,+} satisfies Record<TimelineTab, IconComponent>;const dayFormat = new Intl.DateTimeFormat("en-US", {weekday: "short",@@ -186,7 +190,7 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {return (<div className="flex min-h-0 flex-1 flex-col">- <div className="flex shrink-0 flex-col gap-2 border-b px-5 py-3">+ <div className="flex shrink-0 flex-col gap-2 border-b pb-3"><ActivityComposer anchor={anchor} /><ToggleGroup@@ -212,9 +216,15 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {</div>{history.isPending ? (- <div className="flex min-h-0 flex-1 items-center justify-center">- <Spinner />- </div>+ <ul aria-busy className="flex flex-col gap-3 pt-1">+ {skeletonRows(SKELETON.rows.feed).map((row) => (+ <li key={row} className="flex items-center gap-3">+ <Skeleton className="size-6 shrink-0 rounded-full" />+ <Skeleton className="h-4 flex-1" />+ <Skeleton className="h-4 w-10" />+ </li>+ ))}+ </ul>) : entries.length === 0 && pinnedEntries.length === 0 ? (<DetailSheetEmptyicon={EMPTY_ICONS[tab]}@@ -222,7 +232,7 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {description={EMPTY_STATES[tab].description}/>) : (- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 pb-4">+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto pb-4">{pinnedEntries.length > 0 ? (<TimelineDaylabel="Outstanding"diff --git a/apps/app/components/crm/website-activity.tsx b/apps/app/components/crm/website-activity.tsxindex 96659509..eff6a0b0 100644--- a/apps/app/components/crm/website-activity.tsx+++ b/apps/app/components/crm/website-activity.tsx@@ -58,28 +58,27 @@ export function WebsiteActivity({<span className="tabular-nums">{activity.views.toLocaleString()}</span>- {activity.lastSeenAt ? (- <span className="text-muted-foreground">- {" · last seen "}- <LocalRelativeTime date={activity.lastSeenAt} />- </span>- ) : null}</DetailSheetProperty>+ {activity.lastSeenAt ? (+ <DetailSheetProperty label="Last seen">+ <LocalRelativeTime date={activity.lastSeenAt} />+ </DetailSheetProperty>+ ) : null}+{first ? (<DetailSheetProperty label="Original source">- {channel(first)}+ <Channel touch={first} /></DetailSheetProperty>) : null}{topPage ? (<DetailSheetProperty label="Top page">- <span className="flex min-w-0 items-baseline gap-1">+ <span className="flex min-w-0 items-baseline gap-3"><span className="truncate font-mono" title={topPage.path}>{topPage.path}</span><span className="shrink-0 text-muted-foreground">- {"· "}<span className="tabular-nums">{topPage.views}</span> views</span></span>@@ -88,7 +87,7 @@ export function WebsiteActivity({{channelChanged ? (<DetailSheetProperty label="Latest source">- {channel(last)}+ <Channel touch={last} /></DetailSheetProperty>) : null}@@ -109,5 +108,16 @@ export function WebsiteActivity({function channel(touch: Touch | null): string {if (!touch) return "Unknown";if (!touch.medium || touch.medium === "direct") return touch.source;- return `${touch.source} · ${touch.medium}`;+ return `${touch.source}/${touch.medium}`;+}++function Channel({ touch }: { touch: Touch | null }) {+ if (!touch) return "Unknown";+ if (!touch.medium || touch.medium === "direct") return touch.source;+ return (+ <span className="flex min-w-0 items-baseline gap-3">+ <span>{touch.source}</span>+ <span className="text-muted-foreground">{touch.medium}</span>+ </span>+ );}diff --git a/apps/app/components/dashboard-charts.tsx b/apps/app/components/dashboard-charts.tsxindex 5d26b1e6..74a18e5e 100644--- a/apps/app/components/dashboard-charts.tsx+++ b/apps/app/components/dashboard-charts.tsx@@ -1,22 +1,42 @@"use client";-import { Spinner } from "@crm/ui/components/spinner";+import { Skeleton } from "@crm/ui/components/skeleton";+import { CHART_CONFIG } from "@crm/ui/lib/chart-config";import dynamic from "next/dynamic";const load = () => import("@crm/ui/components/dashboard-chart");-const loading = () => (- <div className="flex h-[200px] items-center justify-center">- <Spinner />+const trendLoading = () => (+ <div className="flex w-full min-w-0 flex-col gap-3">+ <div className="p-1" style={{ height: CHART_CONFIG.height.dashboardTrend }}>+ <Skeleton className="h-full w-full" />+ </div>+ <div className="flex min-h-5 items-center px-5 md:px-6">+ <Skeleton className="h-3 w-48" />+ </div></div>);+const donutLoading = () => (+ <div className="flex w-full min-w-0 flex-col items-center">+ <Skeleton+ className="aspect-square max-w-full rounded-full"+ style={{ height: CHART_CONFIG.height.dashboardDonut }}+ />+ </div>+);++export type {+ DonutSlice,+ SeriesConfig,+} from "@crm/ui/components/dashboard-chart";+export const AreaTrend = dynamic(() => load().then((m) => m.AreaTrend), {ssr: false,- loading,+ loading: trendLoading,});export const DonutStat = dynamic(() => load().then((m) => m.DonutStat), {ssr: false,- loading,+ loading: donutLoading,});diff --git a/apps/app/components/data-table/list-empty.tsx b/apps/app/components/data-table/list-empty.tsxnew file mode 100644index 00000000..95ede663--- /dev/null+++ b/apps/app/components/data-table/list-empty.tsx@@ -0,0 +1,39 @@+"use client";++import { TableEmpty } from "@crm/ui/components/table-empty";+import type { TableQueryState } from "@crm/ui/lib/table-query";+import { useQueryStates } from "nuqs";+import { NoSearchMatch } from "./list-search";+import { searchParsers } from "./list-search-params";++export function ListEmpty({+ query,+ noun,+ archived = false,+ blank,+}: {+ query: TableQueryState;+ noun: string;+ archived?: boolean;+ blank: { title: string; description: string };+}) {+ const [{ q }] = useQueryStates(searchParsers);++ if (q) return <NoSearchMatch query={q} noun={noun} />;++ if (archived) {+ return <p className="text-muted-foreground">No archived {noun}.</p>;+ }++ const filtered = Object.entries(query.filters).some(([id, values]) =>+ id === query.tabId ? query.tab !== "all" : values.length > 0,+ );++ if (filtered) {+ return (+ <p className="text-muted-foreground">No {noun} match these filters.</p>+ );+ }++ return <TableEmpty title={blank.title} description={blank.description} />;+}diff --git a/apps/app/components/data-table/list-search.tsx b/apps/app/components/data-table/list-search.tsxindex f82b7c90..5b85b0ac 100644--- a/apps/app/components/data-table/list-search.tsx+++ b/apps/app/components/data-table/list-search.tsx@@ -1,12 +1,21 @@"use client";-import Search from "@carbon/icons-react/es/Search";+import { Button } from "@crm/ui/components/button";+import {+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@crm/ui/components/empty";import {InputGroup,InputGroupAddon,+ InputGroupButton,InputGroupInput,} from "@crm/ui/components/input-group";import { useSearchInput } from "@crm/ui/hooks/use-search-input";+import { SearchIcon, XIcon } from "lucide-react";import { useQueryStates } from "nuqs";import type { Ref } from "react";import { searchParsers } from "./list-search-params";@@ -46,15 +55,64 @@ function ListSearchInput({return (<InputGroup className="w-full sm:w-64"><InputGroupAddon>- <Search />+ <SearchIcon /></InputGroupAddon><InputGroupInputref={inputRef}+ aria-label={placeholder}+ type="search"placeholder={placeholder}value={value}onChange={(event) => setValue(event.target.value)}autoComplete="off"/>+ {value ? (+ <InputGroupAddon align="inline-end">+ <InputGroupButton+ aria-label="Clear search"+ size="icon-xs"+ onClick={() => {+ setValue("");+ commit("");+ }}+ >+ <XIcon />+ </InputGroupButton>+ </InputGroupAddon>+ ) : null}</InputGroup>);}++export function NoSearchMatch({+ query,+ noun,+}: {+ query: string;+ noun: string;+}) {+ const [, setState] = useQueryStates(searchParsers);++ return (+ <Empty>+ <EmptyMedia variant="icon">+ <SearchIcon />+ </EmptyMedia>+ <EmptyHeader>+ <EmptyTitle>+ No {noun} match “{query}”+ </EmptyTitle>+ <EmptyDescription>+ Check the spelling or try a shorter word.+ </EmptyDescription>+ </EmptyHeader>+ <Button+ onClick={() => setState({ q: "", page: 1 })}+ size="sm"+ variant="outline"+ >+ Clear search+ </Button>+ </Empty>+ );+}diff --git a/apps/app/components/data-table/saved-views-menu.tsx b/apps/app/components/data-table/saved-views-menu.tsxindex a1734239..8053c23c 100644--- a/apps/app/components/data-table/saved-views-menu.tsx+++ b/apps/app/components/data-table/saved-views-menu.tsx@@ -1,7 +1,5 @@"use client";-import Bookmark from "@carbon/icons-react/es/Bookmark";-import Close from "@carbon/icons-react/es/Close";import { Button } from "@crm/ui/components/button";import {Dialog,@@ -22,6 +20,7 @@ import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";import { Switch } from "@crm/ui/components/switch";import { useMutation, useQuery } from "@tanstack/react-query";+import { BookmarkIcon, XIcon } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import type { FieldEntity } from "@/components/crm/fields/fields-entity";@@ -95,7 +94,7 @@ export function SavedViewsMenu({size="sm"className="justify-start sm:justify-center">- <Bookmark data-icon="inline-start" />+ <BookmarkIcon data-icon="inline-start" />Views</Button></DropdownMenuTrigger>@@ -199,7 +198,7 @@ function ViewItem({className="shrink-0"onSelect={onDelete}>- <Close />+ <XIcon /><span className="sr-only">Delete {view.name}</span></DropdownMenuItem></div>diff --git a/apps/app/components/detail-sheet.tsx b/apps/app/components/detail-sheet.tsxindex cb630749..781f9358 100644--- a/apps/app/components/detail-sheet.tsx+++ b/apps/app/components/detail-sheet.tsx@@ -1,7 +1,5 @@"use client";-import ArrowLeft from "@carbon/icons-react/es/ArrowLeft";-import Close from "@carbon/icons-react/es/Close";import { Button } from "@crm/ui/components/button";import {Empty,@@ -11,23 +9,20 @@ import {EmptyMedia,EmptyTitle,} from "@crm/ui/components/empty";-import type { CarbonIcon } from "@crm/ui/components/icon";+import type { IconComponent } from "@crm/ui/components/icon";import { Icon } from "@crm/ui/components/icon";+import { RecordSection } from "@crm/ui/components/record-sheet";import { Separator } from "@crm/ui/components/separator";import type { SheetSize } from "@crm/ui/components/sheet";-import {- Tabs,- TabsContent,- TabsList,- TabsTrigger,-} from "@crm/ui/components/tabs";import {Tooltip,TooltipContent,TooltipTrigger,} from "@crm/ui/components/tooltip";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";import { cn } from "@crm/ui/lib/utils";-import { type ReactNode, useRef, useState } from "react";+import { ArrowLeftIcon, XIcon } from "lucide-react";+import { type ReactNode, useRef } from "react";import {Sheet,SheetContent,@@ -35,17 +30,45 @@ import {SheetHeader,SheetTitle,} from "@/components/responsive-sheet";+import { type RecentRecord, rememberRecentRecord } from "@/lib/recent-records";+import { useWorkspaceSlug } from "@/lib/use-workspace-url";const GUTTER = "px-5";export const SECTION_TITLE ="font-medium text-muted-foreground text-xs uppercase tracking-wider";-export const PROPERTY_ROW = "grid grid-cols-[6.5rem_minmax(0,1fr)] gap-2";+export const PROPERTY_ROW = "grid min-h-9 grid-cols-[7rem_minmax(0,1fr)] gap-3";++export const PROPERTY_LABEL = "truncate text-muted-foreground text-sm";-export const PROPERTY_LABEL = "truncate text-muted-foreground text-xs";+const PROPERTY_CELL = "border border-transparent py-1.5";++function RememberLoadedRecord({ record }: { record: RecentRecord }) {+ const slug = useWorkspaceSlug();+ useMountEffect(() => rememberRecentRecord(slug, record));+ return null;+}-const PROPERTY_CELL = "border border-transparent py-1";+export function DetailSheetLoaded({+ record,+ children,+}: {+ record: RecentRecord | null;+ children: ReactNode;+}) {+ return (+ <>+ {record ? (+ <RememberLoadedRecord+ key={`${record.kind}:${record.id}`}+ record={record}+ />+ ) : null}+ {children}+ </>+ );+}export function DetailSheet({open,@@ -105,7 +128,7 @@ export function DetailSheetHeader({<Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon-sm" onClick={onBack}>- <Icon icon={ArrowLeft} />+ <Icon icon={ArrowLeftIcon} /><span className="sr-only">Back</span></Button></TooltipTrigger>@@ -137,7 +160,7 @@ export function DetailSheetHeader({<Separator orientation="vertical" className="mx-1 h-5" />) : null}<Button variant="ghost" size="icon-sm" onClick={onClose}>- <Icon icon={Close} />+ <Icon icon={XIcon} /><span className="sr-only">Close</span></Button></div>@@ -146,95 +169,6 @@ export function DetailSheetHeader({);}-export function DetailSheetStats({ children }: { children: ReactNode }) {- return (- <dl className="flex shrink-0 divide-x border-b bg-muted/40">{children}</dl>- );-}--export function DetailSheetStat({- label,- children,-}: {- label: ReactNode;- children: ReactNode;-}) {- return (- <div className={cn("flex min-w-0 flex-1 flex-col gap-1 py-2.5", GUTTER)}>- <dt className="truncate text-muted-foreground text-xs/5">{label}</dt>- <dd className="min-w-0 truncate font-medium text-foreground text-sm/5">- {children}- </dd>- </div>- );-}--export type DetailSheetTab = {- value: string;- label: string;- count?: number | null;- content: ReactNode;- keepMounted?: boolean;-};--export function DetailSheetTabs({- tabs,- value,- onValueChange,-}: {- tabs: DetailSheetTab[];- value: string;- onValueChange: (value: string) => void;-}) {- const [opened] = useState(() => new Set<string>());- opened.add(value);-- return (- <Tabs- value={value}- onValueChange={onValueChange}- className="flex min-h-0 flex-1 flex-col gap-0"- >- <TabsList- variant="line"- className={cn("w-full shrink-0 justify-start gap-6 border-b", GUTTER)}- >- {tabs.map((tab) => (- <TabsTrigger key={tab.value} value={tab.value}>- {tab.label}- {tab.count ? (- <span className="text-muted-foreground tabular-nums">- {tab.count}- </span>- ) : null}- </TabsTrigger>- ))}- </TabsList>-- {tabs.map((tab) => (- <TabsContent- key={tab.value}- value={tab.value}- forceMount={- tab.keepMounted && opened.has(tab.value) ? true : undefined- }- className="flex min-h-0 flex-1 flex-col overflow-hidden outline-none data-[state=inactive]:hidden"- >- {tab.content}- </TabsContent>- ))}- </Tabs>- );-}--export function DetailSheetBody({ children }: { children: ReactNode }) {- return (- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">- {children}- </div>- );-}-export function DetailSheetSection({title,action,@@ -247,41 +181,9 @@ export function DetailSheetSection({children: ReactNode;}) {return (- <section- className={cn(- "space-y-2 border-b py-3 last:border-b-0",- GUTTER,- className,- )}- >- {title || action ? (- <div className="flex h-5 items-center justify-between gap-3">- {title ? <h3 className={SECTION_TITLE}>{title}</h3> : <span />}- {action}- </div>- ) : null}- {children}- </section>- );-}--export function DetailSheetSplit({ children }: { children: ReactNode }) {- return (- <div className="flex flex-col gap-6 lg:flex-row lg:items-start lg:gap-8">- {children}- </div>- );-}--export function DetailSheetMain({ children }: { children: ReactNode }) {- return <div className="flex min-w-0 flex-1 flex-col">{children}</div>;-}--export function DetailSheetRail({ children }: { children: ReactNode }) {- return (- <div className="flex w-full min-w-0 shrink-0 flex-col lg:w-80">+ <RecordSection label={title} action={action} className={className}>{children}- </div>+ </RecordSection>);}@@ -293,7 +195,7 @@ export function DetailSheetProperties({columns?: 1 | 2;}) {return (- <div className={cn("grid gap-x-8", columns === 2 && "sm:grid-cols-2")}>+ <div className={cn("grid gap-x-6", columns === 2 && "sm:grid-cols-2")}>{children}</div>);@@ -318,11 +220,11 @@ export function DetailSheetPending({running ? "bg-primary" : "bg-muted-foreground",)}/>- <span className="font-medium text-xs">+ <span className="font-medium text-13">{running ? "Agent is researching" : "Not known yet"}</span></div>- <p className="text-pretty text-muted-foreground text-xs/5">+ <p className="text-pretty text-13 text-muted-foreground">{fields.join(", ")}</p></div>@@ -340,10 +242,10 @@ export function DetailSheetProperty({}) {return (<div className={cn(PROPERTY_ROW, "items-start", wide && "sm:col-span-2")}>- <span className={cn(PROPERTY_LABEL, PROPERTY_CELL, "text-xs/5")}>+ <span className={cn(PROPERTY_LABEL, PROPERTY_CELL, "text-sm/5")}>{label}</span>- <div className={cn(PROPERTY_CELL, "min-w-0 px-2 text-xs/5")}>+ <div className={cn(PROPERTY_CELL, "min-w-0 px-2 text-sm/5")}>{children}</div></div>@@ -351,9 +253,7 @@ export function DetailSheetProperty({}export function DetailSheetProse({ children }: { children: ReactNode }) {- return (- <p className="text-pretty text-muted-foreground text-xs/5">{children}</p>- );+ return <p className="text-pretty text-foreground text-sm/6">{children}</p>;}export function DetailSheetEmpty({@@ -362,7 +262,7 @@ export function DetailSheetEmpty({description,action,}: {- icon: CarbonIcon;+ icon: IconComponent;title: string;description: string;action?: ReactNode;diff --git a/apps/app/components/enrichment-queue.tsx b/apps/app/components/enrichment-queue.tsxindex 555f0524..5a606556 100644--- a/apps/app/components/enrichment-queue.tsx+++ b/apps/app/components/enrichment-queue.tsx@@ -1,6 +1,5 @@"use client";-import ChevronRight from "@carbon/icons-react/es/ChevronRight";import { Button } from "@crm/ui/components/button";import {Collapsible,@@ -28,6 +27,7 @@ import {ENRICHMENT_PAGE_MAX,} from "@crm/validation/enrichment-queue";import { keepPreviousData, useQuery } from "@tanstack/react-query";+import { ChevronRightIcon } from "lucide-react";import { useState } from "react";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";import { elapsedLabel, queueFooter } from "@/lib/enrichment-queue";@@ -72,6 +72,7 @@ export function EnrichmentQueue() {const scheduled = queue.data?.scheduled ?? [];const scheduledTotal = queue.data?.scheduledTotal ?? 0;const visible = expanded ? rows : rows.slice(0, VISIBLE_ROWS);+ const triggerLabel = total > 0 ? `Enriching ${total}` : "Enrichment";const footer = queueFooter({total,fetched: rows.length,@@ -96,11 +97,12 @@ export function EnrichmentQueue() {onOpenChange={(next) => (next ? setOpen(true) : close())}><PopoverTrigger asChild>- <Button variant="outline" size="sm">+ <Button variant="outline" size="sm" aria-label={triggerLabel}><StatusIndicatortone={total > 0 ? "primary" : "neutral"}busy={total > 0}- label={total > 0 ? `Enriching ${total}` : "Enrichment"}+ label={triggerLabel}+ iconOnlyBelowSm/></Button></PopoverTrigger>@@ -237,7 +239,7 @@ function QueueRowButton({<span className="font-mono text-muted-foreground text-xs group-hover:hidden">{elapsedLabel(row.state, row.startedAt, now)}</span>- <ChevronRight+ <ChevronRightIconclassName="hidden size-3.5 text-muted-foreground group-hover:block"aria-hidden="true"/>diff --git a/apps/app/components/landing/agent-section.tsx b/apps/app/components/landing/agent-section.tsxindex f85b8558..4f1e200b 100644--- a/apps/app/components/landing/agent-section.tsx+++ b/apps/app/components/landing/agent-section.tsx@@ -1,12 +1,14 @@-import Add from "@carbon/icons-react/es/Add";-import ArrowRight from "@carbon/icons-react/es/ArrowRight";-import ArrowUp from "@carbon/icons-react/es/ArrowUp";-import Attachment from "@carbon/icons-react/es/Attachment";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";-import Renew from "@carbon/icons-react/es/Renew";-import Time from "@carbon/icons-react/es/Time";import SlackLogo from "@crm/ui/components/brand-logos/slack";import { cn } from "@crm/ui/lib/utils";+import {+ ArrowRightIcon,+ ArrowUpIcon,+ ChevronDownIcon,+ Clock3Icon,+ PaperclipIcon,+ PlusIcon,+ RefreshCwIcon,+} from "lucide-react";import Image from "next/image";import type * as React from "react";import { Chip } from "./chip";@@ -56,13 +58,13 @@ function Composer() {<div className="flex items-center"><div className="flex items-center gap-[14px] text-muted-foreground">- <Add size={16} />- <Attachment size={16} />+ <PlusIcon size={16} />+ <PaperclipIcon size={16} /><span className="font-mono text-sm/4">/</span></div><div className="grow" /><span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary">- <ArrowUp size={14} className="text-primary-foreground" />+ <ArrowUpIcon size={14} className="text-primary-foreground" /></span></div></div>@@ -74,7 +76,7 @@ function SuggestedActions() {<div className="flex w-3xl max-w-full shrink-0 select-none flex-col pt-1"><div className="flex h-7 shrink-0 items-center gap-1.5 text-muted-foreground"><span className="text-[13px]/4">Suggested actions</span>- <ChevronDown size={12} />+ <ChevronDownIcon size={12} /></div><SuggestedAction>@@ -106,12 +108,13 @@ function SuggestedActions() {<SuggestedAction><span className="shrink-0">Every Monday,</span><Chip className="px-2">- <Renew size={13} className="shrink-0" />+ <RefreshCwIcon size={13} className="shrink-0" />re-enrich contacts</Chip><span className="shrink-0">that haven't been contacted in</span><Chip className="px-2">- <Time size={13} className="shrink-0 text-muted-foreground" />4 weeks+ <Clock3Icon size={13} className="shrink-0 text-muted-foreground" />4+ weeks</Chip></SuggestedAction></div>@@ -135,7 +138,7 @@ function SuggestedAction({>{children}</span>- <ArrowRight size={16} className="shrink-0 text-muted-foreground" />+ <ArrowRightIcon size={16} className="shrink-0 text-muted-foreground" /></div>);}diff --git a/apps/app/components/landing/capabilities-section.tsx b/apps/app/components/landing/capabilities-section.tsxindex 6876ed0c..efebf0a4 100644--- a/apps/app/components/landing/capabilities-section.tsx+++ b/apps/app/components/landing/capabilities-section.tsx@@ -1,8 +1,8 @@-import ArrowRight from "@carbon/icons-react/es/ArrowRight";import GitHubLogo from "@crm/ui/components/brand-logos/github";import StripeLogo from "@crm/ui/components/brand-logos/stripe";import VercelLogo from "@crm/ui/components/brand-logos/vercel";import { cn } from "@crm/ui/lib/utils";+import { ArrowRightIcon } from "lucide-react";import type * as React from "react";import { AskCard } from "./ask-card";import {@@ -117,7 +117,7 @@ function AgentBuilderCard() {<CardTitle>Agents that build agents</CardTitle><CardBody>Describe a process in a sentence and the agent writes another agent to- run it — on its own queue, on its own schedule.+ run it on its own queue and schedule.</CardBody><div className="flex select-none flex-col">@@ -130,7 +130,10 @@ function AgentBuilderCard() {<span className="min-w-0 grow font-medium text-[13px]/[18px]">{agent}</span>- <ArrowRight size={14} className="shrink-0 text-muted-foreground" />+ <ArrowRightIcon+ size={14}+ className="shrink-0 text-muted-foreground"+ /></div>))}</div>diff --git a/apps/app/components/landing/hero.tsx b/apps/app/components/landing/hero.tsxindex 3fd11ef6..427b596c 100644--- a/apps/app/components/landing/hero.tsx+++ b/apps/app/components/landing/hero.tsx@@ -11,7 +11,7 @@ export function Hero() {<p className="max-w-[640px] text-pretty text-center text-muted-foreground text-lg/[28px] md:text-xl/[30px]">Humans shouldn't be manually moving pipeline. The first agentic CRM- experience — durable research agents that read your team's inbox,+ experience. Durable research agents that read your team's inbox,enrich companies and contacts, and create agentic workflows.</p>diff --git a/apps/app/components/landing/product-shot/companies-page.tsx b/apps/app/components/landing/product-shot/companies-page.tsxindex 96d5aab5..e86eac62 100644--- a/apps/app/components/landing/product-shot/companies-page.tsx+++ b/apps/app/components/landing/product-shot/companies-page.tsx@@ -1,10 +1,12 @@-import Add from "@carbon/icons-react/es/Add";-import ArrowsVertical from "@carbon/icons-react/es/ArrowsVertical";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";-import ChevronLeft from "@carbon/icons-react/es/ChevronLeft";-import ChevronRight from "@carbon/icons-react/es/ChevronRight";-import Column from "@carbon/icons-react/es/Column";-import Search from "@carbon/icons-react/es/Search";+import {+ ArrowUpDownIcon,+ ChevronDownIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+ Columns3Icon,+ PlusIcon,+ SearchIcon,+} from "lucide-react";import Image from "next/image";import { COMPANY_COLUMNS, MOCK_COMPANIES } from "./companies";import { CompanyMark } from "./company-mark";@@ -37,7 +39,7 @@ export function CompaniesList() {<p className="font-medium text-xl/[120%] tracking-[-0.5px]">Companies</p><div className="flex h-8 shrink-0 items-center rounded-md border border-border bg-muted px-2">- <Search size={14} className="shrink-0 text-muted-foreground" />+ <SearchIcon size={14} className="shrink-0 text-muted-foreground" /><span className="truncate pl-1.5 text-muted-foreground text-xs">Search companies…</span>@@ -73,7 +75,7 @@ function PageHeader() {Every account in the pipeline.</p><span className="col-start-2 row-start-1 flex h-8 shrink-0 items-center justify-self-end rounded-md bg-primary pr-2.5 pl-2 text-primary-foreground shadow-2xs">- <Add size={16} />+ <PlusIcon size={16} /><span className="pl-1.5 font-medium text-xs/[133%]">New company</span></span></div>@@ -84,7 +86,7 @@ function Toolbar() {return (<div className="flex flex-wrap items-center justify-between gap-2"><div className="flex h-8 w-64 shrink-0 items-center rounded-md border border-border bg-muted pl-2">- <Search size={16} className="shrink-0 text-muted-foreground" />+ <SearchIcon size={16} className="shrink-0 text-muted-foreground" /><span className="truncate pl-1.5 text-muted-foreground text-xs">Search companies by name or domain…</span>@@ -97,15 +99,15 @@ function Toolbar() {className="flex h-7 shrink-0 items-center gap-1 rounded-md border border-border bg-muted pr-1.5 pl-2.5 font-medium text-xs/[133%] shadow-2xs">{facet}- <ChevronDown size={14} className="shrink-0 opacity-60" />+ <ChevronDownIcon size={14} className="shrink-0 opacity-60" /></span>))}<span className="flex h-7 shrink-0 items-center gap-1 rounded-md border border-border bg-muted pr-2.5 pl-1.5 font-medium text-xs/[133%] shadow-2xs">- <ArrowsVertical size={14} className="shrink-0" />+ <ArrowUpDownIcon size={14} className="shrink-0" />Sort</span><span className="flex h-7 shrink-0 items-center gap-1 rounded-md border border-border bg-muted pr-2.5 pl-1.5 font-medium text-xs/[133%] shadow-2xs">- <Column size={14} className="shrink-0" />+ <Columns3Icon size={14} className="shrink-0" />Columns<span className="opacity-60">(7)</span></span>@@ -128,7 +130,7 @@ function CompaniesTable() {><span className="-ml-2 inline-flex h-6 items-center gap-1 rounded-sm px-2 text-muted-foreground text-xs/[133%]">{column.label}- <ArrowsVertical size={12} className="shrink-0 opacity-40" />+ <ArrowUpDownIcon size={12} className="shrink-0 opacity-40" /></span></th>))}@@ -197,7 +199,7 @@ function Pagination() {<div className="flex items-center gap-2"><span className="flex h-7 shrink-0 items-center gap-1 rounded-md pr-2.5 pl-1.5 font-medium text-xs/[133%] opacity-50">- <ChevronLeft size={14} className="shrink-0" />+ <ChevronLeftIcon size={14} className="shrink-0" />Previous</span><span className="text-muted-foreground text-xs/[133%] tabular-nums">@@ -205,7 +207,7 @@ function Pagination() {</span><span className="flex h-7 shrink-0 items-center gap-1 rounded-md bg-foreground pr-1.5 pl-2.5 font-medium text-background text-xs/[133%] shadow-2xs">Next- <ChevronRight size={14} className="shrink-0" />+ <ChevronRightIcon size={14} className="shrink-0" /></span></div></div>diff --git a/apps/app/components/landing/product-shot/company-sheet.tsx b/apps/app/components/landing/product-shot/company-sheet.tsxindex 1b1dc883..b97ad97e 100644--- a/apps/app/components/landing/product-shot/company-sheet.tsx+++ b/apps/app/components/landing/product-shot/company-sheet.tsx@@ -1,10 +1,12 @@-import Close from "@carbon/icons-react/es/Close";-import MagicWand from "@carbon/icons-react/es/MagicWand";-import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";-import Renew from "@carbon/icons-react/es/Renew";-import Send from "@carbon/icons-react/es/Send";import Logo from "@crm/ui/components/logo";import { cn } from "@crm/ui/lib/utils";+import {+ ArrowUpIcon,+ EllipsisVerticalIcon,+ RefreshCwIcon,+ WandSparklesIcon,+ XIcon,+} from "lucide-react";import Image from "next/image";import { OWNER } from "./companies";import { CompanyMark } from "./company-mark";@@ -20,7 +22,7 @@ const TABS = [const STATS = [{ label: "Open pipeline", value: "$0" },{ label: "Open deals", value: "0" },- { label: "Next close", value: "—", muted: true },+ { label: "Next close", value: "", muted: true },];const QUESTIONS = [@@ -60,30 +62,31 @@ function SheetHeader({ compact }: { compact?: boolean }) {<p className="mb-0.5 font-medium text-lg/[125%] tracking-[-0.45px]">Comp AI</p>- <p className="text-muted-foreground text-xs/[162.5%]">- trycomp.ai · Compliance+ <p className="flex gap-x-3 text-muted-foreground text-xs/[162.5%]">+ <span>trycomp.ai</span>+ <span>Compliance</span></p></div><div className="flex shrink-0 items-center gap-1">{compact ? null : (<span className="flex h-7 items-center gap-1 rounded-md border border-border bg-muted pr-2.5 pl-1.5 font-medium text-xs/[133%] shadow-2xs">- <Renew size={14} className="shrink-0" />+ <RefreshCwIcon size={14} className="shrink-0" />Re-enrich</span>)}<span className="flex h-7 items-center gap-1 rounded-md bg-primary pr-2.5 pl-1.5 font-medium text-primary-foreground text-xs/[133%] shadow-2xs">- <MagicWand size={14} className="shrink-0" />+ <WandSparklesIcon size={14} className="shrink-0" />Research</span>{compact ? null : (<><span className="flex size-7 items-center justify-center rounded-md">- <OverflowMenuVertical size={16} />+ <EllipsisVerticalIcon size={16} /></span><span className="mx-1 h-5 w-px shrink-0 bg-border" /><span className="flex size-7 items-center justify-center rounded-md">- <Close size={16} />+ <XIcon size={16} /></span></>)}@@ -245,7 +248,7 @@ function SheetComposer({ compact }: { compact?: boolean }) {</span></div><span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-muted">- <Send size={14} />+ <ArrowUpIcon size={14} /></span></div>);diff --git a/apps/app/components/landing/product-shot/product-shot.tsx b/apps/app/components/landing/product-shot/product-shot.tsxindex f8446f3b..1212e9fa 100644--- a/apps/app/components/landing/product-shot/product-shot.tsx+++ b/apps/app/components/landing/product-shot/product-shot.tsx@@ -1,20 +1,22 @@-import Building from "@carbon/icons-react/es/Building";-import Dashboard from "@carbon/icons-react/es/Dashboard";-import Group from "@carbon/icons-react/es/Group";-import Partnership from "@carbon/icons-react/es/Partnership";-import Settings from "@carbon/icons-react/es/Settings";import Logo from "@crm/ui/components/logo";+import {+ Building2Icon,+ HandshakeIcon,+ LayoutDashboardIcon,+ SettingsIcon,+ UsersIcon,+} from "lucide-react";import Image from "next/image";import { BuiltWith } from "../built-with";import { CompaniesList, CompaniesPage } from "./companies-page";import { CompanyDrawer, CompanySheet } from "./company-sheet";const RAIL = [- { icon: Dashboard, label: "Overview", active: false },- { icon: Building, label: "Companies", active: true },- { icon: Group, label: "Contacts", active: false },- { icon: Partnership, label: "Deals", active: false },- { icon: Settings, label: "Settings", active: false },+ { icon: LayoutDashboardIcon, label: "Overview", active: false },+ { icon: Building2Icon, label: "Companies", active: true },+ { icon: UsersIcon, label: "Contacts", active: false },+ { icon: HandshakeIcon, label: "Deals", active: false },+ { icon: SettingsIcon, label: "Settings", active: false },];export function ProductShot() {diff --git a/apps/app/components/landing/setup-prompt-button.tsx b/apps/app/components/landing/setup-prompt-button.tsxindex 3358ecd7..6dc6d0af 100644--- a/apps/app/components/landing/setup-prompt-button.tsx+++ b/apps/app/components/landing/setup-prompt-button.tsx@@ -1,14 +1,13 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Copy from "@carbon/icons-react/es/Copy";import ClaudeLogo from "@crm/ui/components/brand-logos/claude";import { Button } from "@crm/ui/components/button";+import { CheckIcon, CopyIcon } from "lucide-react";import { useState } from "react";import { type CtaLocation, captureLanding } from "./analytics";const SETUP_PROMPT =- "Set up trycompai/crm — install the dependencies, start Postgres, create my .env, and tell me which keys I still need.";+ "Set up trycompai/crm: install the dependencies, start Postgres, create my .env, and tell me which keys I still need.";/*** The page's leading action: hand the whole setup to a coding agent. It stands@@ -35,12 +34,12 @@ export function SetupPromptButton({ location }: { location: CtaLocation }) {<ClaudeLogo data-icon="inline-start" className="size-4" />{copied ? "Copied to clipboard" : "Copy the setup prompt"}{copied ? (- <Checkmark+ <CheckIcondata-icon="inline-end"className="ml-1.5 size-3.5 text-primary"/>) : (- <Copy+ <CopyIcondata-icon="inline-end"className="ml-1.5 size-3.5 text-muted-foreground"/>diff --git a/apps/app/components/local-date-time.tsx b/apps/app/components/local-date-time.tsxindex 22f9fcd8..d7e58d02 100644--- a/apps/app/components/local-date-time.tsx+++ b/apps/app/components/local-date-time.tsx@@ -14,7 +14,7 @@ const LOCAL_DAY_OPTIONS = {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})}`;+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,@@ -128,7 +128,7 @@ function formatRelativeDate(date: string): string {function formatRelativeTime(date: string): string {const then = new Date(date).getTime();- if (!Number.isFinite(then)) return "—";+ if (!Number.isFinite(then)) return "";const difference = Date.now() - then;const absolute = Math.abs(difference);if (absolute < MINUTE_MS) return "just now";diff --git a/apps/app/components/mobile-nav.tsx b/apps/app/components/mobile-nav.tsxindex 5b8e07ba..791ca30a 100644--- a/apps/app/components/mobile-nav.tsx+++ b/apps/app/components/mobile-nav.tsx@@ -1,5 +1,7 @@"use client";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { LAYOUT } from "@crm/ui/lib/layout-config";import { createContext, useContext, useMemo, useState } from "react";type MobileNavContextValue = {@@ -11,6 +13,15 @@ const MobileNavContext = createContext<MobileNavContextValue | null>(null);export function MobileNavProvider({ children }: { children: React.ReactNode }) {const [open, setOpen] = useState(false);+ useMountEffect(() => {+ const desktop = window.matchMedia(LAYOUT.desktopMediaQuery);+ const closeOnDesktop = () => {+ if (desktop.matches) setOpen(false);+ };+ desktop.addEventListener("change", closeOnDesktop);+ closeOnDesktop();+ return () => desktop.removeEventListener("change", closeOnDesktop);+ });const value = useMemo(() => ({ open, setOpen }), [open]);return (<MobileNavContext.Provider value={value}>diff --git a/apps/app/components/page-shell.tsx b/apps/app/components/page-shell.tsxdeleted file mode 100644index 90e16422..00000000--- a/apps/app/components/page-shell.tsx+++ /dev/null@@ -1,171 +0,0 @@-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";-import { PageTransition } from "./page-transition";--function PageShell({- className,- contained = false,- ...props-}: React.ComponentProps<"div"> & { contained?: boolean }) {- return (- <PageTransition>- <main- data-slot="page-shell-scroll"- className={cn(- "flex min-w-0 flex-1 flex-col px-4 pt-4 pb-4 md:px-6 md:pt-6 md:pb-6",- contained ? "min-h-0 overflow-hidden" : "overflow-y-auto",- )}- >- <div- data-slot="page-shell"- className={cn(- "mx-auto flex w-full min-w-0 max-w-7xl flex-1 flex-col gap-6",- className,- )}- {...props}- />- </main>- </PageTransition>- );-}--function PageShellHeader({- className,- children,- ...props-}: React.ComponentProps<"div">) {- return (- <header- data-slot="page-shell-header"- className={cn(- "flex flex-col gap-3 [view-transition-name:page-header]",- className,- )}- {...props}- >- <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2">- {children}- </div>- </header>- );-}--function PageShellHeading({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="page-shell-heading"- className={cn("contents", className)}- {...props}- />- );-}--function PageShellTitle({ className, ...props }: React.ComponentProps<"h1">) {- return (- <h1- data-slot="page-shell-title"- className={cn(- "col-start-1 row-start-1 min-w-0 self-center text-balance font-medium text-2xl tracking-tight md:text-3xl",- className,- )}- {...props}- />- );-}--function PageShellDescription({- className,- ...props-}: React.ComponentProps<"p">) {- return (- <p- data-slot="page-shell-description"- className={cn(- "col-span-full row-start-2 text-balance text-muted-foreground text-sm",- className,- )}- {...props}- />- );-}--function PageShellActions({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="page-shell-actions"- className={cn(- "col-start-2 row-start-1 flex flex-wrap items-center gap-2 self-center justify-self-end",- className,- )}- {...props}- />- );-}--function PageShellContent({- className,- children,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="page-shell-content"- className={cn(- "@container/page-content flex flex-1 flex-col gap-6",- className,- )}- {...props}- >- {children}- </div>- );-}--function PageShellLoading() {- return (- <div aria-busy="true" className="flex justify-center py-12">- <Spinner size="lg" />- </div>- );-}--function PageShellFallback() {- return (- <PageShell aria-busy="true">- <div className="flex flex-col gap-6" aria-hidden="true">- <div className="flex flex-col gap-3">- <Skeleton className="h-8 w-48 max-w-full" />- <Skeleton className="h-4 w-72 max-w-full" />- </div>- <div className="flex flex-col gap-3">- <Skeleton className="h-14 w-full rounded-lg" />- <Skeleton className="h-14 w-full rounded-lg" />- <Skeleton className="h-40 w-full rounded-lg" />- </div>- </div>- <span role="status" className="sr-only">- Loading page…- </span>- </PageShell>- );-}--export {- PageShell,- PageShellActions,- PageShellContent,- PageShellDescription,- PageShellFallback,- PageShellHeader,- PageShellHeading,- PageShellLoading,- PageShellTitle,-};diff --git a/apps/app/components/page-transition.tsx b/apps/app/components/page-transition.tsxdeleted file mode 100644index 99417e45..00000000--- a/apps/app/components/page-transition.tsx+++ /dev/null@@ -1,29 +0,0 @@-import type * as React from "react";-import { ViewTransition } from "react";--const directional = {- "nav-forward": "nav-forward",- "nav-back": "nav-back",- "nav-lateral": "nav-lateral",- default: "none",-} as const;--const enter = {- "nav-forward": "nav-forward",- "nav-back": "nav-back",- "nav-lateral": "nav-lateral",- default: "none",-} as const;--export function PageTransition({ children }: { children: React.ReactNode }) {- return (- <ViewTransition- enter={enter}- exit={directional}- update={directional}- default="none"- >- {children}- </ViewTransition>- );-}diff --git a/apps/app/components/slack/channel-picker.tsx b/apps/app/components/slack/channel-picker.tsxindex dc2ed4b3..16602202 100644--- a/apps/app/components/slack/channel-picker.tsx+++ b/apps/app/components/slack/channel-picker.tsx@@ -1,10 +1,9 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Locked from "@carbon/icons-react/es/Locked";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import { cn } from "@crm/ui/lib/utils";+import { CheckIcon, LockIcon } from "lucide-react";export type PickerChannel = {id: string;@@ -67,7 +66,7 @@ export function ChannelPicker({<span className="flex w-5 shrink-0 items-center justify-center text-muted-foreground">{channel.isPrivate ? (- <Icon className="size-3.5" icon={Locked} motion="none" />+ <Icon className="size-3.5" icon={LockIcon} motion="none" />) : ("#")}@@ -82,8 +81,13 @@ export function ChannelPicker({>{channel.name}</span>- <span className="text-muted-foreground text-xs">- {describe(channel, canInviteItself)}+ <span className="flex flex-wrap gap-x-3 text-muted-foreground text-xs">+ <span>{describe(channel, canInviteItself)}</span>+ {channel.memberCount === null ? null : (+ <span className="tabular-nums">+ {channel.memberCount} people+ </span>+ )}</span></span>@@ -91,7 +95,7 @@ export function ChannelPicker({{selected || (value === null && channel.isMember) ? (<IconclassName="size-4 text-success"- icon={Checkmark}+ icon={CheckIcon}motion="none"/>) : needsHuman && onRequest ? (@@ -122,14 +126,10 @@ export function ChannelPicker({}function describe(channel: PickerChannel, canInviteItself: boolean): string {- const people =- channel.memberCount === null ? "" : ` · ${channel.memberCount} people`;-- if (channel.isMember) return `Comp AI is in${people}`;- if (!channel.classified) return `Not read from Slack yet${people}`;- if (!channel.isPrivate) return `Comp AI can join this one${people}`;- if (canInviteItself) return `Private. Comp AI joins as you${people}`;- if (channel.inviteRequestedAt)- return `Private. Waiting on an invite${people}`;- return `Private. Someone inside has to invite Comp AI${people}`;+ if (channel.isMember) return "Comp AI is in";+ if (!channel.classified) return "Not read from Slack yet";+ if (!channel.isPrivate) return "Comp AI can join this one";+ if (canInviteItself) return "Private. Comp AI joins as you";+ if (channel.inviteRequestedAt) return "Private. Waiting on an invite";+ return "Private. Someone inside has to invite Comp AI";}diff --git a/apps/app/components/theme-provider.tsx b/apps/app/components/theme-provider.tsxindex 179ae36e..7839a052 100644--- a/apps/app/components/theme-provider.tsx+++ b/apps/app/components/theme-provider.tsx@@ -10,7 +10,7 @@ export function ThemeProvider({return (<NextThemesProviderattribute="class"- defaultTheme="system"+ defaultTheme="light"enableSystemdisableTransitionOnChange{...props}diff --git a/apps/app/components/workspace-nav.tsx b/apps/app/components/workspace-nav.tsxnew file mode 100644index 00000000..0ca4ab56--- /dev/null+++ b/apps/app/components/workspace-nav.tsx@@ -0,0 +1,254 @@+"use client";++import { useAppShellNav } from "@crm/ui/components/app-shell";+import {+ AppSidebar,+ AppSidebarGroup,+ AppSidebarItem,+ AppSidebarSection,+ AppSidebarSkeleton,+ AppSidebarWorkspace,+} from "@crm/ui/components/app-sidebar";+import { DropdownMenuItem } from "@crm/ui/components/dropdown-menu";+import { WorkspaceSwitcher } from "@crm/ui/components/workspace-switcher";+import { useQuery } from "@tanstack/react-query";+import {+ Building2Icon,+ HandshakeIcon,+ LayoutDashboardIcon,+ ListChecksIcon,+ type LucideIcon,+ MessagesSquareIcon,+ SettingsIcon,+ UserPlusIcon,+ UsersIcon,+} from "lucide-react";+import Link from "next/link";+import { usePathname, useRouter } from "next/navigation";+import { AgentChatNav } from "@/components/agent-builder/agent-builder-sidebar";+import { usePrefetchSection } from "@/components/crm/section-prefetch";+import { useTRPC } from "@/lib/trpc/client";+import { useWorkspaceUrl } from "@/lib/use-workspace-url";++type NavItem = {+ title: string;+ href: string;+ icon: LucideIcon;+ match: "exact" | "prefix";+ related?: string[];+};++type WorkspaceData = {+ id: string;+ slug: string;+ name: string;+ website: string | null;+ onboarded: boolean;+ viewerRole: "owner" | "member" | "admin" | null;+ canRename: boolean;+ canChangeRoles: boolean;+};++const PRIMARY: NavItem[] = [+ { title: "Overview", href: "/", icon: LayoutDashboardIcon, match: "exact" },+ {+ title: "Chat",+ href: "/chat",+ icon: MessagesSquareIcon,+ match: "prefix",+ related: ["/agents"],+ },+ {+ title: "Companies",+ href: "/companies",+ icon: Building2Icon,+ match: "prefix",+ },+ { title: "Contacts", href: "/contacts", icon: UsersIcon, match: "prefix" },+ { title: "Deals", href: "/deals", icon: HandshakeIcon, match: "prefix" },+ { title: "Tasks", href: "/tasks", icon: ListChecksIcon, match: "prefix" },+];++const SETTINGS: NavItem = {+ title: "Settings",+ href: "/settings",+ icon: SettingsIcon,+ match: "prefix",+};++const SETTINGS_PAGES: { title: string; href: string }[] = [+ { title: "General", href: "/settings" },+ { title: "Tracking & Analytics", href: "/settings/tracking" },+ { title: "Connections", href: "/settings/connections" },+ { title: "Currencies", href: "/settings/currencies" },+ { title: "Members", href: "/settings/members" },+ { title: "API Keys", href: "/settings/api-keys" },+ { title: "SSO", href: "/settings/sso" },+];++const WORKSPACE_ACTIONS: { title: string; href: string; icon: LucideIcon }[] = [+ { title: "Workspace settings", href: "/settings", icon: SettingsIcon },+ { title: "Members", href: "/settings/members", icon: UserPlusIcon },+];++function startsWithSegment(pathname: string, href: string): boolean {+ return pathname === href || pathname.startsWith(`${href}/`);+}++function isActive(item: NavItem, pathname: string): boolean {+ return (+ pathname === item.href ||+ (item.match === "prefix" && startsWithSegment(pathname, item.href)) ||+ Boolean(item.related?.some((prefix) => startsWithSegment(pathname, prefix)))+ );+}++function WorkspaceHeader({+ initialWorkspace,+}: {+ initialWorkspace?: WorkspaceData;+}) {+ const trpc = useTRPC();+ const router = useRouter();+ const workspaceUrl = useWorkspaceUrl();+ const nav = useAppShellNav();+ const workspace = useQuery({+ ...trpc.workspace.get.queryOptions(),+ initialData: initialWorkspace,+ });++ if (!workspace.data) {+ return (+ <AppSidebarWorkspace name="Workspace" loading={workspace.isPending} />+ );+ }++ const { id, slug, name } = workspace.data;++ return (+ <WorkspaceSwitcher+ workspaces={[{ id, slug, name: name.trim() || "Workspace", logo: null }]}+ activeSlug={slug}+ onSwitch={() => {+ nav.close();+ router.push(workspaceUrl());+ }}+ label="Workspace"+ actions={WORKSPACE_ACTIONS.map((action) => (+ <DropdownMenuItem key={action.href} asChild onSelect={nav.close}>+ <Link href={workspaceUrl(action.href)}>+ <action.icon aria-hidden />+ {action.title}+ </Link>+ </DropdownMenuItem>+ ))}+ />+ );+}++export function WorkspaceNav({+ initialWorkspace,+}: {+ initialWorkspace?: WorkspaceData;+}) {+ const pathname = usePathname();+ const workspaceUrl = useWorkspaceUrl();+ const prefetchSection = usePrefetchSection();++ const resolve = (item: NavItem): NavItem => ({+ ...item,+ href: workspaceUrl(item.href),+ related: item.related?.map((path) => workspaceUrl(path)),+ });++ const settings = resolve(SETTINGS);++ if (startsWithSegment(pathname, settings.href)) {+ return (+ <AppSidebar+ label="Workspace settings"+ header={<WorkspaceHeader initialWorkspace={initialWorkspace} />}+ >+ <AppSidebarSection+ label="Settings"+ back={<Link href={workspaceUrl()} transitionTypes={["nav-back"]} />}+ >+ <AppSidebarGroup>+ {SETTINGS_PAGES.map((page) => {+ const href = workspaceUrl(page.href);+ const active =+ page.href === SETTINGS.href+ ? pathname === href+ : startsWithSegment(pathname, href);+ return (+ <AppSidebarItem+ key={page.href}+ label={page.title}+ active={active}+ inset+ >+ <Link+ href={href}+ prefetch+ transitionTypes={["nav-lateral"]}+ />+ </AppSidebarItem>+ );+ })}+ </AppSidebarGroup>+ </AppSidebarSection>+ </AppSidebar>+ );+ }++ const items = PRIMARY.map(resolve);+ const chat = items.find((item) => item.href === workspaceUrl("/chat"));++ if (chat && isActive(chat, pathname)) {+ return (+ <AppSidebar+ label="Chats"+ header={<WorkspaceHeader initialWorkspace={initialWorkspace} />}+ >+ <AgentChatNav />+ </AppSidebar>+ );+ }++ const link = (item: NavItem, section: string) => (+ <AppSidebarItem+ key={item.href}+ icon={item.icon}+ label={item.title}+ active={isActive(item, pathname)}+ >+ <Link+ href={item.href}+ prefetch+ onMouseEnter={() => prefetchSection(section)}+ onFocus={() => prefetchSection(section)}+ transitionTypes={["nav-lateral"]}+ />+ </AppSidebarItem>+ );++ return (+ <AppSidebar+ label="Primary"+ header={<WorkspaceHeader initialWorkspace={initialWorkspace} />}+ footer={link(settings, SETTINGS.href)}+ >+ <AppSidebarGroup>+ {items.map((item, index) => link(item, PRIMARY[index]?.href ?? "/"))}+ </AppSidebarGroup>+ </AppSidebar>+ );+}++export function WorkspaceNavFallback() {+ return (+ <AppSidebar label="Primary" header={<AppSidebarWorkspace loading />}>+ <AppSidebarSkeleton rows={PRIMARY.length} />+ </AppSidebar>+ );+}diff --git a/apps/app/components/workspace-shell.tsx b/apps/app/components/workspace-shell.tsxnew file mode 100644index 00000000..4e01ddef--- /dev/null+++ b/apps/app/components/workspace-shell.tsx@@ -0,0 +1,104 @@+"use client";++import { AgentPresence } from "@crm/ui/components/agent-presence";+import {+ AppShell,+ AppShellHome,+ AppShellSearch,+} from "@crm/ui/components/app-shell";+import Link from "next/link";+import { parseAsBoolean, useQueryState } from "nuqs";+import { Suspense } from "react";+import { useMobileNav } from "@/components/mobile-nav";+import { SEARCH_PARAM } from "@/lib/search-param-keys";+import { useWorkspaceUrl } from "@/lib/use-workspace-url";++const SEARCH_PLACEHOLDER = "Search companies, contacts and deals…";+const CHAT_LABEL = "Ask Comp AI";++function WorkspaceHome() {+ const workspaceUrl = useWorkspaceUrl();++ return (+ <AppShellHome asChild>+ <Link+ href={workspaceUrl()}+ aria-label="Overview"+ transitionTypes={["nav-lateral"]}+ />+ </AppShellHome>+ );+}++function WorkspaceChatLink() {+ const workspaceUrl = useWorkspaceUrl();++ return (+ <AgentPresence label={CHAT_LABEL} asChild>+ <Link href={workspaceUrl("/chat")} transitionTypes={["nav-lateral"]} />+ </AgentPresence>+ );+}++function WorkspaceSearch() {+ const [, setOpen] = useQueryState(+ SEARCH_PARAM.dialog.switcher,+ parseAsBoolean.withDefault(false),+ );++ return (+ <AppShellSearch+ placeholder={SEARCH_PLACEHOLDER}+ onOpen={() => void setOpen(true)}+ />+ );+}++export function WorkspaceShell({+ end,+ sidebar,+ children,+}: {+ end: React.ReactNode;+ sidebar: React.ReactNode;+ children: React.ReactNode;+}) {+ const { open, setOpen } = useMobileNav();++ return (+ <AppShell+ navOpen={open}+ onNavOpenChange={setOpen}+ product="CRM"+ home={+ <Suspense+ fallback={+ <AppShellHome asChild>+ <span />+ </AppShellHome>+ }+ >+ <WorkspaceHome />+ </Suspense>+ }+ search={+ <Suspense+ fallback={+ <AppShellSearch placeholder={SEARCH_PLACEHOLDER} disabled />+ }+ >+ <WorkspaceSearch />+ </Suspense>+ }+ agent={+ <Suspense fallback={<AgentPresence label={CHAT_LABEL} disabled />}>+ <WorkspaceChatLink />+ </Suspense>+ }+ sidebar={sidebar}+ end={end}+ >+ {children}+ </AppShell>+ );+}diff --git a/apps/app/lib/activity-presentation.ts b/apps/app/lib/activity-presentation.tsindex 3f199188..19be2cc3 100644--- a/apps/app/lib/activity-presentation.ts+++ b/apps/app/lib/activity-presentation.ts@@ -1,32 +1,34 @@-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 type { IconComponent } from "@crm/ui/components/icon";+import {+ ArrowRightIcon,+ CalendarDaysIcon,+ MailIcon,+ MessageSquareIcon,+ PhoneIcon,+ SquareCheckIcon,+ WandSparklesIcon,+} from "lucide-react";type ActivityPresentation = Record<ActivityType,- { icon: CarbonIcon; label: string }+ { icon: IconComponent; label: string }>;const PRESENTATION: ActivityPresentation = {- 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" },+ NOTE: { icon: MessageSquareIcon, label: "Note" },+ CALL: { icon: PhoneIcon, label: "Call" },+ EMAIL: { icon: MailIcon, label: "Email" },+ MEETING: { icon: CalendarDaysIcon, label: "Meeting" },+ TASK: { icon: SquareCheckIcon, label: "Task" },+ STAGE_CHANGE: { icon: ArrowRightIcon, label: "Stage change" },+ ENRICHMENT: { icon: WandSparklesIcon, label: "Enrichment" },};export function activityLabel(type: ActivityType): string {return PRESENTATION[type].label;}-export function activityIcon(type: ActivityType): CarbonIcon {+export function activityIcon(type: ActivityType): IconComponent {return PRESENTATION[type].icon;}diff --git a/apps/app/lib/agent-record.ts b/apps/app/lib/agent-record.tsindex b6136ad1..056ab46b 100644--- a/apps/app/lib/agent-record.ts+++ b/apps/app/lib/agent-record.ts@@ -27,7 +27,7 @@ const COPY: RecordCopyByKind = {field: "contactId",title: "Ask about this person",blurb:- "Every step is shown as it happens — including the leads it throws away.",+ "Every step is shown as it happens, including the leads it throws away.",placeholder: "Are they still there?",suggestions: ["Who is this person?",diff --git a/apps/app/lib/command-search-config.ts b/apps/app/lib/command-search-config.tsnew file mode 100644index 00000000..38d20dfd--- /dev/null+++ b/apps/app/lib/command-search-config.ts@@ -0,0 +1,9 @@+import { QUICK_SEARCH } from "@crm/validation/search-config";++const SECOND_MS = 1_000;++export const COMMAND_SEARCH = {+ query: { ...QUICK_SEARCH.query, debounceMs: 0.15 * SECOND_MS },+ results: QUICK_SEARCH.results,+ recents: { limit: 5 },+} as const;diff --git a/apps/app/lib/conversation-cursor.test.ts b/apps/app/lib/conversation-cursor.test.tsnew file mode 100644index 00000000..fb89d91e--- /dev/null+++ b/apps/app/lib/conversation-cursor.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from "bun:test";+import { claimCursor, conversationCursor } from "./conversation-cursor";++describe("conversationCursor", () => {+ test("has no cursor before eve assigns a session", () => {+ expect(+ conversationCursor({ sessionId: null, token: "t", messages: 2 }),+ ).toBeNull();+ expect(+ conversationCursor({ sessionId: "", token: null, messages: 0 }),+ ).toBeNull();+ });++ test("changes when the session, the token or the message count changes", () => {+ const base = conversationCursor({+ sessionId: "s1",+ token: "t1",+ messages: 1,+ });+ expect(base).toBe("s1:t1:1");+ expect(+ conversationCursor({ sessionId: "s2", token: "t1", messages: 1 }),+ ).not.toBe(base);+ expect(+ conversationCursor({ sessionId: "s1", token: "t2", messages: 1 }),+ ).not.toBe(base);+ expect(+ conversationCursor({ sessionId: "s1", token: null, messages: 1 }),+ ).toBe("s1::1");+ expect(+ conversationCursor({ sessionId: "s1", token: "t1", messages: 2 }),+ ).not.toBe(base);+ });+});++describe("claimCursor", () => {+ test("claims each cursor once, so a remount does not save twice", () => {+ const written = { current: null as string | null };+ expect(claimCursor(written, "s1:t1:1")).toBe(true);+ expect(claimCursor(written, "s1:t1:1")).toBe(false);+ expect(claimCursor(written, "s1:t1:2")).toBe(true);+ expect(claimCursor(written, "s1:t1:2")).toBe(false);+ });++ test("claims a cursor again after a different one was written", () => {+ const written = { current: null as string | null };+ claimCursor(written, "s1:t1:1");+ claimCursor(written, "s1:t2:1");+ expect(claimCursor(written, "s1:t1:1")).toBe(true);+ });+});diff --git a/apps/app/lib/conversation-cursor.ts b/apps/app/lib/conversation-cursor.tsnew file mode 100644index 00000000..bfdd40fd--- /dev/null+++ b/apps/app/lib/conversation-cursor.ts@@ -0,0 +1,21 @@+export function conversationCursor({+ sessionId,+ token,+ messages,+}: {+ sessionId: string | null;+ token: string | null;+ messages: number;+}): string | null {+ if (!sessionId) return null;+ return `${sessionId}:${token ?? ""}:${messages}`;+}++export function claimCursor(+ written: { current: string | null },+ cursor: string,+): boolean {+ if (written.current === cursor) return false;+ written.current = cursor;+ return true;+}diff --git a/apps/app/lib/deal-stage.ts b/apps/app/lib/deal-stage.tsindex 758f08f2..3380967d 100644--- a/apps/app/lib/deal-stage.ts+++ b/apps/app/lib/deal-stage.ts@@ -1,5 +1,6 @@import { DealStage } from "@crm/db/enums";import type { StatusTone } from "@crm/ui/components/status-indicator";+import { type ChartColor, stageChartColor } from "@crm/ui/lib/chart-config";const ORDER = [DealStage.DEMO_BOOKED,@@ -38,19 +39,12 @@ export const DEAL_STAGE_OPTIONS = ORDER.map((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 dealStageChartColor(stage: DealStage): ChartColor {+ return stageChartColor(OPEN_STAGES.indexOf(stage));}export function dealStageLabel(stage: DealStage): string {diff --git a/apps/app/lib/enrichment-queue.ts b/apps/app/lib/enrichment-queue.tsindex 26b81b75..b9486540 100644--- a/apps/app/lib/enrichment-queue.ts+++ b/apps/app/lib/enrichment-queue.ts@@ -4,7 +4,7 @@ const SECOND_MS = 1_000;const MINUTE_S = 60;const HOUR_S = 60 * MINUTE_S;-export const NO_ELAPSED = "—";+export const NO_ELAPSED = "";export type QueueFooter = {more: number;diff --git a/apps/app/lib/recent-records.ts b/apps/app/lib/recent-records.tsnew file mode 100644index 00000000..122026be--- /dev/null+++ b/apps/app/lib/recent-records.ts@@ -0,0 +1,166 @@+"use client";++import { useSyncExternalStore } from "react";+import { toast } from "sonner";+import { z } from "zod";+import { COMMAND_SEARCH } from "@/lib/command-search-config";++const STORAGE_PREFIX = "crm:recent-records:";++export const entityLogoTone = z.enum(["opaque", "dark", "light"]);++export const recentRecord = z.object({+ kind: z.enum(["company", "contact", "deal"]),+ id: z.string().min(1),+ label: z.string(),+ detail: z.string().nullable(),+ iconUrl: z.string().nullable(),+ iconDarkUrl: z.string().nullable(),+ iconTone: entityLogoTone.nullable(),+ imageUrl: z.string().nullable(),+});++export type RecentRecord = z.infer<typeof recentRecord>;++const recentRecords = z.array(recentRecord);++const listeners = new Set<() => void>();++function storageKey(slug: string): string {+ return `${STORAGE_PREFIX}${slug}`;+}++function readRaw(slug: string): string | null {+ try {+ return window.localStorage.getItem(storageKey(slug));+ } catch {+ return null;+ }+}++export function parseRecentRecords(raw: string | null): RecentRecord[] {+ if (raw === null) return [];++ try {+ return recentRecords.parse(JSON.parse(raw));+ } catch (cause) {+ throw new Error("Recent records contain invalid saved data.", { cause });+ }+}++export function readRecentRecords(raw: string | null) {+ try {+ return { status: "ready", records: parseRecentRecords(raw) } as const;+ } catch (error) {+ return {+ status: "invalid",+ message:+ error instanceof Error+ ? error.message+ : "Recent records cannot be read.",+ raw,+ } as const;+ }+}++function publish() {+ for (const listener of listeners) listener();+}++export function recoverRecentRecords(slug: string, raw: string | null) {+ if (readRaw(slug) !== raw) return;+ try {+ window.localStorage.removeItem(storageKey(slug));+ publish();+ toast.error(+ "Recent records contain invalid saved data. The cache is reset.",+ {+ id: "recent-records-invalid",+ },+ );+ } catch {+ toast.error("Recent records cannot be reset in this browser.", {+ id: "recent-records-storage",+ });+ }+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ window.addEventListener("storage", listener);++ return () => {+ listeners.delete(listener);+ window.removeEventListener("storage", listener);+ };+}++export function useRecentRecordsRaw(slug: string): string | null {+ return useSyncExternalStore(+ subscribe,+ () => readRaw(slug),+ () => null,+ );+}++export function rememberRecentRecord(slug: string, record: RecentRecord) {+ const parsed = recentRecord.parse(record);+ const state = readRecentRecords(readRaw(slug));+ if (state.status === "invalid") recoverRecentRecords(slug, state.raw);+ const next = [+ parsed,+ ...(state.status === "ready" ? state.records : []).filter(+ (entry) => entry.kind !== parsed.kind || entry.id !== parsed.id,+ ),+ ].slice(0, COMMAND_SEARCH.recents.limit);++ try {+ window.localStorage.setItem(storageKey(slug), JSON.stringify(next));+ } catch {+ toast.error("Recent records cannot be saved in this browser.", {+ id: "recent-records-storage",+ });+ return;+ }++ publish();+}++export function forgetRecentRecord(+ slug: string,+ record: Pick<RecentRecord, "kind" | "id">,+) {+ const state = readRecentRecords(readRaw(slug));+ if (state.status === "invalid") {+ recoverRecentRecords(slug, state.raw);+ return;+ }+ const next = state.records.filter(+ (entry) => entry.kind !== record.kind || entry.id !== record.id,+ );+ try {+ window.localStorage.setItem(storageKey(slug), JSON.stringify(next));+ publish();+ } catch {+ toast.error("Recent records cannot be saved in this browser.", {+ id: "recent-records-storage",+ });+ }+}++export async function resolveRecentRecord(+ load: () => Promise<unknown>,+ onMissing: () => void,+): Promise<boolean> {+ try {+ await load();+ return true;+ } catch (error) {+ const missing = z+ .object({ data: z.object({ code: z.literal("NOT_FOUND") }) })+ .safeParse(error);+ if (!missing.success) throw error;+ onMissing();+ return false;+ }+}diff --git a/apps/app/lib/social-links.ts b/apps/app/lib/social-links.tsindex 7315b5f7..7132e162 100644--- a/apps/app/lib/social-links.ts+++ b/apps/app/lib/social-links.ts@@ -1,11 +1,10 @@-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";+import GitHubLogo from "@crm/ui/components/brand-logos/github";+import LinkedInLogo from "@crm/ui/components/brand-logos/linkedin";+import XLogo from "@crm/ui/components/brand-logos/x";+import type { IconComponent } from "@crm/ui/components/icon";+import { BanknoteIcon, UsersIcon } from "lucide-react";-type SocialLink<T> = { key: keyof T; label: string; icon: CarbonIcon };+type SocialLink<T> = { key: keyof T; label: string; icon: IconComponent };export type CompanyLinks = {linkedinUrl: string | null;@@ -22,17 +21,17 @@ export type ContactLinks = {};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 },+ { key: "linkedinUrl", label: "LinkedIn", icon: LinkedInLogo },+ { key: "twitterUrl", label: "X", icon: XLogo },+ { key: "githubUrl", label: "GitHub", icon: GitHubLogo },+ { key: "pricingUrl", label: "Pricing", icon: BanknoteIcon },+ { key: "careersUrl", label: "Careers", icon: UsersIcon },];const CONTACT_LINKS: SocialLink<ContactLinks>[] = [- { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },- { key: "twitterUrl", label: "X", icon: LogoX },- { key: "githubUrl", label: "GitHub", icon: LogoGithub },+ { key: "linkedinUrl", label: "LinkedIn", icon: LinkedInLogo },+ { key: "twitterUrl", label: "X", icon: XLogo },+ { key: "githubUrl", label: "GitHub", icon: GitHubLogo },];function present<T extends Record<string, string | null>>(diff --git a/apps/app/package.json b/apps/app/package.jsonindex 7702e3b0..f05fddf8 100644--- a/apps/app/package.json+++ b/apps/app/package.json@@ -12,7 +12,6 @@"lint": "biome check ."},"dependencies": {- "@carbon/icons-react": "^11.82.0","@crm/auth": "workspace:*","@crm/db": "workspace:*","@crm/env": "workspace:*",@@ -27,9 +26,10 @@"@trpc/server": "^11.18.0","@trpc/tanstack-react-query": "^11.18.0","api": "workspace:*",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","eve": "^0.69.0","graphql": "^17.0.2",+ "lucide-react": "1.48.0","next": "16.4.2","next-themes": "^0.4.6","nuqs": "^2.8.9",diff --git a/apps/app/test/agent-session.spec.ts b/apps/app/test/agent-session.spec.tsindex 7fa9654f..390899e6 100644--- a/apps/app/test/agent-session.spec.ts+++ b/apps/app/test/agent-session.spec.ts@@ -175,7 +175,10 @@ describe("the record sheet", () => {}const sheet = readFileSync(- new URL("../components/detail-sheet.tsx", import.meta.url),+ new URL(+ "../../../packages/ui/src/components/record-sheet.tsx",+ import.meta.url,+ ),"utf8",);diff --git a/apps/app/test/day.spec.ts b/apps/app/test/day.spec.tsindex 551f44c4..c96590de 100644--- a/apps/app/test/day.spec.ts+++ b/apps/app/test/day.spec.ts@@ -21,6 +21,6 @@ describe("day strings", () => {expect(fromDay(null)).toBeUndefined();expect(fromDay("")).toBeUndefined();expect(fromDay("someday")).toBeUndefined();- expect(formatDay(null)).toBe("—");+ expect(formatDay(null)).toBe("");});});diff --git a/apps/app/test/recent-records.spec.ts b/apps/app/test/recent-records.spec.tsnew file mode 100644index 00000000..6b1b0a3a--- /dev/null+++ b/apps/app/test/recent-records.spec.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";+import { toast } from "sonner";+import { COMMAND_SEARCH } from "@/lib/command-search-config";+import {+ forgetRecentRecord,+ parseRecentRecords,+ type RecentRecord,+ readRecentRecords,+ recoverRecentRecords,+ rememberRecentRecord,+ resolveRecentRecord,+} from "@/lib/recent-records";++const key = "crm:recent-records:workspace";+const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");+const storage = new Map<string, string>();++function record(+ id: string,+ kind: RecentRecord["kind"] = "company",+): RecentRecord {+ return {+ kind,+ id,+ label: `Record ${id}`,+ detail: null,+ iconUrl: null,+ iconDarkUrl: null,+ iconTone: null,+ imageUrl: null,+ };+}++beforeEach(() => {+ storage.clear();+ Object.defineProperty(globalThis, "window", {+ configurable: true,+ value: {+ localStorage: {+ getItem: (name: string) => storage.get(name) ?? null,+ setItem: (name: string, value: string) => storage.set(name, value),+ removeItem: (name: string) => storage.delete(name),+ },+ },+ });+});++afterEach(() => {+ if (originalWindow)+ Object.defineProperty(globalThis, "window", originalWindow);+ else Reflect.deleteProperty(globalThis, "window");+});++describe("recent record cache", () => {+ it("distinguishes missing storage from invalid stored records", () => {+ expect(parseRecentRecords(null)).toEqual([]);+ for (const raw of ["", "broken", "{}", '[{"kind":"company","id":"one"}]']) {+ expect(() => parseRecentRecords(raw)).toThrow("invalid saved data");+ expect(readRecentRecords(raw).status).toBe("invalid");+ }+ });++ it("deduplicates by kind and id, updates metadata, and keeps the recent limit", () => {+ for (let id = 0; id <= COMMAND_SEARCH.recents.limit; id++) {+ rememberRecentRecord("workspace", record(String(id)));+ }+ const updated = { ...record("2"), label: "Renamed" };+ rememberRecentRecord("workspace", updated);+ rememberRecentRecord("workspace", record("2", "contact"));+ const recent = parseRecentRecords(storage.get(key) ?? null);+ expect(recent).toHaveLength(COMMAND_SEARCH.recents.limit);+ expect(recent[0]).toEqual(record("2", "contact"));+ expect(recent[1]).toEqual(updated);+ expect(+ recent.filter((entry) => entry.kind === "company" && entry.id === "2"),+ ).toHaveLength(1);+ expect(recent.some((entry) => entry.id === "0")).toBe(false);+ });++ it("reports corrupt storage and saves the newly loaded record after recovery", () => {+ const report = spyOn(toast, "error").mockImplementation(() => "test-toast");+ try {+ storage.set(key, "broken");+ rememberRecentRecord("workspace", record("loaded"));+ expect(parseRecentRecords(storage.get(key) ?? null)).toEqual([+ record("loaded"),+ ]);+ expect(report).toHaveBeenCalledWith(+ "Recent records contain invalid saved data. The cache is reset.",+ { id: "recent-records-invalid" },+ );+ } finally {+ report.mockRestore();+ }+ });++ it("preserves a newer cache write during recovery", () => {+ storage.set(key, JSON.stringify([record("newer")]));+ recoverRecentRecords("workspace", "broken");+ expect(parseRecentRecords(storage.get(key) ?? null)).toEqual([+ record("newer"),+ ]);+ });++ it("removes the missing record and preserves another kind with the same id", () => {+ rememberRecentRecord("workspace", record("one"));+ rememberRecentRecord("workspace", record("one", "deal"));+ forgetRecentRecord("workspace", record("one"));+ expect(parseRecentRecords(storage.get(key) ?? null)).toEqual([+ record("one", "deal"),+ ]);+ });+});++describe("recent record validation", () => {+ it("opens only after the record read succeeds", async () => {+ let finish: () => void = () => undefined;+ let opened = false;+ const missing: string[] = [];+ const pending = resolveRecentRecord(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ () => missing.push("missing"),+ ).then((exists) => {+ opened = exists;+ return exists;+ });+ await Promise.resolve();+ expect(opened).toBe(false);+ finish();+ expect(await pending).toBe(true);+ expect(opened).toBe(true);+ expect(missing).toEqual([]);+ });++ it("prunes a deleted recent and prevents its sheet from opening", async () => {+ rememberRecentRecord("workspace", record("deleted"));+ const exists = await resolveRecentRecord(+ () => Promise.reject({ data: { code: "NOT_FOUND" } }),+ () => forgetRecentRecord("workspace", record("deleted")),+ );+ expect(exists).toBe(false);+ expect(parseRecentRecords(storage.get(key) ?? null)).toEqual([]);+ });++ it("keeps a recent on network errors and reports the failure", async () => {+ rememberRecentRecord("workspace", record("offline"));+ const error = new Error("Network unavailable");+ await expect(+ resolveRecentRecord(+ () => Promise.reject(error),+ () => forgetRecentRecord("workspace", record("offline")),+ ),+ ).rejects.toBe(error);+ expect(parseRecentRecords(storage.get(key) ?? null)).toEqual([+ record("offline"),+ ]);+ });+});diff --git a/apps/app/test/record-navigation.spec.ts b/apps/app/test/record-navigation.spec.tsnew file mode 100644index 00000000..74cba2bb--- /dev/null+++ b/apps/app/test/record-navigation.spec.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "bun:test";+import {+ closeRecordNavigation,+ getRecordNavigation,+ moveRecordNavigation,+ openRecordNavigation,+} from "@/components/crm/record-sheet/record-navigation";+import type { RecordRef } from "@/components/crm/record-sheet/record-stack";++const company: RecordRef = { kind: "company", id: "company" };+const first: RecordRef = { kind: "deal", id: "first" };+const second: RecordRef = { kind: "deal", id: "second" };+const third: RecordRef = { kind: "deal", id: "third" };+const contact: RecordRef = { kind: "contact", id: "contact" };++describe("record list navigation", () => {+ it("does not invent a queue for empty lists, direct links, or search opens", () => {+ expect(getRecordNavigation([], [])).toBeNull();+ expect(getRecordNavigation([first], [])).toBeNull();+ for (const refs of [undefined, [], [second]]) {+ const opened = openRecordNavigation([], [], first, refs);+ expect(getRecordNavigation(opened.stack, opened.queues)).toBeNull();+ expect(moveRecordNavigation(opened.stack, opened.queues, 1)).toBeNull();+ }+ });++ it("captures only the visible page order and preserves its filtered order", () => {+ const page = [third, first, second];+ const opened = openRecordNavigation([], [], first, page);+ page.reverse();+ expect(getRecordNavigation(opened.stack, opened.queues)).toEqual({+ index: 1,+ total: 3,+ });+ expect(+ moveRecordNavigation(opened.stack, opened.queues, -1)?.stack,+ ).toEqual([third]);+ expect(moveRecordNavigation(opened.stack, opened.queues, 1)?.stack).toEqual(+ [second],+ );+ });++ it("stops at both bounds and keeps a single-record page truthful", () => {+ const opened = openRecordNavigation([], [], first, [first, second]);+ expect(moveRecordNavigation(opened.stack, opened.queues, -1)).toBeNull();+ const next = moveRecordNavigation(opened.stack, opened.queues, 1);+ expect(next).not.toBeNull();+ if (!next) throw new Error("Next record is missing.");+ expect(getRecordNavigation(next.stack, next.queues)).toEqual({+ index: 1,+ total: 2,+ });+ expect(moveRecordNavigation(next.stack, next.queues, 1)).toBeNull();+ const single = openRecordNavigation([], [], first, [first]);+ expect(getRecordNavigation(single.stack, single.queues)).toEqual({+ index: 0,+ total: 1,+ });+ expect(moveRecordNavigation(single.stack, single.queues, -1)).toBeNull();+ expect(moveRecordNavigation(single.stack, single.queues, 1)).toBeNull();+ });++ it("replaces only the top entry and keeps nested Back distinct from queue moves", () => {+ const parent = openRecordNavigation([], [], company, [company]);+ const opened = openRecordNavigation(parent.stack, parent.queues, first, [+ first,+ second,+ ]);+ const moved = moveRecordNavigation(opened.stack, opened.queues, 1);+ if (!moved) throw new Error("Next record is missing.");+ expect(moved.stack).toEqual([company, second]);+ expect(moved.history).toBe("replace");+ const nested = openRecordNavigation(moved.stack, moved.queues, contact);+ expect(getRecordNavigation(nested.stack, nested.queues)).toBeNull();+ const back = closeRecordNavigation(nested.stack, nested.queues);+ expect(back.stack).toEqual([company, second]);+ expect(getRecordNavigation(back.stack, back.queues)).toEqual({+ index: 1,+ total: 2,+ });+ const parentBack = closeRecordNavigation(back.stack, back.queues);+ expect(parentBack.stack).toEqual([company]);+ expect(getRecordNavigation(parentBack.stack, parentBack.queues)).toEqual({+ index: 0,+ total: 1,+ });+ });++ it("pushes only the initial open and clears the queue on close", () => {+ const opened = openRecordNavigation([], [], first, [first, second]);+ expect(opened.history).toBe("push");+ const nested = openRecordNavigation(opened.stack, opened.queues, company);+ expect(nested.history).toBe("replace");+ const closed = closeRecordNavigation(nested.stack, nested.queues, true);+ expect(closed).toEqual({ stack: [], queues: [], history: "replace" });+ const reopened = openRecordNavigation(closed.stack, closed.queues, first);+ expect(getRecordNavigation(reopened.stack, reopened.queues)).toBeNull();+ });++ it("does not apply a queue to a different URL stack or record kind", () => {+ const opened = openRecordNavigation([], [], first, [first, second]);+ expect(getRecordNavigation([], opened.queues)).toBeNull();+ expect(getRecordNavigation([company, first], opened.queues)).toBeNull();+ expect(+ getRecordNavigation([{ kind: "contact", id: first.id }], opened.queues),+ ).toBeNull();+ const searched = openRecordNavigation(opened.stack, opened.queues, first);+ expect(getRecordNavigation(searched.stack, searched.queues)).toBeNull();+ });++ it("keeps browser Back outside the queue and restores the same queue on Forward", () => {+ const opened = openRecordNavigation([], [], first, [first, second]);+ const moved = moveRecordNavigation(opened.stack, opened.queues, 1);+ if (!moved) throw new Error("Next record is missing.");+ const history: [RecordRef[], RecordRef[]] = [[], opened.stack];+ if (moved.history === "replace") history[1] = moved.stack;+ expect(history).toEqual([[], [second]]);+ expect(getRecordNavigation(history[0], moved.queues)).toBeNull();+ expect(getRecordNavigation(history[1], moved.queues)).toEqual({+ index: 1,+ total: 2,+ });+ });+});diff --git a/biome.jsonc b/biome.jsoncindex f93ad238..1298c792 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -1,5 +1,5 @@{- "$schema": "https://biomejs.dev/schemas/2.5.6/schema.json",+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json","vcs": {"enabled": true,"clientKind": "git",@@ -67,6 +67,37 @@}},"overrides": [+ {+ "includes": ["packages/ui/src/components/dashboard-chart.tsx"],+ "linter": {+ "rules": {+ "a11y": {+ "useSemanticElements": "off",+ "noNoninteractiveTabindex": "off"+ }+ }+ }+ },+ {+ "includes": ["packages/ui/src/components/data-table.tsx"],+ "linter": {+ "rules": {+ "a11y": {+ "noNoninteractiveTabindex": "off"+ }+ }+ }+ },+ {+ "includes": ["packages/ui/src/styles/reduced-motion.css"],+ "linter": {+ "rules": {+ "complexity": {+ "noImportantStyles": "off"+ }+ }+ }+ },{"includes": ["apps/app/**"],"linter": {diff --git a/bun.lock b/bun.lockindex 81579ea8..0880185a 100644--- a/bun.lock+++ b/bun.lock@@ -54,7 +54,7 @@"@nestjs/swagger": "^11.4.7","@thallesp/nestjs-better-auth": "^2.8.0","@trpc/server": "^11.18.0",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","cache-manager": "^7.2.9","class-transformer": "^0.5.1","class-validator": "^0.15.1",@@ -81,7 +81,6 @@"name": "app","version": "0.1.0","dependencies": {- "@carbon/icons-react": "^11.82.0","@crm/auth": "workspace:*","@crm/db": "workspace:*","@crm/env": "workspace:*",@@ -96,9 +95,10 @@"@trpc/server": "^11.18.0","@trpc/tanstack-react-query": "^11.18.0","api": "workspace:*",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","eve": "^0.69.0","graphql": "^17.0.2",+ "lucide-react": "1.48.0","next": "16.4.2","next-themes": "^0.4.6","nuqs": "^2.8.9",@@ -125,20 +125,20 @@"name": "@crm/auth","version": "0.0.0","dependencies": {- "@better-auth/api-key": "1.6.33",- "@better-auth/sso": "1.6.33",+ "@better-auth/api-key": "1.7.7",+ "@better-auth/sso": "1.7.7","@crm/db": "workspace:*","@crm/env": "workspace:*","@crm/mcp-integrations": "workspace:*","@crm/validation": "workspace:*",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","zod": "^4.4.3",},"devDependencies": {"@crm/typescript-config": "workspace:*","@types/node": "^24.10.1","@types/react": "^19.2.18",- "auth": "1.6.33",+ "auth": "1.7.7","react": "^19.2.8","typescript": "5.9.2",},@@ -213,17 +213,18 @@"name": "@crm/ui","version": "0.0.0","dependencies": {- "@carbon/icons-react": "^11.82.0","@crm/db": "workspace:*","@dnd-kit/core": "^6.3.1","@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@paper-design/shaders-react": "0.0.81","@shadcn/react": "^0.3.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",- "lucide-react": "^1.28.0",+ "echarts": "^6.1.0",+ "lucide-react": "1.48.0","motion": "^12.42.2","next-themes": "^0.4.6","nuqs": "^2.8.9",@@ -274,15 +275,21 @@"sharp",],"overrides": {- "@better-auth/core": "1.6.33",+ "@better-auth/core": "1.7.7",+ "@nestjs/platform-express": {+ "multer": "2.5.0",+ },"@nestjs/swagger": {"js-yaml": "5.4.2",},+ "@vercel/cli-config": {+ "zod": "4.6.7",+ },"auth": {"@mrleebo/prisma-ast": "0.16.0",},"eve": {- "undici": "8.10.2",+ "undici": "8.12.2",},"guarded-fetch": {"undici": "7.30.1",@@ -370,27 +377,27 @@"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],- "@better-auth/api-key": ["@better-auth/[email protected]", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "better-auth": "^1.6.33", "better-call": "1.4.0" } }, "sha512-rShZRCJvas/dgubG7a7wf85F/VQ40u0x7vNSMEdTBArzaquDlyQ656kKS6+lbkqyO3hrI8IaPq251QOzvomh4w=="],+ "@better-auth/api-key": ["@better-auth/[email protected]", "", { "dependencies": { "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "better-auth": "^1.7.7", "better-call": "1.4.0" } }, "sha512-XWtZxF37A7BURHh/GvsYh2Vype1p+R1ZxvQHkRzB4tK3uniZpILe2WRIXfVj3m8NIBHdg8Ez8S8sZJY/ewTu7w=="],- "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-DTadFTdcEad+IAmcJAEVGjD+6wtjt8BkLqmfBdRK+AeYOHaKy/gwtSlmxDuHKfsRaOmn1P8/gtEi/L5wVeEojQ=="],+ "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.41.1", "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-srgFzHEjB2WWlokFz1i4BfG41sNhsA105Pukgqu6RrEh5A+LSkzf1mCHydVipkjt9l5qswtBMi7IL6ouHbZL4Q=="],- "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2" }, "optionalPeers": ["drizzle-orm"] }, "sha512-/BXRx0FoqoWKV3LZLWjnPJHHGvXEZro7goVzzV7K7ZPZG+PbBa+HYN+eJuXSMFb3JCwJEhW+JNLHWekzHQnTLA=="],+ "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-qon0U94PR5FQysuyGoAlGVQpIIiNg5dtDpwjE63sN/HjoRWZadZzHPcS9mn7JsJyQZK6iTNhd7LD0AaXt2f78w=="],- "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-CUYXGxJhx29iilmCr2jdzWBGg/Iq1XjghGlRO15N5SsR+hz8KOGob57UFMVtHEQAhN3tcdgJNllx/ZLmNCyO/A=="],+ "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-9FONOCgOcrQI9wJ5v1oDGIg9sT7pa9RjZZQ4fsCTudo8R87SrIGNUvUxDFTJhZvUblvFfGaIBR9Vb8LA+8bqLQ=="],- "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2" } }, "sha512-vw8uuW+zWUd4TLNnmtlwIiUb4jcj/mAopKWohv7ojDR6Esha7ZkM6EsW8W1PVdRhAfLiHeGqh0RvNtFm5mNDjQ=="],+ "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2" } }, "sha512-FqKFEe+b5tXXV0gRbyirca+qXgMpLOeJ8Wk19yykb/scQKy0WJ4k22WzEV3TTPctQV9DZhwCXPlDtQhnlOv5Gg=="],- "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-JxAENypnmQbYcNboePWafLaP2egLgKQYoKPnZ8dNvaV50/h/dSlBDn1KaUrEMkJWjRXQ2rwgJzUl2yvGxQUZow=="],+ "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],- "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-wloYc35VpI7tjuWgOckB4GVX8y0Ow12ER5CfSqc55K88BefgRtR3brruZ9GhHSll+ZIxjf/0p5IGa+z8rKUR2Q=="],+ "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],- "@better-auth/sso": ["@better-auth/[email protected]", "", { "dependencies": { "fast-xml-parser": "^5.8.0", "jose": "^6.1.3", "samlify": "^2.13.1", "tldts": "^6.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "better-auth": "^1.6.33", "better-call": "1.4.0" } }, "sha512-UaucU9E/DKEmY6MIimCAEyzi3z1Fp8A5nMDsLUHmQ2U1f/00sqtIvmmsUb9i5w2f4V0OdAqeaEtV63Ntc3IjcQ=="],+ "@better-auth/sso": ["@better-auth/[email protected]", "", { "dependencies": { "@xmldom/xmldom": "^0.9.12", "fast-xml-parser": "^5.8.0", "jose": "^6.2.3", "samlify": "^2.13.1", "tldts": "^7.4.3", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "better-auth": "^1.7.7", "better-call": "1.4.0" } }, "sha512-xfKBXUKVPTuxS4dmsTJG04ws1wJQ+fDuGgupmeBfCFoxLF6S7mYoKLh2BZtq/wY0wea4DS5kCyqZU99T6aiQnQ=="],- "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.6.33", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1" } }, "sha512-k8BmE90sWIXlst84zyvCjWoXuftdujCmevlDDI86zXg81Pl+F2AZFPZFXzWkqaNmecnUjbm9bohNGCY6JonWQQ=="],+ "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],"@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="],- "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="],+ "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],"@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.15", "@biomejs/cli-darwin-x64": "2.5.15", "@biomejs/cli-linux-arm64": "2.5.15", "@biomejs/cli-linux-arm64-musl": "2.5.15", "@biomejs/cli-linux-x64": "2.5.15", "@biomejs/cli-linux-x64-musl": "2.5.15", "@biomejs/cli-win32-arm64": "2.5.15", "@biomejs/cli-win32-x64": "2.5.15" }, "bin": { "biome": "bin/biome" } }, "sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ=="],@@ -416,10 +423,6 @@"@cacheable/utils": ["@cacheable/[email protected]", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="],- "@carbon/icon-helpers": ["@carbon/[email protected]", "", { "dependencies": { "@ibm/telemetry-js": "^1.5.0" } }, "sha512-sg5bL9Y/Vns4W7iNRaIMoNc/FtuzJE8G5VvCbC8xcrrNoZmfhhiPFHyU8CFhrf19HJdAxOvXShIBxmm3glLAYw=="],-- "@carbon/icons-react": ["@carbon/[email protected]", "", { "dependencies": { "@carbon/icon-helpers": "^10.79.0", "@ibm/telemetry-js": "^1.5.0", "prop-types": "^15.8.1" }, "peerDependencies": { "react": ">=16" } }, "sha512-+fRNYyqR8aCZRSgMA8sJ+GVfCmS0pK8FaDl9rQDuy4ZqYldZ4Yj8K3YIxmcSLlvTxMmNtGAxoa80xlhXROYDQg=="],-"@chevrotain/cst-dts-gen": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/gast": "12.0.0", "@chevrotain/types": "12.0.0" } }, "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg=="],"@chevrotain/gast": ["@chevrotain/[email protected]", "", { "dependencies": { "@chevrotain/types": "12.0.0" } }, "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ=="],@@ -486,8 +489,6 @@"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg=="],- "@ibm/telemetry-js": ["@ibm/[email protected]", "", { "bin": { "ibmtelemetry": "dist/collect.js" } }, "sha512-RO/9j+URJnSfseWg9ZkEX9p+a3Ousd33DBU7rOafoZB08RqdzxFVYJ2/iM50dkBuD0o7WX7GYt1sLbNgCoE+pA=="],-"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],"@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="],@@ -778,6 +779,10 @@"@oxlint/plugins": ["@oxlint/[email protected]", "", {}, "sha512-TJBBNl4KIxbxrSk7gsqlz6iM1kxidfyTizEzfWqXvijF2Ou8/Da58GvjemBVmCmaUamwRij+JwsVc0kpBFuqfg=="],+ "@paper-design/shaders": ["@paper-design/[email protected]", "", {}, "sha512-jeGdyjMscZ2bxmQdo8lhwUufHUf4iq3s1ayjh8PXU7Go42Rw8E3I0It1FZdc3HuWt5J82m//DRWaxsRqRfA4Gg=="],++ "@paper-design/shaders-react": ["@paper-design/[email protected]", "", { "dependencies": { "@paper-design/shaders": "0.0.81" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-3FMkeZqj9sSvK/WkgekGu3crnOQd4R2iH8IT+jVBuQmq1m8p88VFvxh63s9bSt2exBwjBNaRfSo0FSCeNxqh3w=="],+"@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="],"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theme": "2.0.0", "@pierre/theming": "1.0.1", "@shikijs/transformers": "^3.0.0 || ^4.0.0", "diff": "9.0.0", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0 || ^4.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-6Dt48jQIL+H54QyNB943Oqn5p4uRw7NpiXLSEapnaYgYvTmSHNPAUCDfg6AcRC+W02z0IYJnJJvcs3lsNp7gCw=="],@@ -1248,7 +1253,7 @@"@xmldom/is-dom-node": ["@xmldom/[email protected]", "", {}, "sha512-CJDxIgE5I0FH+ttq/Fxy6nRpxP70+e2O048EPe85J2use3XKdatVM7dDVvFNjQudd9B49NPoZ+8PG49zj4Er8Q=="],- "@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],+ "@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A=="],"@yuku-core/binding-android-arm64": ["@yuku-core/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw=="],@@ -1314,7 +1319,7 @@"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],- "auth": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.29.7", "@babel/preset-react": "^7.28.5", "@babel/preset-typescript": "^7.28.5", "@better-auth/core": "1.6.33", "@better-auth/telemetry": "1.6.33", "@better-auth/utils": "0.4.2", "@clack/prompts": "^1.6.0", "@mrleebo/prisma-ast": "^0.13.1", "better-auth": "1.6.33", "c12": "^3.3.3", "chalk": "^5.6.2", "commander": "^12.1.0", "dotenv": "^17.3.1", "get-tsconfig": "^4.13.6", "open": "^10.2.0", "prettier": "^3.8.1", "prompts": "^2.4.2", "semver": "^7.7.4", "yocto-spinner": "^0.2.3", "zod": "^4.3.6" }, "bin": { "auth": "./dist/index.mjs", "better-auth": "./dist/index.mjs" } }, "sha512-eM3vAovK2VvD8alYa5wCpLLjBrbfUEQnRjh9TcVAKeK8FNhvqJ04gDOkVrGSuIfMzK7XBoKfQDYT/x9jRWKTrg=="],+ "auth": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.29.7", "@babel/preset-react": "^7.28.5", "@babel/preset-typescript": "^7.28.5", "@better-auth/core": "1.7.7", "@better-auth/telemetry": "1.7.7", "@better-auth/utils": "0.4.2", "@clack/prompts": "^1.6.0", "@mrleebo/prisma-ast": "^0.16.0", "better-auth": "1.7.7", "c12": "^4.0.0-beta.5", "chalk": "^5.6.2", "commander": "^15.0.0", "dotenv": "^17.3.1", "get-tsconfig": "^4.14.0", "jiti": "^2.7.0", "open": "^11.0.0", "prettier": "^3.8.1", "prompts": "^2.4.2", "semver": "^7.8.4", "yocto-spinner": "^1.2.0", "zod": "^4.5.4" }, "bin": { "auth": "./dist/index.mjs", "better-auth": "./dist/index.mjs" } }, "sha512-Iuka9UTqPUI4qQORHjZ0U4D/ceH3q11e1iGU+j2N/Flfy2jQK/vGACzrBBXDArE7kFAn468g/P8+aAOonU8s0A=="],"aws-ssl-profiles": ["[email protected]", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="],@@ -1322,13 +1327,13 @@"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-zAgkquC2WYF0PIc6XbNYkA2uuxxFavzgmX61R+dHDUa558V8Ejf8ozTZFR6QzM24RWu4kBcRkhJ5kpz77j9fnQ=="],- "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.6.33", "@better-auth/drizzle-adapter": "1.6.33", "@better-auth/kysely-adapter": "1.6.33", "@better-auth/memory-adapter": "1.6.33", "@better-auth/mongo-adapter": "1.6.33", "@better-auth/prisma-adapter": "1.6.33", "@better-auth/telemetry": "1.6.33", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-QkVKOmJw/LQ3HjIib2wx2Td0xB9EuPgw0ARYPKeFu3niN0VSBW32j4QwfewFZOQi5Hb/jOB6U+wdvtBhF7+URw=="],+ "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.7.7", "@better-auth/drizzle-adapter": "1.7.7", "@better-auth/kysely-adapter": "1.7.7", "@better-auth/memory-adapter": "1.7.7", "@better-auth/mongo-adapter": "1.7.7", "@better-auth/prisma-adapter": "1.7.7", "@better-auth/telemetry": "1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-Zhgxi/c5ylmfB/sX+nwnBbsFf/j6k0L8DvL6CJXZSrXgxc5pPMC/e7j812zNd4L4B4ELmdURCPw3X8nAOUdcjw=="],"better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="],"better-result": ["[email protected]", "", {}, "sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw=="],- "body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="],+ "body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="],"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.10.44", "caniuse-lite": "^1.0.30001806", "electron-to-chromium": "^1.5.393", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw=="],@@ -1342,7 +1347,7 @@"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],- "c12": ["[email protected]", "", { "dependencies": { "chokidar": "^5.0.0", "confbox": "^0.2.4", "defu": "^6.1.6", "dotenv": "^17.3.1", "exsolve": "^1.0.8", "giget": "^3.2.0", "jiti": "^2.6.1", "ohash": "^2.0.11", "pathe": "^2.0.3", "perfect-debounce": "^2.1.0", "pkg-types": "^2.3.0", "rc9": "^3.0.1" }, "peerDependencies": { "magicast": "*" }, "optionalPeers": ["magicast"] }, "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA=="],+ "c12": ["[email protected]", "", { "dependencies": { "confbox": "^0.3.1", "defu": "^6.1.7", "exsolve": "^1.1.3", "pathe": "^2.0.3", "pkg-types": "^2.4.0", "rc9": "^3.1.0" }, "peerDependencies": { "dotenv": "*", "giget": ">=3.3.1", "jiti": "*", "magicast": "*" }, "optionalPeers": ["dotenv", "giget", "jiti", "magicast"] }, "sha512-SdcZfDXUc7ownRiqbEf5yjaVlbWN9GuWS6SSPlKJ1cFOQYMrb1ouU8YWxZoPfXZbF/tw+f4HjjJS0tlXQJfkEg=="],"cache-manager": ["[email protected]", "", { "dependencies": { "@cacheable/utils": "^2.5.0", "keyv": "^5.6.0" } }, "sha512-d4vceEyYe95gPxEyQchlEOH9vJlkNRW8G6gzFzzMTxJK9PahYMhC9chrEqgZN0HulROjgw3IzmWVNk7Q7ytiGw=="],@@ -1394,13 +1399,13 @@"comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],- "commander": ["[email protected]", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],+ "commander": ["[email protected]", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="],"component-emitter": ["[email protected]", "", {}, "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ=="],"concurrently": ["[email protected]", "", { "dependencies": { "chalk": "5.6.2", "rxjs": "7.8.2", "shell-quote": "1.12.0", "supports-color": "10.2.2", "tree-kill": "1.2.2", "yargs": "18.0.0" }, "bin": { "conc": "dist/bin/index.js", "concurrently": "dist/bin/index.js" } }, "sha512-qgICXXFp2/3nAebRLmxcINKEXM1mLK3ij/y31P02VTs/KIkddIeC05n73DxOXsXMB9LFSqNU1/na3lDlOhcbIw=="],- "confbox": ["[email protected]", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],+ "confbox": ["[email protected]", "", {}, "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA=="],"consola": ["[email protected]", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],@@ -1506,6 +1511,8 @@"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],+ "echarts": ["[email protected]", "", { "dependencies": { "tslib": "2.3.0", "zrender": "6.1.0" } }, "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA=="],+"ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw=="],@@ -1568,7 +1575,7 @@"express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA=="],- "exsolve": ["[email protected]", "", {}, "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g=="],+ "exsolve": ["[email protected]", "", {}, "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg=="],"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],@@ -1586,7 +1593,7 @@"fast-string-width": ["[email protected]", "", { "dependencies": { "fast-string-truncated-width": "^3.0.2" } }, "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg=="],- "fast-uri": ["[email protected]", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],+ "fast-uri": ["[email protected]", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="],"fast-wrap-ansi": ["[email protected]", "", { "dependencies": { "fast-string-width": "^3.0.2" } }, "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q=="],@@ -1738,6 +1745,8 @@"is-hexadecimal": ["[email protected]", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],+ "is-in-ssh": ["[email protected]", "", {}, "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw=="],+"is-inside-container": ["[email protected]", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="],"is-node-process": ["[email protected]", "", {}, "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw=="],@@ -1820,15 +1829,13 @@"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],- "loose-envify": ["[email protected]", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],-"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],"lru.min": ["[email protected]", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],- "lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-fARAFJULsGuDDydjp6+6blekG/sBIM29TerzLjc9bQUKAcEfrSc4ZQKb25KRz4OMKd87cZTb5dgq0w/T6KufVg=="],+ "lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-R0CIKY/fXiC6y9xRBADgsK+VW2p/pcTJOMhLZf1T+uG+vJUvyUR02nGOgmIIC7MPkiNK4Ox8QDnbqF8rJYWPZQ=="],"lz-string": ["[email protected]", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],@@ -1954,7 +1961,7 @@"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],- "multer": ["[email protected]", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "type-is": "^1.6.18" } }, "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg=="],+ "multer": ["[email protected]", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "type-is": "^1.6.18" } }, "sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw=="],"mysql2": ["[email protected]", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "generate-function": "^2.3.1", "iconv-lite": "^0.7.3", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.5.1" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-A2olluVlj0mvgyIRRISMEzXc51m+21mRtcMVjJyIpt2GG98+XrC9m9HzsqcMsX2LcnfccJvY5NB22g8fENBnOA=="],@@ -2006,7 +2013,7 @@"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="],- "open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],+ "open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.5.1", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.2.1", "wsl-utils": "^1.0.0" } }, "sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg=="],"openapi3-ts": ["[email protected]", "", { "dependencies": { "yaml": "^2.5.0" } }, "sha512-9asTNB9IkKEzWMcHmVZE7Ts3kC9G7AFHfs8i7caD8HbI76gEjdkId4z/AkP83xdZsH7PLAnnbl47qZkXuxpArw=="],@@ -2062,7 +2069,7 @@"pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],- "pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],+ "pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.3.1", "exsolve": "^1.1.3", "pathe": "^2.0.3" } }, "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA=="],"pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],@@ -2082,6 +2089,8 @@"posthog-node": ["[email protected]", "", { "dependencies": { "@posthog/core": "^1.46.8" }, "peerDependencies": { "rxjs": "^7.0.0" }, "optionalPeers": ["rxjs"] }, "sha512-YIH82XV24aa1nnVph1ndiW/vBN2QDIKlrHNEJcmAYutMGeoGC4WeEefg7O5aD3dDcO5dzociy8sVwXq4tNDYsQ=="],+ "powershell-utils": ["[email protected]", "", {}, "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A=="],+"preact": ["[email protected]", "", {}, "sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg=="],"preact-render-to-string": ["[email protected]", "", { "peerDependencies": { "preact": ">=10 || >= 11.0.0-0" } }, "sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA=="],@@ -2094,8 +2103,6 @@"prompts": ["[email protected]", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],- "prop-types": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],-"proper-lockfile": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="],"property-information": ["[email protected]", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="],@@ -2104,7 +2111,7 @@"pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],- "qs": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="],+ "qs": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg=="],"query-selector-shadow-dom": ["[email protected]", "", {}, "sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw=="],@@ -2116,7 +2123,7 @@"raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],- "rc9": ["[email protected]", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],+ "rc9": ["[email protected]", "", { "dependencies": { "defu": "^6.1.7", "destr": "^2.0.5" } }, "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q=="],"react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],@@ -2306,9 +2313,9 @@"tinyrainbow": ["[email protected]", "", {}, "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A=="],- "tldts": ["[email protected]", "", { "dependencies": { "tldts-core": "^6.1.86" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ=="],+ "tldts": ["[email protected]", "", { "dependencies": { "tldts-core": "^7.4.19" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q=="],- "tldts-core": ["[email protected]", "", {}, "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA=="],+ "tldts-core": ["[email protected]", "", {}, "sha512-goNXV6Ho9TIOfpJZanTd6CKG5DyYgYAL+k+22T0SLh8l6+KHIfBUPFuePuSZv05UttIaaLmI9tb7TmGIdK5AkQ=="],"toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],@@ -2344,7 +2351,7 @@"uncrypto": ["[email protected]", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="],- "undici": ["[email protected]", "", {}, "sha512-zWpdTVD54H48CIybL0rWQ3ukpb9d23wM7eH5RtfdmeP70cWHNjtfo7P4vZX+5CoDcO53J4Pu5uXp7lNfjc6DRA=="],+ "undici": ["[email protected]", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="],"undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],@@ -2416,7 +2423,7 @@"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="],- "wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],+ "wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.2.0" } }, "sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ=="],"xdg-app-paths": ["[email protected]", "", { "dependencies": { "os-paths": "^4.0.1", "xdg-portable": "^7.2.0" } }, "sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ=="],@@ -2444,7 +2451,7 @@"yargs-parser": ["[email protected]", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="],- "yocto-spinner": ["[email protected]", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-sqBChb33loEnkoXte1bLg45bEBsOP9N1kzQh5JZNKj/0rik4zAPTNSAVPj3uQAdc6slYJ0Ksc403G2XgxsJQFQ=="],+ "yocto-spinner": ["[email protected]", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="],"yoctocolors": ["[email protected]", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="],@@ -2460,11 +2467,15 @@"zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],+ "zrender": ["[email protected]", "", { "dependencies": { "tslib": "2.3.0" } }, "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ=="],+"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],"@ai-sdk/gateway/@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],- "@ai-sdk/provider-utils/undici": ["[email protected]", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],+ "@ai-sdk/provider-utils/undici": ["[email protected]", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="],++ "@authenio/xml-encryption/@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],"@authenio/xml-encryption/xpath": ["[email protected]", "", {}, "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw=="],@@ -2494,6 +2505,8 @@"@posthog/core/@posthog/types": ["@posthog/[email protected]", "", {}, "sha512-4PZ9wMYI8m8AqJuZ9YR1IAHGVtSnYbBVBgTevrKpzZbcSe/OUwhEV2Ks//rJh/L8eMTU8R5DrD4D/hlrOwaAiQ=="],+ "@prisma/config/c12": ["[email protected]", "", { "dependencies": { "chokidar": "^5.0.0", "confbox": "^0.2.4", "defu": "^6.1.6", "dotenv": "^17.3.1", "exsolve": "^1.0.8", "giget": "^3.2.0", "jiti": "^2.6.1", "ohash": "^2.0.11", "pathe": "^2.0.3", "perfect-debounce": "^2.1.0", "pkg-types": "^2.3.0", "rc9": "^3.0.1" }, "peerDependencies": { "magicast": "*" }, "optionalPeers": ["magicast"] }, "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA=="],+"@prisma/dev/std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],"@prisma/engines/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.10.1" } }, "sha512-iVnghHne5vcaobBjPVCMEjh5r/1UCj394EIGTUclasFRatpR/MQwcM2veLv5kgoFSyYP54nch/lNFCQRYcDxvg=="],@@ -2660,8 +2673,6 @@"@tailwindcss/postcss/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw=="],- "@vercel/cli-config/zod": ["[email protected]", "", {}, "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg=="],-"@vercel/oidc/jose": ["[email protected]", "", {}, "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg=="],"@visx/vendor/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ=="],@@ -2678,13 +2689,9 @@"app/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],- "auth/get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-Dz/6HxkrxgNehhxLVeyv8sad9UzF2xBVeaKBQNDfJ5XiSXmp2gTR0eO0RWiT2NCKS5aGP9jjkOMggTN90qU50A=="],-"better-call/@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],- "better-call/@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],-- "body-parser/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],+ "body-parser/content-type": ["[email protected]", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],"co-body/raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="],@@ -2692,7 +2699,11 @@"dotenv-expand/dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],- "eve/undici": ["[email protected]", "", {}, "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ=="],+ "echarts/tslib": ["[email protected]", "", {}, "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg=="],++ "env-runner/exsolve": ["[email protected]", "", {}, "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g=="],++ "eve/undici": ["[email protected]", "", {}, "sha512-XtuDWVdqTLr3NAxm2ly9/hU6kUsJOgGh1RASzMBbsw6aWCOaQzHdW+QQDfdERjfJ2V5vL5pRPa4RetO9UfivDg=="],"execa/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],@@ -2720,8 +2731,6 @@"pretty-format/react-is": ["[email protected]", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],- "prop-types/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],-"proper-lockfile/retry": ["[email protected]", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="],"proper-lockfile/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],@@ -2730,6 +2739,8 @@"radix-ui/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],+ "samlify/@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],+"strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],"tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],@@ -2744,8 +2755,20 @@"wrap-ansi/ansi-styles": ["[email protected]", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],+ "xml-crypto/@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],+"xml-crypto/xpath": ["[email protected]", "", {}, "sha512-NNXnzrkDrAzalLhIUc01jO2mOzXGXh1JwPgkihcLLzw98c0WgYDmmjSh1Kl3wzaxSVWMuA+fe0WTWOBDWCBmNA=="],+ "zrender/tslib": ["[email protected]", "", {}, "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg=="],++ "@prisma/config/c12/confbox": ["[email protected]", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],++ "@prisma/config/c12/exsolve": ["[email protected]", "", {}, "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g=="],++ "@prisma/config/c12/pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],++ "@prisma/config/c12/rc9": ["[email protected]", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],+"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/primitive": ["@radix-ui/[email protected]", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],diff --git a/docs/agent-panel.md b/docs/agent-panel.mdindex 91c2bbc9..42aa4312 100644--- a/docs/agent-panel.md+++ b/docs/agent-panel.md@@ -44,8 +44,9 @@ claim minted, the field a conversation is filed under, the empty-thread question- **Nothing mounts until the list has loaded**, or a new session starts and remounts.- **The landed thread is captured once** (`resolveThread`), or the first save swaps theopen conversation out from under a live answer. It lives in `?thread=`.-- **`keepMounted` on the tab descriptor** (`detail-sheet.tsx`) — Radix drops an inactive- tab, aborting the stream mid-answer.+- **Set `keepMounted` on the Agent tab descriptor.**+ `packages/ui/src/components/record-sheet.tsx` keeps opened tabs mounted.+ Radix otherwise removes inactive tabs and aborts the stream.- **`autoScroll` and nothing else**; `scrollAnchor` stops it following the bottom.- **One `MessageScrollerItem` per message, not per part**; ids prefer `toolCallId`.- **Scoped to the rep** — a session id in a body decides which row, never whose.diff --git a/docs/connections.md b/docs/connections.mdindex ece46fec..59196bcb 100644--- a/docs/connections.md+++ b/docs/connections.md@@ -45,18 +45,21 @@ undo it.Connecting is the same decision as disconnecting, because `replaceSlackConnection`deletes every other Slack account row: a second person connecting *replaces* theworkspace's Slack, and every deployed agent then reads from and posts to whichever-Slack they installed. Hiding the button is not enough — `authClient.oauth2.link`+Slack they installed. Hiding the button is not enough — `authClient.linkSocial`is one POST.`slackConnectGuard` (`packages/auth/src/slack-connect.ts`) is Better Auth's`hooks.before`, and it asks the same `canManageConnections` the API does. It-covers all three doors: `/oauth2/link`, `/sign-in/oauth2` (Slack is a connection,+covers all three doors: `/link-social`, `/sign-in/social` (Slack is a connection,never a sign-in method, and that endpoint needs no session) and-`/oauth2/callback/slack`. The callback is the one that matters — refusing there+`/callback/slack`. The callback is the one that matters — refusing therehappens **before the code is exchanged**, so a refused attempt writes no`SlackWorkspaceGrant` user token and deletes no bot token. Google and Microsoftsign in on different paths and never reach the guard.+`slackOAuthCallback` redirects the registered `/oauth2/callback/slack` URL to the guarded callback.+It preserves the code and state query parameters. Existing Slack app registrations keep their redirect URL.+A workspace with no owner and no admin lets any member connect. There is nobodyleft to ask, and a fresh install must not be locked out of its first connection.@@ -186,40 +189,31 @@ needs its guardrails legible to whoever turns it on.## Layout-Page metrics are tokens. Never a literal.+Every connection page renders through `ConnectionPage`, which is `PageShell`+with `width="narrow"`. The shell owns the gutters, the top and bottom padding+and the column width, so connection pages line up with every other settings+page. Do not add a page wrapper of your own.++Metrics inside the column are tokens. Never a literal.| Token | Value | Use || --- | --- | --- |-| `--spacing-page-top` | 40px | Top bar to first line of content |-| `--spacing-page-bottom` | 40px | Below the last block |-| `--spacing-page-inline` | 24px | Viewport gutters |-| `--spacing-page-gap` | 24px | Between top-level blocks |-| `--spacing-block-inline` | 20px | Inset on every block, **including the page title** |-| `--container-page` | 820px | Content column |+| `--spacing-page-gap` | 24px | Gap within flat sections |+| `--spacing-block-inline` | 20px | Inset within legacy content blocks || `--container-page-wide` | 1120px | Two-column or table pages || `--container-narrow` | 560px | Empty states, dialogs || `--container-sheet` | 640px | Edit sheet over a page || `--height-tool-panel` | 400–640px | Scrollable tool inventories |-`--spacing-block-inline` is the one doing real work: a card sits flush at the-column edge and carries 20px of its own padding, so card text lands in the same-lane as the title on a flat page. The two page types stay aligned without-matching each other's chrome.--Short single-decision pages (empty state, pre-connect, match people) centre-vertically. List pages top-align so nothing jumps when a row is added.--## Cards versus flat--Cards are for **discrete, independently-actionable objects** — an agent you can-pause on its own, a connection row with its own Manage button, a choice in a-picker, a Questionnaire.--Flat sections separated by a 1px `--color-dark-border` rule are for **a page-describing one thing** — the pre-connect page.+Page headers and section headers align with the column edge.+Shared `SettingsCard` components own their content padding and footer spacing.+Shared component sizes take precedence over the legacy content tokens above.+Use `SettingsColumn` between settings cards and `PageSection` for flat tool inventories.+Do not add an inset to page headers to match card content.-The split is by what the block *is*, not by page. Do not card a section; do not-flatten a list of separately-actionable objects.+Connection status, synchronization choices, revocation, and deletion use separate settings cards.+Tool access, permissions, and agent usage use flat page sections.+Connection pickers retain cards for independent connection choices.## Brand marksdiff --git a/docs/design.md b/docs/design.mdindex 43f71d0c..2426d6d4 100644--- a/docs/design.md+++ b/docs/design.md@@ -1,31 +1,91 @@# Design — Rules for AI Agents-- /packages/ui is the single source of truth for all UI.-- Always use shared shadcn components from /packages/ui.-- Do not override component styles with className.-- Do not introduce custom border radii, spacing, colours, shadows, or other visual deviations.-- Corners are rounded, from the scale only: `rounded-sm` (4px) for the smallest- controls, `rounded-md` (5px) for buttons, inputs and segments, `rounded-lg`- (8px) for surfaces that contain controls — popovers, dialogs, menus, table- shells. Never a literal radius at the call site.-- `rounded-none` is still correct in one case: an element that must join its- neighbour edge to edge. The input inside an input group, the middle cells of- a selected date range, and the drawer handle are the existing examples.-- If a component needs a new variant or style, implement it in /packages/ui so the entire application stays consistent.+The design source is Comp Neo (`comp-neo/packages/ui`): its tokens, density,+geometry and motion, ported onto CRM's Radix components. Match Neo when a rule+here is silent.++## Ownership++- `/packages/ui` is the single source of truth for all UI. Use its shared+ components; a new variant or style is implemented there, never at the call+ site.+- Use semantic tokens and the scale only: no literal colours, radii, spacing or+ shadows at the call site, and no `className` that restyles a shared component.+- Port Neo by class string onto the existing Radix API. Neo runs on Base UI;+ CRM stays on Radix. Radix state reaches Tailwind through the `data-open`,+ `data-checked`, `data-active` and related variants in `globals.css`, which+ match `data-state`.## Colour-Flat white, neutral greys, and one brand green (`#006B4F`). The greys are-untinted on purpose: there is no scene to tint them toward, and a tinted grey-without a reason reads as indecision.+Neutral greys, alpha edges, and one emerald accent.++- `primary` is monochrome: near-black in light, near-white in dark. It is the+ one filled action. `destructive-solid` fills the one action you cannot undo.+ Everything else is outline, ghost or secondary.+- `brand` (emerald) is the accent, never a fill for buttons: focus ring, caret,+ selection, switches, progress, success.+- Edges are translucent (`border`, `input`) so they read on any surface. A+ surface draws its edge with `shadow-border`, a menu with `shadow-menu`, a+ dialog with `shadow-modal`, focus with `shadow-focus`.+- Status: `status-info`, `status-warning`, `status-success`, `status-danger`.+ Words in a status colour use the `-text` token. `success`, `warning` and+ `info` are aliases of these; `severity-*`, `code-*` and `tag` stay CRM+ tokens.++## Density and geometry++- Controls are 36px (`h-9`) with 14px text; `sm` is 32px. Secondary lines,+ hints, table headers and meta are `text-13`.+- Radii from the scale only: `rounded-sm` 4px, `rounded-md` 6px for controls,+ `rounded-lg` 8px, `rounded-xl` 12px for menus and dialogs. `rounded-none`+ only joins an element to its neighbour edge to edge.++## Charts++Charts use EvilCharts' Apache ECharts provider from `packages/ui/src/components/evilcharts`.+Shared dashboard chart wrappers own presentation and formatting.+Keep server amounts in reporting-currency cents and preserve missing-data states.+Use theme-aware colors and the same mapping across charts, legends, and tooltips.+Canvas is the default renderer. SVG is an explicit chart option.+Canvas charts expose their values through accessible summaries.+Respect reduced motion and dynamic resizing.++Dashboard chart groups keep a keyboard tab stop for reading values and activating chart items.+They use `role="group"` because a form fieldset does not describe these chart controls.+The scoped Biome override permits these group roles and tab stops only in `dashboard-chart.tsx`.+It keeps every other accessibility rule enabled.++## Motion++- Surfaces open on `ease-spring` and close faster on `ease-out`: menus and+ dialogs 200ms in, 100ms out; sheets 300ms in, 150ms out. Switch thumbs use+ `ease-spring-bouncy`.+- Motion lives in `packages/ui`. Apps never pick durations or easings.+- Reduced motion: everything still changes state, nothing travels. The base+ layer cuts every animation and transition to 1ms and one iteration; JS+ motion reads `useReducedMotion`.++`reduced-motion.css` owns the global accessibility overrides.+Its `!important` declarations beat component utilities, so only this stylesheet permits them in lint.++Sheets use interruptible translate and opacity transitions in `sheet.css`.+Nonvisual presence animations keep Radix mounted through exit.+Preserve both parts: Radix watches animation events to remove the sheet.++## Layout++Separate items with layout, never with glyphs. Inline metadata (a date, an+owner, a count) goes in `MetaRow` from `@crm/ui/components/meta-row`: each+child is its own item and the row wraps. A string that cannot hold layout, such+as a `title` attribute or an option label, joins with a comma.++DataTable keeps its named scroll region in the tab order, including during loading.+Its lint override permits this tab stop for keyboard scrolling.-**Only two things are filled**: `primary` for the action you want, `destructive`-for the one you cannot undo. Everything else — secondary, outline, ghost — is a-white chip in light and a dark chip in dark. That is what keeps a rep's eye-landing on *go* or *stop* and skimming past the rest.+## Auth exception-`--primary` and `--destructive` hold the **same value in both themes**. A brand-colour that changes per theme is not one colour, it is two, and both then need-maintaining. The single exception is `--ring`, which lightens in dark: a fill-carries the brand, but a ring only has to be seen, and `#006B4F` is too close to-the dark background to register.\ No newline at end of file+`AuthShell` (sign-in, grant access, onboarding) keeps the pre-Neo look exactly.+It carries `dark theme-classic`, which restores the classic dark tokens and the+5px radius. It uses `AuthButton`, `AuthInput`, the `AuthField` and `AuthInputGroup`+parts, and `LogoSpinner`. Keep these frozen components inside `AuthShell`.diff --git a/docs/setup.md b/docs/setup.mdindex 03b8912f..c292752b 100644--- a/docs/setup.md+++ b/docs/setup.md@@ -175,3 +175,17 @@ A rebuild drops the database and re-runs every migration, and it says which of ttwo reasons fired. Force one with `bun run db:test --reset`. Nothing else in therepo may drop a database, and this may only because the `_test` suffix is checkedfirst.+++## Better Auth 1.7 upgrade++CRM uses Better Auth 1.7.7 and matching plugins.+The account schema stays the same as 1.6.+The existing Slack redirect URL stays valid through `slackOAuthCallback`.++Microsoft accounts need an identity check before deployment.+Version 1.7 uses the verified Microsoft `oid` instead of the previous `sub` account identifier.+Existing Microsoft accounts need a verified mapping from the identity provider before sign-in resumes.+Follow the [Microsoft account migration guide](https://better-auth.com/docs/guides/1-7-upgrade-guide#migrate-microsoft-account-identifiers).+Do not decode stored tokens without signature verification or infer identifiers from email addresses.+Google account identifiers stay the same.diff --git a/package.json b/package.jsonindex 08cc3c97..3e2eb7d2 100644--- a/package.json+++ b/package.json@@ -43,11 +43,13 @@}},"overrides": {- "@better-auth/core": "1.6.33",+ "@better-auth/core": "1.7.7","@nestjs/swagger>js-yaml": "5.4.2","auth>@mrleebo/prisma-ast": "0.16.0",- "eve>undici": "8.10.2",- "guarded-fetch>undici": "7.30.1"+ "eve>undici": "8.12.2",+ "guarded-fetch>undici": "7.30.1",+ "@nestjs/platform-express>multer": "2.5.0",+ "@vercel/cli-config>zod": "4.6.7"},"catalog": {"vite-plus": "1.3.0"diff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 8b37dc0d..00149ad7 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -29,13 +29,13 @@"clean": "rm -rf .turbo node_modules"},"dependencies": {- "@better-auth/api-key": "1.6.33",- "@better-auth/sso": "1.6.33",+ "@better-auth/api-key": "1.7.7",+ "@better-auth/sso": "1.7.7","@crm/db": "workspace:*","@crm/env": "workspace:*","@crm/mcp-integrations": "workspace:*","@crm/validation": "workspace:*",- "better-auth": "1.6.33",+ "better-auth": "1.7.7","zod": "^4.4.3"},"peerDependencies": {@@ -47,7 +47,7 @@}},"devDependencies": {- "auth": "1.6.33",+ "auth": "1.7.7","@crm/typescript-config": "workspace:*","@types/node": "^24.10.1","@types/react": "^19.2.18",diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.tsindex cb49764f..3d75124b 100644--- a/packages/auth/src/auth.ts+++ b/packages/auth/src/auth.ts@@ -21,6 +21,7 @@ import {import { notifySignedIn } from "./signed-in";import { slackConnectGuard } from "./slack-connect";import { rememberSlackInstall, replaceSlackConnection } from "./slack-grant";+import { slackOAuthCallback } from "./slack-oauth-callback";import { SLACK_REQUESTED_SCOPES, SLACK_USER_SCOPES } from "./slack-scopes";import { queueSlackInventorySync } from "./slack-sync";import {@@ -209,6 +210,7 @@ export const auth = betterAuth({},],}),+ slackOAuthCallback,]: []),organization({diff --git a/packages/auth/src/client.ts b/packages/auth/src/client.tsindex 980a37b6..3a02fc8a 100644--- a/packages/auth/src/client.ts+++ b/packages/auth/src/client.ts@@ -1,11 +1,10 @@import { apiKeyClient } from "@better-auth/api-key/client";import { ssoClient } from "@better-auth/sso/client";-import { genericOAuthClient } from "better-auth/client/plugins";import { createAuthClient } from "better-auth/react";export const authClient = createAuthClient({baseURL: globalThis.window?.location.origin,- plugins: [ssoClient(), genericOAuthClient(), apiKeyClient()],+ plugins: [ssoClient(), apiKeyClient()],});export const { getSession, signIn, signOut, useSession } = authClient;diff --git a/packages/auth/src/slack-connect.ts b/packages/auth/src/slack-connect.tsindex 1632c335..24070e01 100644--- a/packages/auth/src/slack-connect.ts+++ b/packages/auth/src/slack-connect.ts@@ -18,11 +18,11 @@ const CONNECT_MANAGER_ROLES = WORKSPACE_ROLES.filter((role) =>canManageConnections(role),);-const SLACK_CONNECT_START_PATHS = ["/oauth2/link", "/sign-in/oauth2"];-const OAUTH_CALLBACK_PATH = "/oauth2/callback";+const SLACK_CONNECT_START_PATHS = ["/link-social", "/sign-in/social"];+const OAUTH_CALLBACK_PATH = "/callback";-const connectStartBody = z.object({ providerId: z.string() });-const callbackParams = z.object({ providerId: z.string() });+const connectStartBody = z.object({ provider: z.string() });+const callbackParams = z.object({ id: z.string() });export const slackConnectGuard = createAuthMiddleware(async (ctx) => {const guarded =@@ -68,7 +68,7 @@ function startsSlackConnect(): boolean {if (!SLACK_CONNECT_START_PATHS.includes(path)) return false;const parsed = connectStartBody.safeParse(body);- return parsed.success && parsed.data.providerId === SLACK_PROVIDER_ID;+ return parsed.success && parsed.data.provider === SLACK_PROVIDER_ID;}function completesSlackConnect(@@ -77,5 +77,5 @@ function completesSlackConnect(): boolean {if (!path.startsWith(OAUTH_CALLBACK_PATH)) return false;const parsed = callbackParams.safeParse(params);- return parsed.success && parsed.data.providerId === SLACK_PROVIDER_ID;+ return parsed.success && parsed.data.id === SLACK_PROVIDER_ID;}diff --git a/packages/auth/src/slack-oauth-callback.ts b/packages/auth/src/slack-oauth-callback.tsnew file mode 100644index 00000000..27e404a5--- /dev/null+++ b/packages/auth/src/slack-oauth-callback.ts@@ -0,0 +1,17 @@+import type { BetterAuthPlugin } from "better-auth";+import { createAuthEndpoint } from "better-auth/api";++export const slackOAuthCallback = {+ id: "slack-oauth-callback",+ endpoints: {+ legacySlackCallback: createAuthEndpoint(+ "/oauth2/callback/slack",+ { method: "GET", requireRequest: true },+ async (ctx) => {+ const target = new URL(`${ctx.context.baseURL}/callback/slack`);+ target.search = new URL(ctx.request.url).search;+ throw ctx.redirect(target.toString());+ },+ ),+ },+} satisfies BetterAuthPlugin;diff --git a/packages/auth/test/slack-connect.integration.spec.ts b/packages/auth/test/slack-connect.integration.spec.tsindex c5b7e920..d8d5ebcb 100644--- a/packages/auth/test/slack-connect.integration.spec.ts+++ b/packages/auth/test/slack-connect.integration.spec.ts@@ -8,11 +8,15 @@ import {} from "bun:test";import { db } from "@crm/db";import { workspaceSlug } from "@crm/db/workspace";-import { type BetterAuthPlugin, betterAuth } from "better-auth";+import { betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";-import { createAuthEndpoint, createAuthMiddleware } from "better-auth/api";+import {+ callbackOAuth,+ createAuthMiddleware,+ linkSocialAccount,+ signInSocial,+} from "better-auth/api";import { applySetCookies } from "better-auth/cookies";-import { genericOAuth } from "better-auth/plugins/generic-oauth";import * as z from "zod";import {DEFAULT_WORKSPACE_NAME,@@ -21,6 +25,7 @@ import {} from "../src/organization";import { GOOGLE_PROVIDER_ID, SLACK_PROVIDER_ID } from "../src/scopes";import { slackConnectGuard } from "../src/slack-connect";+import { slackOAuthCallback } from "../src/slack-oauth-callback";const suffix = process.env.TEST_RUN_ID ?? "slack-connect-spec";@@ -31,32 +36,24 @@ const JSON_HEADERS = { "content-type": "application/json" };const reached = { reached: true };-const probe = {- id: "slack-connect-probe",- endpoints: {- link: createAuthEndpoint("/oauth2/link", { method: "POST" }, async (ctx) =>- ctx.json(reached),- ),- signIn: createAuthEndpoint(- "/sign-in/oauth2",- { method: "POST" },- async (ctx) => ctx.json(reached),- ),- callback: createAuthEndpoint(- "/oauth2/callback/:providerId",- { method: "GET" },- async (ctx) => ctx.json(reached),- ),- },-} satisfies BetterAuthPlugin;-const guarded = betterAuth({baseURL: BASE_URL,secret: "slack-connect-spec-secret",database: prismaAdapter(db, { provider: "postgresql" }),emailAndPassword: { enabled: false },- hooks: { before: slackConnectGuard },- plugins: [probe],+ hooks: {+ before: createAuthMiddleware(async (ctx) => {+ await slackConnectGuard(ctx);+ if (+ ctx.path === "/link-social" ||+ ctx.path === "/sign-in/social" ||+ ctx.path.startsWith("/callback/")+ ) {+ return ctx.json(reached);+ }+ }),+ },+ plugins: [slackOAuthCallback],});const arrival = z.object({ reached: z.literal(true) });@@ -143,11 +140,11 @@ const startConnect = (new Request(`${BASE_URL}/api/auth${path}`, {method: "POST",headers: cookie ? { ...JSON_HEADERS, cookie } : JSON_HEADERS,- body: JSON.stringify({ providerId, callbackURL: "/" }),+ body: JSON.stringify({ provider: providerId, callbackURL: "/" }),}),);-const linkSlack = (cookie?: string) => startConnect("/oauth2/link", cookie);+const linkSlack = (cookie?: string) => startConnect("/link-social", cookie);const completeConnect = (cookie?: string,@@ -155,7 +152,7 @@ const completeConnect = () =>guarded.handler(new Request(- `${BASE_URL}/api/auth/oauth2/callback/${providerId}?code=test-code&state=test-state`,+ `${BASE_URL}/api/auth/callback/${providerId}?code=test-code&state=test-state`,{ headers: cookie ? { cookie } : undefined },),);@@ -281,7 +278,7 @@ describe("the two paths that start a Slack connection", () => {it("turns away a member who asks to sign in with Slack", async () => {await seat("owner", "owner");const response = await startConnect(- "/sign-in/oauth2",+ "/sign-in/social",await seat("rep", "member"),);@@ -307,7 +304,7 @@ describe("every provider that is not Slack", () => {it("lets a member link Google", async () => {await seat("owner", "owner");const response = await startConnect(- "/oauth2/link",+ "/link-social",await seat("rep", "member"),GOOGLE_PROVIDER_ID,);@@ -325,15 +322,25 @@ describe("every provider that is not Slack", () => {});describe("the paths the guard has to know about", () => {- it("is every path the generic OAuth plugin mounts", () => {- const paths = Object.values(genericOAuth({ config: [] }).endpoints)+ it("matches the shared social OAuth endpoints", () => {+ const paths = [callbackOAuth, linkSocialAccount, signInSocial()].map((endpoint) => endpoint.path).sort();- expect(paths).toEqual([- "/oauth2/callback/:providerId",- "/oauth2/link",- "/sign-in/oauth2",- ]);+ expect(paths).toEqual(["/callback/:id", "/link-social", "/sign-in/social"]);+ });+});++describe("registered Slack callback", () => {+ it("keeps the existing callback URL and passes its state to the guarded endpoint", async () => {+ const response = await guarded.handler(+ new Request(+ `${BASE_URL}/api/auth/oauth2/callback/slack?code=callback-code&state=callback-state`,+ ),+ );+ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(+ `${BASE_URL}/api/auth/callback/slack?code=callback-code&state=callback-state`,+ );});});diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.tsindex 556f2e2e..1ef7e7ea 100644--- a/packages/db/prisma/seed.ts+++ b/packages/db/prisma/seed.ts@@ -814,9 +814,7 @@ async function seedDeals(create: {id,name:- n === 0- ? `${company.name} — Comp AI`- : `${company.name} — expansion`,+ n === 0 ? `${company.name} Comp AI` : `${company.name} expansion`,description: pick(DEAL_DESCRIPTIONS),companyId: company.id,ownerId,diff --git a/packages/ui/components.json b/packages/ui/components.jsonindex 3ccf2601..4a7dff3f 100644--- a/packages/ui/components.json+++ b/packages/ui/components.json@@ -19,5 +19,8 @@},"rtl": false,"menuColor": "default",- "menuAccent": "subtle"+ "menuAccent": "subtle",+ "registries": {+ "@evilcharts": "https://evilcharts.com/r/{name}.json"+ }}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex a6151791..8bbc2a9b 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -17,17 +17,18 @@"clean": "rm -rf .turbo node_modules"},"dependencies": {- "@carbon/icons-react": "^11.82.0","@crm/db": "workspace:*","@dnd-kit/core": "^6.3.1","@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@paper-design/shaders-react": "0.0.81","@shadcn/react": "^0.3.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",- "lucide-react": "^1.28.0",+ "echarts": "^6.1.0",+ "lucide-react": "1.48.0","motion": "^12.42.2","next-themes": "^0.4.6","nuqs": "^2.8.9",diff --git a/packages/ui/src/components/accordion.tsx b/packages/ui/src/components/accordion.tsxindex bc16f5c4..e639056b 100644--- a/packages/ui/src/components/accordion.tsx+++ b/packages/ui/src/components/accordion.tsx@@ -36,16 +36,16 @@ function AccordionItem({}const accordionTriggerVariants = cva(- "group/accordion-trigger relative flex items-start rounded-md border border-transparent text-left outline-none transition-all focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:after:border-ring disabled:pointer-events-none disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",+ "group/accordion-trigger relative flex items-start rounded-md border border-transparent text-left outline-none transition-[color,box-shadow,text-decoration-color] focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",{variants: {variant: {default:- "flex-1 justify-between py-2.5 font-medium text-sm hover:underline **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4",+ "flex-1 justify-between py-4 font-medium text-sm hover:underline **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4",plain:"flex-1 justify-between py-2.5 text-left **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4",subtle:- "w-fit max-w-full items-center gap-1 py-1 text-muted-foreground text-xs hover:text-foreground **:data-[slot=accordion-trigger-icon]:size-3",+ "w-fit max-w-full items-center gap-1 py-1 text-muted-foreground text-13 hover:text-foreground **:data-[slot=accordion-trigger-icon]:size-3",},},defaultVariants: { variant: "default" },@@ -81,7 +81,7 @@ function AccordionTrigger({}const accordionContentVariants = cva(- "pt-0 pb-2.5 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",+ "pt-0 pb-4 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",{variants: {layout: {@@ -139,7 +139,7 @@ const MotionAccordionContent = forwardRef<transition={reducedMotion ? UI_MOTION.instant : UI_MOTION.accordion}aria-hidden={!open}inert={open ? undefined : true}- className={cn("overflow-hidden text-xs", className)}+ className={cn("overflow-hidden text-sm", className)}/></LazyMotion>);diff --git a/packages/ui/src/components/agent-presence.tsx b/packages/ui/src/components/agent-presence.tsxnew file mode 100644index 00000000..9ae7e982--- /dev/null+++ b/packages/ui/src/components/agent-presence.tsx@@ -0,0 +1,59 @@+import { cn } from "@crm/ui/lib/utils";+import { Slot } from "radix-ui";+import type * as React from "react";++function AgentFace({ className }: { className?: string }) {+ return (+ <svg+ aria-hidden+ data-slot="agent-face"+ data-state="idle"+ fill="none"+ viewBox="0 0 24 24"+ className={cn("size-4 shrink-0 text-brand", className)}+ >+ <path+ d="M12 2.5l9.5 7.4v4.2L12 21.5l-9.5-7.4V9.9z"+ stroke="currentColor"+ strokeLinejoin="round"+ strokeWidth={1.6}+ />+ <g fill="currentColor">+ <circle cx="9.6" cy="12" r="1.15" />+ <circle cx="14.4" cy="12" r="1.15" />+ </g>+ </svg>+ );+}++function AgentPresence({+ label,+ asChild = false,+ className,+ children,+ ...props+}: Omit<React.ComponentProps<"button">, "aria-label"> & {+ label: string;+ asChild?: boolean;+}) {+ const Comp = asChild ? Slot.Root : "button";++ return (+ <Comp+ data-slot="agent-presence"+ type={asChild ? undefined : "button"}+ aria-label={label}+ className={cn(+ "inline-flex h-8 shrink-0 items-center gap-2 rounded-lg bg-background px-2.5 font-medium text-13 text-foreground shadow-border outline-none transition-colors hover:bg-accent focus-visible:shadow-focus",+ className,+ )}+ {...props}+ >+ <Slot.Slottable>{children}</Slot.Slottable>+ <AgentFace />+ <span className="hidden max-w-48 truncate sm:inline">{label}</span>+ </Comp>+ );+}++export { AgentFace, AgentPresence };diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsxindex 42ad878d..bbe995ff 100644--- a/packages/ui/src/components/alert-dialog.tsx+++ b/packages/ui/src/components/alert-dialog.tsx@@ -36,7 +36,7 @@ function AlertDialogOverlay({<AlertDialogPrimitive.Overlaydata-slot="alert-dialog-overlay"className={cn(- "fixed inset-0 isolate z-50 bg-overlay duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 isolate z-50 bg-overlay duration-200 ease-spring data-closed:duration-100 data-closed:ease-out data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className,)}{...props}@@ -54,7 +54,7 @@ function AlertDialogContent({<AlertDialogPrimitive.Contentdata-slot="alert-dialog-content"className={cn(- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg bg-popover p-4 text-xs/relaxed text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-xs -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground shadow-modal duration-200 ease-spring outline-none sm:max-w-100 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",className,)}{...props}@@ -70,7 +70,10 @@ function AlertDialogHeader({return (<divdata-slot="alert-dialog-header"- className={cn("flex flex-col gap-1 text-left", className)}+ className={cn(+ "grid place-items-center gap-1.5 text-center sm:place-items-start sm:text-left",+ className,+ )}{...props}/>);@@ -84,7 +87,7 @@ function AlertDialogFooter({<divdata-slot="alert-dialog-footer"className={cn(- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",+ "-mx-6 -mb-6 mt-2 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-sidebar px-6 py-3 sm:flex-row sm:justify-end",className,)}{...props}@@ -100,7 +103,7 @@ function AlertDialogTitle({<AlertDialogPrimitive.Titledata-slot="alert-dialog-title"className={cn(- "font-heading text-sm font-medium wrap-anywhere",+ "font-heading text-xl font-semibold tracking-tight wrap-anywhere",className,)}{...props}@@ -116,7 +119,7 @@ function AlertDialogDescription({<AlertDialogPrimitive.Descriptiondata-slot="alert-dialog-description"className={cn(- "text-xs/relaxed text-muted-foreground wrap-anywhere *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",+ "text-sm text-balance text-muted-foreground wrap-anywhere md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",className,)}{...props}diff --git a/packages/ui/src/components/anchored-tooltip.tsx b/packages/ui/src/components/anchored-tooltip.tsxnew file mode 100644index 00000000..469a0df2--- /dev/null+++ b/packages/ui/src/components/anchored-tooltip.tsx@@ -0,0 +1,42 @@+"use client";++import { TooltipContent } from "@crm/ui/components/tooltip";+import { Tooltip as TooltipPrimitive } from "radix-ui";+import type * as React from "react";+import { createPortal } from "react-dom";++export type TooltipAnchor = {+ top: number;+ left: number;+ width: number;+ height: number;+};++function AnchoredTooltipContent({+ anchor,+ children,+ ...props+}: React.ComponentProps<typeof TooltipContent> & {+ anchor: TooltipAnchor | undefined;+}) {+ if (!anchor) return null;++ return (+ <>+ {createPortal(+ <TooltipPrimitive.Trigger asChild>+ <span+ aria-hidden+ data-slot="tooltip-anchor"+ className="pointer-events-none fixed"+ style={anchor}+ />+ </TooltipPrimitive.Trigger>,+ document.body,+ )}+ <TooltipContent {...props}>{children}</TooltipContent>+ </>+ );+}++export { AnchoredTooltipContent };diff --git a/packages/ui/src/components/app-shell.tsx b/packages/ui/src/components/app-shell.tsxnew file mode 100644index 00000000..0ece5635--- /dev/null+++ b/packages/ui/src/components/app-shell.tsx@@ -0,0 +1,247 @@+"use client";++import { Button } from "@crm/ui/components/button";+import { InkField } from "@crm/ui/components/ink-field";+import { Kbd } from "@crm/ui/components/kbd";+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetTitle,+} from "@crm/ui/components/sheet";+import { cn } from "@crm/ui/lib/utils";+import { MenuIcon, SearchIcon } from "lucide-react";+import { Slot } from "radix-ui";+import type * as React from "react";+import { createContext, useContext, useMemo, useRef } from "react";++const MARK_PATH =+ "M199.73 49.56L199.73 49.56Q195.47 46.24 191.20 42.92L151.80 12.28Q136.01 0.00 120.22 12.28L15.79 93.49Q0.00 105.77 0.00 125.77L0.00 146.22Q0.00 166.22 15.79 178.50L120.22 259.72Q136.01 272.00 151.80 259.72L256.21 178.50Q272.00 166.22 272.00 146.22L272.00 125.77Q272.00 105.77 256.21 93.49L208.27 56.21Q204.00 52.88 199.73 49.56ZM151.80 38.91L167.48 51.10Q178.35 59.55 167.47 68.00L157.57 75.70Q156.60 76.45 155.63 77.20L155.63 77.20Q154.65 77.96 153.68 77.20L145.33 70.71Q136.01 63.46 126.69 70.71L90.93 98.52Q81.61 105.77 90.93 113.02L91.69 113.61Q100.25 120.27 108.81 126.93L108.81 126.93Q117.37 133.59 125.93 140.25L126.69 140.84Q136.01 148.09 145.33 140.84L181.09 113.00Q190.40 105.76 181.09 98.51L172.75 92.02Q171.78 91.26 172.75 90.51L172.75 90.51Q173.72 89.75 174.70 89.00L184.60 81.31Q195.48 72.86 206.35 81.31L226.91 97.31Q237.79 105.77 226.92 114.23L226.92 114.23Q216.04 122.69 205.16 131.15L151.81 172.65Q136.02 184.93 120.23 172.66L102.24 158.66Q93.69 152.01 85.13 145.36L85.13 145.36Q76.57 138.71 68.01 132.05L66.28 130.70Q55.98 122.70 45.69 114.70L45.11 114.24Q34.24 105.78 45.12 97.33L120.22 38.91Q136.01 26.63 151.80 38.91Z";++const WORDMARK_PATH =+ "M356.9 136.2L357.0 140.2L357.2 144.2L357.5 148.0L357.9 151.8L358.4 155.4L359.1 159.0L359.9 162.5L360.8 165.8L361.8 169.1L362.9 172.3L364.2 175.4L365.5 178.4L367.0 181.2L368.6 184.0L370.3 186.7L372.1 189.2L373.9 191.7L375.9 194.0L377.9 196.2L380.1 198.3L382.4 200.2L384.7 202.1L387.2 203.9L389.7 205.5L392.3 207.0L395.0 208.4L397.8 209.6L400.6 210.8L403.5 211.7L406.4 212.6L409.4 213.3L412.5 213.9L415.6 214.4L418.8 214.7L422.1 214.9L425.5 215.0L428.5 214.9L431.5 214.8L434.4 214.5L437.2 214.2L440.0 213.8L442.7 213.2L445.3 212.6L447.9 211.9L450.4 211.1L452.8 210.2L455.1 209.1L457.4 208.0L459.6 206.9L461.7 205.6L463.8 204.2L465.7 202.8L467.7 201.3L469.5 199.7L471.3 198.1L473.0 196.4L474.6 194.6L476.2 192.7L477.7 190.7L479.1 188.7L480.4 186.6L481.7 184.4L482.9 182.2L484.0 179.9L485.0 177.5L486.0 175.1L486.4 174.0Q486.8 172.9 485.9 172.2L468.9 159.0Q467.8 158.1 467.6 159.5L467.3 160.9L466.7 163.6L466.0 166.2L465.2 168.7L464.3 171.1L463.3 173.4L462.1 175.6L460.9 177.7L459.5 179.7L458.1 181.6L456.5 183.4L454.8 185.2L453.0 186.8L451.1 188.2L449.1 189.5L446.9 190.7L444.7 191.8L442.3 192.7L439.8 193.4L437.2 194.1L434.5 194.5L431.7 194.9L428.7 195.1L425.7 195.2L423.3 195.1L421.1 195.0L418.9 194.7L416.7 194.4L414.6 193.9L412.5 193.4L410.5 192.8L408.5 192.0L406.6 191.2L404.8 190.3L403.0 189.3L401.2 188.1L399.5 186.9L397.8 185.6L396.3 184.2L394.7 182.8L393.3 181.2L391.9 179.6L390.6 177.8L389.3 176.0L388.1 174.1L387.0 172.2L385.9 170.1L384.9 167.9L384.0 165.7L383.1 163.4L382.3 161.0L381.7 158.5L381.0 156.0L380.5 153.4L380.1 150.7L379.7 148.0L379.4 145.1L379.2 142.2L379.1 139.3L379.1 136.2L379.1 133.2L379.2 130.2L379.4 127.3L379.7 124.4L380.1 121.7L380.5 119.0L381.0 116.4L381.7 113.8L382.3 111.4L383.1 109.0L384.0 106.6L384.9 104.4L385.9 102.2L387.0 100.1L388.1 98.1L389.3 96.2L390.6 94.4L391.9 92.6L393.3 91.0L394.7 89.4L396.3 87.9L397.8 86.5L399.5 85.2L401.2 84.0L403.0 82.8L404.8 81.8L406.6 80.8L408.5 80.0L410.5 79.3L412.5 78.6L414.6 78.1L416.7 77.6L418.9 77.3L421.1 77.0L423.3 76.9L425.7 76.8L428.6 76.9L431.4 77.1L434.1 77.4L436.7 77.8L439.2 78.4L441.6 79.1L443.9 79.9L446.0 80.9L448.1 81.9L450.1 83.1L451.9 84.4L453.7 85.9L455.3 87.4L456.8 89.1L458.3 90.8L459.6 92.7L460.8 94.6L462.0 96.6L463.0 98.7L464.0 100.9L464.8 103.2L465.6 105.6L466.2 108.1L466.5 109.4Q466.7 110.7 467.8 109.9L484.5 96.9Q485.3 96.2 484.9 95.2L484.6 94.2L483.1 90.8L481.5 87.6L479.8 84.4L477.9 81.4L475.9 78.6L473.7 75.9L471.4 73.4L468.9 71.0L466.2 68.8L463.4 66.7L460.4 64.9L457.3 63.2L453.9 61.8L450.4 60.5L446.7 59.5L442.9 58.6L438.8 57.9L434.6 57.4L430.2 57.1L425.7 57.0L422.3 57.1L418.9 57.3L415.7 57.6L412.5 58.1L409.4 58.7L406.3 59.4L403.4 60.3L400.5 61.3L397.6 62.4L394.9 63.7L392.2 65.1L389.6 66.6L387.1 68.3L384.6 70.0L382.3 71.9L380.1 73.9L377.9 76.0L375.9 78.2L373.9 80.6L372.0 83.0L370.3 85.6L368.6 88.3L367.0 91.1L365.5 94.0L364.2 97.0L362.9 100.1L361.8 103.3L360.8 106.6L359.9 109.9L359.1 113.4L358.4 117.0L357.9 120.6L357.5 124.4L357.2 128.2L357.0 132.2ZM503.3 154.9L503.4 157.9L503.5 160.8L503.8 163.7L504.1 166.5L504.5 169.2L505.0 171.8L505.6 174.4L506.2 176.9L507.0 179.4L507.9 181.8L508.8 184.1L509.8 186.3L511.0 188.5L512.2 190.6L513.4 192.6L514.8 194.5L516.2 196.4L517.7 198.1L519.3 199.8L521.0 201.4L522.7 202.9L524.5 204.3L526.4 205.6L528.4 206.9L530.4 208.0L532.5 209.1L534.6 210.0L536.8 210.9L539.0 211.6L541.3 212.3L543.7 212.9L546.0 213.3L548.5 213.7L551.0 213.9L553.5 214.1L556.1 214.1L558.8 214.1L561.3 213.9L563.9 213.7L566.3 213.3L568.7 212.9L571.1 212.3L573.4 211.6L575.6 210.9L577.8 210.0L579.9 209.1L582.0 208.0L584.0 206.9L586.0 205.6L587.8 204.3L589.6 202.9L591.4 201.4L593.0 199.8L594.6 198.1L596.1 196.4L597.5 194.5L598.8 192.6L600.1 190.6L601.3 188.5L602.4 186.3L603.5 184.1L604.4 181.8L605.3 179.4L606.0 176.9L606.7 174.4L607.3 171.8L607.8 169.2L608.2 166.5L608.5 163.7L608.7 160.8L608.9 157.9L608.9 154.9L608.9 152.0L608.7 149.0L608.5 146.2L608.2 143.4L607.8 140.7L607.3 138.1L606.7 135.5L606.0 133.0L605.3 130.6L604.4 128.2L603.5 125.9L602.4 123.7L601.3 121.5L600.1 119.4L598.8 117.4L597.5 115.5L596.1 113.7L594.6 111.9L593.0 110.3L591.4 108.7L589.6 107.2L587.8 105.8L586.0 104.5L584.0 103.2L582.0 102.1L579.9 101.0L577.8 100.1L575.6 99.2L573.4 98.4L571.1 97.8L568.7 97.2L566.3 96.8L563.9 96.4L561.3 96.2L558.8 96.0L556.1 96.0L553.5 96.0L551.0 96.2L548.5 96.4L546.0 96.8L543.7 97.2L541.3 97.8L539.0 98.4L536.8 99.2L534.6 100.1L532.5 101.0L530.4 102.1L528.4 103.2L526.4 104.5L524.5 105.8L522.7 107.2L521.0 108.7L519.3 110.3L517.7 111.9L516.2 113.7L514.8 115.5L513.4 117.4L512.2 119.4L511.0 121.5L509.8 123.7L508.8 125.9L507.9 128.2L507.0 130.6L506.2 133.0L505.6 135.5L505.0 138.1L504.5 140.7L504.1 143.4L503.8 146.2L503.5 149.0L503.4 152.0ZM524.8 154.9L524.9 151.8L525.1 148.9L525.4 146.0L525.8 143.2L526.3 140.6L526.9 138.0L527.7 135.6L528.5 133.3L529.5 131.1L530.6 129.1L531.8 127.1L533.1 125.3L534.6 123.5L536.1 122.0L537.7 120.5L539.4 119.3L541.2 118.2L543.0 117.2L545.0 116.4L547.1 115.7L549.2 115.2L551.4 114.8L553.7 114.6L556.1 114.5L558.6 114.6L560.9 114.8L563.2 115.2L565.3 115.7L567.4 116.4L569.4 117.2L571.2 118.2L573.0 119.3L574.7 120.5L576.3 122.0L577.8 123.5L579.2 125.3L580.5 127.1L581.7 129.1L582.8 131.1L583.8 133.3L584.6 135.6L585.4 138.0L586.0 140.6L586.5 143.2L586.9 146.0L587.2 148.9L587.4 151.8L587.4 154.9L587.4 158.1L587.2 161.1L586.9 164.0L586.5 166.8L586.0 169.4L585.4 172.0L584.6 174.4L583.8 176.7L582.8 178.9L581.7 181.0L580.5 183.0L579.2 184.8L577.8 186.6L576.3 188.1L574.7 189.5L573.0 190.8L571.2 191.9L569.4 192.9L567.4 193.7L565.3 194.4L563.2 194.9L560.9 195.3L558.6 195.5L556.1 195.6L553.7 195.5L551.4 195.3L549.2 194.9L547.1 194.4L545.0 193.7L543.0 192.9L541.2 191.9L539.4 190.8L537.7 189.5L536.1 188.1L534.6 186.6L533.1 184.8L531.8 183.0L530.6 181.0L529.5 178.9L528.5 176.7L527.7 174.4L526.9 172.0L526.3 169.4L525.8 166.8L525.4 164.0L525.1 161.1L524.9 158.1ZM629.8 206.2Q629.8 211.6 635.1 211.6L645.1 211.6Q650.4 211.6 650.4 206.2L650.4 144.7L650.4 143.1L650.5 141.6L650.6 140.1L650.8 138.6L651.0 137.2L651.2 135.8L651.5 134.4L651.8 133.1L652.2 131.8L652.6 130.5L653.0 129.3L653.5 128.1L654.0 127.0L654.6 125.9L655.2 124.8L655.8 123.8L656.5 122.8L657.2 121.9L657.9 121.1L658.7 120.2L659.5 119.4L660.3 118.7L661.2 118.0L662.1 117.4L663.1 116.8L664.0 116.2L665.0 115.7L666.0 115.3L667.1 114.9L668.1 114.6L669.2 114.3L670.4 114.1L671.5 113.9L672.7 113.8L673.9 113.7L675.1 113.7L677.0 113.7L678.9 113.9L680.6 114.2L682.3 114.6L683.8 115.1L685.3 115.7L686.7 116.4L687.9 117.3L689.1 118.3L690.2 119.3L691.1 120.5L692.0 121.8L692.8 123.3L693.6 124.8L694.2 126.3L694.8 128.0L695.3 129.8L695.8 131.7L696.2 133.6L696.5 135.7L696.7 137.8L696.9 140.0L697.0 142.3L697.0 144.7L697.0 206.2Q697.0 211.6 702.4 211.6L711.7 211.6Q717.0 211.6 717.0 206.2L717.0 144.7L717.1 143.1L717.1 141.5L717.2 140.0L717.4 138.5L717.6 137.1L717.8 135.7L718.1 134.3L718.4 132.9L718.8 131.7L719.2 130.4L719.6 129.2L720.1 128.0L720.6 126.9L721.2 125.8L721.8 124.8L722.4 123.8L723.1 122.8L723.8 121.9L724.5 121.0L725.3 120.2L726.1 119.4L726.9 118.7L727.7 118.0L728.6 117.4L729.6 116.8L730.5 116.2L731.5 115.7L732.5 115.3L733.5 114.9L734.6 114.6L735.7 114.3L736.8 114.1L737.9 113.9L739.1 113.8L740.3 113.7L741.5 113.7L743.3 113.7L745.1 113.9L746.8 114.1L748.4 114.5L749.9 115.0L751.4 115.5L752.7 116.2L754.0 117.0L755.2 117.9L756.3 118.9L757.4 120.0L758.3 121.2L759.2 122.5L760.0 123.9L760.7 125.4L761.4 127.1L762.0 128.8L762.5 130.6L762.9 132.5L763.2 134.5L763.5 136.7L763.7 138.9L763.8 141.2L763.9 143.7L763.9 206.2Q763.9 211.6 769.2 211.6L779.2 211.6Q784.5 211.6 784.5 206.2L784.5 138.8L784.5 136.5L784.4 134.3L784.2 132.2L784.0 130.1L783.8 128.1L783.4 126.2L783.1 124.3L782.6 122.4L782.1 120.6L781.5 118.9L780.9 117.2L780.2 115.6L779.5 114.0L778.7 112.5L777.9 111.1L776.9 109.7L776.0 108.4L774.9 107.1L773.9 106.0L772.7 104.8L771.5 103.8L770.3 102.8L769.0 101.9L767.6 101.0L766.2 100.2L764.7 99.5L763.1 98.8L761.6 98.2L759.9 97.7L758.2 97.2L756.5 96.9L754.7 96.5L752.9 96.3L751.0 96.1L749.0 96.0L747.0 96.0L745.5 96.0L744.0 96.1L742.6 96.2L741.2 96.4L739.7 96.6L738.4 96.9L737.0 97.2L735.7 97.6L734.4 98.0L733.1 98.5L731.9 99.0L730.7 99.6L729.5 100.2L728.3 100.9L727.2 101.6L726.1 102.4L725.1 103.2L724.1 104.0L723.1 104.9L722.2 105.8L721.3 106.8L720.4 107.8L719.6 108.8L718.8 109.9L718.1 111.1L717.4 112.2L716.7 113.5L716.1 114.7L715.5 116.1L715.0 117.4L714.5 118.8L714.4 119.1Q714.3 119.5 714.1 119.1L713.7 117.7L712.8 115.7L711.9 113.8L710.9 111.9L709.8 110.2L708.6 108.5L707.3 106.9L706.0 105.5L704.5 104.1L702.9 102.8L701.3 101.6L699.6 100.5L697.8 99.6L695.9 98.7L693.9 98.0L691.9 97.4L689.8 96.9L687.6 96.5L685.4 96.2L683.0 96.0L680.6 96.0L679.3 96.0L677.9 96.1L676.6 96.2L675.2 96.4L673.9 96.6L672.7 96.9L671.4 97.2L670.1 97.6L668.9 98.0L667.7 98.5L666.5 99.0L665.3 99.6L664.2 100.2L663.0 100.9L661.9 101.6L660.9 102.4L659.8 103.2L658.8 104.0L657.9 104.9L656.9 105.8L656.0 106.8L655.2 107.8L654.3 108.8L653.5 109.9L652.7 111.1L652.0 112.2L651.3 113.4L650.6 114.7L650.0 115.9L649.4 117.2L649.3 117.6Q649.2 117.9 649.1 117.6L648.8 103.9Q648.7 98.5 643.4 98.5L635.1 98.5Q629.8 98.5 629.8 103.9ZM810.8 238.2Q810.8 243.5 816.2 243.5L826.2 243.5Q831.5 243.5 831.5 238.2L831.5 196.6Q831.5 196.2 831.7 196.5L831.8 196.8L832.5 197.9L833.1 198.9L833.9 199.9L834.6 200.9L835.4 201.8L836.3 202.7L837.2 203.6L838.1 204.5L839.0 205.3L840.0 206.1L841.0 206.8L842.0 207.5L843.1 208.2L844.2 208.9L845.4 209.5L846.5 210.1L847.7 210.6L848.9 211.1L850.2 211.6L851.5 212.0L852.7 212.4L854.0 212.8L855.4 213.1L856.7 213.4L858.1 213.6L859.4 213.8L860.8 213.9L862.2 214.0L863.7 214.1L865.1 214.1L867.8 214.1L870.5 213.9L873.0 213.6L875.5 213.2L877.9 212.7L880.3 212.1L882.5 211.3L884.6 210.5L886.7 209.5L888.7 208.4L890.6 207.2L892.5 205.9L894.2 204.5L895.9 203.0L897.5 201.5L899.0 199.9L900.5 198.2L901.8 196.4L903.1 194.5L904.3 192.6L905.5 190.6L906.5 188.6L907.5 186.4L908.4 184.2L909.3 181.9L910.0 179.6L910.7 177.3L911.3 174.9L911.9 172.6L912.3 170.1L912.7 167.7L913.1 165.2L913.3 162.7L913.5 160.1L913.6 157.6L913.6 154.9L913.6 152.3L913.5 149.8L913.3 147.2L913.1 144.7L912.7 142.2L912.3 139.8L911.9 137.4L911.3 135.0L910.7 132.6L910.0 130.3L909.3 128.0L908.4 125.8L907.5 123.6L906.5 121.5L905.5 119.4L904.3 117.4L903.1 115.5L901.8 113.7L900.5 111.9L899.0 110.2L897.5 108.6L895.9 107.1L894.2 105.6L892.5 104.2L890.6 102.9L888.7 101.7L886.7 100.6L884.6 99.6L882.5 98.8L880.3 98.0L877.9 97.4L875.5 96.9L873.0 96.5L870.5 96.2L867.8 96.0L865.1 96.0L863.0 96.0L860.9 96.2L858.8 96.4L856.8 96.7L854.8 97.1L852.9 97.6L851.1 98.2L849.2 98.9L847.4 99.6L845.7 100.5L844.0 101.4L842.3 102.5L840.7 103.6L839.2 104.8L837.8 106.1L836.4 107.5L835.1 108.9L833.9 110.5L832.8 112.1L831.7 113.8L830.8 115.6L830.7 115.7Q830.7 115.8 830.7 115.7L830.3 103.9Q830.2 98.5 824.9 98.5L816.2 98.5Q810.8 98.5 810.8 103.9ZM831.5 154.9L831.5 152.8L831.6 150.7L831.7 148.6L831.9 146.6L832.1 144.6L832.4 142.8L832.8 140.9L833.1 139.1L833.6 137.4L834.1 135.8L834.6 134.1L835.2 132.6L835.9 131.1L836.5 129.7L837.3 128.3L838.0 127.0L838.8 125.8L839.7 124.6L840.6 123.5L841.5 122.5L842.5 121.5L843.6 120.6L844.6 119.8L845.7 119.0L846.9 118.3L848.1 117.6L849.3 117.0L850.6 116.5L851.9 116.0L853.2 115.6L854.6 115.3L856.0 115.0L857.4 114.8L858.9 114.6L860.4 114.5L861.9 114.5L864.2 114.6L866.4 114.8L868.6 115.2L870.6 115.7L872.6 116.4L874.5 117.2L876.3 118.2L878.0 119.3L879.6 120.5L881.2 122.0L882.7 123.5L884.1 125.3L885.3 127.1L886.5 129.1L887.6 131.1L888.5 133.3L889.4 135.6L890.1 138.0L890.7 140.6L891.2 143.2L891.6 146.0L891.9 148.9L892.1 151.8L892.1 154.9L892.1 158.1L891.9 161.1L891.6 164.0L891.2 166.8L890.7 169.4L890.1 172.0L889.4 174.4L888.5 176.7L887.6 178.9L886.5 181.0L885.3 183.0L884.1 184.8L882.7 186.6L881.2 188.1L879.6 189.5L878.0 190.8L876.3 191.9L874.5 192.9L872.6 193.7L870.6 194.4L868.6 194.9L866.4 195.3L864.2 195.5L861.9 195.6L860.4 195.6L858.9 195.5L857.4 195.3L856.0 195.1L854.6 194.8L853.2 194.4L851.9 194.0L850.6 193.6L849.3 193.0L848.1 192.4L846.9 191.7L845.7 191.0L844.6 190.2L843.6 189.4L842.5 188.4L841.5 187.5L840.6 186.4L839.7 185.3L838.8 184.2L838.0 182.9L837.3 181.6L836.5 180.3L835.9 178.9L835.2 177.4L834.6 175.9L834.1 174.3L833.6 172.6L833.1 170.9L832.8 169.1L832.4 167.3L832.1 165.4L831.9 163.4L831.7 161.4L831.6 159.3L831.5 157.1ZM976.0 206.5Q974.2 211.6 979.5 211.6L991.4 211.6Q996.7 211.6 998.5 206.5L1009.4 175.7Q1011.2 170.7 1016.5 170.7L1068.3 170.7Q1073.6 170.7 1075.3 175.7L1086.1 206.5Q1087.8 211.6 1093.2 211.6L1105.3 211.6Q1110.6 211.6 1108.8 206.5L1057.9 65.5Q1056.1 60.4 1050.8 60.4L1034.0 60.4Q1028.7 60.4 1026.9 65.5ZM1023.1 151.1Q1017.8 151.1 1019.6 146.1L1040.6 85.1Q1042.3 80.0 1044.0 85.1L1065.0 146.1Q1066.8 151.1 1061.4 151.1ZM1126.4 206.2Q1126.4 211.6 1131.7 211.6L1142.4 211.6Q1147.7 211.6 1147.7 206.2L1147.7 65.8Q1147.7 60.4 1142.4 60.4L1131.7 60.4Q1126.4 60.4 1126.4 65.8Z";++type AppShellNav = { close: () => void };++const AppShellNavContext = createContext<AppShellNav>({ close: () => {} });++function useAppShellNav(): AppShellNav {+ return useContext(AppShellNavContext);+}++function Wordmark(props: React.SVGProps<SVGSVGElement>) {+ return (+ <svg+ width={1167}+ height={272}+ viewBox="0 0 1167 272"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ className="h-5 w-auto"+ {...props}+ >+ <path d={MARK_PATH} fill="currentColor" />+ <path d={WORDMARK_PATH} fill="currentColor" />+ </svg>+ );+}++function AppShellHome({+ asChild = false,+ className,+ children,+ onClick,+ ...props+}: React.ComponentProps<"a"> & { asChild?: boolean }) {+ const Comp = asChild ? Slot.Root : "a";+ const { close } = useAppShellNav();++ return (+ <Comp+ data-slot="app-shell-home"+ className={cn(+ "flex shrink-0 items-center rounded-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",+ className,+ )}+ {...props}+ onClick={(event) => {+ onClick?.(event);+ if (!event.defaultPrevented) close();+ }}+ >+ <Slot.Slottable>{children}</Slot.Slottable>+ <Wordmark aria-hidden />+ </Comp>+ );+}++function AppShellSearch({+ placeholder,+ label = "Search",+ shortcut = "⌘K",+ disabled = false,+ onOpen,+}: {+ placeholder: string;+ label?: string;+ shortcut?: string;+ disabled?: boolean;+ onOpen?: () => void;+}) {+ return (+ <>+ <button+ type="button"+ data-slot="app-shell-search"+ aria-label={label}+ aria-keyshortcuts="Meta+K Control+K"+ disabled={disabled}+ onClick={onOpen}+ className="hidden h-8 w-full max-w-md items-center gap-2 rounded-md bg-background px-2.5 text-muted-foreground text-sm shadow-border outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:shadow-focus disabled:pointer-events-none sm:flex"+ >+ <SearchIcon aria-hidden className="size-4 shrink-0" />+ <span className="flex-1 truncate text-left">{placeholder}</span>+ <Kbd>{shortcut}</Kbd>+ </button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={label}+ disabled={disabled}+ onClick={onOpen}+ className="sm:hidden"+ >+ <SearchIcon aria-hidden />+ </Button>+ </>+ );+}++function AppShell({+ sidebar,+ mobileSidebar,+ home,+ product,+ search,+ agent,+ end,+ navOpen,+ onNavOpenChange,+ children,+}: {+ sidebar: React.ReactNode;+ mobileSidebar?: React.ReactNode;+ home: React.ReactNode;+ product?: string;+ search?: React.ReactNode;+ agent?: React.ReactNode;+ end?: React.ReactNode;+ navOpen: boolean;+ onNavOpenChange: (open: boolean) => void;+ children: React.ReactNode;+}) {+ const menuRef = useRef<HTMLButtonElement>(null);+ const nav = useMemo(+ () => ({ close: () => onNavOpenChange(false) }),+ [onNavOpenChange],+ );++ return (+ <AppShellNavContext.Provider value={nav}>+ <div+ data-slot="app-shell"+ className="relative isolate flex h-svh min-h-0 bg-background md:bg-[var(--rail,#0c1712)]"+ >+ <InkField className="hidden w-64 md:block" />+ <div+ data-slot="app-shell-rail"+ className="shell-rail relative z-1 hidden w-58 shrink-0 flex-col md:flex [view-transition-name:app-rail]"+ >+ <div className="flex h-13 shrink-0 items-center gap-2.5 pl-5">+ {home}+ {product ? (+ <span className="border-l pl-2.5 font-medium text-[0.8125rem] text-muted-foreground">+ {product}+ </span>+ ) : null}+ </div>+ {sidebar}+ </div>+ <div+ data-slot="app-shell-sheet"+ className="flex min-w-0 flex-1 flex-col bg-background md:shell-cut"+ >+ <svg+ aria-hidden+ data-slot="app-shell-cut-edge"+ className="pointer-events-none absolute inset-y-0 left-0 z-10 hidden h-full w-6 text-border md:dark:block"+ >+ <path+ d="M26 0.5Q22.17 0.5 19.15 2.85L3.47 15.03Q0.5 17.34 0.5 21.1V100000"+ fill="none"+ stroke="currentColor"+ strokeLinejoin="round"+ strokeWidth={1}+ />+ </svg>+ <header+ data-slot="app-shell-top-bar"+ className="flex h-13 shrink-0 items-center gap-2 border-b px-2 md:px-4 [view-transition-name:app-header]"+ >+ <div className="flex shrink-0 items-center gap-1 md:hidden">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ ref={menuRef}+ aria-label="Open navigation"+ aria-expanded={navOpen}+ onClick={() => onNavOpenChange(true)}+ >+ <MenuIcon aria-hidden />+ </Button>+ {home}+ </div>+ <div className="flex min-w-0 flex-1 items-center justify-end gap-2 sm:grid sm:grid-cols-[1fr_minmax(0,28rem)_1fr]">+ <div className="flex min-w-0 justify-center sm:col-start-2">+ {search}+ </div>+ <div className="flex items-center justify-end gap-2 sm:col-start-3">+ {agent}+ {end}+ </div>+ </div>+ </header>+ <div+ data-slot="app-shell-body"+ className="flex min-h-0 min-w-0 flex-1"+ >+ {children}+ </div>+ </div>+ </div>+ <Sheet open={navOpen} onOpenChange={onNavOpenChange}>+ <SheetContent+ side="left"+ showCloseButton={false}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ menuRef.current?.focus();+ }}+ className="w-72 gap-0 overflow-hidden bg-background p-0 text-foreground md:hidden"+ >+ <div className="flex min-h-0 flex-1 flex-col pt-2">+ <SheetTitle className="sr-only">Navigation</SheetTitle>+ <SheetDescription className="sr-only">+ Move between the pages of this workspace.+ </SheetDescription>+ {mobileSidebar ?? sidebar}+ </div>+ </SheetContent>+ </Sheet>+ </AppShellNavContext.Provider>+ );+}++export { AppShell, AppShellHome, AppShellSearch, useAppShellNav };diff --git a/packages/ui/src/components/app-sidebar.tsx b/packages/ui/src/components/app-sidebar.tsxnew file mode 100644index 00000000..4b32bb3d--- /dev/null+++ b/packages/ui/src/components/app-sidebar.tsx@@ -0,0 +1,207 @@+"use client";++import { useAppShellNav } from "@crm/ui/components/app-shell";+import { GeneratedAvatar } from "@crm/ui/components/generated-avatar";+import { Skeleton } from "@crm/ui/components/skeleton";+import { cn } from "@crm/ui/lib/utils";+import { ChevronLeftIcon, type LucideIcon } from "lucide-react";+import { Slot } from "radix-ui";+import type * as React from "react";++function AppSidebar({+ label,+ header,+ footer,+ children,+}: {+ label: string;+ header?: React.ReactNode;+ footer?: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <div data-slot="app-sidebar" className="flex min-h-0 flex-1 flex-col">+ {header ? <div className="shrink-0 px-2 pt-1">{header}</div> : null}+ <nav aria-label={label} className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ {children}+ </div>+ {footer ? (+ <div className="shrink-0 p-2">+ <ul className="flex flex-col gap-0.5">{footer}</ul>+ </div>+ ) : null}+ </nav>+ </div>+ );+}++function AppSidebarWorkspace({+ name,+ loading = false,+}: {+ name?: string;+ loading?: boolean;+}) {+ return (+ <div+ data-slot="app-sidebar-workspace"+ className="flex h-10 min-w-0 items-center gap-2 px-2"+ >+ {loading || !name ? (+ <>+ <Skeleton className="size-5 rounded-sm" />+ <Skeleton className="h-3.5 w-24" />+ </>+ ) : (+ <>+ <GeneratedAvatar kind="workspace" seed={name} size="sm" />+ <span className="min-w-0 flex-1 truncate font-medium text-foreground text-sm">+ {name}+ </span>+ </>+ )}+ </div>+ );+}++function AppSidebarGroup({+ label,+ stacked = false,+ children,+}: {+ label?: string;+ stacked?: boolean;+ children: React.ReactNode;+}) {+ return (+ <div+ data-slot="app-sidebar-group"+ className={cn("flex flex-col p-2", stacked && "py-0")}+ >+ {label ? (+ <div className="flex h-8 shrink-0 items-center px-2.5 font-medium text-muted-foreground text-xs">+ {label}+ </div>+ ) : null}+ <ul className="flex flex-col gap-0.5">{children}</ul>+ </div>+ );+}++const itemClassName =+ "flex h-9 w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-2.5 text-left text-muted-foreground text-sm outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring aria-[current=page]:bg-accent aria-[current=page]:text-foreground [&_svg]:size-4 [&_svg]:shrink-0";++const actionClassName =+ "absolute inset-y-0 right-1 flex items-center opacity-100 motion-safe:transition-opacity [@media(hover:hover)]:pointer-events-none [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within/item:pointer-events-auto [@media(hover:hover)]:group-focus-within/item:opacity-100 [@media(hover:hover)]:group-hover/item:pointer-events-auto [@media(hover:hover)]:group-hover/item:opacity-100";++function AppSidebarItem({+ icon: Glyph,+ label,+ active = false,+ inset = false,+ indicator,+ action,+ onClick,+ children,+}: {+ icon?: LucideIcon;+ label: string;+ active?: boolean;+ inset?: boolean;+ indicator?: React.ReactNode;+ action?: React.ReactNode;+ onClick?: React.MouseEventHandler<HTMLElement>;+ children: React.ReactElement;+}) {+ const nav = useAppShellNav();++ return (+ <li+ data-slot="app-sidebar-item"+ data-active={active || undefined}+ className="group/item relative before:absolute before:inset-y-1.5 before:-left-2 before:w-0.5 before:rounded-r-full before:bg-brand before:opacity-0 before:transition-opacity data-active:before:opacity-100 in-data-[slot=sheet-content]:before:-left-1 in-data-[slot=sheet-content]:before:rounded-full"+ >+ <Slot.Root+ aria-current={active ? "page" : undefined}+ className={cn(+ itemClassName,+ inset && "pl-8.5",+ action ? "pr-9" : null,+ )}+ onClick={(event: React.MouseEvent<HTMLElement>) => {+ onClick?.(event);+ nav.close();+ }}+ >+ {Glyph && !inset ? <Glyph aria-hidden /> : null}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {indicator ? (+ <span className="flex shrink-0 items-center text-muted-foreground [&_svg]:size-3.5">+ {indicator}+ </span>+ ) : null}+ <Slot.Slottable>{children}</Slot.Slottable>+ </Slot.Root>+ {action ? (+ <div data-slot="app-sidebar-item-action" className={actionClassName}>+ {action}+ </div>+ ) : null}+ </li>+ );+}++function AppSidebarSection({+ label,+ back,+ children,+}: {+ label: string;+ back: React.ReactElement;+ children: React.ReactNode;+}) {+ const nav = useAppShellNav();++ return (+ <>+ <div className="flex flex-col p-2 pb-0">+ <Slot.Root+ data-slot="app-sidebar-back"+ className="group/back flex h-9 w-full items-center gap-1 rounded-md pr-2.5 pl-1 font-semibold text-foreground text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"+ onClick={() => nav.close()}+ >+ <ChevronLeftIcon+ aria-hidden+ className="size-4 text-muted-foreground transition-transform group-hover/back:-translate-x-0.5 group-hover/back:text-foreground"+ />+ <span className="min-w-0 truncate">{label}</span>+ <Slot.Slottable>{back}</Slot.Slottable>+ </Slot.Root>+ </div>+ {children}+ </>+ );+}++function AppSidebarSkeleton({ rows = 6 }: { rows?: number }) {+ return (+ <div aria-hidden className="flex flex-col gap-0.5 p-2">+ {Array.from({ length: rows }, (_, index) => (+ <div key={index} className="flex h-9 items-center gap-2 px-2.5">+ <Skeleton className="size-4 rounded-sm" />+ <Skeleton className="h-3.5 w-24" />+ </div>+ ))}+ </div>+ );+}++export {+ AppSidebar,+ AppSidebarGroup,+ AppSidebarItem,+ AppSidebarSection,+ AppSidebarSkeleton,+ AppSidebarWorkspace,+};diff --git a/packages/ui/src/components/async-action.tsx b/packages/ui/src/components/async-action.tsxindex faaaab7a..b4abbf1f 100644--- a/packages/ui/src/components/async-action.tsx+++ b/packages/ui/src/components/async-action.tsx@@ -1,15 +1,10 @@"use client";-import { CircleAlertIcon, CheckIcon } from "lucide-react";-import { domAnimation, LazyMotion, m, useReducedMotion } from "motion/react";-import {- type ReactNode,- useCallback,- useEffect,- useRef,- useState,-} from "react";import { Spinner } from "@crm/ui/components/spinner";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { CheckIcon, CircleAlertIcon } from "lucide-react";+import { domAnimation, LazyMotion, m, useReducedMotion } from "motion/react";+import { type ReactNode, useCallback, useRef, useState } from "react";const TRANSITION = {type: "spring",@@ -92,13 +87,13 @@ export function useAsyncAction<TArgs extends unknown[], TResult>({[action, clear, onError, onSuccess, resetAfter],);- useEffect(() => {+ useMountEffect(() => {alive.current = true;return () => {alive.current = false;clear();};- }, [clear]);+ });return {status,diff --git a/packages/ui/src/components/auth-button.tsx b/packages/ui/src/components/auth-button.tsxnew file mode 100644index 00000000..f91f9c5a--- /dev/null+++ b/packages/ui/src/components/auth-button.tsx@@ -0,0 +1,47 @@+import { cn } from "@crm/ui/lib/utils";+import { cva, type VariantProps } from "class-variance-authority";+import { Slot } from "radix-ui";+import type * as React from "react";++const authButtonVariants = cva(+ "group/button inline-flex h-8 shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent bg-clip-padding px-2.5 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 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ {+ variants: {+ variant: {+ default:+ "bg-primary text-primary-foreground shadow-2xs hover:bg-[color-mix(in_oklch,var(--primary),black_12%)] active:bg-[color-mix(in_oklch,var(--primary),black_22%)] active:shadow-none",+ outline:+ "border-border bg-background shadow-2xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:bg-muted dark:hover:bg-accent",+ ghost:+ "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ },+);++function AuthButton({+ className,+ variant = "default",+ asChild = false,+ ...props+}: React.ComponentProps<"button"> &+ VariantProps<typeof authButtonVariants> & {+ asChild?: boolean;+ }) {+ const Comp = asChild ? Slot.Root : "button";++ return (+ <Comp+ data-slot="button"+ data-variant={variant}+ data-size="default"+ className={cn(authButtonVariants({ variant, className }))}+ {...props}+ />+ );+}++export { AuthButton };diff --git a/packages/ui/src/components/auth-field.tsx b/packages/ui/src/components/auth-field.tsxnew file mode 100644index 00000000..b76290a0--- /dev/null+++ b/packages/ui/src/components/auth-field.tsx@@ -0,0 +1,106 @@+"use client";++import { cn } from "@crm/ui/lib/utils";+import { cva, type VariantProps } from "class-variance-authority";+import { Label as LabelPrimitive } from "radix-ui";+import type * as React from "react";++function AuthLabel({+ className,+ ...props+}: React.ComponentProps<typeof LabelPrimitive.Root>) {+ return (+ <LabelPrimitive.Root+ data-slot="label"+ className={cn(+ "flex items-center gap-2 text-xs leading-none select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",+ className,+ )}+ {...props}+ />+ );+}++function AuthFieldGroup({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="field-group"+ className={cn(+ "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",+ className,+ )}+ {...props}+ />+ );+}++const authFieldVariants = cva(+ "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",+ {+ variants: {+ orientation: {+ vertical: "flex-col *:w-full [&>.sr-only]:w-auto",+ horizontal:+ "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",+ responsive:+ "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",+ },+ },+ defaultVariants: {+ orientation: "vertical",+ },+ },+);++function AuthField({+ className,+ orientation = "vertical",+ ...props+}: React.ComponentProps<"div"> & VariantProps<typeof authFieldVariants>) {+ return (+ <div+ role="group"+ data-slot="field"+ data-orientation={orientation}+ className={cn(authFieldVariants({ orientation }), className)}+ {...props}+ />+ );+}++function AuthFieldLabel({+ className,+ ...props+}: React.ComponentProps<typeof AuthLabel>) {+ return (+ <AuthLabel+ data-slot="field-label"+ className={cn(+ "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",+ "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",+ className,+ )}+ {...props}+ />+ );+}++function AuthFieldDescription({+ className,+ ...props+}: React.ComponentProps<"p">) {+ return (+ <p+ data-slot="field-description"+ className={cn(+ "text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",+ "last:mt-0 nth-last-2:-mt-1",+ "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",+ className,+ )}+ {...props}+ />+ );+}++export { AuthField, AuthFieldDescription, AuthFieldGroup, AuthFieldLabel };diff --git a/packages/ui/src/components/auth-input-group.tsx b/packages/ui/src/components/auth-input-group.tsxnew file mode 100644index 00000000..5f3004ea--- /dev/null+++ b/packages/ui/src/components/auth-input-group.tsx@@ -0,0 +1,102 @@+"use client";++import { AuthInput as Input } from "@crm/ui/components/auth-input";+import { cn } from "@crm/ui/lib/utils";+import { cva, type VariantProps } from "class-variance-authority";+import type * as React from "react";++function AuthInputGroup({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="input-group"+ role="group"+ className={cn(+ "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-md border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-1 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-muted dark:shadow-[inset_0_1px_1px_rgb(0_0_0/0.30)] dark:has-disabled:bg-muted dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",+ className,+ )}+ {...props}+ />+ );+}++const inputGroupAddonVariants = cva(+ "flex h-auto items-center justify-center gap-2 py-1.5 text-xs font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-none [&>svg:not([class*='size-'])]:size-4",+ {+ variants: {+ align: {+ "inline-start":+ "order-first cursor-text pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",+ "inline-end":+ "order-last cursor-text pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",+ "block-start":+ "order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",+ "block-end":+ "order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",+ },+ },+ defaultVariants: {+ align: "inline-start",+ },+ },+);++function AuthInputGroupAddon({+ className,+ align = "inline-start",+ ...props+}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {+ return (+ <div+ role="group"+ data-slot="input-group-addon"+ data-align={align}+ className={cn(inputGroupAddonVariants({ align }), className)}+ onClick={(e) => {+ if (align === "block-start" || align === "block-end") return;+ if ((e.target as HTMLElement).closest("button")) {+ return;+ }+ e.currentTarget.parentElement?.querySelector("input")?.focus();+ }}+ {...props}+ />+ );+}++function AuthInputGroupText({+ className,+ ...props+}: React.ComponentProps<"span">) {+ return (+ <span+ className={cn(+ "flex items-center gap-2 text-xs text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",+ className,+ )}+ {...props}+ />+ );+}++function AuthInputGroupInput({+ className,+ ...props+}: React.ComponentProps<"input">) {+ return (+ <Input+ data-slot="input-group-control"+ className={cn(+ "flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",+ className,+ )}+ {...props}+ />+ );+}++export {+ AuthInputGroup,+ AuthInputGroupAddon,+ AuthInputGroupInput,+ AuthInputGroupText,+};diff --git a/packages/ui/src/components/auth-input.tsx b/packages/ui/src/components/auth-input.tsxnew file mode 100644index 00000000..1f69edf0--- /dev/null+++ b/packages/ui/src/components/auth-input.tsx@@ -0,0 +1,22 @@+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";++function AuthInput({+ className,+ type,+ ...props+}: React.ComponentProps<"input">) {+ return (+ <input+ type={type}+ data-slot="input"+ className={cn(+ "h-8 w-full min-w-0 rounded-md border border-input bg-background px-2.5 py-1 text-xs transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-xs file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none 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",+ className,+ )}+ {...props}+ />+ );+}++export { AuthInput };diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsxindex 96bbbc95..5493eda9 100644--- a/packages/ui/src/components/badge.tsx+++ b/packages/ui/src/components/badge.tsx@@ -5,24 +5,23 @@ import { Slot } from "radix-ui"import { cn } from "@crm/ui/lib/utils"const badgeVariants = cva(- "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",+ "group/badge inline-flex h-6 w-fit shrink-0 items-center justify-center gap-1.25 overflow-hidden rounded-4xl border border-transparent px-3 text-xs font-medium whitespace-nowrap tabular-nums transition-[color,background-color,border-color,box-shadow] outline-none focus-visible:shadow-focus has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 aria-invalid:border-destructive [&>svg]:pointer-events-none [&>svg]:size-3.5!",{variants: {variant: {default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",secondary:- "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",+ "bg-secondary text-secondary-foreground [a]:hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",destructive:- "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",- "scope-read": "border-primary/30 bg-background text-foreground",- "scope-change": "border-warning/30 bg-background text-foreground",+ "bg-destructive/10 text-destructive dark:bg-destructive/20 [a]:hover:bg-destructive/20",+ "scope-read": "border-brand/30 bg-background text-foreground",+ "scope-change": "border-status-warning/40 bg-background text-foreground","scope-sensitive":"border-destructive/30 bg-background text-foreground",outline:- "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",- ghost:- "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",- link: "text-primary underline-offset-4 hover:underline",+ "border-border text-foreground [a]:hover:border-input [a]:hover:bg-accent",+ ghost: "[a]:hover:bg-accent",+ link: "text-primary underline-offset-4 [a]:hover:underline",mono: "rounded-sm bg-muted font-mono font-normal text-muted-foreground",token: "rounded-sm border-border font-normal text-foreground",},diff --git a/packages/ui/src/components/brand-logos/linkedin.tsx b/packages/ui/src/components/brand-logos/linkedin.tsxnew file mode 100644index 00000000..60000de9--- /dev/null+++ b/packages/ui/src/components/brand-logos/linkedin.tsx@@ -0,0 +1,17 @@+import type * as React from "react";++const LinkedInLogo = (props: React.SVGProps<SVGSVGElement>) => (+ <svg+ viewBox="0 0 16 16"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ {...props}+ >+ <path+ d="M14.816 0H1.18C.528 0 0 .516 0 1.153v13.69C0 15.48.528 16 1.18 16h13.635c.652 0 1.185-.52 1.185-1.156V1.153C16 .516 15.467 0 14.816 0ZM4.746 13.635H2.372V5.999h2.374v7.636ZM3.56 4.956a1.376 1.376 0 1 1 0-2.752 1.376 1.376 0 0 1 0 2.752Zm10.075 8.679H11.26V9.921c0-.886-.018-2.025-1.234-2.025-1.235 0-1.424.964-1.424 1.96v3.779H6.23V5.999h2.277v1.043h.031c.318-.602 1.092-1.234 2.247-1.234 2.403 0 2.85 1.582 2.85 3.638v4.189Z"+ fill="currentColor"+ />+ </svg>+);++export default LinkedInLogo;diff --git a/packages/ui/src/components/brand-logos/x.tsx b/packages/ui/src/components/brand-logos/x.tsxnew file mode 100644index 00000000..56af2712--- /dev/null+++ b/packages/ui/src/components/brand-logos/x.tsx@@ -0,0 +1,17 @@+import type * as React from "react";++const XLogo = (props: React.SVGProps<SVGSVGElement>) => (+ <svg+ viewBox="0 0 16 16"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ {...props}+ >+ <path+ d="M9.49 6.775 15.318 0h-1.381L8.877 5.883 4.834 0H.172l6.112 8.895L.172 16h1.381l5.344-6.212L11.166 16h4.662L9.49 6.775Zm-1.891 2.2-.619-.886L2.05 1.04h2.121l3.977 5.688.619.886 5.17 7.393h-2.121L7.599 8.975Z"+ fill="currentColor"+ />+ </svg>+);++export default XLogo;diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsxindex 2376bafa..fc44fed7 100644--- a/packages/ui/src/components/button.tsx+++ b/packages/ui/src/components/button.tsx@@ -4,37 +4,40 @@ 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-[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",+ "group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow] outline-none select-none focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {default:- "bg-primary text-primary-foreground shadow-2xs hover:bg-[color-mix(in_oklch,var(--primary),black_12%)] active:bg-[color-mix(in_oklch,var(--primary),black_22%)] active:shadow-none",+ "bg-primary text-primary-foreground hover:bg-primary/80 disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",outline:- "border-border bg-background shadow-2xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:bg-muted dark:hover:bg-accent",+ "border-border bg-background hover:border-input hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100","outline-ghost":- "border-border hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground",+ "border-border hover:border-input hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground",secondary:- "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",+ "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",ghost:- "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",+ "hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground",destructive:- "bg-destructive text-destructive-foreground shadow-2xs hover:bg-[color-mix(in_oklch,var(--destructive),black_12%)] active:bg-[color-mix(in_oklch,var(--destructive),black_22%)] active:shadow-none focus-visible:ring-destructive/50",+ "bg-destructive-solid text-destructive-foreground hover:bg-destructive-solid/90 disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",contrast:- "bg-foreground text-background shadow-2xs hover:bg-foreground/90 active:bg-foreground/80 active:shadow-none",+ "bg-foreground text-background hover:bg-foreground/80 disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",link: "text-primary underline-offset-4 hover:underline",},size: {default:- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- xs: "h-6 gap-1 rounded-sm px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",- sm: "h-7 gap-1 px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- xl: "h-10 gap-2 px-5 text-[15px] has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4",- icon: "size-8",- "icon-xs": "size-6 rounded-sm [&_svg:not([class*='size-'])]:size-3",- "icon-sm": "size-7",- "icon-lg": "size-9",+ "h-9 gap-1.5 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",+ xs: "h-6 gap-1 px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",+ sm: "h-8 gap-1.5 px-3 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",+ "sm-flush": "-ml-2 h-8 gap-1.5 px-2",+ "block-flush":+ "-mx-1 h-auto min-h-16 w-[calc(100%+--spacing(2))] items-start justify-start gap-1.5 whitespace-pre-wrap px-1 py-2 text-left font-normal leading-5 [--focus-outline-offset:-2px] focus-visible:border-ring focus-visible:shadow-[inset_0_0_0_1px_var(--ring)]",+ lg: "h-10 gap-2 rounded-lg px-5 text-base has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4",+ xl: "h-10 gap-2 px-5 text-15 has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4",+ icon: "size-9",+ "icon-xs": "size-6 [&_svg:not([class*='size-'])]:size-3",+ "icon-sm": "size-8",+ "icon-lg": "size-10 rounded-lg",inline: "h-auto w-fit p-0",},},diff --git a/packages/ui/src/components/calendar.tsx b/packages/ui/src/components/calendar.tsxindex 3fccae86..e150dccf 100644--- a/packages/ui/src/components/calendar.tsx+++ b/packages/ui/src/components/calendar.tsx@@ -1,223 +1,232 @@-"use client"+"use client";-import * as React from "react"-import {- DayPicker,- getDefaultClassNames,- type DayButton,- type Locale,-} from "react-day-picker"+import { Button, buttonVariants } from "@crm/ui/components/button";+import { toDay } from "@crm/ui/lib/format";-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"+import { cn } from "@crm/ui/lib/utils";+import {+ ChevronDownIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+} from "lucide-react";+import * as React from "react";+import {+ type DayButton,+ DayPicker,+ getDefaultClassNames,+ type Locale,+} from "react-day-picker";function Calendar({- className,- classNames,- showOutsideDays = true,- captionLayout = "label",- buttonVariant = "ghost",- locale,- formatters,- components,- ...props+ className,+ classNames,+ showOutsideDays = true,+ captionLayout = "label",+ buttonVariant = "ghost",+ locale,+ formatters,+ components,+ ...props}: React.ComponentProps<typeof DayPicker> & {- buttonVariant?: React.ComponentProps<typeof Button>["variant"]+ buttonVariant?: React.ComponentProps<typeof Button>["variant"];}) {- const defaultClassNames = getDefaultClassNames()+ const defaultClassNames = getDefaultClassNames();- return (- <DayPicker- showOutsideDays={showOutsideDays}- className={cn(- "group/calendar bg-background p-2 [--cell-radius:0px] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",- String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,- String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,- className- )}- captionLayout={captionLayout}- locale={locale}- formatters={{- formatMonthDropdown: (date) =>- date.toLocaleString(locale?.code, { month: "short" }),- ...formatters,- }}- classNames={{- root: cn("w-fit", defaultClassNames.root),- months: cn(- "relative flex flex-col gap-4 md:flex-row",- defaultClassNames.months- ),- month: cn("flex w-full flex-col gap-4", defaultClassNames.month),- nav: cn(- "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",- defaultClassNames.nav- ),- button_previous: cn(- buttonVariants({ variant: buttonVariant }),- "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",- defaultClassNames.button_previous- ),- button_next: cn(- buttonVariants({ variant: buttonVariant }),- "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",- defaultClassNames.button_next- ),- month_caption: cn(- "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",- defaultClassNames.month_caption- ),- dropdowns: cn(- "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-xs font-medium",- defaultClassNames.dropdowns- ),- dropdown_root: cn(- "relative rounded-(--cell-radius)",- defaultClassNames.dropdown_root- ),- dropdown: cn(- "absolute inset-0 bg-popover opacity-0",- defaultClassNames.dropdown- ),- caption_label: cn(- "font-medium select-none",- captionLayout === "label"- ? "text-xs"- : "flex items-center gap-1 rounded-(--cell-radius) text-xs [&>svg]:size-3.5 [&>svg]:text-muted-foreground",- defaultClassNames.caption_label- ),- month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),- weekdays: cn("flex", defaultClassNames.weekdays),- weekday: cn(- "flex-1 rounded-(--cell-radius) text-xs font-normal text-muted-foreground select-none",- defaultClassNames.weekday- ),- week: cn("mt-2 flex w-full", defaultClassNames.week),- week_number_header: cn(- "w-(--cell-size) select-none",- defaultClassNames.week_number_header- ),- week_number: cn(- "text-[0.8rem] text-muted-foreground select-none",- defaultClassNames.week_number- ),- day: cn(- "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",- props.showWeekNumber- ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"- : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",- defaultClassNames.day- ),- range_start: cn(- "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",- defaultClassNames.range_start- ),- range_middle: cn("rounded-none", defaultClassNames.range_middle),- range_end: cn(- "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",- defaultClassNames.range_end- ),- today: cn(- "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",- defaultClassNames.today- ),- outside: cn(- "text-muted-foreground aria-selected:text-muted-foreground",- defaultClassNames.outside- ),- disabled: cn(- "text-muted-foreground opacity-50",- defaultClassNames.disabled- ),- hidden: cn("invisible", defaultClassNames.hidden),- ...classNames,- }}- components={{- Root: ({ className, rootRef, ...props }) => {- return (- <div- data-slot="calendar"- ref={rootRef}- className={cn(className)}- {...props}- />- )- },- Chevron: ({ className, orientation, ...props }) => {- if (orientation === "left") {- return (- <ChevronLeftIcon className={cn("size-4", className)} {...props} />- )- }+ return (+ <DayPicker+ showOutsideDays={showOutsideDays}+ className={cn(+ "group/calendar bg-background p-2 [--cell-radius:0px] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,+ className,+ )}+ captionLayout={captionLayout}+ locale={locale}+ formatters={{+ formatMonthDropdown: (date) =>+ date.toLocaleString(locale?.code, { month: "short" }),+ ...formatters,+ }}+ classNames={{+ root: cn("w-fit", defaultClassNames.root),+ months: cn(+ "relative flex flex-col gap-4 md:flex-row",+ defaultClassNames.months,+ ),+ month: cn("flex w-full flex-col gap-4", defaultClassNames.month),+ nav: cn(+ "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",+ defaultClassNames.nav,+ ),+ button_previous: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",+ defaultClassNames.button_previous,+ ),+ button_next: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) p-0 select-none aria-disabled:opacity-50",+ defaultClassNames.button_next,+ ),+ month_caption: cn(+ "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",+ defaultClassNames.month_caption,+ ),+ dropdowns: cn(+ "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-xs font-medium",+ defaultClassNames.dropdowns,+ ),+ dropdown_root: cn(+ "relative rounded-(--cell-radius)",+ defaultClassNames.dropdown_root,+ ),+ dropdown: cn(+ "absolute inset-0 bg-popover opacity-0",+ defaultClassNames.dropdown,+ ),+ caption_label: cn(+ "font-medium select-none",+ captionLayout === "label"+ ? "text-xs"+ : "flex items-center gap-1 rounded-(--cell-radius) text-xs [&>svg]:size-3.5 [&>svg]:text-muted-foreground",+ defaultClassNames.caption_label,+ ),+ month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),+ weekdays: cn("flex", defaultClassNames.weekdays),+ weekday: cn(+ "flex-1 rounded-(--cell-radius) text-xs font-normal text-muted-foreground select-none",+ defaultClassNames.weekday,+ ),+ week: cn("mt-2 flex w-full", defaultClassNames.week),+ week_number_header: cn(+ "w-(--cell-size) select-none",+ defaultClassNames.week_number_header,+ ),+ week_number: cn(+ "text-[0.8rem] text-muted-foreground select-none",+ defaultClassNames.week_number,+ ),+ day: cn(+ "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",+ props.showWeekNumber+ ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"+ : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",+ defaultClassNames.day,+ ),+ range_start: cn(+ "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",+ defaultClassNames.range_start,+ ),+ range_middle: cn("rounded-none", defaultClassNames.range_middle),+ range_end: cn(+ "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",+ defaultClassNames.range_end,+ ),+ today: cn(+ "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",+ defaultClassNames.today,+ ),+ outside: cn(+ "text-muted-foreground aria-selected:text-muted-foreground",+ defaultClassNames.outside,+ ),+ disabled: cn(+ "text-muted-foreground opacity-50",+ defaultClassNames.disabled,+ ),+ hidden: cn("invisible", defaultClassNames.hidden),+ ...classNames,+ }}+ components={{+ Root: ({ className, rootRef, ...props }) => {+ return (+ <div+ data-slot="calendar"+ ref={rootRef}+ className={cn(className)}+ {...props}+ />+ );+ },+ Chevron: ({ className, orientation, ...props }) => {+ if (orientation === "left") {+ return (+ <ChevronLeftIcon className={cn("size-4", className)} {...props} />+ );+ }- if (orientation === "right") {- return (- <ChevronRightIcon className={cn("size-4", className)} {...props} />- )- }+ if (orientation === "right") {+ return (+ <ChevronRightIcon+ className={cn("size-4", className)}+ {...props}+ />+ );+ }- return (- <ChevronDownIcon className={cn("size-4", className)} {...props} />- )- },- DayButton: ({ ...props }) => (- <CalendarDayButton locale={locale} {...props} />- ),- WeekNumber: ({ children, ...props }) => {- return (- <td {...props}>- <div className="flex size-(--cell-size) items-center justify-center text-center">- {children}- </div>- </td>- )- },- ...components,- }}- {...props}- />- )+ return (+ <ChevronDownIcon className={cn("size-4", className)} {...props} />+ );+ },+ DayButton: ({ ...props }) => (+ <CalendarDayButton locale={locale} {...props} />+ ),+ WeekNumber: ({ children, ...props }) => {+ return (+ <td {...props}>+ <div className="flex size-(--cell-size) items-center justify-center text-center">+ {children}+ </div>+ </td>+ );+ },+ ...components,+ }}+ {...props}+ />+ );}function CalendarDayButton({- className,- day,- modifiers,- locale,- ...props+ className,+ day,+ modifiers,+ locale,+ ...props}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {- const defaultClassNames = getDefaultClassNames()+ const defaultClassNames = getDefaultClassNames();- const ref = React.useRef<HTMLButtonElement>(null)- React.useEffect(() => {- if (modifiers.focused) ref.current?.focus()- }, [modifiers.focused])+ const focusDay = React.useCallback(+ (node: HTMLButtonElement | null) => {+ if (modifiers.focused) node?.focus();+ },+ [modifiers.focused],+ );- return (- <Button- ref={ref}- variant="ghost"- size="icon"- data-day={toDay(day.date)}- data-selected-single={- modifiers.selected &&- !modifiers.range_start &&- !modifiers.range_end &&- !modifiers.range_middle- }- data-range-start={modifiers.range_start}- data-range-end={modifiers.range_end}- data-range-middle={modifiers.range_middle}- className={cn(- "relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",- defaultClassNames.day,- className- )}- {...props}- />- )+ return (+ <Button+ ref={focusDay}+ variant="ghost"+ size="icon"+ data-day={toDay(day.date)}+ data-selected-single={+ modifiers.selected &&+ !modifiers.range_start &&+ !modifiers.range_end &&+ !modifiers.range_middle+ }+ data-range-start={modifiers.range_start}+ data-range-end={modifiers.range_end}+ data-range-middle={modifiers.range_middle}+ className={cn(+ "relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",+ defaultClassNames.day,+ className,+ )}+ {...props}+ />+ );}-export { Calendar, CalendarDayButton }+export { Calendar, CalendarDayButton };diff --git a/packages/ui/src/components/card-table.tsx b/packages/ui/src/components/card-table.tsxindex d31c1d61..af429de8 100644--- a/packages/ui/src/components/card-table.tsx+++ b/packages/ui/src/components/card-table.tsx@@ -27,7 +27,7 @@ export function CardTable({export function CardTableEmpty({ children }: { children: ReactNode }) {return (- <p className="border-t py-6 text-center text-muted-foreground text-xs">+ <p className="border-t py-6 text-center text-muted-foreground text-sm">{children}</p>);diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsxindex fdf2305d..df226df4 100644--- a/packages/ui/src/components/card.tsx+++ b/packages/ui/src/components/card.tsx@@ -29,7 +29,10 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="card-title"- className={cn("text-pretty text-sm font-medium", className)}+ className={cn(+ "font-heading text-base leading-normal font-semibold tracking-tight text-pretty",+ className,+ )}{...props}/>);@@ -40,7 +43,7 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="card-description"className={cn(- "hidden text-pretty text-xs/relaxed text-muted-foreground sm:block",+ "hidden text-pretty text-sm text-muted-foreground sm:block",className,)}{...props}@@ -76,7 +79,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="card-content"className={cn(- "flex flex-col gap-4 rounded-lg border bg-card p-4 md:p-6",+ "flex flex-col gap-4 rounded-md bg-card p-5 text-sm text-card-foreground shadow-border",className,)}{...props}@@ -85,7 +88,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {}const cardPanelVariants = cva(- "flex min-h-0 flex-col overflow-hidden rounded-lg border bg-card",+ "flex min-h-0 flex-col overflow-hidden rounded-md bg-card text-sm text-card-foreground shadow-border",{variants: {size: {@@ -116,7 +119,7 @@ function CardPanelEmpty({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="card-panel-empty"className={cn(- "flex flex-1 items-center justify-center p-6 text-center text-muted-foreground text-xs",+ "flex flex-1 items-center justify-center p-6 text-center text-muted-foreground text-sm",className,)}{...props}@@ -155,7 +158,7 @@ function CardPanelGroupHeader({<divdata-slot="card-panel-group-header"className={cn(- "sticky top-0 z-10 flex items-center justify-between gap-4 border-b bg-muted px-4 py-3 md:px-6",+ "sticky top-0 z-10 flex items-center justify-between gap-4 bg-card px-5 py-3 shadow-divider",className,)}{...props}@@ -170,7 +173,7 @@ function CardPanelGroupContent({return (<divdata-slot="card-panel-group-content"- className={cn("px-4 pb-3 md:px-6", className)}+ className={cn("px-5 pb-3", className)}{...props}/>);@@ -184,7 +187,7 @@ function CardPanelDetail({<divdata-slot="card-panel-detail"className={cn(- "flex w-full flex-col gap-3 rounded-md bg-muted p-3 text-muted-foreground text-xs/5",+ "flex w-full flex-col gap-3 rounded-md bg-muted p-3 text-muted-foreground text-13",className,)}{...props}diff --git a/packages/ui/src/components/chart-swatch.tsx b/packages/ui/src/components/chart-swatch.tsxnew file mode 100644index 00000000..5e91c5a6--- /dev/null+++ b/packages/ui/src/components/chart-swatch.tsx@@ -0,0 +1,33 @@+import { cva, type VariantProps } from "class-variance-authority";+import { type ChartColor, chartSwatch } from "../lib/chart-config";++const chartSwatchVariants = cva(+ "shrink-0 forced-colors:outline-1 forced-colors:outline-[CanvasText] forced-colors:outline-solid forced-colors:forced-color-adjust-none",+ {+ variants: {+ size: {+ default: "size-2 rounded-[2px]",+ sm: "size-1.5",+ },+ },+ defaultVariants: {+ size: "default",+ },+ },+);++function ChartSwatch({+ color,+ size,+}: { color: ChartColor } & VariantProps<typeof chartSwatchVariants>) {+ return (+ <span+ aria-hidden+ data-slot="chart-swatch"+ className={chartSwatchVariants({ size })}+ style={{ backgroundColor: chartSwatch(color) }}+ />+ );+}++export { ChartSwatch };diff --git a/packages/ui/src/components/chat-composer.tsx b/packages/ui/src/components/chat-composer.tsxindex e5f4377c..6dcc790d 100644--- a/packages/ui/src/components/chat-composer.tsx+++ b/packages/ui/src/components/chat-composer.tsx@@ -1,7 +1,5 @@"use client";-import ArrowUp from "@carbon/icons-react/es/ArrowUp";-import StopFilled from "@carbon/icons-react/es/StopFilled";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import {@@ -11,12 +9,36 @@ import {} from "@crm/ui/components/input-group";import { Spinner } from "@crm/ui/components/spinner";import { cn } from "@crm/ui/lib/utils";+import { ArrowUpIcon, SquareIcon } from "lucide-react";import type * as React from "react";export type ChatComposerSize = "page" | "panel";export const CHAT_COMPOSER_SURFACE_CLASS_NAME =- "flex w-full flex-col justify-between rounded-xl border border-border bg-background p-[11px] transition-[color,background-color,border-color,box-shadow] focus-within:border-ring focus-within:ring-1 focus-within:ring-ring/40";+ "flex w-full flex-col justify-between rounded-xl border border-border bg-background p-[11px] transition-[color,background-color,border-color,box-shadow] hover:border-input focus-within:border-input";++function SendButton({+ label,+ disabled = false,+ loading = false,+}: {+ label: string;+ disabled?: boolean;+ loading?: boolean;+}) {+ return (+ <Button+ aria-busy={loading || undefined}+ aria-label={label}+ className="rounded-full"+ disabled={disabled}+ size="icon-sm"+ type="submit"+ >+ {loading ? <Spinner /> : <Icon icon={ArrowUpIcon} size="md" />}+ </Button>+ );+}export function ChatComposer({value,@@ -96,18 +118,26 @@ export function ChatComposer({><div className="flex min-w-0 items-center gap-1">{tools}</div>{busy && onStop ? (- <Button aria-label={stopLabel} onClick={onStop} size="icon-sm" type="button">- <Icon icon={StopFilled} motion="none" />- </Button>- ) : (<Button- aria-label={busy ? busyLabel : sendLabel}- disabled={!canSend}+ aria-label={stopLabel}+ className="rounded-full"+ onClick={onStop}size="icon-sm"- type="submit"+ type="button">- {busy ? <Spinner /> : <Icon icon={ArrowUp} motion="none" />}+ <Icon+ className="fill-current"+ icon={SquareIcon}+ motion="none"+ size="xs"+ /></Button>+ ) : (+ <SendButton+ disabled={!canSend}+ label={busy ? busyLabel : sendLabel}+ loading={busy}+ />)}</InputGroupAddon></InputGroup>diff --git a/packages/ui/src/components/chat-thread.tsx b/packages/ui/src/components/chat-thread.tsxindex 9cc4f418..f62c4740 100644--- a/packages/ui/src/components/chat-thread.tsx+++ b/packages/ui/src/components/chat-thread.tsx@@ -1,6 +1,5 @@"use client";-import ArrowRight from "@carbon/icons-react/es/ArrowRight";import { Icon } from "@crm/ui/components/icon";import {MessageScroller,@@ -11,6 +10,7 @@ import {MessageScrollerViewport,} from "@crm/ui/components/message-scroller";import { cn } from "@crm/ui/lib/utils";+import { ArrowRightIcon } from "lucide-react";import { createContext, type ReactNode, useContext } from "react";export type ChatThreadSize = "page" | "panel";@@ -37,25 +37,26 @@ export function ChatThread({label?: string;}) {const page = size === "page";- const footer = composer || notice ? (- <div- className={cn(- "flex shrink-0 flex-col gap-2",- page ? "pb-4 sm:pb-6" : "border-t p-3",- )}- data-slot="chat-thread-composer"- >+ const footer =+ composer || notice ? (<divclassName={cn(- "flex w-full flex-col gap-2",- page && "mx-auto max-w-3xl px-4 sm:px-6",+ "flex shrink-0 flex-col gap-2",+ page ? "pb-4 sm:pb-6" : "border-t p-3",)}+ data-slot="chat-thread-composer">- {notice}- {composer}+ <div+ className={cn(+ "flex w-full flex-col gap-2",+ page && "mx-auto max-w-3xl px-4 sm:px-6",+ )}+ >+ {notice}+ {composer}+ </div></div>- </div>- ) : null;+ ) : null;if (empty && page) {return (@@ -142,12 +143,14 @@ export function ChatThreadItem({export function ChatEmptyState({title,description,+ size,}: {title: string;description?: string;+ size?: ChatThreadSize;}) {- const size = useContext(SizeContext);- const page = size === "page";+ const threadSize = useContext(SizeContext);+ const page = (size ?? threadSize) === "page";return (<div@@ -199,14 +202,14 @@ export function ChatSuggestions({{suggestions.map((suggestion) => (<li className="border-t" key={suggestion}><button- className="group/suggestion flex min-h-10 w-full items-center gap-3 rounded-sm py-2 text-left outline-none transition-colors hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring/60"+ className="group/suggestion flex min-h-10 w-full items-center gap-3 rounded-sm py-2 text-left outline-none transition-colors hover:bg-muted/50 focus-visible:shadow-focus"onClick={() => onSelect(suggestion)}type="button"><span className="min-w-0 flex-1 font-medium text-sm">{suggestion}</span>- <Icon className="text-muted-foreground" icon={ArrowRight} />+ <Icon icon={ArrowRightIcon} size="md" tone="muted" /></button></li>))}diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsxindex 9f017e9c..c6d00327 100644--- a/packages/ui/src/components/checkbox.tsx+++ b/packages/ui/src/components/checkbox.tsx@@ -13,7 +13,7 @@ function Checkbox({<CheckboxPrimitive.Rootdata-slot="checkbox"className={cn(- "peer relative flex size-4 shrink-0 items-center justify-center rounded-sm border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-muted dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-[state=indeterminate]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground",+ "peer group/checkbox relative flex size-4 shrink-0 items-center justify-center rounded-sm border border-muted-foreground/70 transition-[color,background-color,border-color,box-shadow] outline-none group-has-disabled/field:opacity-50 group-has-[>[data-slot=field]]/field-label:focus-visible:shadow-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground data-[state=indeterminate]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground",className,)}{...props}diff --git a/packages/ui/src/components/combobox.tsx b/packages/ui/src/components/combobox.tsxindex 8936e0e2..a832f69b 100644--- a/packages/ui/src/components/combobox.tsx+++ b/packages/ui/src/components/combobox.tsx@@ -118,7 +118,7 @@ function Combobox({{option.label}</span>{option.hint ? (- <span className="shrink-0 truncate text-muted-foreground text-xs">+ <span className="shrink-0 truncate text-muted-foreground text-13">{option.hint}</span>) : null}diff --git a/packages/ui/src/components/command-search.tsx b/packages/ui/src/components/command-search.tsxnew file mode 100644index 00000000..6dcaf538--- /dev/null+++ b/packages/ui/src/components/command-search.tsx@@ -0,0 +1,471 @@+"use client";++import { Button } from "@crm/ui/components/button";+import {+ Command,+ CommandDialog,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandShortcut,+} from "@crm/ui/components/command";+import { Kbd, KbdGroup } from "@crm/ui/components/kbd";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { cn } from "@crm/ui/lib/utils";+import { defaultFilter } from "cmdk";+import {+ ArrowDownIcon,+ ArrowUpIcon,+ ChevronRightIcon,+ CornerDownLeftIcon,+ type LucideIcon,+} from "lucide-react";+import {+ Fragment,+ type KeyboardEvent as ReactKeyboardEvent,+ type ReactNode,+ useCallback,+ useEffectEvent,+ useRef,+ useState,+} from "react";++export type CommandSearchItem = {+ id: string;+ label: string;+ group: string;+ icon?: LucideIcon;+ media?: ReactNode;+ path?: string[];+ snippet?: string;+ keywords?: string[];+ shortcut?: string;+ onSelect: () => void;+};++type Entry = {+ item: CommandSearchItem;+ value: string;+ result: boolean;+};++type Group = { heading: string; entries: Entry[]; result: boolean };++function movesSelection(event: ReactKeyboardEvent) {+ return (+ ["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key) ||+ (event.ctrlKey && ["n", "j", "p", "k"].includes(event.key))+ );+}++function keepKeys(event: ReactKeyboardEvent) {+ if (event.key === "Enter" || event.key === " ") event.stopPropagation();+}++function groupEntries(entries: Entry[]): Group[] {+ const groups = new Map<string, Entry[]>();++ for (const entry of entries) {+ const group = groups.get(entry.item.group) ?? [];+ group.push(entry);+ groups.set(entry.item.group, group);+ }++ return [...groups].map(([heading, grouped]) => ({+ heading,+ entries: grouped,+ result: grouped[0]?.result ?? false,+ }));+}++function itemScore(item: CommandSearchItem, query: string) {+ return defaultFilter(`${item.group} ${item.label}`, query, item.keywords);+}++function queryWords(query: string) {+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].sort(+ (a, b) => b.length - a.length,+ );+}++function Marked({ text, words }: { text: string; words: string[] }) {+ if (words.length === 0) return text;++ const pattern = new RegExp(+ `(${words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`,+ "giu",+ );++ let offset = 0;++ return text.split(pattern).map((part, index) => {+ const key = `${offset}-${offset + part.length}`;+ offset += part.length;++ return index % 2 === 1 ? (+ <mark+ className="rounded-xs bg-status-success/15 font-medium text-foreground"+ key={key}+ >+ {part}+ </mark>+ ) : (+ <Fragment key={key}>{part}</Fragment>+ );+ });+}++function Row({+ entry,+ words,+ first,+ onSelect,+}: {+ entry: Entry;+ words: string[];+ first?: (node: HTMLDivElement | null) => void;+ onSelect: () => void;+}) {+ const { item } = entry;+ const lines = Boolean(item.path || item.snippet);+ const Glyph = item.icon;++ return (+ <CommandItem onSelect={onSelect} ref={first} value={entry.value}>+ {item.media ? (+ <span+ aria-hidden+ className={cn(+ "flex w-6 shrink-0 justify-center",+ lines && "mt-0.5 self-start",+ )}+ >+ {item.media}+ </span>+ ) : Glyph ? (+ <Glyph+ aria-hidden+ className={cn("text-muted-foreground", lines && "mt-0.5 self-start")}+ />+ ) : null}+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="truncate">+ <Marked text={item.label} words={words} />+ </span>+ {item.path ? (+ <span className="flex items-center gap-1 text-muted-foreground text-xs">+ {item.path.map((part, index) => (+ <span className="flex items-center gap-1" key={part}>+ {index > 0 ? (+ <ChevronRightIcon aria-hidden className="size-3" />+ ) : null}+ {part}+ </span>+ ))}+ </span>+ ) : null}+ {item.snippet ? (+ <span className="truncate text-muted-foreground text-xs">+ <Marked text={item.snippet} words={words} />+ </span>+ ) : null}+ </span>+ {item.shortcut ? (+ <CommandShortcut>{item.shortcut}</CommandShortcut>+ ) : null}+ </CommandItem>+ );+}++function toEntries(+ items: CommandSearchItem[],+ result: boolean,+ seen: Set<string>,+) {+ return items.map((item) => {+ const base = `${result ? "result" : "item"}:${item.id}`;+ let value = base;++ for (let count = 2; seen.has(value); count += 1) value = `${base}#${count}`;++ seen.add(value);++ return { item, value, result };+ });+}++function CommandSearch({+ open,+ onOpenChange,+ items,+ results,+ onQueryChange,+ loading = false,+ searchError,+ onRetry,+ workspaceName,+ title = "Search",+ description = "Search records, pages, settings and actions.",+ placeholder = "Search records, pages and actions…",+ loadingLabel = "Searching…",+ emptyLabel = "Nothing matches that.",+ retryLabel = "Try again",+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ items: CommandSearchItem[];+ results?: CommandSearchItem[];+ onQueryChange?: (query: string) => void;+ loading?: boolean;+ searchError?: string;+ onRetry?: () => void;+ workspaceName?: string;+ title?: string;+ description?: string;+ placeholder?: string;+ loadingLabel?: string;+ emptyLabel?: string;+ retryLabel?: string;+}) {+ const [query, setQuery] = useState("");+ const moved = useRef(false);+ const selectingFirst = useRef(false);+ const question = query.trim();+ const words = queryWords(question);++ const seen = new Set<string>();+ const resultEntries = question ? toEntries(results ?? [], true, seen) : [];+ const itemEntries = toEntries(items, false, seen);+ const groups = [...groupEntries(resultEntries), ...groupEntries(itemEntries)];++ const count =+ resultEntries.length ++ (query+ ? itemEntries.filter((entry) => itemScore(entry.item, query) > 0).length+ : itemEntries.length);++ const ranks = new Map(+ resultEntries.map((entry, index) => [entry.value, index]),+ );++ const byValue = new Map(+ itemEntries.map((entry) => [entry.value, entry.item]),+ );++ const filter = (value: string, search: string) => {+ const rank = ranks.get(value);++ if (rank !== undefined) return 2 - rank / (ranks.size + 1);++ const item = byValue.get(value);++ return item ? itemScore(item, search) : 0;+ };++ const firstResult = resultEntries[0]?.value;++ const followSelection = useCallback((root: HTMLDivElement | null) => {+ if (!root) return;++ let selectedId: string | undefined;++ const sync = () => {+ const selected = root.querySelector('[cmdk-item][aria-selected="true"]');+ const id = selected?.id;++ if (selected && id !== selectedId) {+ const list = root.querySelector("[cmdk-list]");++ if (list && list.querySelector("[cmdk-item]") === selected)+ list.scrollTop = 0;+ }++ selectedId = id;++ for (const element of root.querySelectorAll(+ "[cmdk-input], [cmdk-list]",+ )) {+ if (!id) element.removeAttribute("aria-activedescendant");+ else if (element.getAttribute("aria-activedescendant") !== id) {+ element.setAttribute("aria-activedescendant", id);+ }+ }+ };++ const observer = new MutationObserver(sync);++ observer.observe(root, {+ attributeFilter: ["aria-selected", "aria-activedescendant"],+ childList: true,+ subtree: true,+ });+ sync();++ return () => observer.disconnect();+ }, []);++ const selectFirstRecord = useCallback((node: HTMLDivElement | null) => {+ const root = node?.closest("[cmdk-root]");++ if (!root) return;++ requestAnimationFrame(() => {+ if (moved.current || !root.isConnected) return;++ selectingFirst.current = true;+ root.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Home", bubbles: true }),+ );+ selectingFirst.current = false;+ });+ }, []);++ const searching = question !== "";+ const error = searching ? searchError : undefined;++ const status = error+ ? error+ : searching && loading+ ? loadingLabel+ : searching && count === 0+ ? emptyLabel+ : "";++ const changeQuery = (next: string) => {+ setQuery(next);+ moved.current = false;+ onQueryChange?.(next);+ };++ const changeOpen = (next: boolean) => {+ onOpenChange(next);++ if (!next) changeQuery("");+ };++ const onShortcut = useEffectEvent((event: KeyboardEvent) => {+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ changeOpen(!open);+ }+ });++ useMountEffect(() => {+ const listener = (event: KeyboardEvent) => onShortcut(event);++ window.addEventListener("keydown", listener);++ return () => window.removeEventListener("keydown", listener);+ });++ return (+ <CommandDialog+ description={description}+ onOpenChange={changeOpen}+ open={open}+ title={title}+ >+ <Command+ data-slot="command-search"+ filter={filter}+ onKeyDown={(event) => {+ if (movesSelection(event) && !selectingFirst.current) {+ moved.current = true;+ }+ }}+ onPointerMove={(event) => {+ if (+ event.target instanceof Element &&+ event.target.closest("[cmdk-item]")+ )+ moved.current = true;+ }}+ ref={followSelection}+ >+ {workspaceName ? (+ <p className="px-2 pt-0.5 pb-1.5 text-muted-foreground text-xs">+ Search in {workspaceName}+ </p>+ ) : null}+ <CommandInput+ onValueChange={changeQuery}+ placeholder={placeholder}+ value={query}+ />+ <div+ className={cn(+ "flex items-center gap-3 text-muted-foreground",+ !status && "sr-only",+ count === 0 ? "justify-center py-6 text-sm" : "px-2 py-1.5 text-xs",+ )}+ data-slot="command-search-status"+ >+ <output>{status}</output>+ {error && onRetry ? (+ <Button+ onClick={onRetry}+ onKeyDown={keepKeys}+ size="xs"+ variant="outline"+ >+ {retryLabel}+ </Button>+ ) : null}+ </div>+ <CommandList>+ {groups.map((group) => (+ <CommandGroup+ heading={group.heading}+ key={`${group.result ? "result" : "item"}:${group.heading}`}+ >+ {group.entries.map((entry) => (+ <Row+ entry={entry}+ first={+ entry.value === firstResult ? selectFirstRecord : undefined+ }+ key={entry.value}+ onSelect={() => {+ changeOpen(false);+ entry.item.onSelect();+ }}+ words={words}+ />+ ))}+ </CommandGroup>+ ))}+ </CommandList>+ <div+ aria-hidden+ className="-mx-1.5 -mb-1.5 mt-1.5 flex items-center gap-4 border-t px-3 py-2.5 text-muted-foreground text-xs"+ data-slot="command-search-hints"+ >+ <span className="flex items-center gap-1.5">+ <KbdGroup>+ <Kbd size="sm">+ <ArrowUpIcon />+ </Kbd>+ <Kbd size="sm">+ <ArrowDownIcon />+ </Kbd>+ </KbdGroup>+ Select+ </span>+ <span className="flex items-center gap-1.5">+ <Kbd size="sm">+ <CornerDownLeftIcon />+ </Kbd>+ Open+ </span>+ <span className="ml-auto flex items-center gap-1.5">+ <Kbd size="sm">Esc</Kbd>+ Close+ </span>+ </div>+ </Command>+ </CommandDialog>+ );+}++export { CommandSearch };diff --git a/packages/ui/src/components/command.tsx b/packages/ui/src/components/command.tsxindex a3936ef8..4bd1bcc2 100644--- a/packages/ui/src/components/command.tsx+++ b/packages/ui/src/components/command.tsx@@ -15,7 +15,7 @@ import {import { cn } from "@crm/ui/lib/utils";import { Command as CommandPrimitive } from "cmdk";import { CheckIcon, SearchIcon } from "lucide-react";-import type * as React from "react";+import * as React from "react";function Command({className,@@ -25,7 +25,7 @@ function Command({<CommandPrimitivedata-slot="command"className={cn(- "flex size-full flex-col overflow-hidden rounded-lg bg-popover text-popover-foreground",+ "flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1.5 text-popover-foreground",className,)}{...props}@@ -46,6 +46,8 @@ function CommandDialog({className?: string;showCloseButton?: boolean;}) {+ const opener = React.useRef<HTMLElement | null>(null);+return (<Dialog {...props}><DialogHeader className="sr-only">@@ -54,9 +56,23 @@ function CommandDialog({</DialogHeader><DialogContentclassName={cn(- "top-1/3 translate-y-0 overflow-hidden rounded-lg p-0",+ "top-1/3 translate-y-0 overflow-hidden rounded-xl! p-0",className,)}+ onOpenAutoFocus={() => {+ opener.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ }}+ onCloseAutoFocus={(event) => {+ const target = opener.current;+ opener.current = null;+ event.preventDefault();+ const active = document.activeElement;+ if (active && active !== document.body && active.isConnected) return;+ if (target?.isConnected) target.focus();+ }}showCloseButton={showCloseButton}>{children}@@ -67,22 +83,28 @@ function CommandDialog({function CommandInput({className,+ end,...props-}: React.ComponentProps<typeof CommandPrimitive.Input>) {+}: React.ComponentProps<typeof CommandPrimitive.Input> & {+ end?: React.ReactNode;+}) {return (- <div data-slot="command-input-wrapper" className="border-b pb-0">- <InputGroup className="h-8 border-none bg-muted shadow-none! *:data-[slot=input-group-addon]:pl-2!">+ <div data-slot="command-input-wrapper" className="pb-1.5">+ <InputGroup className="h-8! rounded-md! border-border bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!"><CommandPrimitive.Inputdata-slot="command-input"className={cn(- "w-full text-xs outline-hidden disabled:cursor-not-allowed disabled:opacity-50",+ "w-full text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",className,)}{...props}/><InputGroupAddon>- <SearchIcon className="size-4 shrink-0 opacity-50" />+ <SearchIcon className="size-4 shrink-0 text-muted-foreground" /></InputGroupAddon>+ {end ? (+ <InputGroupAddon align="inline-end">{end}</InputGroupAddon>+ ) : null}</InputGroup></div>);@@ -96,7 +118,7 @@ function CommandList({<CommandPrimitive.Listdata-slot="command-list"className={cn(- "no-scrollbar max-h-72 scroll-py-0 overflow-x-hidden overflow-y-auto outline-none",+ "no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none",className,)}{...props}@@ -111,7 +133,7 @@ function CommandEmpty({return (<CommandPrimitive.Emptydata-slot="command-empty"- className={cn("py-6 text-center text-xs", className)}+ className={cn("py-6 text-center text-sm", className)}{...props}/>);@@ -125,7 +147,7 @@ function CommandGroup({<CommandPrimitive.Groupdata-slot="command-group"className={cn(- "overflow-hidden text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:text-muted-foreground",+ "overflow-hidden text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground",className,)}{...props}@@ -140,7 +162,7 @@ function CommandSeparator({return (<CommandPrimitive.Separatordata-slot="command-separator"- className={cn("-mx-1 h-px bg-border", className)}+ className={cn("-mx-1.5 my-1 h-px w-auto bg-border", className)}{...props}/>);@@ -155,7 +177,7 @@ function CommandItem({<CommandPrimitive.Itemdata-slot="command-item"className={cn(- "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-2 text-xs outline-hidden select-none in-data-[slot=dialog-content]:rounded-none! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",+ "group/command-item relative flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:**:[svg]:text-foreground",className,)}{...props}diff --git a/packages/ui/src/components/dashboard-chart.tsx b/packages/ui/src/components/dashboard-chart.tsxindex 85b8a644..6551a257 100644--- a/packages/ui/src/components/dashboard-chart.tsx+++ b/packages/ui/src/components/dashboard-chart.tsx@@ -1,35 +1,29 @@"use client";+import { type KeyboardEvent, type ReactNode, useMemo, useState } from "react";import {- type ChartConfig,- ChartContainer,- ChartLegend,- ChartLegendContent,- ChartTooltip,- ChartTooltipContent,-} from "@crm/ui/components/chart";-import { cn } from "@crm/ui/lib/utils";-import * as React from "react";+ CHART_CONFIG,+ type ChartColor,+ chartThemeColors,+} from "../lib/chart-config";+import { cn } from "../lib/utils";+import { ChartSwatch } from "./chart-swatch";import {- Area,- AreaChart,- Bar,- BarChart,- CartesianGrid,- Cell,- Label,- LabelList,- Pie,- PieChart,- Text,- XAxis,-} from "recharts";+ type ChartConfig,+ EChartsAreaChart,+} from "./evilcharts/charts/echarts-area-chart";+import { EChartsBarChart } from "./evilcharts/charts/echarts-bar-chart";+import { EChartsPieChart } from "./evilcharts/charts/echarts-pie-chart";type Datum = Record<string, number | string | null>;+type SeriesConfig = Record<string, { label: string; color: ChartColor }>;++type FormatValue = (value: number | string) => string;+type CartesianProps = {data: Datum[];- config: ChartConfig;+ config: SeriesConfig;xKey: string;series?: string[];className?: string;@@ -37,281 +31,369 @@ type CartesianProps = {showXAxis?: boolean;showLegend?: boolean;formatX?: (value: string) => string;- formatValue?: (value: number | string) => string;+ formatValue?: FormatValue;+ stacked?: boolean;+ label?: string;+};++type DonutSlice = {+ key: string;+ label: string;+ value: number;+ color: ChartColor;};-function seriesKeys(config: ChartConfig, series?: string[]) {- return series ?? Object.keys(config);+type SeriesEntry = { key: string; label: string; color: ChartColor };++const LABEL_KEY = "__label";+const DEFAULT_LABEL = "Chart";++function formatWith(formatValue: FormatValue | undefined, value: number) {+ return formatValue ? formatValue(value) : value.toLocaleString();+}++function cellValue(+ formatValue: FormatValue | undefined,+ value: Datum[string] | undefined,+) {+ return typeof value === "number" ? formatWith(formatValue, value) : "None";+}++function toChartConfig(entries: SeriesEntry[]): ChartConfig {+ return Object.fromEntries(+ entries.map(({ key, label, color }) => [+ key,+ { label, colors: chartThemeColors(color) },+ ]),+ );}-const tooltip = (+function useSeries(config: SeriesConfig, series?: string[]) {+ const keyList = (series ?? Object.keys(config)).join("\u0000");+ return useMemo(() => {+ const entries = keyList.split("\u0000").flatMap((key) => {+ const entry = config[key];+ return entry ? [{ key, ...entry }] : [];+ });+ return { entries, chartConfig: toChartConfig(entries) };+ }, [config, keyList]);+}++function useLabelledRows(+ data: Datum[],+ xKey: string,formatX?: (value: string) => string,- formatValue?: (value: number | string) => string,-) => (- <ChartTooltip- cursor={false}- content={- <ChartTooltipContent- indicator="dot"- labelFormatter={formatX ? (label) => formatX(String(label)) : undefined}- valueFormatter={formatValue}- />- }- />-);--const X_AXIS_PROPS = {- tickLine: false,- axisLine: false,- tickMargin: 12,-} as const;--function EdgeTick({- x,- y,- payload,- index,- visibleTicksCount,- formatX,-}: {- x?: number;- y?: number;- payload?: { value: string | number };- index?: number;- visibleTicksCount?: number;- formatX?: (value: string) => string;-}) {- const isFirst = index === 0;- const isLast = index === (visibleTicksCount ?? 0) - 1;- const anchor = isFirst ? "start" : isLast ? "end" : "middle";- const raw = String(payload?.value ?? "");- return (- <Text- x={x}- y={y}- textAnchor={anchor}- verticalAnchor="start"- className="fill-muted-foreground text-xs"- >- {formatX ? formatX(raw) : raw}- </Text>+) {+ return useMemo(+ () =>+ data.map((row) => ({+ ...row,+ [LABEL_KEY]: formatX+ ? formatX(String(row[xKey] ?? ""))+ : String(row[xKey] ?? ""),+ })),+ [data, xKey, formatX],);}-type DitherVariant = "gradient" | "dotted" | "hatched" | "solid";-type Bloom = "off" | "low" | "high" | "aura";--function bloomFilter(bloom: Bloom, color: string) {- switch (bloom) {- case "low":- return `drop-shadow(0 0 2px ${color})`;- case "high":- return `drop-shadow(0 0 5px ${color})`;- case "aura":- return `drop-shadow(0 0 3px ${color}) drop-shadow(0 0 9px ${color})`;- default:- return undefined;- }+function useKeyboardIndex(+ length: number,+ onActivate?: (index: number) => void,+) {+ const [keyIndex, setKeyIndex] = useState<number | null>(null);+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (length === 0) return;+ if ((event.key === "Enter" || event.key === " ") && onActivate) {+ event.preventDefault();+ if (keyIndex === null) return;+ onActivate(keyIndex);+ return;+ }+ const current = keyIndex ?? -1;+ const next =+ event.key === "ArrowRight" || event.key === "ArrowDown"+ ? Math.min(length - 1, current + 1)+ : event.key === "ArrowLeft" || event.key === "ArrowUp"+ ? Math.max(0, current < 0 ? length - 1 : current - 1)+ : event.key === "Home"+ ? 0+ : event.key === "End"+ ? length - 1+ : event.key === "Escape"+ ? null+ : undefined;+ if (next === undefined) return;+ event.preventDefault();+ setKeyIndex(next);+ };++ return {+ keyIndex,+ activeIndex: hoverIndex ?? keyIndex,+ setHoverIndex,+ onKeyDown,+ onBlur: () => setKeyIndex(null),+ };+}++function useToggleSelection(onSelect?: (key: string) => void) {+ const [selected, setSelected] = useState<string | null>(null);+ if (!onSelect) return undefined;+ return (key: string | null) => {+ const clicked = key ?? selected;+ setSelected(key);+ if (clicked) onSelect(clicked);+ };}-function ditherPatternId(base: string, key: string) {- return `${base}-dither-${key}`;+function ChartAnnouncement({ text }: { text: string }) {+ return (+ <span aria-live="polite" aria-atomic="true" className="sr-only">+ {text}+ </span>+ );}-function ditherFadeId(base: string, key: string) {- return `${base}-fade-${key}`;+function sliceAnnouncement(+ slice: DonutSlice | null,+ formatValue: FormatValue | undefined,+) {+ return slice ? `${slice.label}: ${formatWith(formatValue, slice.value)}` : "";}-function DitherDefs({- base,- keys,- variant,+function SeriesReadout({+ entries,+ row,+ heading,+ keyRow,+ formatValue,+ visible,}: {- base: string;- keys: string[];- variant: DitherVariant;+ entries: SeriesEntry[];+ row: Datum | null;+ heading: string | null;+ keyRow: (Datum & { [LABEL_KEY]: string }) | null;+ formatValue?: FormatValue;+ visible: boolean;}) {- if (variant === "solid") {- return null;- }+ const announcement = keyRow+ ? [+ keyRow[LABEL_KEY],+ ...entries.map(+ (entry) =>+ `${entry.label} ${cellValue(formatValue, keyRow[entry.key])}`,+ ),+ ].join(", ")+ : "";return (<>- {keys.map((key) => {- const color = `var(--color-${key})`;- const id = ditherPatternId(base, key);- if (variant === "hatched") {- return (- <pattern- key={id}- id={id}- width={6}- height={6}- patternUnits="userSpaceOnUse"- patternTransform="rotate(45)"- >- <line- x1={0}- y1={0}- x2={0}- y2={6}- stroke={color}- strokeWidth={1.5}- />- </pattern>- );- }- return (- <pattern- key={id}- id={id}- width={4}- height={4}- patternUnits="userSpaceOnUse"- >- <rect x={0} y={0} width={1.4} height={1.4} fill={color} />- <rect x={2} y={2} width={1.4} height={1.4} fill={color} />- </pattern>- );- })}- {variant === "gradient"- ? keys.map((key) => {- const fadeId = ditherFadeId(base, key);- const fadeGradId = `${fadeId}-grad`;- return (- <React.Fragment key={fadeId}>- <linearGradient id={fadeGradId} x1="0" y1="0" x2="0" y2="1">- <stop offset="0%" stopColor="white" stopOpacity={0.06} />- <stop offset="55%" stopColor="white" stopOpacity={0.45} />- <stop offset="100%" stopColor="white" stopOpacity={0.95} />- </linearGradient>- <mask id={fadeId}>- <rect- x="0"- y="0"- width="100%"- height="100%"- fill={`url(#${fadeGradId})`}- />- </mask>- </React.Fragment>- );- })- : null}+ {visible ? (+ <div className="flex min-h-5 flex-wrap items-center gap-x-4 gap-y-1 px-5 text-13 text-muted-foreground md:px-6">+ {row && heading ? (+ <span className="font-medium text-foreground">{heading}</span>+ ) : null}+ {entries.map((entry) => (+ <span key={entry.key} className="flex items-center gap-1.5">+ <ChartSwatch color={entry.color} />+ <span>{entry.label}</span>+ {row ? (+ <span className="text-foreground tabular-nums">+ {cellValue(formatValue, row[entry.key])}+ </span>+ ) : null}+ </span>+ ))}+ </div>+ ) : null}+ <ChartAnnouncement text={announcement} /></>);}+function SeriesTable({+ label,+ rows,+ entries,+ formatValue,+}: {+ label: string;+ rows: (Datum & { [LABEL_KEY]: string })[];+ entries: SeriesEntry[];+ formatValue?: FormatValue;+}) {+ return (+ <table className="sr-only">+ <caption>{label}</caption>+ <thead>+ <tr>+ <th scope="col">Period</th>+ {entries.map((entry) => (+ <th key={entry.key} scope="col">+ {entry.label}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <tr key={row[LABEL_KEY]}>+ <th scope="row">{row[LABEL_KEY]}</th>+ {entries.map((entry) => (+ <td key={entry.key}>{cellValue(formatValue, row[entry.key])}</td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ );+}++function SliceTable({+ label,+ data,+ formatValue,+}: {+ label: string;+ data: DonutSlice[];+ formatValue?: FormatValue;+}) {+ return (+ <table className="sr-only">+ <caption>{label}</caption>+ <tbody>+ {data.map((slice) => (+ <tr key={slice.key}>+ <th scope="row">{slice.label}</th>+ <td>{formatWith(formatValue, slice.value)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ );+}++function ChartFrame({+ label,+ hint,+ height,+ keyboard,+ readout,+ table,+ className,+ children,+}: {+ label: string;+ hint: string;+ height: number;+ keyboard: ReturnType<typeof useKeyboardIndex>;+ readout: ReactNode;+ table: ReactNode;+ className?: string;+ children: ReactNode;+}) {+ return (+ <div className={cn("flex w-full min-w-0 flex-col gap-3", className)}>+ <div+ role="group"+ aria-label={`${label}. ${hint}`}+ tabIndex={0}+ onKeyDown={keyboard.onKeyDown}+ onBlur={keyboard.onBlur}+ className="relative rounded-md p-1 outline-none after:pointer-events-none after:absolute after:inset-1 after:rounded-sm focus-visible:after:shadow-focus [--focus-outline-offset:-2px]"+ style={{ height }}+ >+ <div aria-hidden className="h-full w-full">+ {children}+ </div>+ </div>+ {readout}+ {table}+ </div>+ );+}+function AreaTrend({data,config,xKey,series,className,- height = 200,+ height = CHART_CONFIG.height.area,showXAxis = true,showLegend = false,formatX,formatValue,stacked = false,- variant = "gradient",- bloom = "low",-}: CartesianProps & {- stacked?: boolean;- variant?: DitherVariant;- bloom?: Bloom;-}) {- const keys = seriesKeys(config, series);- const gradientId = React.useId().replace(/:/g, "");- const dithered = variant !== "solid";+ label = DEFAULT_LABEL,+}: CartesianProps) {+ const { entries, chartConfig } = useSeries(config, series);+ const rows = useLabelledRows(data, xKey, formatX);+ const keyboard = useKeyboardIndex(rows.length);+ const active =+ keyboard.activeIndex === null ? null : (rows[keyboard.activeIndex] ?? null);+ const parts = useMemo(+ () => [+ <EChartsAreaChart.Grid key="grid" />,+ showXAxis ? <EChartsAreaChart.XAxis key="x" dataKey={LABEL_KEY} /> : null,+ <EChartsAreaChart.Tooltip key="tooltip" valueFormatter={formatValue} />,+ ...entries.map(({ key }) => (+ <EChartsAreaChart.Area+ key={key}+ dataKey={key}+ variant="gradient"+ strokeVariant={CHART_CONFIG.area.stroke}+ strokeWidth={CHART_CONFIG.area.strokeWidth}+ />+ )),+ ],+ [entries, showXAxis, formatValue],+ );return (- <ChartContainer- config={config}- className={cn("aspect-auto w-full", className)}- style={{ height }}- >- <AreaChart data={data} margin={{ left: 0, right: 0, top: 10, bottom: 0 }}>- <defs>- {keys.map((key) => (- <linearGradient- key={key}- id={`${gradientId}-${key}`}- x1="0"- y1="0"- x2="0"- y2="1"- >- <stop- offset="5%"- stopColor={`var(--color-${key})`}- stopOpacity={0.3}- />- <stop- offset="95%"- stopColor={`var(--color-${key})`}- stopOpacity={0}- />- </linearGradient>- ))}- <DitherDefs base={gradientId} keys={keys} variant={variant} />- </defs>- <CartesianGrid vertical={false} stroke="var(--border)" />- <XAxis- dataKey={xKey}- hide={!showXAxis}- tick={<EdgeTick formatX={formatX} />}- {...X_AXIS_PROPS}+ <ChartFrame+ label={label}+ hint="Use the arrow keys to read each period."+ height={height}+ keyboard={keyboard}+ className={className}+ readout={+ <SeriesReadout+ entries={entries}+ row={active}+ heading={active ? active[LABEL_KEY] : null}+ keyRow={+ keyboard.keyIndex === null+ ? null+ : (rows[keyboard.keyIndex] ?? null)+ }+ formatValue={formatValue}+ visible={showLegend || keyboard.keyIndex !== null}/>- {tooltip(formatX, formatValue)}- {keys.map((key) => (- <Area- key={key}- dataKey={key}- type="monotone"- stroke={`var(--color-${key})`}- strokeWidth={2}- fill={`url(#${gradientId}-${key})`}- stackId={stacked ? "stack" : undefined}- dot={false}- activeDot={{ r: 3, strokeWidth: 0 }}- style={- bloom === "off"- ? undefined- : { filter: bloomFilter(bloom, `var(--color-${key})`) }- }- />- ))}- {dithered- ? keys.map((key) => (- <Area- key={`dither-${key}`}- dataKey={key}- type="monotone"- stroke="none"- fill={`url(#${ditherPatternId(gradientId, key)})`}- fillOpacity={1}- mask={- variant === "gradient"- ? `url(#${ditherFadeId(gradientId, key)})`- : undefined- }- stackId={stacked ? "dither-stack" : undefined}- dot={false}- activeDot={false}- isAnimationActive={false}- legendType="none"- tooltipType="none"- />- ))- : null}- {showLegend ? (- <ChartLegend- verticalAlign="bottom"- content={<ChartLegendContent />}- />- ) : null}- </AreaChart>- </ChartContainer>+ }+ table={+ <SeriesTable+ label={label}+ rows={rows}+ entries={entries}+ formatValue={formatValue}+ />+ }+ >+ <EChartsAreaChart+ data={rows}+ config={chartConfig}+ xDataKey={LABEL_KEY}+ className="h-full w-full"+ curveType={CHART_CONFIG.area.curve}+ stackType={stacked ? "stacked" : "default"}+ activeIndex={keyboard.keyIndex}+ onHoverIndexChange={keyboard.setHoverIndex}+ >+ {parts}+ </EChartsAreaChart>+ </ChartFrame>);}@@ -321,232 +403,293 @@ function BarTrend({xKey,series,className,- height = 180,+ height = CHART_CONFIG.height.bar,showXAxis = true,showLegend = false,formatX,formatValue,stacked = false,-}: CartesianProps & { stacked?: boolean }) {- const keys = seriesKeys(config, series);+ label = DEFAULT_LABEL,+}: CartesianProps) {+ const { entries, chartConfig } = useSeries(config, series);+ const rows = useLabelledRows(data, xKey, formatX);+ const keyboard = useKeyboardIndex(rows.length);+ const active =+ keyboard.activeIndex === null ? null : (rows[keyboard.activeIndex] ?? null);+ const parts = useMemo(+ () => [+ <EChartsBarChart.Grid key="grid" />,+ showXAxis ? <EChartsBarChart.XAxis key="x" dataKey={LABEL_KEY} /> : null,+ <EChartsBarChart.Tooltip key="tooltip" valueFormatter={formatValue} />,+ ...entries.map(({ key }) => (+ <EChartsBarChart.Bar key={key} dataKey={key} variant="gradient" />+ )),+ ],+ [entries, showXAxis, formatValue],+ );return (- <ChartContainer- config={config}- className={cn("aspect-auto w-full", className)}- style={{ height }}- >- <BarChart data={data} margin={{ left: 0, right: 0, top: 10, bottom: 0 }}>- <CartesianGrid vertical={false} stroke="var(--border)" />- <XAxis- dataKey={xKey}- hide={!showXAxis}- tick={<EdgeTick formatX={formatX} />}- {...X_AXIS_PROPS}+ <ChartFrame+ label={label}+ hint="Use the arrow keys to read each period."+ height={height}+ keyboard={keyboard}+ className={className}+ readout={+ <SeriesReadout+ entries={entries}+ row={active}+ heading={active ? active[LABEL_KEY] : null}+ keyRow={+ keyboard.keyIndex === null+ ? null+ : (rows[keyboard.keyIndex] ?? null)+ }+ formatValue={formatValue}+ visible={showLegend || keyboard.keyIndex !== null}/>- {tooltip(formatX, formatValue)}- {keys.map((key) => (- <Bar- key={key}- dataKey={key}- fill={`var(--color-${key})`}- radius={0}- stackId={stacked ? "stack" : undefined}- maxBarSize={40}- />- ))}- {showLegend ? (- <ChartLegend- verticalAlign="bottom"- content={<ChartLegendContent />}- />- ) : null}- </BarChart>- </ChartContainer>+ }+ table={+ <SeriesTable+ label={label}+ rows={rows}+ entries={entries}+ formatValue={formatValue}+ />+ }+ >+ <EChartsBarChart+ data={rows}+ config={chartConfig}+ xDataKey={LABEL_KEY}+ className="h-full w-full"+ barRadius={CHART_CONFIG.bar.radius}+ stackType={stacked ? "stacked" : "default"}+ activeIndex={keyboard.keyIndex}+ >+ {parts}+ </EChartsBarChart>+ </ChartFrame>);}-type DonutSlice = { key: string; label: string; value: number; color: string };-function BarStat({data,className,- height = 200,+ height = CHART_CONFIG.height.bar,onBarClick,formatValue,+ label = DEFAULT_LABEL,}: {data: DonutSlice[];className?: string;height?: number;onBarClick?: (key: string) => void;- formatValue?: (value: number | string) => string;+ formatValue?: FormatValue;+ label?: string;}) {- const config: ChartConfig = Object.fromEntries(- data.map((d) => [d.key, { label: d.label, color: d.color }]),+ const chartConfig = useMemo(() => toChartConfig(data), [data]);+ const rows = useMemo(+ () =>+ data.map((slice) => ({+ [LABEL_KEY]: slice.label,+ [slice.key]: slice.value,+ })),+ [data],+ );+ const keyboard = useKeyboardIndex(+ data.length,+ onBarClick+ ? (index) => {+ const slice = data[index];+ if (slice) onBarClick(slice.key);+ }+ : undefined,);+ const onSelectionChange = useToggleSelection(onBarClick);+ const clickable = Boolean(onBarClick);+ const parts = useMemo(+ () => [+ <EChartsBarChart.Grid key="grid" />,+ <EChartsBarChart.XAxis key="x" dataKey={LABEL_KEY} />,+ <EChartsBarChart.Tooltip key="tooltip" valueFormatter={formatValue} />,+ ...data.map((slice) => (+ <EChartsBarChart.Bar+ key={slice.key}+ dataKey={slice.key}+ variant="gradient"+ isClickable={clickable}+ />+ )),+ ],+ [data, clickable, formatValue],+ );+ const active =+ keyboard.activeIndex === null ? null : (data[keyboard.activeIndex] ?? null);+ const focused =+ keyboard.keyIndex === null ? null : (data[keyboard.keyIndex] ?? null);return (- <ChartContainer- config={config}- className={cn("aspect-auto w-full", className)}- style={{ height }}+ <ChartFrame+ label={label}+ hint={+ onBarClick+ ? "Use the arrow keys to read each bar and Enter to open it."+ : "Use the arrow keys to read each bar."+ }+ height={height}+ keyboard={keyboard}+ className={className}+ readout={+ <>+ <ul className="flex flex-wrap gap-x-4 gap-y-1 px-5 text-13 text-muted-foreground md:px-6">+ {data.map((slice) => (+ <li+ key={slice.key}+ className={cn(+ "flex items-center gap-1.5 transition-opacity",+ active && active.key !== slice.key && "opacity-40",+ )}+ >+ <ChartSwatch color={slice.color} />+ <span>{slice.label}</span>+ <span className="text-foreground tabular-nums">+ {formatWith(formatValue, slice.value)}+ </span>+ </li>+ ))}+ </ul>+ <ChartAnnouncement text={sliceAnnouncement(focused, formatValue)} />+ </>+ }+ table={<SliceTable label={label} data={data} formatValue={formatValue} />}>- <BarChart data={data} margin={{ left: 0, right: 0, top: 24, bottom: 0 }}>- <CartesianGrid vertical={false} stroke="var(--border)" />- <XAxis- dataKey="label"- tickLine={false}- axisLine={false}- tickMargin={12}- tick={{ fill: "var(--muted-foreground)", fontSize: 12 }}- />- <ChartTooltip- cursor={false}- content={- <ChartTooltipContent- hideLabel- nameKey="key"- valueFormatter={formatValue}- />- }- />- <Bar- dataKey="value"- radius={0}- maxBarSize={40}- className={onBarClick ? "cursor-pointer" : undefined}- onClick={- onBarClick- ? (_, index) => {- const slice = data[index];- if (slice) onBarClick(slice.key);- }- : undefined- }- >- <LabelList- dataKey="value"- position="top"- className="fill-foreground"- fontSize={12}- />- {data.map((slice) => (- <Cell key={slice.key} fill={slice.color} />- ))}- </Bar>- </BarChart>- </ChartContainer>+ <EChartsBarChart+ data={rows}+ config={chartConfig}+ xDataKey={LABEL_KEY}+ className="h-full w-full"+ barRadius={CHART_CONFIG.bar.radius}+ stackType="stacked"+ activeIndex={keyboard.keyIndex}+ onSelectionChange={onSelectionChange}+ >+ {parts}+ </EChartsBarChart>+ </ChartFrame>);}function DonutStat({data,className,- height = 200,+ height = CHART_CONFIG.height.donut,centerValue,centerLabel,onSliceClick,formatValue,+ label = DEFAULT_LABEL,}: {data: DonutSlice[];className?: string;height?: number;- centerValue?: React.ReactNode;- centerLabel?: React.ReactNode;+ centerValue?: ReactNode;+ centerLabel?: ReactNode;onSliceClick?: (key: string) => void;- formatValue?: (value: number | string) => string;+ formatValue?: FormatValue;+ label?: string;}) {- const config: ChartConfig = Object.fromEntries(- data.map((d) => [d.key, { label: d.label, color: d.color }]),+ const chartConfig = useMemo(() => toChartConfig(data), [data]);+ const chartRows = useMemo(+ () => data.map(({ key, label, value }) => ({ key, label, value })),+ [data],+ );+ const keyboard = useKeyboardIndex(+ data.length,+ onSliceClick+ ? (index) => {+ const slice = data[index];+ if (slice) onSliceClick(slice.key);+ }+ : undefined,);+ const onToggle = useToggleSelection(onSliceClick);+ const clickable = Boolean(onSliceClick);+ const parts = useMemo(+ () => [+ <EChartsPieChart.Tooltip+ key="tooltip"+ position="bottom"+ valueFormatter={formatValue}+ />,+ <EChartsPieChart.Pie+ key="pie"+ variant="gradient"+ innerRadius={CHART_CONFIG.donut.innerRadius}+ outerRadius={CHART_CONFIG.donut.outerRadius}+ cornerRadius={CHART_CONFIG.donut.cornerRadius}+ paddingAngle={CHART_CONFIG.donut.paddingAngle}+ isClickable={clickable}+ />,+ ],+ [clickable, formatValue],+ );+ const focused =+ keyboard.keyIndex === null ? null : (data[keyboard.keyIndex] ?? null);const hasCenter = centerValue != null || centerLabel != null;- const innerRadius = Math.round(height * 0.34);- const outerRadius = Math.round(height * 0.46);return (- <ChartContainer- config={config}- className={cn("mx-auto aspect-square", className)}- style={{ height }}- >- <PieChart>- <ChartTooltip- cursor={false}- content={- <ChartTooltipContent- hideLabel- nameKey="key"- valueFormatter={formatValue}- />- }- />- <Pie- data={[{ value: 1 }]}- dataKey="value"- innerRadius={innerRadius}- outerRadius={outerRadius}- fill="var(--muted)"- fillOpacity={0.45}- stroke="none"- isAnimationActive={false}- />- <Pie- data={data}- dataKey="value"- nameKey="key"- innerRadius={innerRadius}- outerRadius={outerRadius}- paddingAngle={data.length > 1 ? 2 : 0}- className={onSliceClick ? "cursor-pointer" : undefined}- onClick={- onSliceClick- ? (_, index) => {- const slice = data[index];- if (slice) onSliceClick(slice.key);- }- : undefined- }- >- {data.map((slice) => (- <Cell key={slice.key} fill={slice.color} stroke="none" />- ))}- {hasCenter ? (- <Label- content={({ viewBox }) => {- if (!viewBox || !("cx" in viewBox)) return null;- return (- <text- x={viewBox.cx}- y={viewBox.cy}- textAnchor="middle"- dominantBaseline="middle"- >- <tspan- x={viewBox.cx}- y={viewBox.cy}- className="fill-foreground font-medium text-2xl tabular-nums"- >- {String(centerValue ?? "")}- </tspan>- {centerLabel != null ? (- <tspan- x={viewBox.cx}- y={(viewBox.cy ?? 0) + 20}- className="fill-muted-foreground text-xs"- >- {String(centerLabel)}- </tspan>- ) : null}- </text>- );- }}- />- ) : null}- </Pie>- </PieChart>- </ChartContainer>+ <div className={cn("flex w-full min-w-0 flex-col items-center", className)}>+ <div+ role="group"+ aria-label={`${label}. ${+ onSliceClick+ ? "Use the arrow keys to read each slice and Enter to open it."+ : "Use the arrow keys to read each slice."+ }`}+ tabIndex={0}+ onKeyDown={keyboard.onKeyDown}+ onBlur={keyboard.onBlur}+ className="relative aspect-square max-w-full rounded-full outline-none focus-visible:shadow-focus"+ style={{ height }}+ >+ <div aria-hidden className="h-full w-full">+ <EChartsPieChart+ data={chartRows}+ config={chartConfig}+ dataKey="value"+ nameKey="key"+ className="h-full w-full"+ activeSector={focused?.key ?? null}+ onSelectionChange={+ onToggle+ ? (selection) => onToggle(selection?.dataKey ?? null)+ : undefined+ }+ >+ {parts}+ </EChartsPieChart>+ </div>+ {hasCenter ? (+ <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center">+ {centerValue != null ? (+ <span className="font-medium text-2xl text-foreground tabular-nums">+ {centerValue}+ </span>+ ) : null}+ {centerLabel != null ? (+ <span className="text-13 text-muted-foreground">+ {centerLabel}+ </span>+ ) : null}+ </div>+ ) : null}+ <ChartAnnouncement text={sliceAnnouncement(focused, formatValue)} />+ </div>+ <SliceTable label={label} data={data} formatValue={formatValue} />+ </div>);}-export type { Datum, DonutSlice };+export type { Datum, DonutSlice, SeriesConfig };export { AreaTrend, BarStat, BarTrend, DonutStat };diff --git a/packages/ui/src/components/dashboard.tsx b/packages/ui/src/components/dashboard.tsxindex bb6b714f..ece6d983 100644--- a/packages/ui/src/components/dashboard.tsx+++ b/packages/ui/src/components/dashboard.tsx@@ -9,22 +9,32 @@ function StatGroup({return (<divdata-slot="stat-group"- className={cn("@container/stats overflow-hidden border", className)}+ className={cn(+ "@container/stats overflow-hidden rounded-md bg-card text-card-foreground shadow-border",+ className,+ )}{...props}>- <div- className={cn(- "grid grid-cols-2 @2xl/stats:grid-cols-4",- "[&:nth-child(2n)]:border-l [&:nth-child(n+3)]:border-t",- "@2xl/stats:[&>*]:border-t-0 @2xl/stats:[&>*]:border-l @2xl/stats:[&>*:first-child]:border-l-0",- )}- >+ <div className="grid grid-cols-1 divide-y @xl/stats:grid-cols-2 @xl/stats:divide-y-0 @xl/stats:[&>*:nth-child(even)]:border-l @xl/stats:[&>*:nth-child(n+3)]:border-t @4xl/stats:grid-cols-4 @4xl/stats:[&>*:nth-child(n+3)]:border-t-0 @4xl/stats:[&>*:not(:first-child)]:border-l">{children}</div></div>);}+function DashboardPanel({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="dashboard-panel"+ className={cn(+ "flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md bg-card text-card-foreground text-sm shadow-border",+ className,+ )}+ {...props}+ />+ );+}+const GRID_COLS = {2: "@md/dashboard:grid-cols-2",3: "@md/dashboard:grid-cols-2 @4xl/dashboard:grid-cols-3",@@ -86,7 +96,10 @@ function ChartCard({return (<divdata-slot="chart-card"- className={cn("flex flex-col border", className)}+ className={cn(+ "flex flex-col overflow-hidden rounded-md bg-card text-card-foreground shadow-border",+ className,+ )}{...props}>{title || description || action ? (@@ -127,7 +140,10 @@ function KpiCard({return (<divdata-slot="kpi-card"- className={cn("flex flex-col gap-4 border p-5 md:p-6", className)}+ className={cn(+ "flex flex-col gap-4 rounded-md bg-card p-5 text-card-foreground shadow-border md:p-6",+ className,+ )}{...props}><h3 className="truncate font-medium text-muted-foreground text-sm">@@ -178,6 +194,7 @@ function DashboardSection({export {ChartCard,DashboardGrid,+ DashboardPanel,DashboardRow,DashboardSection,KpiCard,diff --git a/packages/ui/src/components/data-table.tsx b/packages/ui/src/components/data-table.tsxindex 2f3663b4..c3b3751a 100644--- a/packages/ui/src/components/data-table.tsx+++ b/packages/ui/src/components/data-table.tsx@@ -1,12 +1,5 @@"use client";-import ArrowDown from "@carbon/icons-react/es/ArrowDown";-import ArrowsVertical from "@carbon/icons-react/es/ArrowsVertical";-import ArrowUp from "@carbon/icons-react/es/ArrowUp";-import ChevronDown from "@carbon/icons-react/es/ChevronDown";-import ChevronRight from "@carbon/icons-react/es/ChevronRight";-import Column from "@carbon/icons-react/es/Column";-import Filter from "@carbon/icons-react/es/Filter";import { Button } from "@crm/ui/components/button";import { Checkbox } from "@crm/ui/components/checkbox";import {@@ -21,6 +14,7 @@ import {DropdownMenu,DropdownMenuCheckboxItem,DropdownMenuContent,+ DropdownMenuGroup,DropdownMenuItem,DropdownMenuLabel,DropdownMenuRadioGroup,@@ -31,8 +25,8 @@ import {DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@crm/ui/components/dropdown-menu";-import { Spinner } from "@crm/ui/components/spinner";-import { TablePagination } from "@crm/ui/components/table-pagination";+import { useOverflowTooltip } from "@crm/ui/components/overflow-tooltip";+import { SkeletonLine } from "@crm/ui/components/skeleton-lines";import {Table,TableBody,@@ -41,33 +35,59 @@ import {TableHeader,TableRow,} from "@crm/ui/components/table";+import { TablePagination } from "@crm/ui/components/table-pagination";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";import type { TableSelection } from "@crm/ui/hooks/use-table-selection";-import { ROW_ACCENT, ROW_ACCENT_EXPANDABLE } from "@crm/ui/lib/row-accent";+import { ROW_ACCENT } from "@crm/ui/lib/row-accent";import type { TableQueryState } from "@crm/ui/lib/table-query";import { cn } from "@crm/ui/lib/utils";+import {+ ArrowDownIcon,+ ArrowUpDownIcon,+ ArrowUpIcon,+ ChevronDownIcon,+ ChevronRightIcon,+ Columns3Icon,+ LayoutListIcon,+ ListFilterIcon,+} from "lucide-react";import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";import {Fragment,type ReactNode,useDeferredValue,useId,- useMemo,useState,} from "react";+export type ColumnWidth =+ | "px"+ | "12"+ | "14"+ | "24"+ | "28"+ | "32"+ | "36"+ | "40"+ | "42"+ | "44"+ | "56"+ | "64";++export type TableSize = "sm" | "md" | "lg" | "xl" | "2xl";+export type DataTableColumn<TRow> = {id: string;header: ReactNode;cell: (row: TRow) => ReactNode;label?: string;sortable?: boolean;- width?: string;+ width?: ColumnWidth | { sm: ColumnWidth };align?: "left" | "right" | "center";- headClassName?: string;- cellClassName?: string;hideable?: boolean;defaultHidden?: boolean;- hideBelow?: "sm" | "md" | "lg";+ hideBelow?: TableSize;+ lines?: 1 | 2;};export type DataTableFacet = {@@ -83,6 +103,7 @@ export type DataTableFacet = {export type DataTableTabs = {id: string;+ label?: string;allLabel?: string;options: { value: string; label: string }[];};@@ -111,7 +132,7 @@ export type DataTableProps<TRow, TSub> = {loading?: boolean;facets?: DataTableFacet[];tabs?: DataTableTabs;- onRowClick?: (row: TRow) => void;+ onRowClick?: (row: TRow, orderedRows: readonly TRow[]) => void;onRowHover?: (row: TRow) => void;expandable?: DataTableExpandable<TRow, TSub>;selection?: DataTableSelection<TRow>;@@ -120,21 +141,139 @@ export type DataTableProps<TRow, TSub> = {search?: ReactNode;meta?: ReactNode;empty?: ReactNode;+ label?: string;className?: string;- tableClassName?: string;};-const HIDE_BELOW_CLASS = {- sm: "hidden sm:table-cell",- md: "hidden md:table-cell",- lg: "hidden lg:table-cell",-} as const;+type ColumnLayout = Pick<+ DataTableColumn<unknown>,+ "width" | "align" | "hideBelow" | "lines"+>;++function columnLayout({ width, align, hideBelow }: ColumnLayout) {+ return {+ "data-align": align,+ "data-hide-below": hideBelow,+ "data-width": typeof width === "string" ? width : undefined,+ "data-width-sm": typeof width === "object" ? width.sm : undefined,+ };+}++const COLUMN_LAYOUT_CLASS = cn(+ "data-[align=center]:text-center data-[align=right]:text-right data-[align=right]:tabular-nums",+ "data-[hide-below=sm]:hidden @xl/table:data-[hide-below=sm]:table-cell",+ "data-[hide-below=md]:hidden @3xl/table:data-[hide-below=md]:table-cell",+ "data-[hide-below=lg]:hidden @4xl/table:data-[hide-below=lg]:table-cell",+ "data-[hide-below=xl]:hidden @5xl/table:data-[hide-below=xl]:table-cell",+ "data-[hide-below=2xl]:hidden @6xl/table:data-[hide-below=2xl]:table-cell",+ "data-[width=px]:w-px data-[width=12]:w-12 data-[width=14]:w-14 data-[width=24]:w-24 data-[width=28]:w-28 data-[width=32]:w-32",+ "data-[width=36]:w-36 data-[width=40]:w-40 data-[width=42]:w-42 data-[width=44]:w-44 data-[width=56]:w-56 data-[width=64]:w-64",+ "@xl/table:data-[width-sm=px]:w-px @xl/table:data-[width-sm=12]:w-12 @xl/table:data-[width-sm=14]:w-14 @xl/table:data-[width-sm=24]:w-24 @xl/table:data-[width-sm=28]:w-28 @xl/table:data-[width-sm=32]:w-32",+ "@xl/table:data-[width-sm=36]:w-36 @xl/table:data-[width-sm=40]:w-40 @xl/table:data-[width-sm=42]:w-42 @xl/table:data-[width-sm=44]:w-44 @xl/table:data-[width-sm=56]:w-56 @xl/table:data-[width-sm=64]:w-64",+);++const COLUMN_HEAD_CLASS = cn(+ "h-10 overflow-hidden px-3 font-medium text-13 text-muted-foreground",+ COLUMN_LAYOUT_CLASS,+);++const COLUMN_CELL_CLASS = cn("overflow-hidden px-3", COLUMN_LAYOUT_CLASS);++const TABLE_CLASS =+ "table-fixed [&_td:first-child]:pl-4 [&_th:first-child]:pl-4 [&_td:last-child]:pr-4 [&_th:last-child]:pr-4";++const TABLE_CONTAINER_CLASS =+ "min-h-0 overflow-auto rounded-md bg-card shadow-border";++const TABLE_HEADER_CLASS =+ "sticky top-0 z-10 bg-card [&_th]:bg-card [&_tr]:border-0 [&_tr]:shadow-divider";++function TableFrame({+ label,+ overlay,+ children,+}: {+ label?: string;+ overlay: ReactNode;+ children: ReactNode;+}) {+ return (+ <section+ aria-label={label}+ data-slot="table-frame"+ onKeyUp={(event) => {+ if (event.key === "Tab") delete event.currentTarget.dataset.pointer;+ }}+ onPointerDown={(event) => {+ event.currentTarget.dataset.pointer = "";+ }}+ className={cn(+ "relative w-full outline-hidden focus-visible:not-data-pointer:outline-2 focus-visible:not-data-pointer:outline-solid focus-visible:not-data-pointer:outline-offset-0 focus-visible:not-data-pointer:outline-ring [&>[data-slot=table-container]]:overflow-visible",+ TABLE_CONTAINER_CLASS,+ overlay && "min-h-80",+ )}+ tabIndex={0}+ >+ {children}+ {overlay}+ </section>+ );+}++const TABLE_EMPTY_OVERLAY_CLASS =+ "absolute inset-0 flex items-center justify-center px-4 py-8 text-center";++const LOADING_ROW_COUNT = 5;-const ALIGN_CLASS = {- left: "",- right: "text-right",- center: "text-center",-} as const;+const NARROW_TABLE_COLUMNS = 3;++function LoadingRows({+ columns,+ selectable,+ expandable,+}: {+ columns: (ColumnLayout & { id: string })[];+ selectable: boolean;+ expandable: boolean;+}) {+ const detailColumn = Math.max(+ 0,+ columns.findIndex((column) => !column.width),+ );++ return Array.from({ length: LOADING_ROW_COUNT }, (_, index) => (+ <TableRow+ className="hover:bg-transparent"+ data-slot="table-loading-row"+ key={index}+ >+ {selectable ? (+ <TableCell+ className={cn("w-10 px-3 py-3", COLUMN_LAYOUT_CLASS)}+ data-hide-below="sm"+ />+ ) : null}+ {expandable ? <TableCell className="w-10 px-3 py-3" /> : null}+ {columns.map((column, position) => (+ <TableCell+ key={column.id}+ {...columnLayout(column)}+ className={cn(COLUMN_CELL_CLASS, "py-3")}+ >+ <div+ className="flex min-h-5 flex-col justify-center gap-2 data-[align=right]:items-end"+ data-align={column.align}+ >+ <SkeletonLine width={column.width === "px" ? "24" : "two-thirds"} />+ {(column.lines ?? (position === detailColumn ? 2 : 1)) === 2 ? (+ <SkeletonLine size="sm" width="40" />+ ) : null}+ </div>+ </TableCell>+ ))}+ </TableRow>+ ));+}function columnLabel<TRow>(column: DataTableColumn<TRow>): string {if (column.label) return column.label;@@ -152,37 +291,49 @@ function SortIndicator({<span className="text-muted-foreground">{active ? (dir === "asc" ? (- <ArrowUp size={12} />+ <ArrowUpIcon size={12} />) : (- <ArrowDown size={12} />+ <ArrowDownIcon size={12} />)) : (- <ArrowsVertical size={12} className="opacity-40" />+ <ArrowUpDownIcon+ size={12}+ className="opacity-0 transition-opacity group-hover/button:opacity-40 group-focus-visible/button:opacity-40"+ />)}</span>);}-function facetLabel(facet: DataTableFacet, selected: string[]): string {- if (selected.length === 0) return facet.label;- if (selected.length === 1) {- const option = facet.options.find((o) => o.value === selected[0]);- return option?.label ?? facet.label;- }- return `${facet.label} (${selected.length})`;-}-function toggle(selected: string[], value: string, checked: boolean): string[] {return checked ? [...selected, value] : selected.filter((v) => v !== value);}+function FacetCount({+ counts,+ value,+}: {+ counts?: Record<string, number>;+ value: string;+}) {+ if (counts === undefined) return null;++ return (+ <span className="ml-2 shrink-0 text-13 text-muted-foreground tabular-nums">+ {counts[value] ?? 0}+ </span>+ );+}+function FacetSubmenu({facet,selected,+ counts,onChange,}: {facet: DataTableFacet;selected: string[];+ counts?: Record<string, number>;onChange: (values: string[]) => void;}) {return (@@ -193,7 +344,13 @@ function FacetSubmenu({<span className="tabular-nums opacity-60">({selected.length})</span>)}</DropdownMenuSubTrigger>- <DropdownMenuSubContent className="max-h-72 min-w-52 overflow-hidden">+ <DropdownMenuSubContent+ className={cn(+ "max-h-72 min-w-52 overflow-hidden",+ facet.searchable && "p-0",+ )}+ sideOffset={4}+ >{facet.searchable ? (<CommandshouldFilter={facet.onSearchChange === undefined}@@ -224,7 +381,8 @@ function FacetSubmenu({checked={checked}className="pointer-events-none"/>- <span className="truncate">{option.label}</span>+ <span className="flex-1 truncate">{option.label}</span>+ <FacetCount counts={counts} value={option.value} /></CommandItem>);})}@@ -232,30 +390,35 @@ function FacetSubmenu({</CommandList></Command>) : (- <div className="max-h-72 overflow-y-auto">+ <div className="max-h-72 overflow-x-hidden overflow-y-auto">{selected.length > 0 && (<>- <DropdownMenuItem onSelect={() => onChange([])}>- Clear- </DropdownMenuItem>+ <DropdownMenuGroup>+ <DropdownMenuItem onSelect={() => onChange([])}>+ Clear+ </DropdownMenuItem>+ </DropdownMenuGroup><DropdownMenuSeparator /></>)}- {facet.options.map((option) => {- const checked = selected.includes(option.value);- return (- <DropdownMenuCheckboxItem- key={option.value}- checked={checked}- onSelect={(event) => event.preventDefault()}- onCheckedChange={(next) =>- onChange(toggle(selected, option.value, next))- }- >- {option.label}- </DropdownMenuCheckboxItem>- );- })}+ <DropdownMenuGroup>+ {facet.options.map((option) => {+ const checked = selected.includes(option.value);+ return (+ <DropdownMenuCheckboxItem+ key={option.value}+ checked={checked}+ onSelect={(event) => event.preventDefault()}+ onCheckedChange={(next) =>+ onChange(toggle(selected, option.value, next))+ }+ >+ <span className="flex-1 truncate">{option.label}</span>+ <FacetCount counts={counts} value={option.value} />+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuGroup></div>)}</DropdownMenuSubContent>@@ -263,6 +426,65 @@ function FacetSubmenu({);}+function ReturnToPage({+ page,+ setPage,+}: {+ page: number;+ setPage: (page: number) => Promise<void>;+}) {+ useMountEffect(() => {+ void setPage(page);+ });++ return null;+}++function SelectionBar<TRow>({+ selection,+ selecting,+}: {+ selection: DataTableSelection<TRow>;+ selecting: boolean;+}) {+ return (+ <div+ aria-hidden={!selecting}+ className={cn(+ "col-start-1 row-start-1 flex h-9 items-center gap-2 self-start",+ !selecting && "invisible",+ )}+ inert={!selecting}+ >+ <span className="truncate text-13 text-muted-foreground">+ <span className="font-medium text-foreground tabular-nums">+ {selection.state.count}+ </span>{" "}+ selected+ </span>+ <div className="ml-auto flex items-center gap-2">+ {selection.actions}+ <Button+ variant="ghost"+ size="sm"+ onClick={() => selection.state.clear()}+ >+ Clear+ </Button>+ </div>+ </div>+ );+}++function CellControl({ children }: { children: ReactNode }) {+ return (+ <span className="inline-flex h-5 items-center">+ {""}+ {children}+ </span>+ );+}+export function DataTable<TRow, TSub = unknown>({query,columns,@@ -270,7 +492,7 @@ export function DataTable<TRow, TSub = unknown>({rows,total,facetCounts,- loading,+ loading = false,facets,tabs,onRowClick,@@ -282,18 +504,17 @@ export function DataTable<TRow, TSub = unknown>({search,meta,empty,+ label,className,- tableClassName,}: DataTableProps<TRow, TSub>) {const [expandedIds, setExpandedIds] = useQueryState("expand",parseAsArrayOf(parseAsString).withDefault([]),);- const expanded = useMemo(() => new Set(expandedIds), [expandedIds]);- const defaultHiddenIds = useMemo(- () => columns.filter((column) => column.defaultHidden).map((c) => c.id),- [columns],- );+ const expanded = new Set(expandedIds);+ const defaultHiddenIds = columns+ .filter((column) => column.defaultHidden)+ .map((column) => column.id);const [hidden, setHidden] = useQueryState("hide",parseAsArrayOf(parseAsString).withDefault(defaultHiddenIds),@@ -324,21 +545,18 @@ export function DataTable<TRow, TSub = unknown>({const pageSize = query.pageSize;const totalPages = Math.max(1, Math.ceil(total / pageSize));+ const pageIsPastEnd = !loading && query.page > totalPages;- const availableFacets = useMemo(- () =>- (facets ?? []).filter(- (facet) =>- facet.options.length > 0 ||- facet.searchable ||- (query.filters[facet.id]?.length ?? 0) > 0,- ),- [facets, query.filters],+ const availableFacets = (facets ?? []).filter(+ (facet) =>+ facet.options.length > 0 ||+ facet.searchable ||+ (query.filters[facet.id]?.length ?? 0) > 0,);const hasFilterControls =tabs != null ||- availableFacets.length > 0 ||+ (facets?.length ?? 0) > 0 ||sortableColumns.length > 0 ||anyExpandable ||hideable.length > 0 ||@@ -350,450 +568,475 @@ export function DataTable<TRow, TSub = unknown>({const activeFilterCount =(tabs && query.tab !== "all" ? 1 : 0) + activeFacetFilterCount;+ const overflow = useOverflowTooltip();++ const showEmpty = deferredRows.length === 0 && !loading;+ const showHeadings = deferredRows.length > 0 || loading;+ const wide =+ visibleColumns.filter((column) => column.hideBelow === undefined).length >+ NARROW_TABLE_COLUMNS;+return (- <div className={cn("flex min-h-0 flex-1 flex-col gap-3", className)}>- {selecting && selection ? (- <div className="flex h-8 items-center gap-2">- <span className="truncate text-xs text-muted-foreground">- <span className="font-medium text-foreground tabular-nums">- {selection.state.count}- </span>{" "}- selected- </span>- <div className="ml-auto flex items-center gap-2">- {selection.actions}- <Button- variant="ghost"- size="sm"- onClick={() => selection.state.clear()}- >- Clear- </Button>- </div>- </div>+ <div+ className={cn(+ "@container/table flex min-h-0 flex-1 flex-col gap-3",+ className,+ )}+ >+ {pageIsPastEnd ? (+ <ReturnToPage+ key={totalPages}+ page={totalPages}+ setPage={query.setPage}+ />) : null}- <div- className={cn(- "flex flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between",- selecting && "hidden",- )}- >- {search}- {hasFilterControls && (- <Button- type="button"- variant="outline"- size="sm"- className="w-full justify-between sm:hidden"- aria-expanded={filtersOpen}- aria-controls={filtersId}- onClick={() => setFiltersOpen((open) => !open)}- >- <span className="flex items-center gap-2">- <Filter />- Filters- {activeFilterCount > 0 && (- <span className="tabular-nums opacity-60">- ({activeFilterCount})- </span>- )}- </span>- <ChevronDown- className={cn(- "shrink-0 opacity-60 transition-transform",- filtersOpen && "rotate-180",- )}- />- </Button>- )}- {/* `lg:contents` so the controls join the search on one row on desktop- while staying a group the Filters button can collapse on mobile —- search itself must never be inside that collapse. */}+ <div className="grid">+ {selection ? (+ <SelectionBar selecting={selecting} selection={selection} />+ ) : null}<div- id={filtersId}+ aria-hidden={selecting || undefined}className={cn(- "flex-col gap-2 lg:contents",- filtersOpen ? "flex" : "hidden sm:flex",+ "col-start-1 row-start-1 flex flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between",+ selecting && "invisible",)}+ inert={selecting}>- {tabs && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- type="button"- variant="outline"- size="sm"- className="w-full justify-between sm:w-auto sm:min-w-44"- >- <span className="truncate">{activeTabLabel}</span>- <ChevronDown className="shrink-0 opacity-60" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="min-w-52">- <DropdownMenuRadioGroup- value={query.tab}- onValueChange={(value) => query.setTab(value)}- >- <DropdownMenuRadioItem value="all">- <span className="flex-1">{tabs.allLabel ?? "All"}</span>- </DropdownMenuRadioItem>- {tabs.options.map((option) => {- if (tabCounts?.[option.value] === 0) return null;- return (- <DropdownMenuRadioItem- key={option.value}- value={option.value}- >- <span className="flex-1">{option.label}</span>- </DropdownMenuRadioItem>- );- })}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ {search}+ {hasFilterControls && (+ <Button+ type="button"+ variant="outline"+ className="w-full justify-between sm:hidden"+ aria-expanded={filtersOpen}+ aria-controls={filtersId}+ onClick={() => setFiltersOpen((open) => !open)}+ >+ <span className="flex items-center gap-2">+ <ListFilterIcon />+ Table options+ {activeFilterCount > 0 && (+ <span className="tabular-nums opacity-60">+ ({activeFilterCount})+ </span>+ )}+ </span>+ <ChevronDownIcon+ className={cn(+ "shrink-0 opacity-60 transition-transform",+ filtersOpen && "rotate-180",+ )}+ />+ </Button>)}+ <div+ id={filtersId}+ className={cn(+ "flex-col gap-2 lg:contents",+ filtersOpen ? "flex" : "hidden sm:flex",+ )}+ >+ {leadingActions}- {leadingActions}-- <div className="grid grid-cols-1 gap-2 sm:flex sm:flex-wrap sm:items-center lg:ml-auto">- {availableFacets.length > 0 && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="sm"- className="justify-start sm:justify-center"- >- <Filter data-icon="inline-start" />- Filters- {activeFacetFilterCount > 0 && (- <span className="tabular-nums opacity-60">- ({activeFacetFilterCount})+ <div className="grid grid-cols-1 gap-2 sm:flex sm:flex-wrap sm:items-center lg:ml-auto">+ {tabs && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="outline"+ className="justify-start sm:justify-center"+ >+ <LayoutListIcon data-icon="inline-start" />+ {tabs.label ?? "View"}+ <span className="truncate opacity-60">+ {activeTabLabel}</span>- )}- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="min-w-48">- {availableFacets.map((facet) => (- <FacetSubmenu- key={facet.id}- facet={facet}- selected={query.filters[facet.id] ?? []}- onChange={(values) => query.setFilter(facet.id, values)}- />- ))}- </DropdownMenuContent>- </DropdownMenu>- )}- {(sortableColumns.length > 0 || anyExpandable) && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="sm"- className="justify-start sm:justify-center"- >- <ArrowsVertical data-icon="inline-start" />- Sort- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="min-w-48">- <DropdownMenuLabel>Sort by</DropdownMenuLabel>- <DropdownMenuRadioGroup- value={query.sort}- onValueChange={query.setSort}- >- {anyExpandable && (- <DropdownMenuRadioItem value="detail">- Detail- </DropdownMenuRadioItem>- )}- {sortableColumns.map((column) => (- <DropdownMenuRadioItem key={column.id} value={column.id}>- {columnLabel(column)}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-52">+ <DropdownMenuRadioGroup+ value={query.tab}+ onValueChange={(value) => query.setTab(value)}+ >+ <DropdownMenuRadioItem value="all">+ <span className="flex-1">{tabs.allLabel ?? "All"}</span></DropdownMenuRadioItem>+ {tabs.options.map((option) => {+ return (+ <DropdownMenuRadioItem+ key={option.value}+ value={option.value}+ disabled={+ tabCounts?.[option.value] === 0 &&+ query.tab !== option.value+ }+ >+ <span className="flex-1">{option.label}</span>+ </DropdownMenuRadioItem>+ );+ })}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {(facets?.length ?? 0) > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ disabled={availableFacets.length === 0}+ className="justify-start sm:justify-center"+ >+ <ListFilterIcon data-icon="inline-start" />+ Filters+ {activeFacetFilterCount > 0 && (+ <span className="tabular-nums opacity-60">+ ({activeFacetFilterCount})+ </span>+ )}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-48">+ {availableFacets.map((facet) => (+ <FacetSubmenu+ key={facet.id}+ counts={facetCounts?.[facet.id]}+ facet={facet}+ selected={query.filters[facet.id] ?? []}+ onChange={(values) => query.setFilter(facet.id, values)}+ />))}- </DropdownMenuRadioGroup>- <DropdownMenuSeparator />- <DropdownMenuRadioGroup- value={query.dir}- onValueChange={(value) =>- query.setDir(value === "desc" ? "desc" : "asc")- }- >- <DropdownMenuRadioItem value="asc">- Ascending- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="desc">- Descending- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- )}- {hideable.length > 0 && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="sm"- className="justify-start sm:justify-center"- >- <Column data-icon="inline-start" />- Columns- <span className="tabular-nums opacity-60">- ({visibleColumns.length})- </span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="min-w-48">- <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>- {hideable.map((column) => (- <DropdownMenuCheckboxItem- key={column.id}- checked={!hidden.includes(column.id)}- onCheckedChange={(checked) =>- setHidden((prev) => {- const set = new Set(prev);- if (checked) set.delete(column.id);- else set.add(column.id);- return [...set];- })+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {(sortableColumns.length > 0 || anyExpandable) && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ className="justify-start sm:justify-center"+ >+ <ArrowUpDownIcon data-icon="inline-start" />+ Sort+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-48">+ <DropdownMenuRadioGroup+ value={query.sort}+ onValueChange={query.setSort}+ >+ <DropdownMenuLabel>Sort by</DropdownMenuLabel>+ {anyExpandable && (+ <DropdownMenuRadioItem value="detail">+ Detail+ </DropdownMenuRadioItem>+ )}+ {sortableColumns.map((column) => (+ <DropdownMenuRadioItem+ key={column.id}+ value={column.id}+ >+ {columnLabel(column)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator />+ <DropdownMenuRadioGroup+ value={query.dir}+ onValueChange={(value) =>+ query.setDir(value === "desc" ? "desc" : "asc")}>- {columnLabel(column)}- </DropdownMenuCheckboxItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- )}- {actions}+ <DropdownMenuRadioItem value="asc">+ Ascending+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="desc">+ Descending+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {hideable.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ className="justify-start sm:justify-center"+ >+ <Columns3Icon data-icon="inline-start" />+ Columns+ <span className="tabular-nums opacity-60">+ (+ {+ visibleColumns.filter(+ (column) => column.hideable !== false,+ ).length+ }+ )+ </span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-48">+ <DropdownMenuGroup>+ <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>+ {hideable.map((column) => (+ <DropdownMenuCheckboxItem+ key={column.id}+ checked={!hidden.includes(column.id)}+ onSelect={(event) => event.preventDefault()}+ onCheckedChange={(checked) =>+ setHidden((prev) => {+ const set = new Set(prev);+ if (checked) set.delete(column.id);+ else set.add(column.id);+ return [...set];+ })+ }+ >+ {columnLabel(column)}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {actions}+ </div></div></div></div>- <Table- className={cn(- "table-fixed [&_td:first-child]:pl-4 [&_th:first-child]:pl-4 [&_td:last-child]:pr-4 [&_th:last-child]:pr-4",- tableClassName,- )}- containerClassName="min-h-0 flex-1 overflow-auto rounded-lg border bg-card"+ <TableFrame+ label={label}overlay={- deferredRows.length === 0 ? (- <div className="absolute inset-x-0 top-11 bottom-0 flex items-center justify-center px-4 py-8 text-center text-muted-foreground">- {loading ? <Spinner /> : (empty ?? "No results found.")}+ showEmpty ? (+ <div className={TABLE_EMPTY_OVERLAY_CLASS}>+ {typeof empty === "string" || empty == null ? (+ <p className="text-muted-foreground">+ {empty ?? "No results found."}+ </p>+ ) : (+ empty+ )}</div>) : null}>- <TableHeader className="sticky top-0 z-10 bg-muted [&_th]:bg-muted [&_tr]:border-0 [&_tr]:shadow-[inset_0_-1px_0_var(--border)]">- <TableRow>- {selection && (- <TableHead className={cn("h-11 w-10 px-3", HIDE_BELOW_CLASS.sm)}>- <Checkbox- checked={- selection.state.allSelected- ? true- : selection.state.someSelected- ? "indeterminate"- : false- }- onCheckedChange={(checked) =>- selection.state.toggleAll(checked === true)- }- disabled={deferredRows.length === 0}- aria-label="Select every row on this page"- />- </TableHead>- )}- {anyExpandable && (- <TableHead className="h-11 w-10 px-3">- <span className="sr-only">Detail</span>- </TableHead>- )}- {visibleColumns.map((column) => {- const isActive = query.sort === column.id;- return (- <TableHead- key={column.id}- className={cn(- "h-11 overflow-hidden px-3 font-normal text-muted-foreground",- column.width,- ALIGN_CLASS[column.align ?? "left"],- column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],- column.headClassName,- )}- aria-sort={- isActive- ? query.dir === "asc"- ? "ascending"- : "descending"- : undefined- }- >- {column.sortable ? (- <Button- variant="ghost"- size="xs"- onClick={() => query.toggleSort(column.id)}- className={cn(- "-ml-2 font-normal text-muted-foreground hover:text-foreground",- column.align === "right" && "-mr-2 ml-0 flex-row-reverse",- column.align === "center" && "mx-auto",- )}- >- {column.header}- <SortIndicator active={isActive} dir={query.dir} />- </Button>- ) : (- column.header- )}- </TableHead>- );- })}- </TableRow>- </TableHeader>- <TableBody>- {deferredRows.map((row) => {- const id = getRowId(row);- const canExpand = expandable?.isExpandable(row) ?? false;- const isOpen = canExpand && expanded.has(id);- const isSelected = selection?.state.has(id) ?? false;- const clickable = canExpand || !!onRowClick;- const handleClick = () => {- if (canExpand) {- setExpandedIds((prev) => {- const set = new Set(prev ?? []);- if (set.has(id)) set.delete(id);- else set.add(id);- const next = [...set];- return next.length > 0 ? next : null;- });- } else {- onRowClick?.(row);- }- };- return (- <Fragment key={id}>- <TableRow- data-state={isSelected ? "selected" : undefined}- onClick={clickable ? handleClick : undefined}- onMouseEnter={onRowHover ? () => onRowHover(row) : undefined}- onFocus={onRowHover ? () => onRowHover(row) : undefined}- className={- clickable- ? anyExpandable- ? ROW_ACCENT_EXPANDABLE- : ROW_ACCENT- : undefined- }- >- {selection && (- <TableCell- className={cn("w-10 px-3 py-3", HIDE_BELOW_CLASS.sm)}- onClick={(event) => event.stopPropagation()}+ <Table+ {...overflow.handlers}+ aria-busy={loading || undefined}+ className={cn(TABLE_CLASS, wide && "min-w-lg")}+ >+ {showHeadings ? (+ <TableHeader className={TABLE_HEADER_CLASS}>+ <TableRow>+ {selection && (+ <TableHead+ className={cn("h-10 w-10 px-3", COLUMN_LAYOUT_CLASS)}+ data-hide-below="sm"+ >+ {deferredRows.length > 0 && (+ <CellControl>+ <Checkbox+ checked={+ selection.state.allSelected+ ? true+ : selection.state.someSelected+ ? "indeterminate"+ : false+ }+ onCheckedChange={(checked) =>+ selection.state.toggleAll(checked === true)+ }+ aria-label="Select every row on this page"+ />+ </CellControl>+ )}+ </TableHead>+ )}+ {anyExpandable && (+ <TableHead className="h-10 w-10 px-3">+ <span className="sr-only">Detail</span>+ </TableHead>+ )}+ {visibleColumns.map((column) => {+ const isActive = query.sort === column.id;+ return (+ <TableHead+ key={column.id}+ {...columnLayout(column)}+ className={COLUMN_HEAD_CLASS}+ aria-sort={+ isActive+ ? query.dir === "asc"+ ? "ascending"+ : "descending"+ : undefined+ }>- <Checkbox- checked={isSelected}- onCheckedChange={(checked) =>- selection.state.toggle(id, checked === true)- }- aria-label={- selection.rowLabel- ? `Select ${selection.rowLabel(row)}`- : "Select row"- }- />- </TableCell>- )}- {anyExpandable && (- <TableCell className="w-10 px-3 py-3 text-center text-muted-foreground">- {canExpand && (- <ChevronRight- size={12}+ {column.sortable ? (+ <Button+ variant="ghost"+ size="xs"+ onClick={() => query.toggleSort(column.id)}className={cn(- "inline-block transition-transform",- isOpen && "rotate-90",+ "-ml-2 font-medium text-13 text-muted-foreground hover:text-foreground",+ column.align === "right" &&+ "-mr-2 ml-0 flex-row-reverse",+ column.align === "center" && "mx-auto",)}- />- )}- </TableCell>- )}- {visibleColumns.map((column) => (- <TableCell- key={column.id}- className={cn(- "overflow-hidden px-3 py-3",- column.width,- ALIGN_CLASS[column.align ?? "left"],- column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],- column.cellClassName,+ >+ {column.header}+ <SortIndicator active={isActive} dir={query.dir} />+ </Button>+ ) : (+ column.header)}- >- {column.cell(row)}- </TableCell>- ))}- </TableRow>- {isOpen &&- expandable?.getSubRows(row).map((sub) => {- const subClickable = !!expandable.onSubRowClick;- return (- <TableRow- key={expandable.getSubRowId(sub, row)}- onClick={- subClickable- ? () => expandable.onSubRowClick?.(sub, row)- : undefined- }- className={cn(- "bg-muted/30",- subClickable &&- (anyExpandable- ? ROW_ACCENT_EXPANDABLE- : ROW_ACCENT),- )}+ </TableHead>+ );+ })}+ </TableRow>+ </TableHeader>+ ) : null}+ <TableBody>+ {loading && deferredRows.length === 0 ? (+ <LoadingRows+ columns={visibleColumns}+ expandable={anyExpandable}+ selectable={!!selection}+ />+ ) : null}+ {deferredRows.map((row) => {+ const id = getRowId(row);+ const canExpand = expandable?.isExpandable(row) ?? false;+ const isOpen = canExpand && expanded.has(id);+ const isSelected = selection?.state.has(id) ?? false;+ const clickable = canExpand || !!onRowClick;+ const handleClick = () => {+ if (canExpand) {+ setExpandedIds((prev) => {+ const set = new Set(prev ?? []);+ if (set.has(id)) set.delete(id);+ else set.add(id);+ const next = [...set];+ return next.length > 0 ? next : null;+ });+ } else {+ onRowClick?.(row, deferredRows);+ }+ };+ return (+ <Fragment key={id}>+ <TableRow+ data-state={isSelected ? "selected" : undefined}+ aria-expanded={canExpand ? isOpen : undefined}+ onClick={clickable ? handleClick : undefined}+ onMouseEnter={+ onRowHover ? () => onRowHover(row) : undefined+ }+ onFocus={onRowHover ? () => onRowHover(row) : undefined}+ className={cn(clickable && ROW_ACCENT)}+ >+ {selection && (+ <TableCell+ className={cn("w-10 px-3 py-3", COLUMN_LAYOUT_CLASS)}+ data-hide-below="sm"+ onClick={(event) => event.stopPropagation()}>- {selection && (- <TableCell+ <CellControl>+ <Checkbox+ checked={isSelected}+ onCheckedChange={(checked) =>+ selection.state.toggle(id, checked === true)+ }+ aria-label={+ selection.rowLabel+ ? `Select ${selection.rowLabel(row)}`+ : "Select row"+ }+ />+ </CellControl>+ </TableCell>+ )}+ {anyExpandable && (+ <TableCell className="w-10 px-3 py-3 text-center text-muted-foreground">+ {canExpand && (+ <ChevronRightIcon+ size={16}className={cn(- "w-10 px-3 py-2.5",- HIDE_BELOW_CLASS.sm,+ "inline-block transition-transform",+ isOpen && "rotate-90",)}/>)}- {anyExpandable && (- <TableCell className="w-10 px-3 py-2.5" />- )}- {visibleColumns.map((column) => (- <TableCell- key={column.id}- className={cn(- "overflow-hidden px-3 py-2.5 align-top",- column.width,- ALIGN_CLASS[column.align ?? "left"],- column.hideBelow &&- HIDE_BELOW_CLASS[column.hideBelow],- column.cellClassName,- )}- >- {expandable.renderSubCell(sub, column.id, row)}- </TableCell>- ))}- </TableRow>- );- })}- </Fragment>- );- })}- </TableBody>- </Table>+ </TableCell>+ )}+ {visibleColumns.map((column) => (+ <TableCell+ key={column.id}+ {...columnLayout(column)}+ className={cn(COLUMN_CELL_CLASS, "py-3")}+ >+ {column.cell(row)}+ </TableCell>+ ))}+ </TableRow>+ {isOpen &&+ expandable?.getSubRows(row).map((sub) => {+ const subClickable = !!expandable.onSubRowClick;+ return (+ <TableRow+ key={expandable.getSubRowId(sub, row)}+ onClick={+ subClickable+ ? () => expandable.onSubRowClick?.(sub, row)+ : undefined+ }+ className={cn(+ "bg-muted/30",+ subClickable && ROW_ACCENT,+ )}+ >+ {selection && (+ <TableCell+ className={cn(+ "w-10 px-3 py-2.5",+ COLUMN_LAYOUT_CLASS,+ )}+ data-hide-below="sm"+ />+ )}+ {anyExpandable && (+ <TableCell className="w-10 px-3 py-2.5" />+ )}+ {visibleColumns.map((column) => (+ <TableCell+ key={column.id}+ {...columnLayout(column)}+ className={cn(COLUMN_CELL_CLASS, "py-2.5")}+ >+ {expandable.renderSubCell(sub, column.id, row)}+ </TableCell>+ ))}+ </TableRow>+ );+ })}+ </Fragment>+ );+ })}+ </TableBody>+ </Table>+ </TableFrame>+ {overflow.tooltip}<TablePaginationpage={query.page}totalPages={totalPages}pageSize={pageSize}total={total}- onPageChange={(page) => query.setPage(page)}+ onPageChange={(page) => void query.setPage(page)}loading={loading}meta={meta}/>diff --git a/packages/ui/src/components/date-picker.tsx b/packages/ui/src/components/date-picker.tsxindex f6bcb138..3cc474db 100644--- a/packages/ui/src/components/date-picker.tsx+++ b/packages/ui/src/components/date-picker.tsx@@ -1,6 +1,5 @@"use client";-import CalendarGlyph from "@carbon/icons-react/es/Calendar";import { Button } from "@crm/ui/components/button";import { Calendar } from "@crm/ui/components/calendar";import { Icon } from "@crm/ui/components/icon";@@ -13,6 +12,7 @@ import { selectTriggerVariants } from "@crm/ui/components/select";import { formatDay, fromDay, toDay } from "@crm/ui/lib/format";import { cn } from "@crm/ui/lib/utils";import type { VariantProps } from "class-variance-authority";+import { CalendarIcon } from "lucide-react";import { useState } from "react";export function DatePicker({@@ -51,7 +51,7 @@ export function DatePicker({{selected ? formatDay(value) : placeholder}</span><Icon- icon={CalendarGlyph}+ icon={CalendarIcon}className="size-4 text-muted-foreground transition-opacity"/></button>diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsxindex 7f86323f..698a2477 100644--- a/packages/ui/src/components/dialog.tsx+++ b/packages/ui/src/components/dialog.tsx@@ -38,7 +38,7 @@ function DialogOverlay({<DialogPrimitive.Overlaydata-slot="dialog-overlay"className={cn(- "fixed inset-0 isolate z-50 bg-overlay duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 isolate z-50 bg-overlay duration-200 ease-spring data-closed:duration-100 data-closed:ease-out data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className,)}{...props}@@ -60,7 +60,7 @@ function DialogContent({<DialogPrimitive.Contentdata-slot="dialog-content"className={cn(- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg bg-popover p-4 text-xs/relaxed text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground shadow-modal duration-200 ease-spring outline-none sm:max-w-128 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",className,)}{...props}@@ -70,7 +70,7 @@ function DialogContent({<DialogPrimitive.Close data-slot="dialog-close" asChild><Buttonvariant="ghost"- className="absolute top-2 right-2"+ className="absolute top-4 right-4"size="icon-sm"><XIcon />@@ -87,7 +87,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="dialog-header"- className={cn("flex flex-col gap-1 text-left", className)}+ className={cn("flex flex-col gap-2 text-left", className)}{...props}/>);@@ -105,7 +105,7 @@ function DialogFooter({<divdata-slot="dialog-footer"className={cn(- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",+ "-mx-6 -mb-6 mt-2 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-sidebar px-6 py-3 sm:flex-row sm:justify-end",className,)}{...props}@@ -128,7 +128,7 @@ function DialogTitle({<DialogPrimitive.Titledata-slot="dialog-title"className={cn(- "font-heading text-sm font-medium wrap-anywhere",+ "font-heading text-xl leading-tight font-semibold tracking-tight wrap-anywhere",className,)}{...props}@@ -144,7 +144,7 @@ function DialogDescription({<DialogPrimitive.Descriptiondata-slot="dialog-description"className={cn(- "text-xs/relaxed text-muted-foreground wrap-anywhere *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",+ "text-sm text-muted-foreground wrap-anywhere *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",className,)}{...props}diff --git a/packages/ui/src/components/discard-changes.tsx b/packages/ui/src/components/discard-changes.tsxnew file mode 100644index 00000000..ce854d84--- /dev/null+++ b/packages/ui/src/components/discard-changes.tsx@@ -0,0 +1,99 @@+"use client";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@crm/ui/components/alert-dialog";+import { useRef, useState } from "react";++type DiscardWording = {+ title: string;+ description: string;+ confirmLabel: string;+ keepLabel: string;+};++function useDiscardChanges({+ open,+ dirty,+ pending = false,+ onOpenChange,+ onDiscard,+ wording = {+ title: "Discard changes?",+ description: "Your changes have not been saved. Discard them and close?",+ confirmLabel: "Discard",+ keepLabel: "Keep editing",+ },+}: {+ open: boolean;+ dirty: boolean;+ pending?: boolean;+ onOpenChange: (open: boolean) => void;+ onDiscard?: () => void;+ wording?: DiscardWording;+}) {+ const [asking, setAsking] = useState(false);+ const returnFocus = useRef<HTMLElement | null>(null);++ const discard = () => {+ if (pending) return;+ setAsking(false);+ returnFocus.current = null;+ onDiscard?.();+ onOpenChange(false);+ };++ const changeOpen = (next: boolean) => {+ if (!next && pending) return;+ if (!next && dirty) {+ returnFocus.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ setAsking(true);+ return;+ }+ setAsking(false);+ onOpenChange(next);+ };++ const dialog = (+ <AlertDialog open={open && asking} onOpenChange={setAsking}>+ <AlertDialogContent+ onCloseAutoFocus={(event) => {+ if (!asking && open && returnFocus.current?.isConnected) {+ event.preventDefault();+ returnFocus.current.focus();+ returnFocus.current = null;+ }+ }}+ >+ <AlertDialogHeader>+ <AlertDialogTitle>{wording.title}</AlertDialogTitle>+ <AlertDialogDescription>{wording.description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{wording.keepLabel}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={pending}+ onClick={discard}+ >+ {wording.confirmLabel}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );++ return { onOpenChange: changeOpen, discard, dialog };+}++export { type DiscardWording, useDiscardChanges };diff --git a/packages/ui/src/components/drawer.tsx b/packages/ui/src/components/drawer.tsxindex 67a2b60f..e3e87f61 100644--- a/packages/ui/src/components/drawer.tsx+++ b/packages/ui/src/components/drawer.tsx@@ -9,7 +9,7 @@ const drawerTitleVariants = cva("font-heading font-medium text-foreground", {variants: {size: {default: "text-sm",- lg: "text-lg leading-tight tracking-tight",+ lg: "text-lg leading-tight font-semibold tracking-tight",},},defaultVariants: {@@ -49,7 +49,7 @@ function DrawerOverlay({<DrawerPrimitive.Overlaydata-slot="drawer-overlay"className={cn(- "fixed inset-0 z-50 bg-overlay supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 z-50 min-h-dvh bg-overlay data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className,)}{...props}@@ -68,12 +68,12 @@ function DrawerContent({<DrawerPrimitive.Contentdata-slot="drawer-content"className={cn(- "group/drawer-content fixed z-50 flex h-auto flex-col bg-popover text-xs/relaxed text-popover-foreground data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-none data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:rounded-none data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:rounded-none data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-none data-[vaul-drawer-direction=top]:border-b data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm",+ "group/drawer-content fixed z-50 flex h-auto flex-col bg-popover text-sm text-popover-foreground outline-none data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[calc(100dvh-6rem)] data-[vaul-drawer-direction=bottom]:rounded-t-xl data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:rounded-r-xl data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:rounded-l-xl data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[calc(100dvh-6rem)] data-[vaul-drawer-direction=top]:rounded-b-xl data-[vaul-drawer-direction=top]:border-b data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm",className,)}{...props}>- <div className="mx-auto mt-4 hidden h-1 w-[100px] shrink-0 rounded-none bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />+ <div className="mx-auto mt-3 hidden h-1.5 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />{children}</DrawerPrimitive.Content></DrawerPortal>@@ -85,7 +85,7 @@ function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="drawer-header"className={cn(- "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-0.5 md:text-left",+ "flex shrink-0 flex-col gap-0.5 p-4 pb-0 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",className,)}{...props}@@ -97,7 +97,7 @@ function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="drawer-footer"- className={cn("mt-auto flex flex-col gap-2 p-4", className)}+ className={cn("mt-auto flex shrink-0 flex-col gap-2 p-4 pt-0", className)}{...props}/>);@@ -125,7 +125,7 @@ function DrawerDescription({return (<DrawerPrimitive.Descriptiondata-slot="drawer-description"- className={cn("text-xs/relaxed text-muted-foreground", className)}+ className={cn("text-sm text-balance text-muted-foreground", className)}{...props}/>);diff --git a/packages/ui/src/components/dropdown-menu.tsx b/packages/ui/src/components/dropdown-menu.tsxindex 8936b287..68ed18df 100644--- a/packages/ui/src/components/dropdown-menu.tsx+++ b/packages/ui/src/components/dropdown-menu.tsx@@ -43,7 +43,7 @@ function DropdownMenuContent({sideOffset={sideOffset}align={align}className={cn(- "z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 max-h-(--radix-dropdown-menu-content-available-height) w-max min-w-48 max-w-80 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-xl bg-popover p-1.5 text-popover-foreground shadow-menu duration-200 ease-spring outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",className,)}{...props}@@ -75,7 +75,7 @@ function DropdownMenuItem({data-inset={inset}data-variant={variant}className={cn(- "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-lg px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",+ "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",className,)}{...props}@@ -97,7 +97,7 @@ function DropdownMenuCheckboxItem({data-slot="dropdown-menu-checkbox-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-2 rounded-sm py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}checked={checked}@@ -140,7 +140,7 @@ function DropdownMenuRadioItem({data-slot="dropdown-menu-radio-item"data-inset={inset}className={cn(- "relative flex cursor-default items-center gap-2 rounded-sm py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "relative flex cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}@@ -170,7 +170,7 @@ function DropdownMenuLabel({data-slot="dropdown-menu-label"data-inset={inset}className={cn(- "px-2 py-2 text-xs text-muted-foreground data-inset:pl-7",+ "px-2 py-1.5 text-xs font-medium text-muted-foreground data-inset:pl-8",className,)}{...props}@@ -185,7 +185,7 @@ function DropdownMenuSeparator({return (<DropdownMenuPrimitive.Separatordata-slot="dropdown-menu-separator"- className={cn("-mx-1 h-px bg-border", className)}+ className={cn("-mx-1.5 my-1 h-px bg-border", className)}{...props}/>);@@ -226,13 +226,13 @@ function DropdownMenuSubTrigger({data-slot="dropdown-menu-sub-trigger"data-inset={inset}className={cn(- "flex cursor-default items-center gap-2 rounded-sm px-2 py-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-8 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",className,)}{...props}>{children}- <ChevronRightIcon className="ml-auto" />+ <ChevronRightIcon className="ml-auto text-muted-foreground" /></DropdownMenuPrimitive.SubTrigger>);}@@ -245,7 +245,7 @@ function DropdownMenuSubContent({<DropdownMenuPrimitive.SubContentdata-slot="dropdown-menu-sub-content"className={cn(- "z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 max-h-(--radix-dropdown-menu-content-available-height) w-max min-w-48 max-w-80 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-xl bg-popover p-1.5 text-popover-foreground shadow-menu duration-200 ease-spring outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",className,)}{...props}diff --git a/packages/ui/src/components/empty-cell.tsx b/packages/ui/src/components/empty-cell.tsxindex f369d6e2..09c776dd 100644--- a/packages/ui/src/components/empty-cell.tsx+++ b/packages/ui/src/components/empty-cell.tsx@@ -1,5 +1,5 @@import { cn } from "../lib/utils";export function EmptyCellValue({ className }: { className?: string }) {- return <span className={cn("text-muted-foreground", className)}>—</span>;+ return <span className={cn("sr-only", className)}>None</span>;}diff --git a/packages/ui/src/components/empty.tsx b/packages/ui/src/components/empty.tsxindex 053a9180..1cafc316 100644--- a/packages/ui/src/components/empty.tsx+++ b/packages/ui/src/components/empty.tsx@@ -2,7 +2,7 @@ import { cn } from "@crm/ui/lib/utils";import { cva, type VariantProps } from "class-variance-authority";const emptyVariants = cva(- "group/empty flex w-full min-w-0 flex-col items-center justify-center gap-4 rounded-lg border-dashed px-6 py-12 text-center text-balance",+ "group/empty flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-md border-dashed p-8 text-center text-balance",{variants: {width: {@@ -46,12 +46,12 @@ function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {}const emptyMediaVariants = cva(- "mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",+ "flex shrink-0 items-center justify-center in-data-[slot=empty-header]:mb-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",{variants: {variant: {default: "bg-transparent",- icon: "flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4",+ icon: "flex size-10 shrink-0 items-center justify-center rounded-lg bg-background text-muted-foreground shadow-border [&_svg:not([class*='size-'])]:size-5",},},defaultVariants: {@@ -79,7 +79,10 @@ function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="empty-title"- className={cn("font-heading text-sm font-medium", className)}+ className={cn(+ "font-heading text-base font-semibold tracking-tight text-foreground",+ className,+ )}{...props}/>);@@ -90,7 +93,7 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {<divdata-slot="empty-description"className={cn(- "text-balance text-xs/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",+ "text-sm text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",className,)}{...props}@@ -99,7 +102,7 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {}const emptyContentVariants = cva(- "flex w-full max-w-sm min-w-0 items-center gap-2.5 text-xs text-balance group-data-[width=wide]/empty:max-w-2xl",+ "flex w-full max-w-sm min-w-0 items-center gap-4 text-sm text-balance group-data-[width=wide]/empty:max-w-2xl",{variants: {layout: {diff --git a/packages/ui/src/components/evilcharts/LICENSE b/packages/ui/src/components/evilcharts/LICENSEnew file mode 100644index 00000000..49228a95--- /dev/null+++ b/packages/ui/src/components/evilcharts/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Gurbinder++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/ui/src/components/evilcharts/REGISTRY.md b/packages/ui/src/components/evilcharts/REGISTRY.mdnew file mode 100644index 00000000..30805922--- /dev/null+++ b/packages/ui/src/components/evilcharts/REGISTRY.md@@ -0,0 +1,24 @@+# EvilCharts ECharts source++Upstream: https://evilcharts.com+Source: https://github.com/legions-developer/evilcharts+License: MIT. The complete notice is in LICENSE.++The official shadcn registry supplies area, bar, and pie components.+Their shared UI modules use Apache ECharts with Canvas by default.+Each root also supports the SVG renderer.++Installed with Bun in packages/ui:++```sh+bunx --bun shadcn@latest add @evilcharts/echarts-area-chart @evilcharts/echarts-bar-chart @evilcharts/echarts-pie-chart+```++packages/ui/components.json owns the registry namespace.+CRM adaptations fix local imports and React lifecycle integration.+Dashboard wrappers preserve reporting-currency values and accessible summaries.++Tooltips add exact-value formatting and controlled keyboard markers.+Keyboard tooltip updates account for native ECharts refresh timing.+Bottom positioning keeps donut totals visible.+Option updates retain tooltip state and remove obsolete series.diff --git a/packages/ui/src/components/evilcharts/charts/echarts-area-chart.tsx b/packages/ui/src/components/evilcharts/charts/echarts-area-chart.tsxnew file mode 100644index 00000000..59c90344--- /dev/null+++ b/packages/ui/src/components/evilcharts/charts/echarts-area-chart.tsx@@ -0,0 +1,2076 @@+"use client";+import { LineChart, type LineSeriesOption } from "echarts/charts";+import {+ DataZoomComponent,+ type DataZoomComponentOption,+ GridComponent,+ type GridComponentOption,+ TooltipComponent,+ type TooltipComponentOption,+} from "echarts/components";+import type { ComposeOption, ImagePatternObject } from "echarts/core";+import * as echarts from "echarts/core";+import {+ Children,+ type CSSProperties,+ type FC,+ isValidElement,+ type ReactNode,+ useCallback,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ Brush,+ type BrushGeometry,+ type BrushOverlayElements,+ type BrushProps,+ type BrushRange,+ buildBrushDataZoom,+ syncBrushOverlay,+} from "../ui/echarts-brush";+import {+ buildChartCss,+ type ChartConfig,+ type ChartRow,+ DEFAULT_ECHARTS_RENDERER,+ type EChartsRenderer,+ finiteSum,+ finiteValue,+ flattenColor,+ getColorsCount,+ type ResolvedColors,+ resolveColors,+ seriesPaint,+ withAlpha,+} from "../ui/echarts-chart";+import { ECHARTS_CONFIG } from "../ui/echarts-config";+import {+ type DotVariant,+ dotItemStyle,+ dotStyle,+ sampleGradient,+} from "../ui/echarts-dot";+import { LegendOverlay, type LegendVariant } from "../ui/echarts-legend";+import {+ boundedIndex,+ cancelActiveTooltip,+ observeChartTheme,+ showActiveIndex,+ useChartLifecycle,+ useReducedMotion,+} from "../ui/echarts-lifecycle";+import { setChartOption } from "../ui/echarts-options";+import {+ type TooltipPosition,+ type TooltipRoundness,+ type TooltipVariant,+ tooltipBaseOption,+ tooltipIndicatorHtml,+ tooltipRow,+ tooltipShell,+} from "../ui/echarts-tooltip";++export type {+ ChartConfig,+ DotVariant,+ EChartsRenderer,+ LegendVariant,+ TooltipPosition,+ TooltipRoundness,+ TooltipVariant,+};++echarts.use([LineChart, GridComponent, TooltipComponent, DataZoomComponent]);+type EChartsInstance = ReturnType<typeof echarts.init>;+type EChartsOption = ComposeOption<+ | LineSeriesOption+ | GridComponentOption+ | TooltipComponentOption+ | DataZoomComponentOption+>;+type ArrayItem<T> = T extends readonly (infer U)[] ? U : T;+type XAxisOption = ArrayItem<NonNullable<EChartsOption["xAxis"]>>;+type YAxisOption = ArrayItem<NonNullable<EChartsOption["yAxis"]>>;+const {+ STROKE_WIDTH,+ LOADING_ANIMATION_DURATION,+ REVEAL_DURATION,+ LOADING_DEFAULT_POINTS,+ BUFFER_DASH,+ GRID_LINE_OPACITY,+ AXIS_POINTER_OPACITY,+ LOADING_STROKE_OPACITY,+ LOADING_SHIMMER_MAX_OPACITY,+ LOADING_SHIMMER_BAND,+ LOADING_SHIMMER_FEATHER,+ BRUSH_STROKE_OPACITY,+ BRUSH_FILL_OPACITY,+ BRUSH_FILLER_OPACITY,+ BUFFER_PREFIX,+ BUFFERFILL_PREFIX,+ REVEAL_PREFIX,+} = ECHARTS_CONFIG.area;++export type AreaVariant =+ | "gradient"+ | "gradient-reverse"+ | "solid"+ | "dotted"+ | "lines"+ | "hatched"+ | "none";+export type StrokeVariant = "solid" | "dashed" | "animated-dashed";+export type StackType = "default" | "stacked" | "expanded";+export type AreaAnimationType =+ | "none"+ | "left-to-right"+ | "right-to-left"+ | "center-out"+ | "edges-in";+export type CurveType =+ | "linear"+ | "smooth"+ | "bump"+ | "monotone"+ | "monotoneX"+ | "monotoneY"+ | "natural"+ | "step";+export interface EChartsAreaChartProps<TData extends ChartRow> {+ data: TData[];+ config: ChartConfig;+ renderer?: EChartsRenderer;+ xDataKey?: keyof TData & string;+ className?: string;+ curveType?: CurveType;+ stackType?: StackType;+ animation?: boolean;+ animationType?: AreaAnimationType;+ enableHoverHighlight?: boolean;+ enableHoverReveal?: boolean;+ defaultSelectedDataKey?: string | null;+ selectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+ isLoading?: boolean;+ loadingPoints?: number;+ chartOptions?: EChartsOption;+ activeIndex?: number | null;+ onHoverIndexChange?: (index: number | null) => void;+ children?: ReactNode;+}+export interface AreaProps {+ dataKey: string;+ variant?: AreaVariant;+ strokeVariant?: StrokeVariant;+ strokeWidth?: number;+ curveType?: CurveType;+ animationType?: AreaAnimationType;+ connectNulls?: boolean;+ isClickable?: boolean;+ enableBufferLine?: boolean;+ children?: ReactNode;+}+const Area: FC<AreaProps> = () => null;+export interface DotProps {+ variant?: DotVariant;+}+const Dot: FC<DotProps> = () => null;+const ActiveDot: FC<DotProps> = () => null;+export interface XAxisProps {+ dataKey?: string;+ tickFormatter?: (value: string, index: number) => string;+ label?: string;+ hideDots?: boolean;+}+const XAxis: FC<XAxisProps> = () => null;+export interface YAxisProps {+ dataKey?: string;+ tickFormatter?: (value: number, index: number) => string;+ label?: string;+ hideDots?: boolean;+}+const YAxis: FC<YAxisProps> = () => null;+const Grid: FC = () => null;+export interface TooltipProps {+ variant?: TooltipVariant;+ roundness?: TooltipRoundness;+ cursor?: boolean;+ position?: TooltipPosition;+ valueFormatter?: (value: number) => string;+}+const Tooltip: FC<TooltipProps> = () => null;+export interface LegendProps {+ variant?: LegendVariant;+ align?: "left" | "center" | "right";+ verticalAlign?: "top" | "middle" | "bottom";+ isClickable?: boolean;+}+const Legend: FC<LegendProps> = () => null;+type AreaSeriesConfig = {+ dataKey: string;+ variant: AreaVariant;+ strokeVariant: StrokeVariant;+ strokeWidth: number;+ curveType?: CurveType;+ animationType?: AreaAnimationType;+ connectNulls: boolean;+ isClickable: boolean;+ enableBufferLine: boolean;+ dotVariant: DotVariant;+ activeDotVariant: DotVariant;+};+type XAxisSlot = {+ present: boolean;+ dataKey?: string;+ tickFormatter?: (value: string, index: number) => string;+ label?: string;+ hideDots: boolean;+};+type YAxisSlot = {+ present: boolean;+ dataKey?: string;+ tickFormatter?: (value: number, index: number) => string;+ label?: string;+ hideDots: boolean;+};+type TooltipSlot = {+ valueFormatter?: (value: number) => string;+ present: boolean;+ variant: TooltipVariant;+ roundness: TooltipRoundness;+ cursor: boolean;+ position: TooltipPosition;+};+type LegendSlot = {+ present: boolean;+ variant: LegendVariant;+ align: "left" | "center" | "right";+ verticalAlign: "top" | "middle" | "bottom";+ isClickable: boolean;+};+type BrushSlot = {+ present: boolean;+ height?: number;+ formatLabel?: (value: string, index: number) => string;+ onChange?: (range: { startIndex: number; endIndex: number }) => void;+};+type CollectedConfig = {+ areas: AreaSeriesConfig[];+ xAxis: XAxisSlot;+ yAxis: YAxisSlot;+ showGrid: boolean;+ tooltip: TooltipSlot;+ legend: LegendSlot;+ brush: BrushSlot;+};+function collectConfig(children: ReactNode): CollectedConfig {+ const areas: AreaSeriesConfig[] = [];+ let xAxis: XAxisSlot = { present: false, hideDots: false };+ let yAxis: YAxisSlot = { present: false, hideDots: false };+ let showGrid = false;+ let tooltip: TooltipSlot = {+ present: false,+ variant: "default",+ roundness: "lg",+ cursor: true,+ position: "variable",+ };+ let legend: LegendSlot = {+ present: false,+ variant: "rounded-square",+ align: "right",+ verticalAlign: "top",+ isClickable: false,+ };+ let brush: BrushSlot = { present: false };+ Children.forEach(children, (child) => {+ if (!isValidElement(child)) return;+ const type = child.type;+ if (type === Area) {+ const props = child.props as AreaProps;+ let dotVariant: DotVariant = "none";+ let activeDotVariant: DotVariant = "none";+ Children.forEach(props.children, (dotChild) => {+ if (!isValidElement(dotChild)) return;+ if (dotChild.type === Dot) {+ dotVariant = (dotChild.props as DotProps).variant ?? "default";+ } else if (dotChild.type === ActiveDot) {+ activeDotVariant = (dotChild.props as DotProps).variant ?? "default";+ }+ });+ areas.push({+ dataKey: props.dataKey,+ variant: props.variant ?? "gradient",+ strokeVariant: props.strokeVariant ?? "dashed",+ strokeWidth: props.strokeWidth ?? STROKE_WIDTH,+ curveType: props.curveType,+ animationType: props.animationType,+ connectNulls: props.connectNulls ?? false,+ isClickable: props.isClickable ?? false,+ enableBufferLine: props.enableBufferLine ?? false,+ dotVariant,+ activeDotVariant,+ });+ } else if (type === XAxis) {+ const props = child.props as XAxisProps;+ xAxis = {+ present: true,+ dataKey: props.dataKey,+ tickFormatter: props.tickFormatter,+ label: props.label,+ hideDots: props.hideDots ?? false,+ };+ } else if (type === YAxis) {+ const props = child.props as YAxisProps;+ yAxis = {+ present: true,+ dataKey: props.dataKey,+ tickFormatter: props.tickFormatter,+ label: props.label,+ hideDots: props.hideDots ?? false,+ };+ } else if (type === Grid) {+ showGrid = true;+ } else if (type === Tooltip) {+ const props = child.props as TooltipProps;+ tooltip = {+ present: true,+ variant: props.variant ?? "default",+ roundness: props.roundness ?? "lg",+ cursor: props.cursor ?? true,+ valueFormatter: props.valueFormatter,+ position: props.position ?? "variable",+ };+ } else if (type === Legend) {+ const props = child.props as LegendProps;+ legend = {+ present: true,+ variant: props.variant ?? "rounded-square",+ align: props.align ?? "right",+ verticalAlign: props.verticalAlign ?? "top",+ isClickable: props.isClickable ?? false,+ };+ } else if (type === Brush) {+ const props = child.props as BrushProps;+ brush = {+ present: true,+ height: props.height,+ formatLabel: props.formatLabel,+ onChange: props.onChange,+ };+ }+ });+ return { areas, xAxis, yAxis, showGrid, tooltip, legend, brush };+}+function patternFill(+ kind: "dotted" | "lines" | "hatched" | "stripe",+ color: string,+): ImagePatternObject | null {+ if (typeof document === "undefined") return null;+ const dpr = Math.max(window.devicePixelRatio || 1, 1);+ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ const size = (width: number, height: number) => {+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ ctx.scale(dpr, dpr);+ };+ const pattern = (rotation = 0): ImagePatternObject => ({+ image: canvas,+ repeat: "repeat",+ rotation,+ scaleX: 1 / dpr,+ scaleY: 1 / dpr,+ });+ if (kind === "dotted") {+ size(6, 6);+ ctx.fillStyle = withAlpha(color, 0.7);+ ctx.beginPath();+ ctx.arc(3, 3, 0.85, 0, Math.PI * 2);+ ctx.fill();+ return pattern();+ }+ if (kind === "lines" || kind === "stripe") {+ size(5, 5);+ ctx.strokeStyle = withAlpha(color, 0.3);+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(2.5, -1);+ ctx.lineTo(2.5, 6);+ ctx.stroke();+ return pattern(-Math.PI / 4);+ }+ size(20, 20);+ ctx.fillStyle = withAlpha(color, 0.06);+ ctx.fillRect(0, 0, 10, 20);+ ctx.fillStyle = withAlpha(color, 0.22);+ ctx.fillRect(10, 0, 10, 20);+ return pattern((20 * Math.PI) / 180);+}+function gradientFillTexture(+ slots: string[],+ width: number,+ height: number,+ reverse: boolean,+): HTMLCanvasElement | null {+ if (typeof document === "undefined" || width < 1 || height < 1) return null;+ const canvas = document.createElement("canvas");+ canvas.width = Math.ceil(width);+ canvas.height = Math.ceil(height);+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ const colors = ctx.createLinearGradient(0, 0, canvas.width, 0);+ slots.forEach((color, i) => {+ colors.addColorStop(i / (slots.length - 1), color);+ });+ ctx.fillStyle = colors;+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ const fade = ctx.createLinearGradient(0, 0, 0, canvas.height);+ fade.addColorStop(0, `rgba(0, 0, 0, ${reverse ? 0 : 0.1})`);+ fade.addColorStop(1, `rgba(0, 0, 0, ${reverse ? 0.1 : 0})`);+ ctx.globalCompositeOperation = "destination-in";+ ctx.fillStyle = fade;+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ return canvas;+}+function patternFadeTexture(+ kind: "dotted" | "lines" | "hatched",+ color: string,+ width: number,+ height: number,+): HTMLCanvasElement | null {+ const patternObj = patternFill(kind, color);+ if (!patternObj || typeof document === "undefined" || width < 1 || height < 1)+ return null;+ const tile = patternObj.image;+ if (!(tile instanceof HTMLCanvasElement)) return null;+ const rotation = patternObj.rotation ?? 0;+ const tileScale = patternObj.scaleX ?? 1;+ const w = Math.ceil(width);+ const h = Math.ceil(height);+ const canvas = document.createElement("canvas");+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ const pat = ctx.createPattern(tile, "repeat");+ if (!pat) return null;+ if (typeof pat.setTransform === "function") {+ const m = new DOMMatrix();+ m.rotateSelf((rotation * 180) / Math.PI);+ m.scaleSelf(tileScale, tileScale);+ pat.setTransform(m);+ }+ ctx.fillStyle = pat;+ ctx.fillRect(0, 0, w, h);+ const fade = ctx.createLinearGradient(0, 0, 0, h);+ fade.addColorStop(0, "rgba(0, 0, 0, 1)");+ fade.addColorStop(1, "rgba(0, 0, 0, 0)");+ ctx.globalCompositeOperation = "destination-in";+ ctx.fillStyle = fade;+ ctx.fillRect(0, 0, w, h);+ return canvas;+}+function fillPaint(+ variant: AreaVariant,+ showUnselected: boolean,+ slots: string[],+ size: {+ width: number;+ height: number;+ },+): string | echarts.graphic.LinearGradient | ImagePatternObject {+ const base = slots[0] ?? "rgba(120, 120, 120, 1)";+ const multi = slots.length > 1;+ if (variant === "none") return "transparent";+ if (showUnselected) {+ return patternFill("stripe", base) ?? withAlpha(base, 0.1);+ }+ switch (variant) {+ case "gradient":+ case "gradient-reverse": {+ const reverse = variant === "gradient-reverse";+ if (multi) {+ const texture = gradientFillTexture(+ slots,+ size.width,+ size.height,+ reverse,+ );+ if (texture) return { image: texture, repeat: "no-repeat" };+ }+ return new echarts.graphic.LinearGradient(0, 0, 0, 1, [+ { offset: 0, color: withAlpha(base, reverse ? 0 : 0.1) },+ { offset: 1, color: withAlpha(base, reverse ? 0.1 : 0) },+ ]);+ }+ case "solid": {+ if (multi) {+ return new echarts.graphic.LinearGradient(+ 0,+ 0,+ 1,+ 0,+ slots.map((color, i) => ({+ offset: i / (slots.length - 1),+ color: withAlpha(color, 0.1),+ })),+ );+ }+ return withAlpha(base, 0.1);+ }+ case "dotted":+ case "lines":+ case "hatched": {+ const texture = patternFadeTexture(+ variant,+ base,+ size.width,+ size.height,+ );+ if (texture) return { image: texture, repeat: "no-repeat" };+ return patternFill(variant, base) ?? withAlpha(base, 0.1);+ }+ default:+ return withAlpha(base, 0.1);+ }+}+function curveConfig(curveType: CurveType): {+ smooth: boolean;+ step: "middle" | false;+} {+ if (curveType === "step") return { smooth: false, step: "middle" };+ if (curveType === "linear") return { smooth: false, step: false };+ return { smooth: true, step: false };+}+function getOpacity(selected: string | null, key: string) {+ if (selected === null || selected === key)+ return { fill: 0.8, stroke: 1, dot: 1 };+ return { fill: 0.1, stroke: 0.3, dot: 0.3 };+}+function getLoadingData(points: number): number[] {+ const rows: number[] = [];+ let value = 30 + Math.random() * 20;+ for (let i = 0; i < points; i++) {+ value = Math.min(58, Math.max(16, value + (Math.random() - 0.5) * 16));+ rows.push(Math.round(value));+ }+ return rows;+}+function shimmerWindowStops(center: number, color: string, peak: number) {+ const half = LOADING_SHIMMER_BAND;+ const feather = LOADING_SHIMMER_FEATHER;+ const alphaAt = (x: number) => {+ const dist = Math.abs(x - center);+ if (dist <= half - feather) return peak;+ if (dist >= half) return 0;+ return (+ peak * Math.sin(((1 - (dist - (half - feather)) / feather) * Math.PI) / 2)+ );+ };+ const offsets = [+ 0,+ center - half,+ center - half + feather,+ center,+ center + half - feather,+ center + half,+ 1,+ ]+ .filter((x) => x >= 0 && x <= 1)+ .sort((a, b) => a - b);+ const stops: {+ offset: number;+ color: string;+ }[] = [];+ for (const offset of offsets) {+ if (+ stops.length === 0 ||+ offset - (stops.at(-1)?.offset ?? -Infinity) > 1e-4+ ) {+ stops.push({ offset, color: withAlpha(color, alphaAt(offset)) });+ }+ }+ return stops;+}++type OptionBuildContext = {+ data: ChartRow[];+ config: ChartConfig;+ areas: AreaSeriesConfig[];+ seriesKeys: string[];+ curveType: CurveType;+ isStacked: boolean;+ isExpanded: boolean;+ selectedDataKey: string | null;+ hasSelection: boolean;+ showGrid: boolean;+ xAxisSlot: XAxisSlot;+ yAxisSlot: YAxisSlot;+ tooltipSlot: TooltipSlot;+ legendSlot: LegendSlot;+ isLoading: boolean;+ loadingData: () => number[];+ showBrush: boolean;+ brushHeight: number;+ enableHoverHighlight: boolean;+ enableHoverReveal: boolean;+ revealIndex: number | null;+ revealSink: Record<string, unknown[]>;+ resolved: ResolvedColors;+ rendererSize: {+ width: number;+ height: number;+ };+ categories: string[];+ brushRange: BrushRange;+ getHoveredKey: () => string | null;+};+function buildChartLayout({+ legendSlot,+ xAxisSlot,+ showBrush,+ brushHeight,+}: OptionBuildContext): {+ grid: GridComponentOption;+ brushBottom: number;+} {+ const legendTop = legendSlot.present && legendSlot.verticalAlign === "top";+ const legendBottom =+ legendSlot.present && legendSlot.verticalAlign === "bottom";+ const brushGap = showBrush+ ? brushHeight + 30 + (xAxisSlot.label ? 22 : 0)+ : 0;+ return {+ grid: {+ left: 8,+ right: 8,+ top: legendTop ? 42 : 16,+ bottom: 8 + brushGap + (legendBottom ? 34 : 0),+ },+ brushBottom: legendBottom ? 34 : 6,+ };+}+function buildMainAxes(ctx: OptionBuildContext): {+ xAxis: XAxisOption;+ yAxis: YAxisOption;+} {+ const {+ xAxisSlot,+ yAxisSlot,+ showGrid,+ isLoading,+ isExpanded,+ categories,+ loadingData,+ } = ctx;+ const { tokens } = ctx.resolved;+ const axisLabelColor = tokens.mutedForeground;+ const splitLineColor = withAlpha(tokens.border, GRID_LINE_OPACITY);+ const tickDotColor = flattenColor(splitLineColor, tokens.background);+ const xTickFormatter = xAxisSlot.tickFormatter;+ const yTickFormatter = yAxisSlot.tickFormatter;+ const xAxis: XAxisOption = {+ type: "category",+ boundaryGap: false,+ show: true,+ data: isLoading ? loadingData().map((_, i) => i) : categories,+ name: isLoading ? undefined : xAxisSlot.label,+ nameLocation: "middle",+ nameGap: 30,+ nameTextStyle: { color: axisLabelColor, fontSize: 10 },+ axisLine: { show: false },+ axisTick: {+ show: !isLoading && xAxisSlot.present && !xAxisSlot.hideDots,+ alignWithLabel: true,+ length: 0.5,+ lineStyle: { color: tickDotColor, width: 3, cap: "round" },+ },+ splitLine: { show: false },+ axisLabel: {+ show: !isLoading && xAxisSlot.present,+ color: axisLabelColor,+ fontSize: 10,+ margin: 8,+ formatter: xTickFormatter+ ? (value: string, index: number) => xTickFormatter(value, index)+ : undefined,+ },+ };+ const yAxis: YAxisOption = {+ type: "value",+ show: yAxisSlot.present || showGrid,+ max: isExpanded ? 1 : undefined,+ name: isLoading ? undefined : yAxisSlot.label,+ nameLocation: "middle",+ nameGap: 38,+ nameTextStyle: { color: axisLabelColor, fontSize: 10 },+ axisLine: { show: false },+ axisTick: {+ show: yAxisSlot.present && !isLoading && !yAxisSlot.hideDots,+ length: 0.5,+ lineStyle: { color: tickDotColor, width: 3, cap: "round" },+ },+ splitLine: {+ show: showGrid && !isLoading,+ lineStyle: {+ color: splitLineColor,+ type: [3, 3] as [number, number],+ width: 1,+ },+ },+ axisLabel: {+ show: yAxisSlot.present && !isLoading,+ color: axisLabelColor,+ fontSize: 10,+ margin: 8,+ formatter: isExpanded+ ? (value: number) => `${Math.round(value * 100)}%`+ : yTickFormatter+ ? (value: number, index: number) => yTickFormatter(value, index)+ : undefined,+ },+ };+ return { xAxis, yAxis };+}+function createTooltipFormatter(ctx: OptionBuildContext) {+ const { config, selectedDataKey, tooltipSlot, getHoveredKey } = ctx;+ return (params: unknown): string => {+ const rows = Array.isArray(params) ? params : [params];+ if (!rows.length) return "";+ const first = rows[0] as {+ axisValue?: string | number;+ name?: string;+ };+ const axisValue = first.axisValue ?? first.name ?? "";+ const label = String(axisValue);+ const seen = new Set<string>();+ const body = rows+ .map((param) => {+ const p = param as {+ seriesId?: string;+ seriesName?: string;+ value?: number | string | null;+ };+ const rawId = String(p.seriesId ?? "");+ const key = rawId.startsWith(BUFFER_PREFIX)+ ? rawId.slice(BUFFER_PREFIX.length)+ : rawId.startsWith("__")+ ? ""+ : (p.seriesId ?? p.seriesName ?? "");+ if (!key) return "";+ if (p.value === null || p.value === undefined) return "";+ if (seen.has(key)) return "";+ seen.add(key);+ const item = config[key];+ const colorsCount = item ? getColorsCount(item) : 1;+ const labelText =+ typeof item?.label === "string" ? item.label : (p.seriesName ?? key);+ const hovered = getHoveredKey();+ const dimmed =+ (selectedDataKey != null && selectedDataKey !== key) ||+ (hovered != null && hovered !== key)+ ? " opacity-30"+ : "";+ const value =+ typeof p.value === "number"+ ? (tooltipSlot.valueFormatter?.(p.value) ??+ p.value.toLocaleString())+ : String(p.value ?? "");+ return tooltipRow({+ indicatorHtml: tooltipIndicatorHtml(key, colorsCount),+ labelText,+ valueText: value,+ dimmed,+ });+ })+ .join("");+ return tooltipShell({+ label,+ body,+ roundness: tooltipSlot.roundness,+ variant: tooltipSlot.variant,+ });+ };+}+function buildTooltipOption(ctx: OptionBuildContext): TooltipComponentOption {+ const { tooltipSlot, isLoading } = ctx;+ const { tokens } = ctx.resolved;+ return {+ ...tooltipBaseOption({+ present: tooltipSlot.present && !isLoading,+ cursor: tooltipSlot.cursor,+ tokens,+ position: tooltipSlot.position,+ axisPointerColor: withAlpha(tokens.border, AXIS_POINTER_OPACITY),+ strokeWidth: STROKE_WIDTH,+ }),+ formatter: createTooltipFormatter(ctx),+ };+}+function buildBrushOption(+ ctx: OptionBuildContext,+ brushBottom: number,+): {+ miniGrid: GridComponentOption;+ miniXAxis: XAxisOption;+ miniYAxis: YAxisOption;+ miniSeries: LineSeriesOption[];+ dataZoom: DataZoomComponentOption[];+} {+ const {+ data,+ areas,+ curveType,+ isStacked,+ selectedDataKey,+ brushHeight,+ categories,+ } = ctx;+ const { tokens } = ctx.resolved;+ const miniGrid: GridComponentOption = {+ left: 8,+ right: 8,+ bottom: brushBottom,+ height: brushHeight,+ outerBoundsMode: "none",+ };+ const miniXAxis: XAxisOption = {+ type: "category",+ gridIndex: 1,+ boundaryGap: false,+ show: false,+ data: categories,+ axisPointer: { show: false },+ };+ const miniYAxis: YAxisOption = { type: "value", gridIndex: 1, show: false };+ const miniSeries: LineSeriesOption[] = areas.map((area) => {+ const key = area.dataKey;+ const base =+ (ctx.resolved.series[key] ?? [])[0] ?? "rgba(120, 120, 120, 1)";+ const curve = curveConfig(area.curveType ?? curveType);+ const opacity = getOpacity(selectedDataKey, key);+ const strokeDim = opacity.stroke;+ const fillDim = opacity.fill / 0.8;+ return {+ id: `__mini-${key}`,+ type: "line",+ xAxisIndex: 1,+ yAxisIndex: 1,+ data: data.map((row) => finiteValue(row[key])),+ stack: isStacked ? "__mini-total" : undefined,+ smooth: curve.smooth,+ step: curve.step,+ connectNulls: area.connectNulls,+ silent: true,+ showSymbol: false,+ emphasis: { disabled: true },+ tooltip: { show: false },+ lineStyle: {+ color: base,+ width: 1,+ opacity: BRUSH_STROKE_OPACITY * strokeDim,+ },+ areaStyle: {+ color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [+ { offset: 0, color: withAlpha(base, BRUSH_FILL_OPACITY * fillDim) },+ { offset: 1, color: withAlpha(base, 0) },+ ]),+ },+ z: 0,+ };+ });+ const dataZoom = buildBrushDataZoom({+ brushBottom,+ brushHeight,+ brushRange: ctx.brushRange,+ fillerColor: withAlpha(tokens.foreground, BRUSH_FILLER_OPACITY),+ });+ return { miniGrid, miniXAxis, miniYAxis, miniSeries, dataZoom };+}+function buildLoadingOption(+ ctx: OptionBuildContext,+ frame: {+ grid: GridComponentOption;+ xAxis: XAxisOption;+ yAxis: YAxisOption;+ },+): EChartsOption {+ const { tokens } = ctx.resolved;+ const curve = curveConfig(ctx.curveType);+ return {+ animation: false,+ grid: frame.grid,+ xAxis: frame.xAxis,+ yAxis: frame.yAxis,+ tooltip: { show: false },+ series: [+ {+ id: "__loading",+ type: "line",+ data: ctx.loadingData(),+ smooth: curve.smooth,+ step: curve.step,+ showSymbol: false,+ silent: true,+ lineStyle: { color: withAlpha(tokens.foreground, 0), width: 1 },+ areaStyle: { color: withAlpha(tokens.foreground, 0) },+ z: 1,+ },+ ],+ };+}+type AreaPoint =+ | number+ | null+ | {+ value: number;+ itemStyle: NonNullable<LineSeriesOption["itemStyle"]>;+ emphasis: {+ itemStyle: NonNullable<LineSeriesOption["itemStyle"]>;+ };+ };+function areaPoints(+ vals: (number | null)[],+ area: AreaSeriesConfig,+ slots: string[],+ background: string,+ dotOpacity: number,+): AreaPoint[] {+ return slots.length <= 1+ ? vals+ : vals.map((value, i): AreaPoint => {+ if (value === null) return null;+ const t = vals.length > 1 ? i / (vals.length - 1) : 0;+ const pointColor = sampleGradient(slots, t);+ return {+ value,+ itemStyle: {+ ...dotItemStyle(+ area.dotVariant !== "none"+ ? area.dotVariant+ : area.activeDotVariant,+ pointColor,+ background,+ ),+ opacity: dotOpacity,+ },+ emphasis: {+ itemStyle: {+ ...dotItemStyle(+ area.activeDotVariant === "none"+ ? "default"+ : area.activeDotVariant,+ pointColor,+ background,+ ),+ opacity: 1,+ },+ },+ };+ });+}++function buildAreaSeries(ctx: OptionBuildContext): LineSeriesOption[] {+ const {+ data,+ config,+ areas,+ seriesKeys,+ curveType,+ isStacked,+ isExpanded,+ selectedDataKey,+ hasSelection,+ enableHoverHighlight,+ enableHoverReveal,+ revealIndex,+ revealSink,+ resolved,+ rendererSize,+ } = ctx;+ const rowTotals = isExpanded+ ? data.map((row) =>+ finiteSum(seriesKeys.map((key) => finiteValue(row[key]) ?? 0)),+ )+ : [];+ return areas.flatMap((area): LineSeriesOption[] => {+ const key = area.dataKey;+ const slots = resolved.series[key] ?? ["rgba(120, 120, 120, 1)"];+ const paint = seriesPaint(slots);+ const isSelected = selectedDataKey === key;+ const showUnselected = hasSelection && !isSelected;+ const opacity = getOpacity(selectedDataKey, key);+ const curve = curveConfig(area.curveType ?? curveType);+ const values = data.map((row, i) => {+ const value = finiteValue(row[key]);+ if (value === null) return null;+ if (!isExpanded) return value;+ const total = rowTotals[i];+ return total ? value / total : 0;+ });+ const n = values.length;+ const reveal = enableHoverReveal;+ const buffer = !reveal && area.enableBufferLine && n >= 2;+ const revealActive = reveal && revealIndex !== null;+ const restingDot = dotStyle(+ area.dotVariant,+ paint,+ resolved.tokens.background,+ );+ const activeDot = dotStyle(+ area.activeDotVariant,+ paint,+ resolved.tokens.background,+ );+ const restingVisible = area.dotVariant !== "none";+ const dotOpacity = opacity.dot;+ const multiColor = slots.length > 1;+ const strokePaint =+ reveal && multiColor+ ? new echarts.graphic.LinearGradient(+ 8,+ 0,+ Math.max(rendererSize.width - 8, 9),+ 0,+ slots.map((color, i) => ({+ offset: i / (slots.length - 1),+ color,+ })),+ true,+ )+ : paint;+ const toPoints = (values: (number | null)[]) =>+ areaPoints(values, area, slots, resolved.tokens.background, dotOpacity);+ if (reveal) revealSink[key] = toPoints(values);+ const mainValues: (number | null)[] = buffer+ ? values.map((v, i) => (i === n - 1 ? null : v))+ : revealActive+ ? sliceToNull(values, revealIndex as number)+ : values;+ const mainDash: "solid" | [number, number] =+ buffer || area.strokeVariant === "solid"+ ? "solid"+ : ([3, 3] as [number, number]);+ const z = isSelected ? 3 : hasSelection ? 1 : 2;+ const mainSeries: LineSeriesOption = {+ id: key,+ name: typeof config[key]?.label === "string" ? config[key]?.label : key,+ type: "line",+ data: toPoints(mainValues),+ stack: isStacked ? "total" : undefined,+ smooth: curve.smooth,+ step: curve.step,+ connectNulls: area.connectNulls,+ cursor: area.isClickable ? "pointer" : "default",+ triggerEvent: area.isClickable,+ showSymbol: restingVisible,+ symbol: "circle",+ symbolSize: restingVisible ? restingDot.size : activeDot.size,+ z,+ lineStyle: {+ color: strokePaint,+ width: area.strokeWidth,+ opacity: opacity.stroke,+ type: mainDash,+ dashOffset: 0,+ },+ itemStyle: multiColor+ ? { opacity: dotOpacity }+ : {+ ...(restingVisible ? restingDot.itemStyle : activeDot.itemStyle),+ opacity: dotOpacity,+ },+ areaStyle: {+ color: fillPaint(area.variant, showUnselected, slots, rendererSize),+ opacity: opacity.fill,+ },+ emphasis: {+ focus:+ enableHoverHighlight && !enableHoverReveal && !hasSelection+ ? "series"+ : "none",+ scale: restingVisible+ ? activeDot.size / Math.max(restingDot.size, 1)+ : 1,+ ...(multiColor+ ? {}+ : { itemStyle: { ...activeDot.itemStyle, opacity: 1 } }),+ },+ blur: {+ lineStyle: { opacity: 0.3 },+ areaStyle: { opacity: 0.1 },+ itemStyle: { opacity: 0.3 },+ },+ };+ if (reveal) {+ const muted = resolved.tokens.mutedForeground;+ const revealBase: LineSeriesOption = {+ id: `${REVEAL_PREFIX}${key}`,+ type: "line",+ data: revealActive ? sliceFrom(values, revealIndex as number) : values,+ stack: isStacked ? "__reveal-total" : undefined,+ smooth: curve.smooth,+ step: curve.step,+ connectNulls: false,+ silent: true,+ showSymbol: false,+ symbol: "circle",+ z: z - 1,+ lineStyle: {+ color: muted,+ width: area.strokeWidth,+ type: mainDash,+ opacity: revealActive ? 0.3 : 0,+ },+ emphasis: { disabled: true },+ blur: { lineStyle: { opacity: revealActive ? 0.3 : 0 } },+ tooltip: { show: false },+ };+ return [revealBase, mainSeries];+ }+ if (!buffer) return [mainSeries];+ return buildBufferSeries(ctx, area, values, mainSeries);+ });+}++function buildBufferSeries(+ ctx: OptionBuildContext,+ area: AreaSeriesConfig,+ values: (number | null)[],+ mainSeries: LineSeriesOption,+): LineSeriesOption[] {+ const key = area.dataKey;+ const {+ isStacked,+ rendererSize,+ resolved,+ hasSelection,+ selectedDataKey,+ curveType,+ } = ctx;+ const slots = resolved.series[key] ?? ["rgba(120, 120, 120, 1)"];+ const paint = seriesPaint(slots);+ const opacity = getOpacity(selectedDataKey, key);+ const dotOpacity = opacity.dot;+ const curve = curveConfig(area.curveType ?? curveType);+ const showUnselected = hasSelection && selectedDataKey !== key;+ const restingVisible = area.dotVariant !== "none";+ const restingDot = dotStyle(+ area.dotVariant,+ paint,+ resolved.tokens.background,+ );+ const activeDot = dotStyle(+ area.activeDotVariant,+ paint,+ resolved.tokens.background,+ );+ const multiColor = slots.length > 1;+ const z = mainSeries.z ?? 2;+ const toPoints = (values: (number | null)[]) =>+ areaPoints(values, area, slots, resolved.tokens.background, dotOpacity);+ const bufferValues: (number | null)[] = values.map((v, i) =>+ i >= values.length - 2 ? v : null,+ );+ const bufferSeries: LineSeriesOption = {+ id: `${BUFFER_PREFIX}${key}`,+ type: "line",+ data: toPoints(bufferValues),+ stack: isStacked ? "__buffer-total" : undefined,+ smooth: curve.smooth,+ step: curve.step,+ connectNulls: true,+ silent: true,+ showSymbol: restingVisible,+ symbol: "circle",+ symbolSize: restingVisible ? restingDot.size : activeDot.size,+ z,+ lineStyle: {+ color: paint,+ width: area.strokeWidth,+ opacity: opacity.stroke,+ type: [...BUFFER_DASH],+ },+ itemStyle: multiColor+ ? { opacity: dotOpacity }+ : {+ ...(restingVisible ? restingDot.itemStyle : activeDot.itemStyle),+ opacity: dotOpacity,+ },+ emphasis: {+ focus: "none",+ scale: false,+ lineStyle: { opacity: opacity.stroke },+ itemStyle: { opacity: dotOpacity },+ },+ blur: { lineStyle: { opacity: 0.3 }, itemStyle: { opacity: 0.3 } },+ };+ const bufferFillSeries: LineSeriesOption = {+ id: `${BUFFERFILL_PREFIX}${key}`,+ type: "line",+ data: toPoints(bufferValues),+ stack: isStacked ? "__bufferfill-total" : undefined,+ smooth: curve.smooth,+ step: curve.step,+ connectNulls: true,+ silent: true,+ showSymbol: false,+ z: z - 1,+ lineStyle: { opacity: 0 },+ areaStyle: {+ color: fillPaint(area.variant, showUnselected, slots, rendererSize),+ opacity: opacity.fill,+ },+ emphasis: { disabled: true },+ blur: { areaStyle: { opacity: 0.1 } },+ tooltip: { show: false },+ };+ return [mainSeries, bufferSeries, bufferFillSeries];+}++function sliceToNull<T>(vals: readonly T[], idx: number): (T | null)[] {+ return vals.map((v, i) => (i > idx ? null : v));+}+function sliceFrom<T>(vals: readonly T[], idx: number): (T | null)[] {+ return vals.map((v, i) => (i < idx ? null : v));+}+function computePlottedTops(+ ctx: OptionBuildContext,+): Record<string, (number | null)[]> {+ const { data, areas, seriesKeys, isStacked, isExpanded } = ctx;+ const rowTotals = isExpanded+ ? data.map((row) =>+ finiteSum(seriesKeys.map((key) => finiteValue(row[key]) ?? 0)),+ )+ : [];+ const running = new Array(data.length).fill(0);+ const tops: Record<string, (number | null)[]> = {};+ for (const area of areas) {+ const key = area.dataKey;+ tops[key] = data.map((row, i) => {+ let value = finiteValue(row[key]);+ if (value === null) return null;+ if (isExpanded) value = rowTotals[i] ? value / rowTotals[i] : 0;+ if (!isStacked) return value;+ running[i] = (running[i] ?? 0) + value;+ return running[i];+ });+ }+ return tops;+}+function resolveAreaAtPixel(+ chart: EChartsInstance,+ tops: Record<string, (number | null)[]>,+ keys: string[],+ x: number,+ y: number,+): string | null {+ if (keys.length < 2) return null;+ if (!chart.containPixel({ gridIndex: 0 }, [x, y])) return null;+ const [rawIndex] = chart.convertFromPixel({ gridIndex: 0 }, [x, y]);+ if (rawIndex === undefined || !Number.isFinite(rawIndex)) return null;+ const index = Math.round(rawIndex);+ let nearest: string | null = null;+ let nearestDist = Infinity;+ let above: string | null = null;+ let abovePixelY = -Infinity;+ for (const key of keys) {+ const value = tops[key]?.[index];+ if (value == null) continue;+ const pixelY = chart.convertToPixel({ gridIndex: 0 }, [index, value])[1];+ if (pixelY === undefined || !Number.isFinite(pixelY)) continue;+ const dist = Math.abs(pixelY - y);+ if (dist < nearestDist) {+ nearestDist = dist;+ nearest = key;+ }+ if (pixelY <= y && pixelY > abovePixelY) {+ abovePixelY = pixelY;+ above = key;+ }+ }+ return nearestDist <= 10 ? nearest : above;+}+type LiveState = {+ resolved: ResolvedColors | null;+ hoveredKey: string | null;+ pointerIndex: number | null;+ syncActive: () => void;+ hasRevealed: boolean;+ revealEndsAt: number;+ loadingRows: number[] | null;+ categories: string[];+ dataLength: number;+ plottedTops: Record<string, (number | null)[]>;+ seriesKeyByIndex: (string | undefined)[];+ companionIdsByKey: Map<string, string[]>;+ revealIndex: number | null;+ revealValues: Record<string, unknown[]>;+ brushRange: BrushRange;+ brushGeom: BrushGeometry | null;+ brushOverlay: BrushOverlayElements | null;+ brushHover: {+ inside: boolean;+ left: boolean;+ right: boolean;+ };+ handlers: {+ onBrushChange?: (range: { startIndex: number; endIndex: number }) => void;+ onSelectionChange?: (key: string | null) => void;+ clickableKeys: Set<string>;+ selectedDataKey: string | null;+ brushFormatLabel?: (value: string, index: number) => string;+ seriesKeys: string[];+ enableHoverHighlight: boolean;+ enableHoverReveal: boolean;+ onHoverIndexChange?: (index: number | null) => void;+ };+ repush: () => void;+};+export function EChartsAreaChart<TData extends ChartRow>({+ data,+ config,+ renderer = DEFAULT_ECHARTS_RENDERER,+ xDataKey,+ className,+ curveType = "linear",+ stackType = "default",+ animation = true,+ animationType = "left-to-right",+ enableHoverHighlight = false,+ enableHoverReveal = false,+ defaultSelectedDataKey = null,+ selectedDataKey: selectedDataKeyProp,+ onSelectionChange,+ isLoading = false,+ loadingPoints = LOADING_DEFAULT_POINTS,+ chartOptions,+ activeIndex,+ onHoverIndexChange,+ children,+}: EChartsAreaChartProps<TData>) {+ const rawId = useId();+ const chartId = `chart-${rawId.replace(/:/g, "")}`;+ const containerRef = useRef<HTMLDivElement>(null);+ const mountRef = useRef<HTMLDivElement>(null);+ const echartsRef = useRef<EChartsInstance | null>(null);+ const live = useRef<LiveState>({+ resolved: null,+ hoveredKey: null,+ pointerIndex: null,+ syncActive: () => {},+ hasRevealed: false,+ revealEndsAt: 0,+ loadingRows: null,+ categories: [],+ dataLength: 0,+ plottedTops: {},+ seriesKeyByIndex: [],+ companionIdsByKey: new Map<string, string[]>(),+ revealIndex: null,+ revealValues: {},+ brushRange: { start: 0, end: 100 },+ brushGeom: null,+ brushOverlay: null,+ brushHover: { inside: false, left: false, right: false },+ handlers: {+ onBrushChange: undefined,+ onSelectionChange,+ clickableKeys: new Set<string>(),+ selectedDataKey: defaultSelectedDataKey,+ brushFormatLabel: undefined,+ seriesKeys: [],+ enableHoverHighlight,+ enableHoverReveal,+ },+ repush: () => {},+ }).current;+ const loadingData = useCallback(+ () => (live.loadingRows ??= getLoadingData(loadingPoints)),+ [live, loadingPoints],+ );+ const shouldReduceMotion = useReducedMotion();+ const [internalSelectedKey, setSelectedDataKey] = useState<string | null>(+ defaultSelectedDataKey,+ );+ const selectedDataKey =+ selectedDataKeyProp !== undefined+ ? selectedDataKeyProp+ : internalSelectedKey;+ const [hoveredDataKey, setHoveredDataKey] = useState<string | null>(null);+ const collected = useMemo(() => collectConfig(children), [children]);+ const {+ areas,+ xAxis: xAxisSlot,+ yAxis: yAxisSlot,+ showGrid,+ tooltip: tooltipSlot,+ legend: legendSlot,+ brush: brushSlot,+ } = collected;+ const showBrush = brushSlot.present;+ const brushHeight = brushSlot.height ?? 56;+ const seriesKeys = useMemo(() => areas.map((area) => area.dataKey), [areas]);+ const xCategoryKey = useMemo(() => {+ if (xAxisSlot.dataKey) return xAxisSlot.dataKey;+ if (xDataKey) return xDataKey as string;+ const firstRow = data[0];+ if (firstRow) {+ const claimed = new Set(seriesKeys);+ const found = Object.keys(firstRow).find((key) => !claimed.has(key));+ if (found) return found;+ }+ return "";+ }, [xAxisSlot.dataKey, xDataKey, data, seriesKeys]);+ const effectiveAnimation = areas[0]?.animationType ?? animationType;+ const css = useMemo(() => buildChartCss(chartId, config), [chartId, config]);+ const hasSelection = selectedDataKey !== null;+ const isExpanded = stackType === "expanded";+ const isStacked = stackType === "stacked" || isExpanded;+ const clickableKeys = useMemo(+ () =>+ new Set(+ areas.filter((area) => area.isClickable).map((area) => area.dataKey),+ ),+ [areas],+ );++ const toggleSelection = useCallback(+ (key: string) => {+ const next = live.handlers.selectedDataKey === key ? null : key;+ if (next !== null && live.hoveredKey !== null) {+ const previous = live.hoveredKey;+ live.hoveredKey = null;+ setHoveredDataKey(null);+ echartsRef.current?.dispatchAction({+ type: "downplay",+ seriesIndex: live.handlers.seriesKeys.indexOf(previous),+ });+ }+ setSelectedDataKey(next);+ live.handlers.onSelectionChange?.(next);+ },+ [live],+ );+ const syncBrushOverlayNow = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart) return;+ const geom = live.brushGeom;+ const tokens = live.resolved?.tokens;+ if (!geom || !tokens) {+ syncBrushOverlay(chart, live, null);+ return;+ }+ const range = live.brushRange;+ const categories = live.categories;+ const format = live.handlers.brushFormatLabel;+ const lastIndex = Math.max(categories.length - 1, 0);+ const startIndex = Math.round((range.start / 100) * lastIndex);+ const endIndex = Math.round((range.end / 100) * lastIndex);+ const labels =+ format && categories.length+ ? {+ start: format(categories[startIndex] ?? "", startIndex),+ end: format(categories[endIndex] ?? "", endIndex),+ }+ : null;+ syncBrushOverlay(chart, live, {+ range,+ geom,+ size: { width: chart.getWidth(), height: chart.getHeight() },+ tokens,+ labels,+ showLabels: live.brushHover.inside,+ hover: live.brushHover,+ });+ }, [live]);+ const buildOption = useCallback((): EChartsOption => {+ const resolved = live.resolved;+ if (!resolved) return {};+ const categories = data.map((row) => String(row[xCategoryKey]));+ live.categories = categories;+ const revealSink: Record<string, unknown[]> = {};+ const ctx: OptionBuildContext = {+ data,+ config,+ areas,+ seriesKeys,+ curveType,+ isStacked,+ isExpanded,+ selectedDataKey,+ hasSelection,+ showGrid,+ xAxisSlot,+ yAxisSlot,+ tooltipSlot,+ legendSlot,+ isLoading,+ loadingData,+ showBrush,+ brushHeight,+ enableHoverHighlight,+ enableHoverReveal,+ revealIndex: live.revealIndex,+ resolved,+ rendererSize: {+ width:+ echartsRef.current?.getWidth() ?? mountRef.current?.clientWidth ?? 0,+ height:+ echartsRef.current?.getHeight() ??+ mountRef.current?.clientHeight ??+ 0,+ },+ categories,+ brushRange: live.brushRange,+ getHoveredKey: () => live.hoveredKey,+ revealSink,+ };+ live.plottedTops = computePlottedTops(ctx);+ const { grid, brushBottom } = buildChartLayout(ctx);+ live.brushGeom = showBrush+ ? { bottom: brushBottom, height: brushHeight }+ : null;+ const { xAxis, yAxis } = buildMainAxes(ctx);+ if (isLoading) return buildLoadingOption(ctx, { grid, xAxis, yAxis });+ const brush = showBrush ? buildBrushOption(ctx, brushBottom) : null;+ const series = [...buildAreaSeries(ctx), ...(brush?.miniSeries ?? [])];+ if (enableHoverReveal) live.revealValues = revealSink;+ live.seriesKeyByIndex = series.map((s) => {+ const id = String(s.id ?? "");+ return id && !id.startsWith("__") ? id : undefined;+ });+ const companionIdsByKey = new Map<string, string[]>();+ for (const area of areas) {+ const ids: string[] = [];+ if (area.enableBufferLine && data.length >= 2) {+ ids.push(+ `${BUFFER_PREFIX}${area.dataKey}`,+ `${BUFFERFILL_PREFIX}${area.dataKey}`,+ );+ }+ if (enableHoverReveal) ids.push(`${REVEAL_PREFIX}${area.dataKey}`);+ if (ids.length) companionIdsByKey.set(area.dataKey, ids);+ }+ live.companionIdsByKey = companionIdsByKey;+ return {+ animation: false,+ grid: brush ? [grid, brush.miniGrid] : grid,+ xAxis: brush ? [xAxis, brush.miniXAxis] : xAxis,+ yAxis: brush ? [yAxis, brush.miniYAxis] : yAxis,+ tooltip: buildTooltipOption(ctx),+ dataZoom: brush?.dataZoom,+ series,+ };+ }, [+ live,+ data,+ config,+ areas,+ seriesKeys,+ xCategoryKey,+ curveType,+ isStacked,+ isExpanded,+ selectedDataKey,+ hasSelection,+ showGrid,+ xAxisSlot,+ yAxisSlot,+ tooltipSlot,+ legendSlot,+ isLoading,+ loadingData,+ showBrush,+ brushHeight,+ enableHoverHighlight,+ enableHoverReveal,+ ]);+ const setupChart = useCallback(() => {+ const mount = mountRef.current;+ const container = containerRef.current;+ if (!mount || !container) return;+ live.hoveredKey = null;+ live.revealIndex = null;+ live.pointerIndex = null;+ live.brushHover = { inside: false, left: false, right: false };+ setHoveredDataKey(null);+ const chart = echarts.init(mount, null, { renderer });+ echartsRef.current = chart;+ const resizeObserver = new ResizeObserver(() => {+ if (+ mount.clientWidth === chart.getWidth() &&+ mount.clientHeight === chart.getHeight()+ ) {+ return;+ }+ chart.resize();+ live.repush();+ });+ resizeObserver.observe(mount);+ const themeObserver = observeChartTheme(container, () => live.repush());+ chart.on("click", (params) => {+ const { clickableKeys: clickable, seriesKeys: keys } = live.handlers;+ const p = params as {+ seriesId?: string;+ seriesIndex?: number;+ event?: {+ offsetX?: number;+ offsetY?: number;+ };+ };+ let id =+ p.seriesId ??+ (typeof p.seriesIndex === "number"+ ? live.seriesKeyByIndex[p.seriesIndex]+ : undefined);+ if (+ typeof p.event?.offsetX === "number" &&+ typeof p.event?.offsetY === "number"+ ) {+ const resolved = resolveAreaAtPixel(+ chart,+ live.plottedTops,+ keys,+ p.event.offsetX,+ p.event.offsetY,+ );+ if (resolved) id = resolved;+ }+ if (typeof id === "string" && clickable.has(id)) toggleSelection(id);+ });+ const applyHoverKey = (key: string | null) => {+ if (live.hoveredKey === key) return;+ const previous = live.hoveredKey;+ live.hoveredKey = key;+ setHoveredDataKey(key);+ if (previous) {+ chart.dispatchAction({ type: "downplay", seriesId: previous });+ for (const id of live.companionIdsByKey.get(previous) ?? [])+ chart.dispatchAction({ type: "downplay", seriesId: id });+ }+ if (key) {+ chart.dispatchAction({ type: "highlight", seriesId: key });+ for (const id of live.companionIdsByKey.get(key) ?? [])+ chart.dispatchAction({ type: "highlight", seriesId: id });+ }+ };+ const pushReveal = (idx: number | null) => {+ const keys = live.handlers.seriesKeys;+ const on = idx !== null;+ chart.setOption(+ {+ series: keys.flatMap((key) => [+ {+ id: key,+ data: on+ ? sliceToNull(live.revealValues[key] ?? [], idx)+ : (live.revealValues[key] ?? []),+ },+ {+ id: `${REVEAL_PREFIX}${key}`,+ data: on+ ? sliceFrom(live.revealValues[key] ?? [], idx)+ : (live.revealValues[key] ?? []),+ lineStyle: { opacity: on ? 0.3 : 0 },+ },+ ]),+ },+ { silent: true },+ );+ for (const key of keys) {+ chart.dispatchAction(+ on+ ? { type: "highlight", seriesId: key, dataIndex: idx as number }+ : { type: "downplay", seriesId: key },+ );+ }+ };+ const applyReveal = (event: { offsetX?: number; offsetY?: number }) => {+ const len = live.dataLength;+ if (len < 1) return;+ const x = event.offsetX ?? -1;+ const y = event.offsetY ?? -1;+ if (!chart.containPixel({ gridIndex: 0 }, [x, y])) {+ clearReveal();+ return;+ }+ const raw = chart.convertFromPixel({ gridIndex: 0 }, [x, y])[0];+ if (raw === undefined || !Number.isFinite(raw)) return;+ const idx = Math.max(0, Math.min(len - 1, Math.round(raw)));+ if (idx === live.revealIndex) return;+ live.revealIndex = idx;+ pushReveal(idx);+ };+ const clearReveal = () => {+ if (live.revealIndex === null) return;+ live.revealIndex = null;+ pushReveal(null);+ };+ const zrHover = chart.getZr();+ const notifyHoverIndex = (index: number | null) => {+ if (index === live.pointerIndex) return;+ live.pointerIndex = index;+ live.handlers.onHoverIndexChange?.(index);+ live.syncActive();+ };+ const onZrHoverMove = (event: { offsetX?: number; offsetY?: number }) => {+ const point = [event.offsetX ?? -1, event.offsetY ?? -1];+ const index = chart.containPixel({ gridIndex: 0 }, point)+ ? chart.convertFromPixel({ gridIndex: 0 }, point)[0]+ : null;+ notifyHoverIndex(+ boundedIndex(+ typeof index === "number" ? Math.round(index) : null,+ live.dataLength,+ ),+ );+ if (live.handlers.enableHoverReveal) {+ applyReveal(event);+ return;+ }+ if (!live.handlers.enableHoverHighlight) return;+ if (live.handlers.selectedDataKey !== null) return;+ applyHoverKey(+ resolveAreaAtPixel(+ chart,+ live.plottedTops,+ live.handlers.seriesKeys,+ event.offsetX ?? -1,+ event.offsetY ?? -1,+ ),+ );+ };+ const onZrHoverOut = () => {+ notifyHoverIndex(null);+ if (live.handlers.enableHoverReveal) clearReveal();+ else if (live.handlers.enableHoverHighlight) applyHoverKey(null);+ };+ zrHover.on("mousemove", onZrHoverMove);+ zrHover.on("globalout", onZrHoverOut);+ chart.on("mouseover", (params) => {+ const { enableHoverHighlight: hoverOn, enableHoverReveal: revealOn } =+ live.handlers;+ if (!hoverOn || revealOn) return;+ if (live.handlers.selectedDataKey !== null) return;+ const p = params as {+ seriesIndex?: number;+ componentType?: string;+ };+ if (p.componentType !== "series" || typeof p.seriesIndex !== "number")+ return;+ const key = live.seriesKeyByIndex[p.seriesIndex];+ if (!key || key.startsWith("__")) return;+ if (key !== live.hoveredKey) {+ chart.dispatchAction({ type: "downplay", seriesIndex: p.seriesIndex });+ if (live.hoveredKey) {+ chart.dispatchAction({+ type: "highlight",+ seriesId: live.hoveredKey,+ });+ }+ }+ });+ chart.on("datazoom", () => {+ const option = chart.getOption() as {+ dataZoom?: {+ start?: number;+ end?: number;+ }[];+ };+ const zoom = option.dataZoom?.[0];+ if (!zoom) return;+ live.brushRange = { start: zoom.start ?? 0, end: zoom.end ?? 100 };+ syncBrushOverlayNow();+ const { onBrushChange: onChange } = live.handlers;+ if (!onChange) return;+ const len = live.dataLength;+ if (len < 1) return;+ const startIndex = Math.round(((zoom.start ?? 0) / 100) * (len - 1));+ const endIndex = Math.round(((zoom.end ?? 100) / 100) * (len - 1));+ onChange({ startIndex, endIndex });+ });+ const zr = chart.getZr();+ const applyHover = (next: {+ inside: boolean;+ left: boolean;+ right: boolean;+ }) => {+ const prev = live.brushHover;+ if (+ prev.inside === next.inside &&+ prev.left === next.left &&+ prev.right === next.right+ ) {+ return;+ }+ live.brushHover = next;+ syncBrushOverlayNow();+ };+ const onZrMove = (event: { offsetX?: number; offsetY?: number }) => {+ const geom = live.brushGeom;+ if (!geom) return;+ const x = event.offsetX ?? -1;+ const y = event.offsetY ?? -1;+ const top = chart.getHeight() - geom.bottom - geom.height;+ const inside = y >= top - 4 && y <= top + geom.height + 4;+ const trackLeft = 8;+ const trackWidth = Math.max(chart.getWidth() - 16, 1);+ const { start, end } = live.brushRange;+ const selectionLeft = trackLeft + (trackWidth * start) / 100;+ const selectionRight = trackLeft + (trackWidth * end) / 100;+ applyHover({+ inside,+ left: inside && Math.abs(x - selectionLeft) <= 8,+ right: inside && Math.abs(x - selectionRight) <= 8,+ });+ };+ const onZrOut = () =>+ applyHover({ inside: false, left: false, right: false });+ zr.on("mousemove", onZrMove);+ zr.on("globalout", onZrOut);+ return () => {+ zrHover.off("mousemove", onZrHoverMove);+ zrHover.off("globalout", onZrHoverOut);+ zr.off("mousemove", onZrMove);+ zr.off("globalout", onZrOut);+ resizeObserver.disconnect();+ themeObserver.disconnect();+ cancelActiveTooltip(chart);+ chart.off();+ chart.getZr().off();+ chart.dispose();+ live.repush = () => {};+ live.syncActive = () => {};+ echartsRef.current = null;+ live.brushOverlay = null;+ live.hasRevealed = false;+ };+ }, [renderer]);+ const synchronizeChart = useCallback(() => {+ const chart = echartsRef.current;+ const container = containerRef.current;+ if (!chart || !container) return;+ live.resolved = resolveColors(container, config, seriesKeys);+ live.syncActive = () => {+ if (activeIndex !== undefined || live.pointerIndex !== null) {+ showActiveIndex(+ chart,+ isLoading+ ? null+ : boundedIndex(live.pointerIndex ?? activeIndex, data.length),+ seriesKeys[0],+ );+ }+ };+ const push = (withEntrance: boolean) => {+ const option = buildOption();+ const merged = chartOptions ? { ...option, ...chartOptions } : option;+ Object.assign(merged, {+ animation: withEntrance,+ animationDuration: REVEAL_DURATION,+ animationDurationUpdate: 0,+ });+ setChartOption(chart, merged);+ live.syncActive();+ syncBrushOverlayNow();+ };+ if (isLoading) live.hasRevealed = false;+ const shouldReveal = !live.hasRevealed && !isLoading;+ if (shouldReveal) live.hasRevealed = true;+ const revealEnabled =+ animation &&+ shouldReveal &&+ effectiveAnimation !== "none" &&+ !shouldReduceMotion;+ if (revealEnabled) live.revealEndsAt = performance.now() + REVEAL_DURATION;+ push(revealEnabled);+ live.repush = () => {+ live.resolved = resolveColors(container, config, seriesKeys);+ push(false);+ };+ }, [+ renderer,+ live,+ buildOption,+ chartOptions,+ activeIndex,+ data.length,+ isLoading,+ animation,+ effectiveAnimation,+ shouldReduceMotion,+ config,+ seriesKeys,+ syncBrushOverlayNow,+ ]);+ const animatePrimary = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart || isLoading || shouldReduceMotion) return;+ const animatedKeys = areas+ .filter(+ (area) =>+ area.strokeVariant === "animated-dashed" && !area.enableBufferLine,+ )+ .map((area) => area.dataKey);+ if (animatedKeys.length === 0 || hasSelection) return;+ let raf = 0;+ let delayTimer: ReturnType<typeof setTimeout> | undefined;+ const begin = () => {+ const loopStart = performance.now();+ const tick = (now: number) => {+ const offset = -(((now - loopStart) / 1000) % 1) * 6;+ chart.setOption(+ {+ series: animatedKeys.map((id) => ({+ id,+ lineStyle: { dashOffset: offset },+ })),+ },+ { silent: true, lazyUpdate: true },+ );+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ };+ const delay = Math.max(0, live.revealEndsAt - performance.now());+ if (delay > 0) delayTimer = setTimeout(begin, delay + 50);+ else begin();+ return () => {+ if (delayTimer !== undefined) clearTimeout(delayTimer);+ cancelAnimationFrame(raf);+ };+ }, [renderer, live, areas, hasSelection, isLoading, shouldReduceMotion]);+ const animateLoading = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart || !isLoading || shouldReduceMotion) return;+ let raf = 0;+ let lastPhase = 0;+ const start = performance.now();+ const tick = (now: number) => {+ const phase =+ ((((now - start) / LOADING_ANIMATION_DURATION) % 1) + 1) % 1;+ if (phase < lastPhase) live.loadingRows = getLoadingData(loadingPoints);+ lastPhase = phase;+ const foreground =+ live.resolved?.tokens.foreground ?? "rgba(120, 120, 120, 1)";+ const w = chart.getWidth();+ const h = chart.getHeight();+ if (!w || !h) {+ raf = requestAnimationFrame(tick);+ return;+ }+ const maxT = (w + h) / (2 * w);+ const center =+ phase * (maxT + 2 * LOADING_SHIMMER_BAND) - LOADING_SHIMMER_BAND;+ const clip = (peak: number) =>+ new echarts.graphic.LinearGradient(+ 0,+ 0,+ w,+ w,+ shimmerWindowStops(center, foreground, peak),+ true,+ );+ chart.setOption(+ {+ series: [+ {+ id: "__loading",+ data: loadingData(),+ lineStyle: { color: clip(LOADING_STROKE_OPACITY), width: 1 },+ areaStyle: { color: clip(LOADING_SHIMMER_MAX_OPACITY) },+ },+ ],+ },+ { silent: true, lazyUpdate: true },+ );+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [+ renderer,+ live,+ isLoading,+ loadingPoints,+ loadingData,+ shouldReduceMotion,+ ]);+ const commitChart = useChartLifecycle(+ {+ prepare: () => {+ live.handlers = {+ onBrushChange: brushSlot.onChange,+ onHoverIndexChange,+ onSelectionChange,+ clickableKeys,+ selectedDataKey,+ brushFormatLabel: brushSlot.formatLabel,+ seriesKeys,+ enableHoverHighlight,+ enableHoverReveal,+ };+ live.dataLength = data.length;+ },+ setup: setupChart,+ synchronize: synchronizeChart,+ animate: [animatePrimary, animateLoading],+ },+ containerRef,+ );++ const legendStyle: CSSProperties = {+ position: "absolute",+ left: 16,+ right: 16,+ pointerEvents: "auto",+ ...(legendSlot.verticalAlign === "top"+ ? { top: 12 }+ : legendSlot.verticalAlign === "bottom"+ ? { bottom: showBrush ? brushHeight + 16 : 12 }+ : { top: "50%", transform: "translateY(-50%)" }),+ };+ return (+ <div+ ref={commitChart}+ data-chart={chartId}+ className={`relative flex flex-col text-xs ${className ?? ""}`}+ >+ <style dangerouslySetInnerHTML={{ __html: css }} />++ <div className="relative min-h-0 w-full flex-1">+ <div ref={mountRef} className="h-full min-h-0 w-full" />+ </div>++ {legendSlot.present && !isLoading && (+ <LegendOverlay+ seriesKeys={seriesKeys}+ config={config}+ variant={legendSlot.variant}+ align={legendSlot.align}+ verticalAlign={legendSlot.verticalAlign}+ selectedKey={selectedDataKey}+ hoveredKey={hoveredDataKey}+ isClickable={legendSlot.isClickable}+ onToggle={toggleSelection}+ style={legendStyle}+ />+ )}+ </div>+ );+}+EChartsAreaChart.Area = Area;+EChartsAreaChart.Dot = Dot;+EChartsAreaChart.ActiveDot = ActiveDot;+EChartsAreaChart.XAxis = XAxis;+EChartsAreaChart.YAxis = YAxis;+EChartsAreaChart.Grid = Grid;+EChartsAreaChart.Tooltip = Tooltip;+EChartsAreaChart.Legend = Legend;+EChartsAreaChart.Brush = Brush;diff --git a/packages/ui/src/components/evilcharts/charts/echarts-bar-chart.tsx b/packages/ui/src/components/evilcharts/charts/echarts-bar-chart.tsxnew file mode 100644index 00000000..69dab771--- /dev/null+++ b/packages/ui/src/components/evilcharts/charts/echarts-bar-chart.tsx@@ -0,0 +1,1877 @@+"use client";+import { BarChart, type BarSeriesOption } from "echarts/charts";+import {+ DataZoomComponent,+ type DataZoomComponentOption,+ GridComponent,+ type GridComponentOption,+ TooltipComponent,+ type TooltipComponentOption,+} from "echarts/components";+import type { ComposeOption, ImagePatternObject } from "echarts/core";+import * as echarts from "echarts/core";+import {+ Children,+ type CSSProperties,+ type FC,+ isValidElement,+ type ReactNode,+ useCallback,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ Brush,+ type BrushGeometry,+ type BrushOverlayElements,+ type BrushProps,+ type BrushRange,+ buildBrushDataZoom,+ syncBrushOverlay,+} from "../ui/echarts-brush";+import {+ buildChartCss,+ type ChartConfig,+ type ChartRow,+ DEFAULT_ECHARTS_RENDERER,+ type EChartsRenderer,+ finiteSum,+ finiteValue,+ flattenColor,+ getColorsCount,+ type ResolvedColors,+ resolveColors,+ withAlpha,+} from "../ui/echarts-chart";+import { ECHARTS_CONFIG } from "../ui/echarts-config";+import { sampleGradient } from "../ui/echarts-dot";+import { LegendOverlay, type LegendVariant } from "../ui/echarts-legend";+import {+ boundedIndex,+ cancelActiveTooltip,+ observeChartTheme,+ showActiveIndex,+ useChartLifecycle,+ useReducedMotion,+} from "../ui/echarts-lifecycle";+import { setChartOption } from "../ui/echarts-options";+import {+ type TooltipPosition,+ type TooltipRoundness,+ type TooltipVariant,+ tooltipBaseOption,+ tooltipIndicatorHtml,+ tooltipRow,+ tooltipShell,+} from "../ui/echarts-tooltip";++export type {+ ChartConfig,+ EChartsRenderer,+ LegendVariant,+ TooltipPosition,+ TooltipRoundness,+ TooltipVariant,+};++echarts.use([BarChart, GridComponent, TooltipComponent, DataZoomComponent]);+type EChartsInstance = ReturnType<typeof echarts.init>;+type EChartsOption = ComposeOption<+ | BarSeriesOption+ | GridComponentOption+ | TooltipComponentOption+ | DataZoomComponentOption+>;+type ArrayItem<T> = T extends readonly (infer U)[] ? U : T;+type XAxisOption = ArrayItem<NonNullable<EChartsOption["xAxis"]>>;+type YAxisOption = ArrayItem<NonNullable<EChartsOption["yAxis"]>>;+const {+ DEFAULT_BAR_RADIUS,+ STROKE_WIDTH,+ LOADING_ANIMATION_DURATION,+ BAR_GROW_DURATION,+ BAR_STAGGER,+ LOADING_DEFAULT_BARS,+ SELECTION_DIM,+ HOVER_BLUR,+ GLOW_BLUR,+ GLOW_OPACITY,+ EXPAND_COLLAPSED,+ EXPAND_TAU,+ BLOCK_SIZE,+ BLOCK_GAP,+ BLOCK_TRACK_OPACITY,+ STACK_SEGMENT_GAP,+ MAX_HIGHLIGHT_DIM,+ STRIPPED_CAP_HEIGHT,+ STRIPPED_BODY_ALPHA,+ STRIPPED_CAP_MAX_FRACTION,+ STRIPPED_FALLBACK_FRACTION,+ GRID_LINE_OPACITY,+ LOADING_SHIMMER_MAX_OPACITY,+ LOADING_SHIMMER_BAND,+ LOADING_SHIMMER_FEATHER,+ BRUSH_FILL_OPACITY,+ BRUSH_FILLER_OPACITY,+ GRAY,+} = ECHARTS_CONFIG.bar;++export type BarVariant =+ | "default"+ | "hatched"+ | "duotone"+ | "duotone-reverse"+ | "gradient"+ | "stripped"+ | "blocks"+ | "expandable";+export type StackType = "default" | "stacked" | "percent";+export type BarLayout = "vertical" | "horizontal";+export type BarAnimationType =+ | "none"+ | "left-to-right"+ | "right-to-left"+ | "center-out"+ | "edges-in";+export interface EChartsBarChartProps<TData extends ChartRow> {+ data: TData[];+ config: ChartConfig;+ renderer?: EChartsRenderer;+ xDataKey?: keyof TData & string;+ className?: string;+ stackType?: StackType;+ layout?: BarLayout;+ barRadius?: number;+ animation?: boolean;+ animationType?: BarAnimationType;+ barGap?: number;+ barCategoryGap?: number;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+ enableMaxValueHighlight?: boolean;+ isLoading?: boolean;+ loadingBars?: number;+ chartOptions?: EChartsOption;+ activeIndex?: number | null;+ children?: ReactNode;+}+export interface BarProps {+ dataKey: string;+ variant?: BarVariant;+ radius?: number;+ animationType?: BarAnimationType;+ isClickable?: boolean;+ enableHoverHighlight?: boolean;+ glowing?: boolean;+ bufferBar?: boolean;+}+const Bar: FC<BarProps> = () => null;+export interface XAxisProps {+ dataKey?: string;+ tickFormatter?: (value: string, index: number) => string;+ label?: string;+ hideDots?: boolean;+}+const XAxis: FC<XAxisProps> = () => null;+export interface YAxisProps {+ dataKey?: string;+ tickFormatter?: (value: string, index: number) => string;+ label?: string;+ hideDots?: boolean;+}+const YAxis: FC<YAxisProps> = () => null;+const Grid: FC = () => null;+export interface TooltipProps {+ variant?: TooltipVariant;+ roundness?: TooltipRoundness;+ defaultIndex?: number;+ position?: TooltipPosition;+ valueFormatter?: (value: number) => string;+}+const Tooltip: FC<TooltipProps> = () => null;+export interface LegendProps {+ variant?: LegendVariant;+ align?: "left" | "center" | "right";+ verticalAlign?: "top" | "middle" | "bottom";+ isClickable?: boolean;+}+const Legend: FC<LegendProps> = () => null;+type BarSeriesConfig = {+ dataKey: string;+ variant: BarVariant;+ radius?: number;+ animationType?: BarAnimationType;+ isClickable: boolean;+ enableHoverHighlight: boolean;+ glowing: boolean;+ bufferBar: boolean;+};+type AxisSlot = {+ present: boolean;+ dataKey?: string;+ tickFormatter?: (value: string, index: number) => string;+ label?: string;+ hideDots: boolean;+};+type TooltipSlot = {+ valueFormatter?: (value: number) => string;+ present: boolean;+ variant: TooltipVariant;+ roundness: TooltipRoundness;+ defaultIndex?: number;+ position: TooltipPosition;+};+type LegendSlot = {+ present: boolean;+ variant: LegendVariant;+ align: "left" | "center" | "right";+ verticalAlign: "top" | "middle" | "bottom";+ isClickable: boolean;+};+type BrushSlot = {+ present: boolean;+ height?: number;+ formatLabel?: (value: string, index: number) => string;+ onChange?: (range: { startIndex: number; endIndex: number }) => void;+};+type CollectedConfig = {+ bars: BarSeriesConfig[];+ xAxis: AxisSlot;+ yAxis: AxisSlot;+ showGrid: boolean;+ tooltip: TooltipSlot;+ legend: LegendSlot;+ brush: BrushSlot;+};+function collectConfig(children: ReactNode): CollectedConfig {+ const bars: BarSeriesConfig[] = [];+ let xAxis: AxisSlot = { present: false, hideDots: false };+ let yAxis: AxisSlot = { present: false, hideDots: false };+ let showGrid = false;+ let tooltip: TooltipSlot = {+ present: false,+ variant: "default",+ roundness: "lg",+ position: "variable",+ };+ let legend: LegendSlot = {+ present: false,+ variant: "rounded-square",+ align: "right",+ verticalAlign: "top",+ isClickable: false,+ };+ let brush: BrushSlot = { present: false };+ Children.forEach(children, (child) => {+ if (!isValidElement(child)) return;+ const type = child.type;+ if (type === Bar) {+ const props = child.props as BarProps;+ bars.push({+ dataKey: props.dataKey,+ variant: props.variant ?? "default",+ radius: props.radius,+ animationType: props.animationType,+ isClickable: props.isClickable ?? false,+ enableHoverHighlight: props.enableHoverHighlight ?? false,+ glowing: props.glowing ?? false,+ bufferBar: props.bufferBar ?? false,+ });+ } else if (type === XAxis) {+ const props = child.props as XAxisProps;+ xAxis = {+ present: true,+ dataKey: props.dataKey,+ tickFormatter: props.tickFormatter,+ label: props.label,+ hideDots: props.hideDots ?? false,+ };+ } else if (type === YAxis) {+ const props = child.props as YAxisProps;+ yAxis = {+ present: true,+ dataKey: props.dataKey,+ tickFormatter: props.tickFormatter,+ label: props.label,+ hideDots: props.hideDots ?? false,+ };+ } else if (type === Grid) {+ showGrid = true;+ } else if (type === Tooltip) {+ const props = child.props as TooltipProps;+ tooltip = {+ present: true,+ variant: props.variant ?? "default",+ roundness: props.roundness ?? "lg",+ defaultIndex: props.defaultIndex,+ valueFormatter: props.valueFormatter,+ position: props.position ?? "variable",+ };+ } else if (type === Legend) {+ const props = child.props as LegendProps;+ legend = {+ present: true,+ variant: props.variant ?? "rounded-square",+ align: props.align ?? "right",+ verticalAlign: props.verticalAlign ?? "top",+ isClickable: props.isClickable ?? false,+ };+ } else if (type === Brush) {+ const props = child.props as BrushProps;+ brush = {+ present: true,+ height: props.height,+ formatLabel: props.formatLabel,+ onChange: props.onChange,+ };+ }+ });+ return { bars, xAxis, yAxis, showGrid, tooltip, legend, brush };+}++function solidVerticalPaint(+ slots: string[],+ alpha: number,+): string | echarts.graphic.LinearGradient {+ if (slots.length <= 1) {+ const base = slots[0] ?? GRAY;+ return alpha === 1 ? base : withAlpha(base, alpha);+ }+ const stops = slots.map((color, i) => ({+ offset: i / (slots.length - 1),+ color: withAlpha(color, alpha),+ }));+ return new echarts.graphic.LinearGradient(0, 0, 0, 1, stops);+}+function verticalFadePaint(slots: string[]): echarts.graphic.LinearGradient {+ const offsets = [0, 0.2, 0.45, 0.7, 0.9, 1];+ const alphaAt = (t: number) =>+ t <= 0.2 ? 1 : t >= 0.9 ? 0 : 1 - (t - 0.2) / 0.7;+ const stops = offsets.map((t) => ({+ offset: t,+ color: withAlpha(sampleGradient(slots, t), alphaAt(t)),+ }));+ return new echarts.graphic.LinearGradient(0, 0, 0, 1, stops);+}+function duotoneSplitPaint(+ base: string,+ leftAlpha: number,+ rightAlpha: number,+ isHorizontal: boolean,+): echarts.graphic.LinearGradient {+ const stops = [+ { offset: 0, color: withAlpha(base, leftAlpha) },+ { offset: 0.5, color: withAlpha(base, leftAlpha) },+ { offset: 0.5, color: withAlpha(base, rightAlpha) },+ { offset: 1, color: withAlpha(base, rightAlpha) },+ ];+ return isHorizontal+ ? new echarts.graphic.LinearGradient(0, 0, 0, 1, stops)+ : new echarts.graphic.LinearGradient(1, 0, 0, 0, stops);+}+function strippedDatumPaint(+ slots: string[],+ isHorizontal: boolean,+ capFraction: number,+): echarts.graphic.LinearGradient {+ const f = Math.min(Math.max(capFraction, 0), 1);+ const cap = withAlpha(sampleGradient(slots, 0), 1);+ const bodyTop = withAlpha(sampleGradient(slots, f), STRIPPED_BODY_ALPHA);+ const bodyEnd = withAlpha(sampleGradient(slots, 1), STRIPPED_BODY_ALPHA);+ const stops = [+ { offset: 0, color: cap },+ { offset: f, color: cap },+ { offset: f, color: bodyTop },+ { offset: 1, color: bodyEnd },+ ];+ return isHorizontal+ ? new echarts.graphic.LinearGradient(1, 0, 0, 0, stops)+ : new echarts.graphic.LinearGradient(0, 0, 0, 1, stops);+}+function strippedCapFraction(+ value: number,+ valuePxPerUnit: number | null,+): number {+ if (valuePxPerUnit == null) return STRIPPED_FALLBACK_FRACTION;+ const barPx = Math.abs(value) * valuePxPerUnit;+ if (!(barPx > 0)) return STRIPPED_FALLBACK_FRACTION;+ return Math.min(STRIPPED_CAP_HEIGHT / barPx, STRIPPED_CAP_MAX_FRACTION);+}+function measureValuePxPerUnit(+ chart: EChartsInstance,+ isHorizontal: boolean,+): number | null {+ const finder = isHorizontal ? { xAxisIndex: 0 } : { yAxisIndex: 0 };+ try {+ const p0 = chart.convertToPixel(finder, 0);+ const p1 = chart.convertToPixel(finder, 1);+ if (typeof p0 !== "number" || typeof p1 !== "number") return null;+ const delta = Math.abs(p1 - p0);+ return Number.isFinite(delta) && delta > 0 ? delta : null;+ } catch {+ return null;+ }+}+function measureBarWidthPx(+ chart: EChartsInstance,+ isHorizontal: boolean,+ barCategoryGap: number | undefined,+): number | null {+ const finder = isHorizontal ? { yAxisIndex: 0 } : { xAxisIndex: 0 };+ try {+ const p0 = chart.convertToPixel(finder, 0);+ const p1 = chart.convertToPixel(finder, 1);+ if (typeof p0 !== "number" || typeof p1 !== "number") return null;+ const pitch = Math.abs(p1 - p0);+ if (!Number.isFinite(pitch) || pitch <= 0) return null;+ const width = barCategoryGap != null ? pitch - barCategoryGap : pitch * 0.8;+ return width > 1 ? width : null;+ } catch {+ return null;+ }+}+function patternFill(+ kind: "hatched" | "buffer" | "blocks",+ color: string,+ blockSize: number = BLOCK_SIZE,+): ImagePatternObject | null {+ if (typeof document === "undefined") return null;+ const dpr = Math.max(window.devicePixelRatio || 1, 1);+ const canvas = document.createElement("canvas");+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ const size = (width: number, height: number) => {+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ ctx.scale(dpr, dpr);+ };+ const pattern = (rotation = 0): ImagePatternObject => ({+ image: canvas,+ repeat: "repeat",+ rotation,+ scaleX: 1 / dpr,+ scaleY: 1 / dpr,+ });+ if (kind === "blocks") {+ size(1, blockSize + BLOCK_GAP);+ ctx.fillStyle = withAlpha(color, 1);+ ctx.fillRect(0, 0, 1, blockSize);+ return pattern();+ }+ if (kind === "hatched") {+ size(5, 5);+ ctx.fillStyle = withAlpha(color, 0.3);+ ctx.fillRect(0, 0, 5, 5);+ ctx.fillStyle = withAlpha(color, 1);+ ctx.fillRect(0, 0, 1.5, 5);+ return pattern(-Math.PI / 4);+ }+ size(5, 5);+ ctx.fillStyle = withAlpha(color, 1);+ ctx.fillRect(0, 0, 1, 5);+ return pattern(-Math.PI / 4);+}+function expandableDatumPaint(+ slots: string[],+ fraction: number,+): echarts.graphic.LinearGradient {+ const base = slots[0] ?? GRAY;+ const half = Math.max(0, Math.min(1, fraction)) / 2;+ const left = 0.5 - half;+ const right = 0.5 + half;+ const clear = withAlpha(base, 0);+ return new echarts.graphic.LinearGradient(0, 0, 1, 0, [+ { offset: 0, color: clear },+ { offset: left, color: clear },+ { offset: left, color: base },+ { offset: right, color: base },+ { offset: right, color: clear },+ { offset: 1, color: clear },+ ]);+}+function barFillPaint(+ variant: BarVariant,+ slots: string[],+ isHorizontal: boolean,+ blockSize: number = BLOCK_SIZE,+): string | echarts.graphic.LinearGradient | ImagePatternObject {+ const base = slots[0] ?? GRAY;+ switch (variant) {+ case "gradient":+ return verticalFadePaint(slots);+ case "duotone":+ return duotoneSplitPaint(base, 0.4, 1, isHorizontal);+ case "duotone-reverse":+ return duotoneSplitPaint(base, 1, 0.4, isHorizontal);+ case "hatched":+ return patternFill("hatched", base) ?? solidVerticalPaint(slots, 1);+ case "blocks":+ return (+ patternFill("blocks", base, blockSize) ?? solidVerticalPaint(slots, 1)+ );+ case "expandable":+ return expandableDatumPaint(slots, EXPAND_COLLAPSED);+ case "stripped":+ return strippedDatumPaint(+ slots,+ isHorizontal,+ STRIPPED_FALLBACK_FRACTION,+ );+ default:+ return solidVerticalPaint(slots, 1);+ }+}+function barBorderRadius(+ radius: number,+ variant: BarVariant,+ isHorizontal: boolean,+): number | number[] {+ if (variant === "blocks" || variant === "expandable") return 0;+ if (variant !== "stripped") return radius;+ return isHorizontal ? [0, radius, radius, 0] : [radius, radius, 0, 0];+}+function selectionOpacity(selected: string | null, key: string): number {+ return selected === null || selected === key ? 1 : SELECTION_DIM;+}+function barStaggerDelay(+ type: BarAnimationType,+ index: number,+ count: number,+): number {+ if (type === "none" || count <= 0) return 0;+ const last = count - 1;+ const center = last / 2;+ let step: number;+ switch (type) {+ case "right-to-left":+ step = last - index;+ break;+ case "center-out":+ step = Math.abs(index - center);+ break;+ case "edges-in":+ step = center - Math.abs(index - center);+ break;+ default:+ step = index;+ }+ return step * BAR_STAGGER;+}+type OptionBuildContext = {+ data: ChartRow[];+ config: ChartConfig;+ bars: BarSeriesConfig[];+ seriesKeys: string[];+ animationType: BarAnimationType;+ barRadius: number;+ isHorizontal: boolean;+ isStacked: boolean;+ isPercent: boolean;+ selectedDataKey: string | null;+ hasSelection: boolean;+ showGrid: boolean;+ categorySlot: AxisSlot;+ valueSlot: AxisSlot;+ tooltipSlot: TooltipSlot;+ legendSlot: LegendSlot;+ isLoading: boolean;+ loadingData: () => number[];+ showBrush: boolean;+ brushHeight: number;+ barGap?: number;+ barCategoryGap?: number;+ resolved: ResolvedColors;+ categories: string[];+ brushRange: BrushRange;+ valuePxPerUnit: number | null;+ barWidthPx: number | null;+ expand: {+ key: string | null;+ hovered: number | null;+ progress: Map<number, number>;+ };+ maxHighlightIndex: number | null;+};+function buildChartLayout({+ legendSlot,+ showBrush,+ brushHeight,+ isHorizontal,+ categorySlot,+ valueSlot,+}: OptionBuildContext): {+ grid: GridComponentOption;+ brushBottom: number;+} {+ const legendTop = legendSlot.present && legendSlot.verticalAlign === "top";+ const legendBottom =+ legendSlot.present && legendSlot.verticalAlign === "bottom";+ const bottomAxisLabel = isHorizontal ? valueSlot.label : categorySlot.label;+ const brushGap = showBrush+ ? brushHeight + 30 + (bottomAxisLabel ? 22 : 0)+ : 0;+ return {+ grid: {+ left: 8,+ right: 8,+ top: legendTop ? 42 : 16,+ bottom: 8 + brushGap + (legendBottom ? 34 : 0),+ },+ brushBottom: legendBottom ? 34 : 6,+ };+}+function buildMainAxes(ctx: OptionBuildContext): {+ xAxis: XAxisOption;+ yAxis: YAxisOption;+} {+ const {+ isHorizontal,+ showGrid,+ isLoading,+ isPercent,+ categories,+ loadingData,+ categorySlot,+ valueSlot,+ } = ctx;+ const { tokens } = ctx.resolved;+ const axisLabelColor = tokens.mutedForeground;+ const splitLineColor = withAlpha(tokens.border, GRID_LINE_OPACITY);+ const tickDotColor = flattenColor(splitLineColor, tokens.background);+ const catData = isLoading ? loadingData().map((_, i) => i) : categories;+ const catFormatter = categorySlot.tickFormatter;+ const valFormatter = valueSlot.tickFormatter;+ const categoryNameGap = isHorizontal ? 38 : 30;+ const valueNameGap = isHorizontal ? 30 : 38;+ const categoryAxis = {+ type: "category" as const,+ boundaryGap: true,+ show: true,+ inverse: isHorizontal,+ data: catData,+ name: isLoading ? undefined : categorySlot.label,+ nameLocation: "middle" as const,+ nameGap: categoryNameGap,+ nameTextStyle: { color: axisLabelColor, fontSize: 10 },+ axisLine: { show: false },+ axisTick: {+ show: !isLoading && categorySlot.present && !categorySlot.hideDots,+ length: 0.5,+ alignWithLabel: true,+ lineStyle: { color: tickDotColor, width: 3, cap: "round" as const },+ },+ splitLine: { show: false },+ axisLabel: {+ show: !isLoading && categorySlot.present,+ color: axisLabelColor,+ fontSize: 10,+ margin: 8,+ formatter: catFormatter+ ? (value: string, index: number) => catFormatter(value, index)+ : undefined,+ },+ };+ const valueAxis = {+ type: "value" as const,+ show: valueSlot.present || showGrid,+ max: isPercent ? 1 : undefined,+ name: isLoading ? undefined : valueSlot.label,+ nameLocation: "middle" as const,+ nameGap: valueNameGap,+ nameTextStyle: { color: axisLabelColor, fontSize: 10 },+ axisLine: { show: false },+ axisTick: {+ show: valueSlot.present && !isLoading && !valueSlot.hideDots,+ length: 0.5,+ lineStyle: { color: tickDotColor, width: 3, cap: "round" as const },+ },+ splitLine: {+ show: showGrid && !isLoading,+ lineStyle: {+ color: splitLineColor,+ type: [3, 3] as [number, number],+ width: 1,+ },+ },+ axisLabel: {+ show: valueSlot.present && !isLoading,+ color: axisLabelColor,+ fontSize: 10,+ margin: 8,+ formatter: isPercent+ ? (value: number) => `${Math.round(value * 100)}%`+ : valFormatter+ ? (value: number, index: number) => valFormatter(String(value), index)+ : undefined,+ },+ };+ return isHorizontal+ ? { xAxis: valueAxis, yAxis: categoryAxis }+ : { xAxis: categoryAxis, yAxis: valueAxis };+}+function createTooltipFormatter(ctx: OptionBuildContext) {+ const { config, selectedDataKey, tooltipSlot } = ctx;+ return (params: unknown): string => {+ const rows = Array.isArray(params) ? params : [params];+ if (!rows.length) return "";+ const first = rows[0] as {+ axisValue?: string | number;+ name?: string;+ };+ const axisValue = first.axisValue ?? first.name ?? "";+ const label = String(axisValue);+ const body = rows+ .map((param) => {+ const p = param as {+ seriesId?: string;+ seriesName?: string;+ value?: number | string | null;+ };+ if (String(p.seriesId ?? "").startsWith("__")) return "";+ if (p.value == null) return "";+ const key = p.seriesId ?? p.seriesName ?? "";+ const item = config[key];+ const colorsCount = item ? getColorsCount(item) : 1;+ const labelText =+ typeof item?.label === "string" ? item.label : (p.seriesName ?? key);+ const dimmed =+ selectedDataKey != null && selectedDataKey !== key+ ? " opacity-30"+ : "";+ const value =+ typeof p.value === "number"+ ? (tooltipSlot.valueFormatter?.(p.value) ??+ p.value.toLocaleString())+ : String(p.value ?? "");+ return tooltipRow({+ indicatorHtml: tooltipIndicatorHtml(key, colorsCount),+ labelText,+ valueText: value,+ dimmed,+ });+ })+ .join("");+ return tooltipShell({+ label,+ body,+ roundness: tooltipSlot.roundness,+ variant: tooltipSlot.variant,+ });+ };+}+function buildTooltipOption(ctx: OptionBuildContext): TooltipComponentOption {+ const { tooltipSlot, isLoading } = ctx;+ const { tokens } = ctx.resolved;+ return {+ ...tooltipBaseOption({+ present: tooltipSlot.present && !isLoading,+ cursor: false,+ tokens,+ position: tooltipSlot.position,+ axisPointerColor: tokens.border,+ strokeWidth: STROKE_WIDTH,+ }),+ formatter: createTooltipFormatter(ctx),+ };+}+function buildBrushOption(+ ctx: OptionBuildContext,+ brushBottom: number,+): {+ miniGrid: GridComponentOption;+ miniXAxis: XAxisOption;+ miniYAxis: YAxisOption;+ miniSeries: BarSeriesOption[];+ dataZoom: DataZoomComponentOption[];+} {+ const {+ data,+ bars,+ isStacked,+ selectedDataKey,+ hasSelection,+ brushHeight,+ categories,+ } = ctx;+ const { tokens } = ctx.resolved;+ const miniGrid: GridComponentOption = {+ left: 8,+ right: 8,+ bottom: brushBottom,+ height: brushHeight,+ outerBoundsMode: "none",+ };+ const miniXAxis: XAxisOption = {+ type: "category",+ gridIndex: 1,+ boundaryGap: true,+ show: false,+ data: categories,+ axisPointer: { show: false },+ };+ const miniYAxis: YAxisOption = { type: "value", gridIndex: 1, show: false };+ const miniSeries: BarSeriesOption[] = bars.map((bar) => {+ const key = bar.dataKey;+ const base = (ctx.resolved.series[key] ?? [])[0] ?? GRAY;+ const dim = hasSelection && selectedDataKey !== key ? SELECTION_DIM : 1;+ return {+ id: `__mini-${key}`,+ type: "bar",+ xAxisIndex: 1,+ yAxisIndex: 1,+ data: data.map((row) => finiteValue(row[key])),+ stack: isStacked ? "__mini-total" : undefined,+ silent: true,+ barCategoryGap: "20%",+ emphasis: { disabled: true },+ tooltip: { show: false },+ itemStyle: {+ color: base,+ opacity: BRUSH_FILL_OPACITY * dim,+ borderRadius: 1,+ },+ z: 0,+ animation: false,+ };+ });+ const dataZoom = buildBrushDataZoom({+ brushBottom,+ brushHeight,+ brushRange: ctx.brushRange,+ fillerColor: withAlpha(tokens.foreground, BRUSH_FILLER_OPACITY),+ });+ return { miniGrid, miniXAxis, miniYAxis, miniSeries, dataZoom };+}+function buildLoadingOption(+ ctx: OptionBuildContext,+ frame: {+ grid: GridComponentOption;+ xAxis: XAxisOption;+ yAxis: YAxisOption;+ },+): EChartsOption {+ const { tokens } = ctx.resolved;+ return {+ animation: false,+ grid: frame.grid,+ xAxis: frame.xAxis,+ yAxis: frame.yAxis,+ tooltip: { show: false },+ series: [+ {+ id: "__loading",+ type: "bar",+ data: ctx.loadingData(),+ barCategoryGap: "30%",+ silent: true,+ itemStyle: {+ color: withAlpha(tokens.foreground, 0),+ borderRadius: barBorderRadius(+ DEFAULT_BAR_RADIUS,+ "default",+ ctx.isHorizontal,+ ),+ },+ z: 1,+ },+ ],+ };+}+function buildBarSeries(ctx: OptionBuildContext): BarSeriesOption[] {+ const {+ data,+ config,+ bars,+ seriesKeys,+ animationType,+ isHorizontal,+ isStacked,+ isPercent,+ selectedDataKey,+ hasSelection,+ barGap,+ barCategoryGap,+ resolved,+ } = ctx;+ const lastIndex = data.length - 1;+ const rowTotals = isPercent+ ? data.map((row) =>+ finiteSum(seriesKeys.map((key) => finiteValue(row[key]) ?? 0)),+ )+ : [];+ const series: BarSeriesOption[] = bars.map((bar) => {+ const key = bar.dataKey;+ const slots = resolved.series[key] ?? [GRAY];+ const base = slots[0] ?? GRAY;+ const isSelected = selectedDataKey === key;+ const dim = selectionOpacity(selectedDataKey, key);+ const resolvedRadius = bar.radius ?? ctx.barRadius;+ const borderRadius = barBorderRadius(+ resolvedRadius,+ bar.variant,+ isHorizontal,+ );+ const blockSize = ctx.barWidthPx ?? BLOCK_SIZE;+ const fill = barFillPaint(bar.variant, slots, isHorizontal, blockSize);+ const barAnim = bar.animationType ?? animationType;+ const isStripped = bar.variant === "stripped";+ const isExpandable = bar.variant === "expandable";+ const mutedFill = withAlpha(+ resolved.tokens.mutedForeground,+ MAX_HIGHLIGHT_DIM,+ );+ const isMuted = (i: number) =>+ ctx.maxHighlightIndex != null && i !== ctx.maxHighlightIndex;+ const expandOf = (i: number) =>+ ctx.expand.key === key+ ? (ctx.expand.progress.get(i) ?? EXPAND_COLLAPSED)+ : EXPAND_COLLAPSED;+ const expandHovered = ctx.expand.key === key ? ctx.expand.hovered : null;+ const isBlocks = bar.variant === "blocks";+ const blockTrack = isBlocks+ ? patternFill(+ "blocks",+ withAlpha(resolved.tokens.mutedForeground, BLOCK_TRACK_OPACITY),+ blockSize,+ )+ : null;+ const values = data.map((row, i) => {+ const value = finiteValue(row[key]);+ if (value === null) return null;+ if (!isPercent) return value;+ const total = rowTotals[i];+ return total ? value / total : 0;+ });+ const bufferStyle = bar.bufferBar+ ? {+ color: patternFill("buffer", base) ?? "transparent",+ borderColor: base,+ borderWidth: STROKE_WIDTH,+ borderRadius,+ }+ : null;+ const glowAt = (i: number) => ({+ shadowBlur: GLOW_BLUR,+ shadowColor: withAlpha(+ sampleGradient(slots, values.length > 1 ? i / (values.length - 1) : 0),+ GLOW_OPACITY,+ ),+ });+ const glowFor = bar.glowing+ ? glowAt+ : ctx.maxHighlightIndex != null+ ? (i: number) => (i === ctx.maxHighlightIndex ? glowAt(i) : {})+ : null;+ const dataPoints =+ isStripped ||+ isExpandable ||+ glowFor ||+ ctx.maxHighlightIndex != null ||+ (bufferStyle && lastIndex >= 0)+ ? values.map((value, i) => {+ if (value === null) return null;+ const isBuffer = !!bufferStyle && i === lastIndex;+ if (+ !isBuffer &&+ !glowFor &&+ !isStripped &&+ !isExpandable &&+ !isMuted(i)+ )+ return value;+ return {+ value,+ ...(isExpandable ? { label: { show: i === expandHovered } } : {}),+ itemStyle: {+ ...(isStripped && !isBuffer+ ? {+ color: strippedDatumPaint(+ slots,+ isHorizontal,+ strippedCapFraction(value, ctx.valuePxPerUnit),+ ),+ }+ : {}),+ ...(isExpandable && !isBuffer+ ? { color: expandableDatumPaint(slots, expandOf(i)) }+ : {}),+ ...(isBuffer && bufferStyle ? bufferStyle : {}),+ ...(glowFor ? glowFor(i) : {}),+ ...(isMuted(i) ? { color: mutedFill } : {}),+ },+ };+ })+ : values;+ return {+ id: key,+ name: typeof config[key]?.label === "string" ? config[key]?.label : key,+ type: "bar",+ data: dataPoints,+ stack: isStacked ? "total" : undefined,+ barGap,+ barCategoryGap,+ cursor: bar.isClickable ? "pointer" : "default",+ z: isSelected ? 3 : hasSelection ? 1 : 2,+ label: isExpandable+ ? {+ show: false,+ position: "top",+ color: resolved.tokens.foreground,+ fontFamily: "var(--font-mono, monospace)",+ fontSize: 11,+ }+ : undefined,+ showBackground: isBlocks,+ backgroundStyle: blockTrack+ ? { color: blockTrack, borderRadius }+ : undefined,+ itemStyle: {+ color: fill,+ borderRadius,+ opacity: dim,+ },+ emphasis:+ bar.enableHoverHighlight && !hasSelection+ ? { focus: "self" as const, blurScope: "coordinateSystem" as const }+ : { disabled: true },+ blur:+ bar.enableHoverHighlight && !hasSelection+ ? { itemStyle: { opacity: HOVER_BLUR } }+ : undefined,+ animationDuration: BAR_GROW_DURATION,+ animationEasing: "cubicOut",+ animationDelay: (idx: number) =>+ barStaggerDelay(barAnim, idx, data.length),+ };+ });+ const gapUnits =+ (isStacked || isPercent) && series.length > 1 && ctx.valuePxPerUnit+ ? STACK_SEGMENT_GAP / ctx.valuePxPerUnit+ : 0;+ if (!gapUnits) return series;+ const spaced: BarSeriesOption[] = [];+ series.forEach((entry, i) => {+ spaced.push(entry);+ if (i === series.length - 1) return;+ spaced.push({+ id: `__stackgap-${i}`,+ type: "bar",+ stack: isStacked ? "total" : undefined,+ data: data.map(() => gapUnits),+ itemStyle: { color: "transparent" },+ silent: true,+ tooltip: { show: false },+ legendHoverLink: false,+ emphasis: { disabled: true },+ animation: false,+ z: 1,+ });+ });+ return spaced;+}+type LiveState = {+ resolved: ResolvedColors | null;+ hasRevealed: boolean;+ revealEndsAt: number;+ valuePxPerUnit: number | null;+ barWidthPx: number | null;+ expand: {+ key: string | null;+ hovered: number | null;+ progress: Map<number, number>;+ };+ expandRaf: number;+ animateExpand: (key: string | null, index: number | null) => void;+ loadingRows: number[] | null;+ categories: string[];+ dataLength: number;+ brushRange: BrushRange;+ brushGeom: BrushGeometry | null;+ brushOverlay: BrushOverlayElements | null;+ brushHover: {+ inside: boolean;+ left: boolean;+ right: boolean;+ };+ handlers: {+ onBrushChange?: (range: { startIndex: number; endIndex: number }) => void;+ clickableKeys: Set<string>;+ selectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+ brushFormatLabel?: (value: string, index: number) => string;+ seriesKeys: string[];+ hasStripped: boolean;+ hasBlocks: boolean;+ hasStackGap: boolean;+ expandableKey: string | null;+ barCategoryGap?: number;+ isHorizontal: boolean;+ };+ repush: () => void;+ patchStrippedCaps: () => void;+};+export function EChartsBarChart<TData extends ChartRow>({+ data,+ config,+ renderer = DEFAULT_ECHARTS_RENDERER,+ xDataKey,+ className,+ stackType = "default",+ layout = "vertical",+ barRadius = DEFAULT_BAR_RADIUS,+ animation = true,+ animationType = "left-to-right",+ barGap,+ barCategoryGap,+ defaultSelectedDataKey = null,+ onSelectionChange,+ enableMaxValueHighlight = false,+ isLoading = false,+ loadingBars = LOADING_DEFAULT_BARS,+ chartOptions,+ activeIndex,+ children,+}: EChartsBarChartProps<TData>) {+ const rawId = useId();+ const chartId = `chart-${rawId.replace(/:/g, "")}`;+ const containerRef = useRef<HTMLDivElement>(null);+ const mountRef = useRef<HTMLDivElement>(null);+ const echartsRef = useRef<EChartsInstance | null>(null);+ const live = useRef<LiveState>({+ resolved: null,+ hasRevealed: false,+ revealEndsAt: 0,+ valuePxPerUnit: null,+ barWidthPx: null,+ expand: { key: null, hovered: null, progress: new Map<number, number>() },+ expandRaf: 0,+ animateExpand: () => {},+ loadingRows: null,+ categories: [],+ dataLength: 0,+ brushRange: { start: 0, end: 100 },+ brushGeom: null,+ brushOverlay: null,+ brushHover: { inside: false, left: false, right: false },+ handlers: {+ onBrushChange: undefined,+ clickableKeys: new Set<string>(),+ brushFormatLabel: undefined,+ seriesKeys: [],+ hasStripped: false,+ hasBlocks: false,+ hasStackGap: false,+ expandableKey: null,+ isHorizontal: false,+ },+ repush: () => {},+ patchStrippedCaps: () => {},+ }).current;+ const loadingData = useCallback(+ () => (live.loadingRows ??= getLoadingBarData(loadingBars)),+ [live, loadingBars],+ );+ const shouldReduceMotion = useReducedMotion();+ const [selectedDataKey, setSelectedDataKey] = useState<string | null>(+ defaultSelectedDataKey,+ );+ const collected = useMemo(() => collectConfig(children), [children]);+ const {+ bars,+ xAxis: xAxisSlot,+ yAxis: yAxisSlot,+ showGrid,+ tooltip: tooltipSlot,+ legend: legendSlot,+ brush: brushSlot,+ } = collected;+ const showBrush = brushSlot.present;+ const brushHeight = brushSlot.height ?? 56;+ const isHorizontal = layout === "horizontal";+ const isPercent = stackType === "percent";+ const isStacked = stackType === "stacked" || isPercent;+ const categorySlot = isHorizontal ? yAxisSlot : xAxisSlot;+ const valueSlot = isHorizontal ? xAxisSlot : yAxisSlot;+ const seriesKeys = useMemo(() => bars.map((bar) => bar.dataKey), [bars]);+ const categoryKey = useMemo(() => {+ if (categorySlot.dataKey) return categorySlot.dataKey;+ if (xDataKey) return xDataKey as string;+ const firstRow = data[0];+ if (firstRow) {+ const claimed = new Set(seriesKeys);+ const found = Object.keys(firstRow).find((key) => !claimed.has(key));+ if (found) return found;+ }+ return "";+ }, [categorySlot.dataKey, xDataKey, data, seriesKeys]);+ const effectiveAnimation = bars[0]?.animationType ?? animationType;+ const maxHighlightIndex = useMemo(() => {+ if (!enableMaxValueHighlight || !data.length || !seriesKeys.length)+ return null;+ let best = 0;+ let bestTotal = -Infinity;+ data.forEach((row, i) => {+ const total = finiteSum(+ seriesKeys.map((key) => finiteValue(row[key]) ?? 0),+ );+ if (total > bestTotal) {+ bestTotal = total;+ best = i;+ }+ });+ return best;+ }, [enableMaxValueHighlight, data, seriesKeys]);+ const css = useMemo(() => buildChartCss(chartId, config), [chartId, config]);+ const hasSelection = selectedDataKey !== null;+ const clickableKeys = useMemo(+ () =>+ new Set(bars.filter((bar) => bar.isClickable).map((bar) => bar.dataKey)),+ [bars],+ );+ const hasStrippedBars =+ !isLoading && bars.some((bar) => bar.variant === "stripped");++ const toggleSelection = useCallback(+ (key: string) => {+ const next = live.handlers.selectedDataKey === key ? null : key;+ live.handlers.selectedDataKey = next;+ setSelectedDataKey(next);+ live.handlers.onSelectionChange?.(next);+ },+ [live],+ );+ const brushEnabled = showBrush && !isHorizontal;+ const syncBrushOverlayNow = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart) return;+ const geom = live.brushGeom;+ const tokens = live.resolved?.tokens;+ if (!geom || !tokens) {+ syncBrushOverlay(chart, live, null);+ return;+ }+ const range = live.brushRange;+ const categories = live.categories;+ const format = live.handlers.brushFormatLabel;+ const lastIndex = Math.max(categories.length - 1, 0);+ const startIndex = Math.round((range.start / 100) * lastIndex);+ const endIndex = Math.round((range.end / 100) * lastIndex);+ const labels =+ format && categories.length+ ? {+ start: format(categories[startIndex] ?? "", startIndex),+ end: format(categories[endIndex] ?? "", endIndex),+ }+ : null;+ syncBrushOverlay(chart, live, {+ range,+ geom,+ size: { width: chart.getWidth(), height: chart.getHeight() },+ tokens,+ labels,+ showLabels: live.brushHover.inside,+ hover: live.brushHover,+ });+ }, [live]);+ const buildOption = useCallback((): EChartsOption => {+ const resolved = live.resolved;+ if (!resolved) return {};+ const categories = data.map((row) => String(row[categoryKey]));+ live.categories = categories;+ const ctx: OptionBuildContext = {+ data,+ config,+ bars,+ seriesKeys,+ animationType,+ barRadius,+ isHorizontal,+ isStacked,+ isPercent,+ selectedDataKey,+ hasSelection,+ showGrid,+ categorySlot,+ valueSlot,+ tooltipSlot,+ legendSlot,+ isLoading,+ loadingData,+ showBrush: brushEnabled,+ brushHeight,+ barGap,+ barCategoryGap,+ resolved,+ categories,+ brushRange: live.brushRange,+ valuePxPerUnit: live.valuePxPerUnit,+ barWidthPx: live.barWidthPx,+ expand: live.expand,+ maxHighlightIndex,+ };+ const { grid, brushBottom } = buildChartLayout(ctx);+ live.brushGeom = brushEnabled+ ? { bottom: brushBottom, height: brushHeight }+ : null;+ const { xAxis, yAxis } = buildMainAxes(ctx);+ if (isLoading) return buildLoadingOption(ctx, { grid, xAxis, yAxis });+ const brush = brushEnabled ? buildBrushOption(ctx, brushBottom) : null;+ return {+ animation: false,+ grid: brush ? [grid, brush.miniGrid] : grid,+ xAxis: brush ? [xAxis, brush.miniXAxis] : xAxis,+ yAxis: brush ? [yAxis, brush.miniYAxis] : yAxis,+ tooltip: buildTooltipOption(ctx),+ dataZoom: brush?.dataZoom,+ series: [...buildBarSeries(ctx), ...(brush?.miniSeries ?? [])],+ };+ }, [+ live,+ data,+ config,+ bars,+ seriesKeys,+ categoryKey,+ animationType,+ barRadius,+ isHorizontal,+ isStacked,+ isPercent,+ selectedDataKey,+ hasSelection,+ showGrid,+ categorySlot,+ valueSlot,+ tooltipSlot,+ legendSlot,+ isLoading,+ loadingData,+ brushEnabled,+ brushHeight,+ barGap,+ barCategoryGap,+ maxHighlightIndex,+ ]);+ const setupChart = useCallback(() => {+ const mount = mountRef.current;+ const container = containerRef.current;+ if (!mount || !container) return;+ const chart = echarts.init(mount, null, { renderer });+ echartsRef.current = chart;+ const resizeObserver = new ResizeObserver(() => {+ if (+ mount.clientWidth === chart.getWidth() &&+ mount.clientHeight === chart.getHeight()+ ) {+ return;+ }+ chart.resize();+ live.repush();+ });+ resizeObserver.observe(mount);+ const themeObserver = observeChartTheme(container, () => live.repush());+ chart+ .getZr()+ .on("mousemove", (event: { offsetX: number; offsetY: number }) => {+ const { expandableKey } = live.handlers;+ if (!expandableKey) return;+ const point = [event.offsetX, event.offsetY];+ if (!chart.containPixel({ gridIndex: 0 }, point)) {+ live.animateExpand(expandableKey, null);+ return;+ }+ const converted = chart.convertFromPixel({ gridIndex: 0 }, point);+ const index = Array.isArray(converted)+ ? converted[live.handlers.isHorizontal ? 1 : 0]+ : converted;+ live.animateExpand(+ expandableKey,+ typeof index === "number" ? Math.round(index) : null,+ );+ });+ chart.getZr().on("globalout", () => {+ const { expandableKey } = live.handlers;+ if (expandableKey) live.animateExpand(expandableKey, null);+ });+ chart.on("click", (params) => {+ const { clickableKeys: clickable, seriesKeys: keys } = live.handlers;+ const p = params as {+ seriesId?: string;+ seriesIndex?: number;+ };+ const id =+ p.seriesId ??+ (typeof p.seriesIndex === "number" ? keys[p.seriesIndex] : undefined);+ if (typeof id === "string" && clickable.has(id)) toggleSelection(id);+ });+ chart.on("datazoom", () => {+ const option = chart.getOption() as {+ dataZoom?: {+ start?: number;+ end?: number;+ }[];+ };+ const zoom = option.dataZoom?.[0];+ if (!zoom) return;+ live.brushRange = { start: zoom.start ?? 0, end: zoom.end ?? 100 };+ syncBrushOverlayNow();+ const { onBrushChange: onChange } = live.handlers;+ if (!onChange) return;+ const len = live.dataLength;+ if (len < 1) return;+ const startIndex = Math.round(((zoom.start ?? 0) / 100) * (len - 1));+ const endIndex = Math.round(((zoom.end ?? 100) / 100) * (len - 1));+ onChange({ startIndex, endIndex });+ });+ chart.on("finished", () => {+ const { hasStripped, isHorizontal: horiz } = live.handlers;+ if (!hasStripped || performance.now() < live.revealEndsAt) return;+ const measured = measureValuePxPerUnit(chart, horiz);+ if (measured == null) return;+ if (+ live.valuePxPerUnit != null &&+ Math.abs(measured - live.valuePxPerUnit) < 0.5+ )+ return;+ live.valuePxPerUnit = measured;+ live.patchStrippedCaps();+ });+ const zr = chart.getZr();+ const applyHover = (next: {+ inside: boolean;+ left: boolean;+ right: boolean;+ }) => {+ const prev = live.brushHover;+ if (+ prev.inside === next.inside &&+ prev.left === next.left &&+ prev.right === next.right+ ) {+ return;+ }+ live.brushHover = next;+ syncBrushOverlayNow();+ };+ const onZrMove = (event: { offsetX?: number; offsetY?: number }) => {+ const geom = live.brushGeom;+ if (!geom) return;+ const x = event.offsetX ?? -1;+ const y = event.offsetY ?? -1;+ const top = chart.getHeight() - geom.bottom - geom.height;+ const inside = y >= top - 4 && y <= top + geom.height + 4;+ const trackLeft = 8;+ const trackWidth = Math.max(chart.getWidth() - 16, 1);+ const { start, end } = live.brushRange;+ const selectionLeft = trackLeft + (trackWidth * start) / 100;+ const selectionRight = trackLeft + (trackWidth * end) / 100;+ applyHover({+ inside,+ left: inside && Math.abs(x - selectionLeft) <= 8,+ right: inside && Math.abs(x - selectionRight) <= 8,+ });+ };+ const onZrOut = () =>+ applyHover({ inside: false, left: false, right: false });+ zr.on("mousemove", onZrMove);+ zr.on("globalout", onZrOut);+ return () => {+ zr.off("mousemove", onZrMove);+ zr.off("globalout", onZrOut);+ resizeObserver.disconnect();+ themeObserver.disconnect();+ if (live.expandRaf) {+ cancelAnimationFrame(live.expandRaf);+ live.expandRaf = 0;+ }+ cancelActiveTooltip(chart);+ chart.off();+ chart.getZr().off();+ chart.dispose();+ live.repush = () => {};+ echartsRef.current = null;+ live.brushOverlay = null;+ live.brushHover = { inside: false, left: false, right: false };+ live.expand = {+ key: null,+ hovered: null,+ progress: new Map<number, number>(),+ };+ live.animateExpand = () => {};+ live.valuePxPerUnit = null;+ live.barWidthPx = null;+ live.hasRevealed = false;+ };+ }, [renderer]);+ const synchronizeChart = useCallback(() => {+ if (live.expandRaf) cancelAnimationFrame(live.expandRaf);+ live.expandRaf = 0;+ const hovered = boundedIndex(live.expand.hovered, data.length);+ live.expand.hovered = hovered;+ live.expand.progress.clear();+ if (hovered !== null) live.expand.progress.set(hovered, 1);+ const chart = echartsRef.current;+ const container = containerRef.current;+ if (!chart || !container) return;+ live.resolved = resolveColors(container, config, seriesKeys);+ const push = (withEntrance: boolean) => {+ const measured = measureValuePxPerUnit(chart, isHorizontal);+ if (measured != null) live.valuePxPerUnit = measured;+ const apply = () => {+ const option = buildOption();+ const merged = chartOptions ? { ...option, ...chartOptions } : option;+ Object.assign(merged, {+ animation: withEntrance,+ animationDuration: BAR_GROW_DURATION,+ animationDurationUpdate: 0,+ });+ setChartOption(chart, merged);+ if (activeIndex !== undefined)+ showActiveIndex(+ chart,+ isLoading ? null : boundedIndex(activeIndex, data.length),+ seriesKeys[0],+ );+ };+ apply();+ let needsRebuild = false;+ if (live.handlers.hasBlocks) {+ const width = measureBarWidthPx(chart, isHorizontal, barCategoryGap);+ if (+ width != null &&+ (live.barWidthPx == null || Math.abs(width - live.barWidthPx) > 0.5)+ ) {+ live.barWidthPx = width;+ needsRebuild = true;+ }+ }+ if (live.handlers.hasStackGap || live.handlers.hasStripped) {+ const scale = measureValuePxPerUnit(chart, isHorizontal);+ if (+ scale != null &&+ (live.valuePxPerUnit == null || live.valuePxPerUnit !== scale)+ ) {+ live.valuePxPerUnit = scale;+ needsRebuild = true;+ }+ }+ if (needsRebuild) apply();+ const maxStagger = data.length > 1 ? (data.length - 1) * BAR_STAGGER : 0;+ live.revealEndsAt = withEntrance+ ? performance.now() + BAR_GROW_DURATION + maxStagger+ : 0;+ syncBrushOverlayNow();+ };+ live.animateExpand = (key: string | null, index: number | null) => {+ const expandKeys = new Set(+ bars+ .filter((bar) => bar.variant === "expandable")+ .map((bar) => bar.dataKey),+ );+ if (!expandKeys.size) return;+ const next = key != null ? boundedIndex(index, data.length) : null;+ if (+ live.expand.hovered === next &&+ (key == null || live.expand.key === key)+ )+ return;+ if (key != null) live.expand.key = key;+ live.expand.hovered = next;+ if (next != null && !live.expand.progress.has(next)) {+ live.expand.progress.set(next, EXPAND_COLLAPSED);+ }+ if (live.expandRaf) return;+ const patchOnce = () => {+ const option = buildOption();+ const series = Array.isArray(option.series)+ ? option.series+ : option.series+ ? [option.series]+ : [];+ const patch = series.filter(+ (s): s is BarSeriesOption =>+ typeof s?.id === "string" && expandKeys.has(s.id),+ );+ if (patch.length)+ chart.setOption(+ { series: patch },+ { silent: true, lazyUpdate: true },+ );+ };+ if (shouldReduceMotion) {+ live.expand.progress.clear();+ if (next !== null) live.expand.progress.set(next, 1);+ patchOnce();+ return;+ }+ let last = performance.now();+ const step = () => {+ const now = performance.now();+ const dt = Math.min(64, now - last);+ last = now;+ const k = 1 - Math.exp(-dt / EXPAND_TAU);+ let moving = false;+ for (const [i, value] of live.expand.progress) {+ const target = i === live.expand.hovered ? 1 : EXPAND_COLLAPSED;+ const eased = value + (target - value) * k;+ if (Math.abs(target - eased) < 0.004) {+ if (target === EXPAND_COLLAPSED) live.expand.progress.delete(i);+ else live.expand.progress.set(i, target);+ } else {+ live.expand.progress.set(i, eased);+ moving = true;+ }+ }+ patchOnce();+ live.expandRaf = moving ? requestAnimationFrame(step) : 0;+ };+ live.expandRaf = requestAnimationFrame(step);+ };+ live.patchStrippedCaps = () => {+ const option = buildOption();+ const series = Array.isArray(option.series)+ ? option.series+ : option.series+ ? [option.series]+ : [];+ const strippedKeys = new Set(+ bars+ .filter((bar) => bar.variant === "stripped")+ .map((bar) => bar.dataKey),+ );+ const patch = series.filter(+ (s): s is BarSeriesOption =>+ typeof s?.id === "string" && strippedKeys.has(s.id),+ );+ if (patch.length)+ chart.setOption({ series: patch }, { silent: true, lazyUpdate: true });+ };+ if (isLoading) live.hasRevealed = false;+ const shouldReveal = !live.hasRevealed && !isLoading;+ if (shouldReveal) live.hasRevealed = true;+ const revealEnabled =+ animation &&+ shouldReveal &&+ effectiveAnimation !== "none" &&+ !shouldReduceMotion;+ push(revealEnabled);+ live.repush = () => {+ live.resolved = resolveColors(container, config, seriesKeys);+ push(false);+ };+ }, [+ renderer,+ live,+ buildOption,+ chartOptions,+ activeIndex,+ data.length,+ isLoading,+ animation,+ effectiveAnimation,+ shouldReduceMotion,+ config,+ seriesKeys,+ data.length,+ bars,+ isHorizontal,+ barCategoryGap,+ syncBrushOverlayNow,+ ]);+ const animatePrimary = useCallback(() => {+ const chart = echartsRef.current;+ const index = tooltipSlot.defaultIndex;+ if (+ !chart ||+ isLoading ||+ activeIndex !== undefined ||+ !tooltipSlot.present ||+ boundedIndex(index, data.length) === null+ )+ return;+ const timer = setTimeout(() => {+ chart.dispatchAction({+ type: "showTip",+ seriesIndex: 0,+ dataIndex: index,+ });+ }, 300);+ return () => clearTimeout(timer);+ }, [+ renderer,+ tooltipSlot.present,+ tooltipSlot.defaultIndex,+ activeIndex,+ isLoading,+ data.length,+ seriesKeys.length,+ ]);+ const animateLoading = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart || !isLoading || shouldReduceMotion) return;+ let raf = 0;+ let lastPhase = 0;+ const start = performance.now();+ const tick = (now: number) => {+ const phase =+ ((((now - start) / LOADING_ANIMATION_DURATION) % 1) + 1) % 1;+ if (phase < lastPhase) live.loadingRows = getLoadingBarData(loadingBars);+ lastPhase = phase;+ const foreground = live.resolved?.tokens.foreground ?? GRAY;+ const w = chart.getWidth();+ const h = chart.getHeight();+ if (!w || !h) {+ raf = requestAnimationFrame(tick);+ return;+ }+ const maxT = (w + h) / (2 * w);+ const center =+ phase * (maxT + 2 * LOADING_SHIMMER_BAND) - LOADING_SHIMMER_BAND;+ const fill = new echarts.graphic.LinearGradient(+ 0,+ 0,+ w,+ w,+ shimmerWindowStops(center, foreground, LOADING_SHIMMER_MAX_OPACITY),+ true,+ );+ chart.setOption(+ {+ series: [+ {+ id: "__loading",+ data: loadingData(),+ itemStyle: { color: fill },+ },+ ],+ },+ { silent: true, lazyUpdate: true },+ );+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [renderer, live, isLoading, loadingBars, loadingData, shouldReduceMotion]);+ const commitChart = useChartLifecycle(+ {+ prepare: () => {+ live.handlers = {+ onBrushChange: brushSlot.onChange,+ selectedDataKey,+ onSelectionChange,+ clickableKeys,+ brushFormatLabel: brushSlot.formatLabel,+ seriesKeys,+ hasStripped: hasStrippedBars,+ hasBlocks: bars.some((bar) => bar.variant === "blocks"),+ hasStackGap:+ (stackType === "stacked" || stackType === "percent") &&+ bars.length > 1,+ expandableKey:+ bars.find((bar) => bar.variant === "expandable")?.dataKey ?? null,+ barCategoryGap,+ isHorizontal,+ };+ live.dataLength = data.length;+ },+ setup: setupChart,+ synchronize: synchronizeChart,+ animate: [animatePrimary, animateLoading],+ },+ containerRef,+ );++ const legendStyle: CSSProperties = {+ position: "absolute",+ left: 16,+ right: 16,+ pointerEvents: "auto",+ ...(legendSlot.verticalAlign === "top"+ ? { top: 12 }+ : legendSlot.verticalAlign === "bottom"+ ? { bottom: brushEnabled ? brushHeight + 16 : 12 }+ : { top: "50%", transform: "translateY(-50%)" }),+ };+ return (+ <div+ ref={commitChart}+ data-chart={chartId}+ className={`relative flex flex-col text-xs ${className ?? ""}`}+ >+ <style dangerouslySetInnerHTML={{ __html: css }} />++ <div className="relative min-h-0 w-full flex-1">+ <div ref={mountRef} className="h-full min-h-0 w-full" />+ </div>++ {legendSlot.present && !isLoading && (+ <LegendOverlay+ seriesKeys={seriesKeys}+ config={config}+ variant={legendSlot.variant}+ align={legendSlot.align}+ verticalAlign={legendSlot.verticalAlign}+ selectedKey={selectedDataKey}+ hoveredKey={null}+ isClickable={legendSlot.isClickable}+ onToggle={toggleSelection}+ style={legendStyle}+ />+ )}+ </div>+ );+}+function getLoadingBarData(bars: number): number[] {+ const rows: number[] = [];+ let value = 40 + Math.random() * 25;+ for (let i = 0; i < bars; i++) {+ value = Math.min(85, Math.max(20, value + (Math.random() - 0.5) * 30));+ rows.push(Math.round(value));+ }+ return rows;+}+function shimmerWindowStops(center: number, color: string, peak: number) {+ const half = LOADING_SHIMMER_BAND;+ const feather = LOADING_SHIMMER_FEATHER;+ const alphaAt = (x: number) => {+ const dist = Math.abs(x - center);+ if (dist <= half - feather) return peak;+ if (dist >= half) return 0;+ return (+ peak * Math.sin(((1 - (dist - (half - feather)) / feather) * Math.PI) / 2)+ );+ };+ const offsets = [+ 0,+ center - half,+ center - half + feather,+ center,+ center + half - feather,+ center + half,+ 1,+ ]+ .filter((x) => x >= 0 && x <= 1)+ .sort((a, b) => a - b);+ const stops: {+ offset: number;+ color: string;+ }[] = [];+ for (const offset of offsets) {+ if (+ stops.length === 0 ||+ offset - (stops.at(-1)?.offset ?? -Infinity) > 1e-4+ ) {+ stops.push({ offset, color: withAlpha(color, alphaAt(offset)) });+ }+ }+ return stops;+}+EChartsBarChart.Bar = Bar;+EChartsBarChart.XAxis = XAxis;+EChartsBarChart.YAxis = YAxis;+EChartsBarChart.Grid = Grid;+EChartsBarChart.Tooltip = Tooltip;+EChartsBarChart.Legend = Legend;+EChartsBarChart.Brush = Brush;diff --git a/packages/ui/src/components/evilcharts/charts/echarts-pie-chart.tsx b/packages/ui/src/components/evilcharts/charts/echarts-pie-chart.tsxnew file mode 100644index 00000000..7f592a89--- /dev/null+++ b/packages/ui/src/components/evilcharts/charts/echarts-pie-chart.tsx@@ -0,0 +1,1075 @@+"use client";+import { PieChart, type PieSeriesOption } from "echarts/charts";+import {+ TooltipComponent,+ type TooltipComponentOption,+} from "echarts/components";+import type { ComposeOption } from "echarts/core";+import * as echarts from "echarts/core";+import {+ Children,+ type CSSProperties,+ type FC,+ isValidElement,+ type ReactNode,+ useCallback,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ buildChartCss,+ type ChartConfig,+ type ChartRow,+ DEFAULT_ECHARTS_RENDERER,+ type EChartsRenderer,+ finiteValue,+ getColorsCount,+ type ResolvedColors,+ resolveColors,+ withAlpha,+} from "../ui/echarts-chart";+import { ECHARTS_CONFIG } from "../ui/echarts-config";+import { LegendOverlay, type LegendVariant } from "../ui/echarts-legend";+import {+ boundedIndex,+ cancelActiveTooltip,+ observeChartTheme,+ showActiveIndex,+ useChartLifecycle,+ useReducedMotion,+} from "../ui/echarts-lifecycle";+import { setChartOption } from "../ui/echarts-options";+import {+ resolveTooltipPosition,+ roundnessClass,+ type TooltipPosition,+ type TooltipRoundness,+ type TooltipVariant,+ tooltipIndicatorHtml,+ tooltipRow,+ tooltipVariantClass,+} from "../ui/echarts-tooltip";++export type {+ ChartConfig,+ EChartsRenderer,+ LegendVariant,+ TooltipPosition,+ TooltipRoundness,+ TooltipVariant,+};++echarts.use([PieChart, TooltipComponent]);+type EChartsInstance = ReturnType<typeof echarts.init>;+type EChartsOption = ComposeOption<PieSeriesOption | TooltipComponentOption>;+type PieItemStyle = {+ color: string | echarts.graphic.LinearGradient;+ opacity: number;+ borderRadius: number;+ borderColor?: string;+ borderWidth?: number;+};+const {+ REVEAL_DURATION,+ LOADING_ANIMATION_DURATION,+ LOADING_SECTORS,+ DEFAULT_INNER_RADIUS,+ DEFAULT_OUTER_RADIUS,+ DEFAULT_CORNER_RADIUS,+ DEFAULT_PADDING_ANGLE,+ DEFAULT_START_ANGLE,+ DEFAULT_END_ANGLE,+ FALLBACK_COLOR,+ OVERLAP_BORDER_WIDTH,+ SELECTED_OFFSET,+ DIMMED_OPACITY,+ LOADING_BASE_OPACITY,+ LOADING_PEAK_OPACITY,+ LOADING_SHIMMER_BAND,+ LOADING_SHIMMER_FEATHER,+} = ECHARTS_CONFIG.pie;++function gapBorderWidth(paddingAngle: number): number {+ return Math.max(paddingAngle, 0);+}+function sectorBorder(+ paddingAngle: number,+ background: string,+): {+ borderColor: string;+ borderWidth: number;+} | null {+ if (paddingAngle < 0)+ return { borderColor: background, borderWidth: OVERLAP_BORDER_WIDTH };+ const width = gapBorderWidth(paddingAngle);+ if (width > 0) return { borderColor: background, borderWidth: width };+ return null;+}++export type PieVariant = "gradient";+export type LabelPosition = "inside" | "outside";+export type BackgroundVariant =+ | "dots"+ | "grid"+ | "cross-hatch"+ | "diagonal-lines"+ | "plus"+ | "falling-triangles"+ | "4-pointed-star"+ | "tiny-checkers"+ | "overlapping-circles"+ | "wiggle-lines"+ | "bubbles";+export interface EChartsPieChartProps<TData extends ChartRow> {+ data: TData[];+ config: ChartConfig;+ dataKey: keyof TData & string;+ nameKey: keyof TData & string;+ className?: string;+ renderer?: EChartsRenderer;+ animation?: boolean;+ defaultSelectedSector?: string | null;+ selectedSector?: string | null;+ onSelectionChange?: (+ selection: {+ dataKey: string;+ value: number;+ } | null,+ ) => void;+ isLoading?: boolean;+ chartOptions?: EChartsOption;+ activeSector?: string | null;+ children?: ReactNode;+}+export interface PieProps {+ variant?: PieVariant;+ innerRadius?: number | string;+ outerRadius?: number | string;+ cornerRadius?: number;+ paddingAngle?: number;+ startAngle?: number;+ endAngle?: number;+ isClickable?: boolean;+ children?: ReactNode;+}+const Pie: FC<PieProps> = () => null;+export interface LabelProps {+ dataKey?: string;+ position?: LabelPosition;+}+const Label: FC<LabelProps> = () => null;+export interface TooltipProps {+ variant?: TooltipVariant;+ roundness?: TooltipRoundness;+ defaultIndex?: number;+ position?: TooltipPosition;+ valueFormatter?: (value: number) => string;+}+const Tooltip: FC<TooltipProps> = () => null;+export interface LegendProps {+ variant?: LegendVariant;+ align?: "left" | "center" | "right";+ verticalAlign?: "top" | "middle" | "bottom";+ isClickable?: boolean;+}+const Legend: FC<LegendProps> = () => null;+export interface BackgroundProps {+ variant?: BackgroundVariant;+}+const Background: FC<BackgroundProps> = () => null;+type PieSlot = {+ variant: PieVariant;+ innerRadius: number | string;+ outerRadius: number | string;+ cornerRadius: number;+ paddingAngle: number;+ startAngle: number;+ endAngle: number;+ isClickable: boolean;+ labelDataKey: string | null;+ labelPosition: LabelPosition;+};+type TooltipSlot = {+ valueFormatter?: (value: number) => string;+ present: boolean;+ variant: TooltipVariant;+ roundness: TooltipRoundness;+ defaultIndex?: number;+ position: TooltipPosition;+};+type LegendSlot = {+ present: boolean;+ variant: LegendVariant;+ align: "left" | "center" | "right";+ verticalAlign: "top" | "middle" | "bottom";+ isClickable: boolean;+};+type BackgroundSlot = {+ present: boolean;+ variant: BackgroundVariant;+};+type CollectedConfig = {+ pie: PieSlot | null;+ tooltip: TooltipSlot;+ legend: LegendSlot;+ background: BackgroundSlot;+};+function collectConfig(children: ReactNode): CollectedConfig {+ let pie: PieSlot | null = null;+ let tooltip: TooltipSlot = {+ present: false,+ variant: "default",+ roundness: "lg",+ position: "variable",+ };+ let legend: LegendSlot = {+ present: false,+ variant: "rounded-square",+ align: "center",+ verticalAlign: "bottom",+ isClickable: false,+ };+ let background: BackgroundSlot = { present: false, variant: "dots" };+ Children.forEach(children, (child) => {+ if (!isValidElement(child)) return;+ const type = child.type;+ if (type === Pie) {+ const props = child.props as PieProps;+ let labelDataKey: string | null = null;+ let labelPosition: LabelPosition = "inside";+ Children.forEach(props.children, (labelChild) => {+ if (!isValidElement(labelChild) || labelChild.type !== Label) return;+ const labelProps = labelChild.props as LabelProps;+ labelDataKey = labelProps.dataKey ?? "";+ labelPosition = labelProps.position ?? "inside";+ });+ pie = {+ variant: props.variant ?? "gradient",+ innerRadius: props.innerRadius ?? DEFAULT_INNER_RADIUS,+ outerRadius: props.outerRadius ?? DEFAULT_OUTER_RADIUS,+ cornerRadius: props.cornerRadius ?? DEFAULT_CORNER_RADIUS,+ paddingAngle: props.paddingAngle ?? DEFAULT_PADDING_ANGLE,+ startAngle: props.startAngle ?? DEFAULT_START_ANGLE,+ endAngle: props.endAngle ?? DEFAULT_END_ANGLE,+ isClickable: props.isClickable ?? false,+ labelDataKey,+ labelPosition,+ };+ } else if (type === Tooltip) {+ const props = child.props as TooltipProps;+ tooltip = {+ present: true,+ variant: props.variant ?? "default",+ roundness: props.roundness ?? "lg",+ defaultIndex: props.defaultIndex,+ valueFormatter: props.valueFormatter,+ position: props.position ?? "variable",+ };+ } else if (type === Legend) {+ const props = child.props as LegendProps;+ legend = {+ present: true,+ variant: props.variant ?? "rounded-square",+ align: props.align ?? "center",+ verticalAlign: props.verticalAlign ?? "bottom",+ isClickable: props.isClickable ?? false,+ };+ } else if (type === Background) {+ const props = child.props as BackgroundProps;+ background = { present: true, variant: props.variant ?? "dots" };+ }+ });+ return { pie, tooltip, legend, background };+}+function sectorPaint(slots: string[]): string | echarts.graphic.LinearGradient {+ if (slots.length <= 1) return slots[0] ?? FALLBACK_COLOR;+ const stops = slots.map((color, i) => ({+ offset: i / (slots.length - 1),+ color,+ }));+ return new echarts.graphic.LinearGradient(0, 0, 1, 1, stops);+}+function loadingSectorAlpha(pos: number, center: number): number {+ const raw = Math.abs(pos - center);+ const dist = Math.min(raw, 1 - raw);+ const half = LOADING_SHIMMER_BAND;+ const feather = LOADING_SHIMMER_FEATHER;+ if (dist >= half) return LOADING_BASE_OPACITY;+ if (dist <= half - feather) return LOADING_PEAK_OPACITY;+ const t = 1 - (dist - (half - feather)) / feather;+ const eased = Math.sin((t * Math.PI) / 2);+ return (+ LOADING_BASE_OPACITY + (LOADING_PEAK_OPACITY - LOADING_BASE_OPACITY) * eased+ );+}+type PatternProps = {+ id: string;+};+const BACKGROUND_PATTERNS: Record<BackgroundVariant, FC<PatternProps>> = {+ dots: ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="20"+ height="20"+ patternUnits="userSpaceOnUse"+ >+ <circle className="text-border" cx="2" cy="2" r="1" fill="currentColor" />+ </pattern>+ ),+ grid: ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="20"+ height="20"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border"+ d="M 20 0 L 0 0 0 20"+ fill="none"+ stroke="currentColor"+ strokeWidth="0.5"+ />+ </pattern>+ ),+ "cross-hatch": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="20"+ height="20"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border/60 dark:text-border/50"+ d="M 0 0 L 20 20 M 20 0 L 0 20"+ fill="none"+ stroke="currentColor"+ strokeWidth="0.5"+ />+ </pattern>+ ),+ "diagonal-lines": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="6"+ height="6"+ patternUnits="userSpaceOnUse"+ patternTransform="rotate(45)"+ >+ <line+ className="text-border"+ x1="0"+ y1="0"+ x2="0"+ y2="6"+ stroke="currentColor"+ strokeWidth="0.5"+ />+ </pattern>+ ),+ plus: ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="16"+ height="16"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border"+ d="M 8 4 L 8 12 M 4 8 L 12 8"+ fill="none"+ stroke="currentColor"+ strokeWidth="0.5"+ strokeLinecap="round"+ />+ </pattern>+ ),+ "falling-triangles": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="18"+ height="36"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border"+ d="M2 6h12L8 18 2 6zm18 36h12l-6 12-6-12z"+ transform="scale(0.5)"+ fill="currentColor"+ fillOpacity="0.4"+ />+ </pattern>+ ),+ "4-pointed-star": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="16"+ height="16"+ patternUnits="userSpaceOnUse"+ >+ <polygon+ className="text-border"+ fillRule="evenodd"+ points="5 3 8 4 5 5 4 8 3 5 0 4 3 3 4 0 5 3"+ fill="currentColor"+ fillOpacity="0.4"+ />+ </pattern>+ ),+ "tiny-checkers": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="8"+ height="8"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border"+ fillRule="evenodd"+ d="M0 0h4v4H0V0zm4 4h4v4H4V4z"+ fill="currentColor"+ fillOpacity="0.2"+ />+ </pattern>+ ),+ "overlapping-circles": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="40"+ height="40"+ patternUnits="userSpaceOnUse"+ >+ <path+ className="text-border"+ fillRule="evenodd"+ d="M25 25c0-2.762 2.238-5 5-5s5 2.238 5 5-2.238 5-5 5c0 2.762-2.238 5-5 5s-5-2.238-5-5 2.238-5 5-5zM5 5c0-2.762 2.238-5 5-5s5 2.238 5 5-2.238 5-5 5c0 2.762-2.238 5-5 5S0 12.762 0 10s2.238-5 5-5zm5 4c2.209 0 4-1.791 4-4s-1.791-4-4-4-4 1.791-4 4 1.791 4 4 4zm20 20c2.209 0 4-1.791 4-4s-1.791-4-4-4-4 1.791-4 4 1.791 4 4 4z"+ fill="currentColor"+ fillOpacity="0.4"+ />+ </pattern>+ ),+ "wiggle-lines": ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="52"+ height="26"+ patternUnits="userSpaceOnUse"+ patternTransform="scale(0.6)"+ >+ <path+ className="text-border"+ d="M10 10c0-2.21-1.79-4-4-4-3.314 0-6-2.686-6-6h2c0 2.21 1.79 4 4 4 3.314 0 6 2.686 6 6 0 2.21 1.79 4 4 4 3.314 0 6 2.686 6 6 0 2.21 1.79 4 4 4 3.314 0 6 2.686 6 6 0 2.21 1.79 4 4 4v2c-3.314 0-6-2.686-6-6 0-2.21-1.79-4-4-4-3.314 0-6-2.686-6-6zm25.464-1.95l8.486 8.486-1.414 1.414-8.486-8.486 1.414-1.414z"+ fill="currentColor"+ fillOpacity="0.4"+ />+ </pattern>+ ),+ bubbles: ({ id }) => (+ <pattern+ id={id}+ x="0"+ y="0"+ width="100"+ height="100"+ patternUnits="userSpaceOnUse"+ patternTransform="scale(0.6667)"+ >+ <path+ className="text-border"+ d="M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z"+ fill="currentColor"+ fillOpacity="0.4"+ fillRule="evenodd"+ />+ </pattern>+ ),+};+function BackgroundLayer({ variant }: { variant: BackgroundVariant }) {+ const baseId = useId().replace(/:/g, "");+ const patternId = `${baseId}-bg-${variant}`;+ const maskId = `${baseId}-bg-edge-fade`;+ const filterId = `${baseId}-bg-blur`;+ const PatternComponent = BACKGROUND_PATTERNS[variant];+ return (+ <svg+ className="pointer-events-none absolute inset-0 h-full w-full"+ aria-hidden+ preserveAspectRatio="none"+ >+ <defs>+ <PatternComponent id={patternId} />++ <filter id={filterId}>+ <feGaussianBlur stdDeviation="25" />+ </filter>+ <mask id={maskId} maskUnits="userSpaceOnUse">+ <rect+ x="8%"+ y="20%"+ width="85%"+ height="60%"+ fill="white"+ filter={`url(#${filterId})`}+ />+ </mask>+ </defs>+ <rect+ width="100%"+ height="100%"+ fill={`url(#${patternId})`}+ mask={`url(#${maskId})`}+ />+ </svg>+ );+}+type OptionBuildContext = {+ data: ChartRow[];+ config: ChartConfig;+ nameKey: string;+ dataKey: string;+ pie: PieSlot | null;+ selectedSector: string | null;+ tooltipSlot: TooltipSlot;+ legendSlot: LegendSlot;+ isLoading: boolean;+ resolved: ResolvedColors;+};+function pieCenterY(legendSlot: LegendSlot): string {+ if (!legendSlot.present) return "50%";+ if (legendSlot.verticalAlign === "bottom") return "45%";+ if (legendSlot.verticalAlign === "top") return "55%";+ return "50%";+}+function createTooltipFormatter(ctx: OptionBuildContext) {+ const { config, selectedSector, tooltipSlot } = ctx;+ return (params: unknown): string => {+ const p = (Array.isArray(params) ? params[0] : params) as {+ name?: string;+ value?: number | string;+ seriesId?: string;+ } | null;+ if (!p || String(p.seriesId ?? "").startsWith("__")) return "";+ const name = String(p.name ?? "");+ const item = config[name];+ const colorsCount = item ? getColorsCount(item) : 1;+ const labelText = typeof item?.label === "string" ? item.label : name;+ const value =+ typeof p.value === "number"+ ? (tooltipSlot.valueFormatter?.(p.value) ?? p.value.toLocaleString())+ : String(p.value ?? "");+ const dimmed =+ selectedSector != null && selectedSector !== name ? " opacity-30" : "";+ const row = tooltipRow({+ indicatorHtml: tooltipIndicatorHtml(name, colorsCount),+ labelText,+ valueText: value,+ dimmed,+ });+ return `<div class="grid w-max min-w-32 items-start gap-1.5 border border-border/50 px-2.5 py-1.5 text-xs shadow-xl ${roundnessClass[tooltipSlot.roundness]} ${tooltipVariantClass[tooltipSlot.variant]}">+ <div class="grid gap-1.5">${row}</div>+ </div>`;+ };+}+function buildTooltipOption(ctx: OptionBuildContext): TooltipComponentOption {+ const { tooltipSlot, isLoading } = ctx;+ return {+ show: tooltipSlot.present && !isLoading,+ trigger: "item",+ confine: tooltipSlot.position !== "bottom",+ backgroundColor: "transparent",+ borderWidth: 0,+ padding: 0,+ extraCssText: "box-shadow:none;",+ displayTransition: false,+ position: resolveTooltipPosition(tooltipSlot.position),+ formatter: createTooltipFormatter(ctx),+ };+}+function buildPieSeries(ctx: OptionBuildContext): PieSeriesOption[] {+ const {+ data,+ config,+ nameKey,+ dataKey,+ pie,+ selectedSector,+ legendSlot,+ resolved,+ } = ctx;+ if (!pie) return [];+ const { tokens } = resolved;+ const hasSelection = selectedSector !== null;+ const border = sectorBorder(pie.paddingAngle, tokens.background);+ const sectors = data.map((row) => {+ const name = String(row[nameKey]);+ const slots = resolved.series[name] ?? [FALLBACK_COLOR];+ const isSelected = pie.isClickable && selectedSector === name;+ const isDimmed = pie.isClickable && hasSelection && selectedSector !== name;+ const itemStyle: PieItemStyle = {+ color: sectorPaint(slots),+ opacity: isDimmed ? DIMMED_OPACITY : 1,+ borderRadius: pie.cornerRadius,+ };+ if (border) {+ itemStyle.borderColor = border.borderColor;+ itemStyle.borderWidth = border.borderWidth;+ }+ const value: number | "-" = finiteValue(row[dataKey]) ?? "-";+ return { name, value, itemStyle, selected: isSelected };+ });+ const showLabel = pie.labelDataKey !== null;+ const isOutside = pie.labelPosition === "outside";+ const explicitKey = pie.labelDataKey ? pie.labelDataKey : null;+ const labelFormatter = (labelParams: {+ dataIndex: number;+ name?: string;+ value?: unknown;+ }) => {+ if (explicitKey)+ return String(data[labelParams.dataIndex]?.[explicitKey] ?? "");+ if (isOutside) {+ const item = config[String(labelParams.name ?? "")];+ return typeof item?.label === "string"+ ? item.label+ : String(labelParams.name ?? "");+ }+ return String(+ data[labelParams.dataIndex]?.[dataKey] ?? labelParams.value ?? "",+ );+ };+ const label = {+ show: showLabel,+ position: (isOutside ? "outside" : "inner") as "outside" | "inner",+ color: isOutside ? tokens.mutedForeground : tokens.background,+ fontSize: 12,+ fontWeight: 500,+ formatter: labelFormatter,+ };+ return [+ {+ id: "pie",+ type: "pie",+ center: ["50%", pieCenterY(legendSlot)],+ radius: [pie.innerRadius, pie.outerRadius],+ startAngle: pie.startAngle,+ endAngle: pie.endAngle,+ clockwise: false,+ padAngle: Math.min(pie.paddingAngle, 0),+ cursor: pie.isClickable ? "pointer" : "default",+ emphasis: { scale: false },+ selectedMode: pie.isClickable ? "single" : false,+ selectedOffset: SELECTED_OFFSET,+ select: { itemStyle: {} },+ label,+ labelLine: isOutside+ ? {+ show: true,+ length: 14,+ length2: 14,+ smooth: false,+ lineStyle: {+ color: withAlpha(tokens.mutedForeground, 0.45),+ width: 1,+ },+ }+ : { show: false },+ data: sectors,+ },+ ];+}+function buildLoadingOption(ctx: OptionBuildContext): EChartsOption {+ const { pie, legendSlot, resolved } = ctx;+ const { tokens } = resolved;+ const innerRadius = pie?.innerRadius ?? DEFAULT_INNER_RADIUS;+ const outerRadius = pie?.outerRadius ?? DEFAULT_OUTER_RADIUS;+ const cornerRadius = pie?.cornerRadius ?? DEFAULT_CORNER_RADIUS;+ const paddingAngle = pie?.paddingAngle ?? DEFAULT_PADDING_ANGLE;+ const startAngle = pie?.startAngle ?? DEFAULT_START_ANGLE;+ const endAngle = pie?.endAngle ?? DEFAULT_END_ANGLE;+ const border = sectorBorder(paddingAngle, tokens.background);+ const sectors = Array.from({ length: LOADING_SECTORS }, (_, i) => {+ const itemStyle: PieItemStyle = {+ color: withAlpha(tokens.foreground, LOADING_BASE_OPACITY),+ opacity: 1,+ borderRadius: cornerRadius,+ };+ if (border) {+ itemStyle.borderColor = border.borderColor;+ itemStyle.borderWidth = border.borderWidth;+ }+ return { name: `__loading-${i}`, value: 1, itemStyle };+ });+ return {+ animation: false,+ tooltip: { show: false },+ series: [+ {+ id: "__loading",+ type: "pie",+ center: ["50%", pieCenterY(legendSlot)],+ radius: [innerRadius, outerRadius],+ startAngle,+ endAngle,+ clockwise: false,+ padAngle: Math.min(paddingAngle, 0),+ silent: true,+ emphasis: { scale: false },+ label: { show: false },+ labelLine: { show: false },+ data: sectors,+ },+ ],+ };+}+type LiveState = {+ resolved: ResolvedColors | null;+ hasRevealed: boolean;+ handlers: {+ isClickable: boolean;+ selectedSector: string | null;+ selectSector: (name: string | null) => void;+ };+ repush: () => void;+};+export function EChartsPieChart<TData extends ChartRow>({+ data,+ config,+ dataKey,+ nameKey,+ className,+ renderer = DEFAULT_ECHARTS_RENDERER,+ animation = true,+ defaultSelectedSector = null,+ selectedSector: selectedSectorProp,+ onSelectionChange,+ isLoading = false,+ chartOptions,+ activeSector,+ children,+}: EChartsPieChartProps<TData>) {+ const rawId = useId();+ const chartId = `chart-${rawId.replace(/:/g, "")}`;+ const containerRef = useRef<HTMLDivElement>(null);+ const mountRef = useRef<HTMLDivElement>(null);+ const echartsRef = useRef<EChartsInstance | null>(null);+ const live = useRef<LiveState>({+ resolved: null,+ hasRevealed: false,+ handlers: {+ isClickable: false,+ selectedSector: defaultSelectedSector,+ selectSector: () => {},+ },+ repush: () => {},+ }).current;+ const shouldReduceMotion = useReducedMotion();+ const [internalSelectedSector, setSelectedSector] = useState<string | null>(+ defaultSelectedSector,+ );+ const selectedSector =+ selectedSectorProp !== undefined+ ? selectedSectorProp+ : internalSelectedSector;+ const collected = useMemo(() => collectConfig(children), [children]);+ const {+ pie,+ tooltip: tooltipSlot,+ legend: legendSlot,+ background: backgroundSlot,+ } = collected;+ const sectorKeys = useMemo(+ () => data.map((row) => String(row[nameKey as string])),+ [data, nameKey],+ );+ const css = useMemo(() => buildChartCss(chartId, config), [chartId, config]);+ const selectSector = useCallback(+ (name: string | null) => {+ if (name === null) {+ setSelectedSector(null);+ onSelectionChange?.(null);+ return;+ }+ const item = data.find((row) => String(row[nameKey]) === name);+ const value = finiteValue(item?.[dataKey]);+ if (value === null) return;+ setSelectedSector(name);+ onSelectionChange?.({ dataKey: name, value });+ },+ [data, dataKey, nameKey, onSelectionChange],+ );++ const buildOption = useCallback((): EChartsOption => {+ const resolved = live.resolved;+ if (!resolved) return {};+ const ctx: OptionBuildContext = {+ data,+ config,+ nameKey: nameKey as string,+ dataKey: dataKey as string,+ pie,+ selectedSector,+ tooltipSlot,+ legendSlot,+ isLoading,+ resolved,+ };+ if (isLoading) return buildLoadingOption(ctx);+ return {+ animation: false,+ tooltip: buildTooltipOption(ctx),+ series: buildPieSeries(ctx),+ };+ }, [+ live,+ data,+ config,+ nameKey,+ dataKey,+ pie,+ selectedSector,+ tooltipSlot,+ legendSlot,+ isLoading,+ ]);+ const setupChart = useCallback(() => {+ const mount = mountRef.current;+ const container = containerRef.current;+ if (!mount || !container) return;+ const chart = echarts.init(mount, null, { renderer });+ echartsRef.current = chart;+ chart.getZr().on("mousemove", () => cancelActiveTooltip(chart));+ const resizeObserver = new ResizeObserver(() => {+ if (+ mount.clientWidth === chart.getWidth() &&+ mount.clientHeight === chart.getHeight()+ ) {+ return;+ }+ chart.resize();+ });+ resizeObserver.observe(mount);+ const themeObserver = observeChartTheme(container, () => live.repush());+ chart.on("click", (params) => {+ const {+ isClickable,+ selectedSector: selected,+ selectSector: select,+ } = live.handlers;+ if (!isClickable) return;+ const p = params as {+ name?: string;+ seriesId?: string;+ };+ if (String(p.seriesId ?? "").startsWith("__")) return;+ const name = p.name;+ if (typeof name !== "string") return;+ select(selected === name ? null : name);+ });+ return () => {+ resizeObserver.disconnect();+ themeObserver.disconnect();+ cancelActiveTooltip(chart);+ chart.off();+ chart.getZr().off();+ chart.dispose();+ live.repush = () => {};+ echartsRef.current = null;+ live.hasRevealed = false;+ };+ }, [renderer]);+ const synchronizeChart = useCallback(() => {+ const chart = echartsRef.current;+ const container = containerRef.current;+ if (!chart || !container) return;+ live.resolved = resolveColors(container, config, sectorKeys);+ const activeSectorIndex = boundedIndex(+ sectorKeys.indexOf(activeSector ?? ""),+ data.length,+ );+ const visibleSectorIndex =+ activeSectorIndex !== null &&+ finiteValue(data[activeSectorIndex]?.[dataKey]) !== null+ ? activeSectorIndex+ : null;+ const push = (withEntrance: boolean) => {+ const option = buildOption();+ const merged = chartOptions ? { ...option, ...chartOptions } : option;+ Object.assign(merged, {+ animation: withEntrance,+ animationDuration: REVEAL_DURATION,+ animationDurationUpdate: 0,+ });+ setChartOption(chart, merged);+ if (activeSector !== undefined)+ showActiveIndex(chart, isLoading ? null : visibleSectorIndex);+ };+ if (isLoading) live.hasRevealed = false;+ const shouldReveal = !live.hasRevealed && !isLoading;+ if (shouldReveal) live.hasRevealed = true;+ const revealEnabled = animation && shouldReveal && !shouldReduceMotion;+ push(revealEnabled);+ live.repush = () => {+ live.resolved = resolveColors(container, config, sectorKeys);+ push(false);+ };+ }, [+ live,+ buildOption,+ chartOptions,+ activeSector,+ data,+ dataKey,+ isLoading,+ animation,+ shouldReduceMotion,+ config,+ renderer,+ sectorKeys,+ ]);+ const animatePrimary = useCallback(() => {+ const chart = echartsRef.current;+ if (+ !chart ||+ isLoading ||+ activeSector !== undefined ||+ !tooltipSlot.present ||+ boundedIndex(tooltipSlot.defaultIndex, data.length) === null+ )+ return;+ const raf = requestAnimationFrame(() => {+ chart.dispatchAction({+ type: "showTip",+ seriesIndex: 0,+ dataIndex: tooltipSlot.defaultIndex,+ });+ });+ return () => cancelAnimationFrame(raf);+ }, [+ isLoading,+ tooltipSlot.present,+ tooltipSlot.defaultIndex,+ renderer,+ activeSector,+ data.length,+ ]);+ const animateLoading = useCallback(() => {+ const chart = echartsRef.current;+ if (!chart || !isLoading || shouldReduceMotion) return;+ const cornerRadius = pie?.cornerRadius ?? DEFAULT_CORNER_RADIUS;+ const paddingAngle = pie?.paddingAngle ?? DEFAULT_PADDING_ANGLE;+ let raf = 0;+ const start = performance.now();+ const tick = (now: number) => {+ const phase =+ ((((now - start) / LOADING_ANIMATION_DURATION) % 1) + 1) % 1;+ const foreground = live.resolved?.tokens.foreground ?? FALLBACK_COLOR;+ const background = live.resolved?.tokens.background ?? FALLBACK_COLOR;+ const border = sectorBorder(paddingAngle, background);+ const sectors = Array.from({ length: LOADING_SECTORS }, (_, i) => {+ const pos = (i + 0.5) / LOADING_SECTORS;+ const itemStyle: PieItemStyle = {+ color: withAlpha(foreground, loadingSectorAlpha(pos, phase)),+ opacity: 1,+ borderRadius: cornerRadius,+ };+ if (border) {+ itemStyle.borderColor = border.borderColor;+ itemStyle.borderWidth = border.borderWidth;+ }+ return { value: 1, itemStyle };+ });+ chart.setOption(+ { series: [{ id: "__loading", data: sectors }] },+ { silent: true, lazyUpdate: true },+ );+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [live, isLoading, pie, renderer, shouldReduceMotion]);+ const commitChart = useChartLifecycle(+ {+ prepare: () => {+ live.handlers = {+ isClickable: pie?.isClickable ?? false,+ selectedSector,+ selectSector,+ };+ },+ setup: setupChart,+ synchronize: synchronizeChart,+ animate: [animatePrimary, animateLoading],+ },+ containerRef,+ );++ const legendStyle: CSSProperties = {+ position: "absolute",+ left: 16,+ right: 16,+ pointerEvents: "auto",+ ...(legendSlot.verticalAlign === "top"+ ? { top: 12 }+ : legendSlot.verticalAlign === "bottom"+ ? { bottom: 12 }+ : { top: "50%", transform: "translateY(-50%)" }),+ };+ return (+ <div+ ref={commitChart}+ data-chart={chartId}+ className={`relative flex flex-col text-xs ${className ?? ""}`}+ >+ <style dangerouslySetInnerHTML={{ __html: css }} />++ <div className="relative min-h-0 w-full flex-1">+ {backgroundSlot.present && !isLoading && (+ <BackgroundLayer variant={backgroundSlot.variant} />+ )}+ <div ref={mountRef} className="relative h-full min-h-0 w-full" />+ </div>++ {legendSlot.present && !isLoading && (+ <LegendOverlay+ seriesKeys={sectorKeys}+ config={config}+ variant={legendSlot.variant}+ align={legendSlot.align}+ verticalAlign={legendSlot.verticalAlign}+ selectedKey={selectedSector}+ hoveredKey={null}+ isClickable={legendSlot.isClickable}+ onToggle={(key) => selectSector(selectedSector === key ? null : key)}+ style={legendStyle}+ />+ )}+ </div>+ );+}+EChartsPieChart.Pie = Pie;+EChartsPieChart.Label = Label;+EChartsPieChart.Tooltip = Tooltip;+EChartsPieChart.Legend = Legend;+EChartsPieChart.Background = Background;diff --git a/packages/ui/src/components/evilcharts/ui/echarts-brush.tsx b/packages/ui/src/components/evilcharts/ui/echarts-brush.tsxnew file mode 100644index 00000000..3218fc0a--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-brush.tsx@@ -0,0 +1,213 @@+import type { DataZoomComponentOption } from "echarts/components";+import * as echarts from "echarts/core";+import type { FC } from "react";+import { type ResolvedColors, withAlpha } from "./echarts-chart";+import { ECHARTS_CONFIG } from "./echarts-config";++type EChartsInstance = ReturnType<typeof echarts.init>;+const { BRUSH_BORDER_OPACITY } = ECHARTS_CONFIG.brush;++export { BRUSH_BORDER_OPACITY };+export interface BrushProps {+ height?: number;+ formatLabel?: (value: string, index: number) => string;+ onChange?: (range: { startIndex: number; endIndex: number }) => void;+}+export const Brush: FC<BrushProps> = () => null;+export type BrushRange = {+ start: number;+ end: number;+};+export type BrushGeometry = {+ bottom: number;+ height: number;+};+export type BrushOverlayParams = {+ range: BrushRange;+ geom: BrushGeometry;+ size: {+ width: number;+ height: number;+ };+ tokens: ResolvedColors["tokens"];+ labels: {+ start: string;+ end: string;+ } | null;+ showLabels: boolean;+ hover: {+ left: boolean;+ right: boolean;+ };+};+type ZrRect = InstanceType<typeof echarts.graphic.Rect>;+type ZrCircle = InstanceType<typeof echarts.graphic.Circle>;+type ZrText = InstanceType<typeof echarts.graphic.Text>;+export type BrushOverlayElements = {+ dimLeft: ZrRect;+ dimRight: ZrRect;+ frame: ZrRect;+ pillLeft: ZrRect;+ pillRight: ZrRect;+ grips: ZrCircle[];+ labelStart: ZrText;+ labelEnd: ZrText;+};+export function syncBrushOverlay(+ chart: EChartsInstance,+ store: {+ brushOverlay: BrushOverlayElements | null;+ },+ params: BrushOverlayParams | null,+) {+ const zr = chart.getZr();+ if (!zr) return;+ if (!params) {+ if (store.brushOverlay) {+ const { grips, ...rest } = store.brushOverlay;+ [...Object.values(rest), ...grips].forEach((el) => {+ zr.remove(el);+ });+ store.brushOverlay = null;+ }+ return;+ }+ if (!store.brushOverlay) {+ const rect = (z: number) =>+ new echarts.graphic.Rect({ silent: true, z, shape: {} });+ const els: BrushOverlayElements = {+ dimLeft: rect(100),+ dimRight: rect(100),+ frame: rect(101),+ pillLeft: rect(102),+ pillRight: rect(102),+ grips: Array.from(+ { length: 6 },+ () => new echarts.graphic.Circle({ silent: true, z: 103, shape: {} }),+ ),+ labelStart: new echarts.graphic.Text({ silent: true, z: 104 }),+ labelEnd: new echarts.graphic.Text({ silent: true, z: 104 }),+ };+ const { grips, ...rest } = els;+ [...Object.values(rest), ...grips].forEach((el) => {+ zr.add(el);+ });+ store.brushOverlay = els;+ }+ const els = store.brushOverlay;+ const { range, geom, size, tokens, labels, showLabels, hover } = params;+ const trackLeft = 8;+ const trackRight = Math.max(size.width - 8, trackLeft);+ const trackWidth = trackRight - trackLeft;+ const top = size.height - geom.bottom - geom.height;+ const centerY = top + geom.height / 2;+ const selectionLeft = trackLeft + (trackWidth * range.start) / 100;+ const selectionRight = trackLeft + (trackWidth * range.end) / 100;+ const dimFill = withAlpha(tokens.background, 0.7);+ els.dimLeft.setShape({+ x: trackLeft,+ y: top,+ width: Math.max(selectionLeft - trackLeft, 0),+ height: geom.height,+ });+ els.dimLeft.setStyle({ fill: dimFill });+ els.dimRight.setShape({+ x: selectionRight,+ y: top,+ width: Math.max(trackRight - selectionRight, 0),+ height: geom.height,+ });+ els.dimRight.setStyle({ fill: dimFill });+ els.frame.setShape({+ x: selectionLeft,+ y: top,+ width: Math.max(selectionRight - selectionLeft, 0),+ height: geom.height,+ r: 6,+ });+ els.frame.setStyle({+ fill: "none",+ stroke: withAlpha(tokens.border, BRUSH_BORDER_OPACITY),+ lineWidth: 1,+ });+ const pill = (el: ZrRect, x: number, hovered: boolean) => {+ el.setShape({ x: x - 3, y: centerY - 8, width: 6, height: 16, r: 3 });+ el.setStyle({ fill: hovered ? tokens.foreground : tokens.mutedForeground });+ };+ pill(els.pillLeft, selectionLeft, hover.left);+ pill(els.pillRight, selectionRight, hover.right);+ const gripFill = withAlpha(tokens.background, 0.7);+ [-4, 0, 4].forEach((offset, i) => {+ els.grips[i]?.setShape({ cx: selectionLeft, cy: centerY + offset, r: 1 });+ els.grips[i]?.setStyle({ fill: gripFill });+ els.grips[i + 3]?.setShape({+ cx: selectionRight,+ cy: centerY + offset,+ r: 1,+ });+ els.grips[i + 3]?.setStyle({ fill: gripFill });+ });+ const label = (+ el: ZrText,+ text: string,+ x: number,+ align: "left" | "right",+ ) => {+ el.setStyle({+ text,+ x:+ align === "left"+ ? Math.max(x + 6, trackLeft + 2)+ : Math.min(x - 6, trackRight - 2),+ y: top + geom.height,+ align,+ verticalAlign: "middle",+ fill: tokens.background,+ backgroundColor: tokens.foreground,+ padding: [2, 5],+ borderRadius: 4,+ font: "500 9px system-ui, sans-serif",+ });+ el.attr("invisible", !showLabels || !text);+ };+ label(els.labelStart, labels?.start ?? "", selectionLeft, "left");+ label(els.labelEnd, labels?.end ?? "", selectionRight, "right");+}+export function buildBrushDataZoom(params: {+ brushBottom: number;+ brushHeight: number;+ brushRange: BrushRange;+ fillerColor: string;+}): DataZoomComponentOption[] {+ const { brushBottom, brushHeight, brushRange, fillerColor } = params;+ return [+ {+ type: "slider",+ show: true,+ xAxisIndex: [0],+ left: 8,+ right: 8,+ bottom: brushBottom,+ height: brushHeight,+ start: brushRange.start,+ end: brushRange.end,+ brushSelect: false,+ showDetail: false,+ backgroundColor: "transparent",+ borderColor: "transparent",+ fillerColor,+ dataBackground: { lineStyle: { opacity: 0 }, areaStyle: { opacity: 0 } },+ selectedDataBackground: {+ lineStyle: { opacity: 0 },+ areaStyle: { opacity: 0 },+ },+ handleIcon:+ "path://M -3 -5 L -3 5 A 3 3 0 0 0 3 5 L 3 -5 A 3 3 0 0 0 -3 -5 Z",+ handleSize: "35%",+ handleStyle: { opacity: 0 },+ moveHandleSize: 0,+ emphasis: { handleStyle: { opacity: 0 } },+ },+ { type: "inside", xAxisIndex: [0] },+ ];+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-chart.tsx b/packages/ui/src/components/evilcharts/ui/echarts-chart.tsxnew file mode 100644index 00000000..84abed6c--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-chart.tsx@@ -0,0 +1,185 @@+"use client";+import * as echarts from "echarts/core";+import { CanvasRenderer, SVGRenderer } from "echarts/renderers";+import type { ComponentType, ReactNode } from "react";+export const ECHARTS_RENDERERS = {+ canvas: "canvas",+ svg: "svg",+} as const;+export type EChartsRenderer =+ (typeof ECHARTS_RENDERERS)[keyof typeof ECHARTS_RENDERERS];+export const DEFAULT_ECHARTS_RENDERER = ECHARTS_RENDERERS.canvas;+echarts.use([CanvasRenderer, SVGRenderer]);+export const THEMES = { light: "", dark: ".dark" } as const;+export type ThemeKey = keyof typeof THEMES;+export const THEME_KEYS = Object.keys(THEMES) as ThemeKey[];+export type AtLeastOneThemeColor =+ | {+ light: string[];+ dark?: string[];+ }+ | {+ light?: string[];+ dark: string[];+ };+export type ChartValue = string | number | boolean | null | undefined;+export type ChartRow = Record<string, ChartValue>;++export function finiteValue(value: ChartValue): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}++export function finiteSum(values: number[]): number {+ const total = values.reduce((sum, value) => sum + value, 0);+ return Number.isFinite(total) ? total : 0;+}++export type ChartConfig = Record<+ string,+ {+ label?: ReactNode;+ icon?: ComponentType;+ colors?: AtLeastOneThemeColor;+ }+>;+export function getColorsCount(item: ChartConfig[string]): number {+ if (!item.colors) return 1;+ const counts = THEME_KEYS.map((theme) => item.colors?.[theme]?.length ?? 0);+ return Math.max(...counts, 1);+}+export function distributeColors(colors: string[], maxCount: number): string[] {+ const available = colors.length;+ if (!available || maxCount < 1) return [];+ if (available >= maxCount) return colors.slice(0, maxCount);+ const result: string[] = [];+ const baseSlots = Math.floor(maxCount / available);+ const extraSlots = maxCount % available;+ for (let i = 0; i < available; i++) {+ const isExtra = i >= available - extraSlots;+ const slots = baseSlots + (isExtra ? 1 : 0);+ for (let j = 0; j < slots; j++) result.push(colors[i] ?? "transparent");+ }+ return result;+}+export function buildChartCss(id: string, config: ChartConfig): string {+ const colorConfig = Object.entries(config).filter(([, item]) => item.colors);+ if (!colorConfig.length) return "";+ const varsFor = (theme: ThemeKey) =>+ colorConfig+ .flatMap(([key, item]) => {+ const authored = item.colors?.[theme];+ if (!authored || authored.length === 0) return [];+ return distributeColors(authored, getColorsCount(item)).map(+ (color, index) => ` --color-${key}-${index}: ${color};`,+ );+ })+ .join("\n");+ return Object.entries(THEMES)+ .map(+ ([theme, prefix]) =>+ `${prefix} [data-chart=${id}] {\n${varsFor(theme as ThemeKey)}\n}`,+ )+ .join("\n");+}+let normalizerCtx: CanvasRenderingContext2D | null = null;+export function normalizeColor(value: string): string {+ const raw = value.trim();+ if (!raw || typeof document === "undefined") return raw;+ if (!normalizerCtx) {+ const canvas = document.createElement("canvas");+ canvas.width = 1;+ canvas.height = 1;+ normalizerCtx = canvas.getContext("2d", { willReadFrequently: true });+ }+ if (!normalizerCtx) return raw;+ normalizerCtx.clearRect(0, 0, 1, 1);+ normalizerCtx.fillStyle = "#000";+ normalizerCtx.fillStyle = raw;+ normalizerCtx.fillRect(0, 0, 1, 1);+ const [r = 0, g = 0, b = 0, a = 255] = normalizerCtx.getImageData(+ 0,+ 0,+ 1,+ 1,+ ).data;+ return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(3)})`;+}+export function withAlpha(color: string, alpha: number): string {+ const match = color.match(/rgba?\(([^)]+)\)/);+ if (!match) return color;+ const [r, g, b, a] = (match[1] ?? "").split(",").map((p) => p.trim());+ const base = a === undefined ? 1 : Number.parseFloat(a) || 0;+ return `rgba(${r}, ${g}, ${b}, ${(base * alpha).toFixed(3)})`;+}+export type ResolvedColors = {+ series: Record<string, string[]>;+ tokens: {+ mutedForeground: string;+ border: string;+ foreground: string;+ background: string;+ };+};+export function resolveColors(+ container: HTMLElement,+ config: ChartConfig,+ seriesKeys: string[],+): ResolvedColors {+ const computed = getComputedStyle(container);+ const series: Record<string, string[]> = {};+ for (const key of seriesKeys) {+ const count = getColorsCount(config[key] ?? {});+ const slots: string[] = [];+ for (let n = 0; n < count; n++) {+ const raw = computed.getPropertyValue(`--color-${key}-${n}`).trim();+ slots.push(raw ? normalizeColor(raw) : "rgba(120, 120, 120, 1)");+ }+ series[key] = slots;+ }+ const probe = document.createElement("span");+ probe.style.cssText =+ "position:absolute;width:0;height:0;visibility:hidden;pointer-events:none;";+ container.appendChild(probe);+ const readToken = (className: string) => {+ probe.className = className;+ return normalizeColor(getComputedStyle(probe).color);+ };+ const tokens = {+ mutedForeground: readToken("text-muted-foreground"),+ border: readToken("text-border"),+ foreground: readToken("text-foreground"),+ background: readToken("text-background"),+ };+ container.removeChild(probe);+ return { series, tokens };+}+export function seriesPaint(+ slots: string[],+): string | echarts.graphic.LinearGradient {+ if (slots.length <= 1) return slots[0] ?? "rgba(120, 120, 120, 1)";+ const stops = slots.map((color, i) => ({+ offset: i / (slots.length - 1),+ color,+ }));+ return new echarts.graphic.LinearGradient(0, 0, 1, 0, stops);+}+export function indicatorBackground(key: string, colorsCount: number): string {+ if (colorsCount <= 1) return `var(--color-${key}-0)`;+ const stops = Array.from({ length: colorsCount }, (_, i) => {+ const offset = (i / (colorsCount - 1)) * 100;+ return `var(--color-${key}-${i}) ${offset}%`;+ }).join(", ");+ return `linear-gradient(to right, ${stops})`;+}+export function flattenColor(color: string, base: string): string {+ const parse = (value: string) =>+ value+ .match(/rgba?\(([^)]+)\)/)?.[1]+ ?.split(",")+ .map((part) => Number.parseFloat(part)) ?? [0, 0, 0, 1];+ const [r = 0, g = 0, b = 0, a = 1] = parse(color);+ const [baseR = 0, baseG = 0, baseB = 0] = parse(base);+ const mix = (channel: number, baseChannel: number) =>+ Math.round(channel * a + baseChannel * (1 - a));+ return `rgb(${mix(r, baseR)}, ${mix(g, baseG)}, ${mix(b, baseB)})`;+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-config.ts b/packages/ui/src/components/evilcharts/ui/echarts-config.tsnew file mode 100644index 00000000..281003fc--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-config.ts@@ -0,0 +1,74 @@+const SECOND_MS = 1000;++export const ECHARTS_CONFIG = {+ area: {+ STROKE_WIDTH: 0.8,+ LOADING_ANIMATION_DURATION: 2 * SECOND_MS,+ REVEAL_DURATION: SECOND_MS,+ LOADING_DEFAULT_POINTS: 14,+ BUFFER_DASH: [4, 3],+ GRID_LINE_OPACITY: 1,+ AXIS_POINTER_OPACITY: 1,+ LOADING_STROKE_OPACITY: 0.5,+ LOADING_SHIMMER_MAX_OPACITY: 0.03,+ LOADING_SHIMMER_BAND: 0.2,+ LOADING_SHIMMER_FEATHER: 0.2,+ BRUSH_STROKE_OPACITY: 0.5,+ BRUSH_FILL_OPACITY: 0.15,+ BRUSH_FILLER_OPACITY: 0,+ BUFFER_PREFIX: "__buffer-",+ BUFFERFILL_PREFIX: "__bufferfill-",+ REVEAL_PREFIX: "__reveal-",+ },+ bar: {+ DEFAULT_BAR_RADIUS: 2,+ STROKE_WIDTH: 1,+ LOADING_ANIMATION_DURATION: 2 * SECOND_MS,+ BAR_GROW_DURATION: SECOND_MS / 2,+ BAR_STAGGER: SECOND_MS / 20,+ LOADING_DEFAULT_BARS: 12,+ SELECTION_DIM: 0.3,+ HOVER_BLUR: 0.3,+ GLOW_BLUR: 18,+ GLOW_OPACITY: 0.65,+ EXPAND_COLLAPSED: 0.12,+ EXPAND_TAU: 70,+ BLOCK_SIZE: 8,+ BLOCK_GAP: 4,+ BLOCK_TRACK_OPACITY: 0.22,+ STACK_SEGMENT_GAP: 4,+ MAX_HIGHLIGHT_DIM: 0.16,+ STRIPPED_CAP_HEIGHT: 4,+ STRIPPED_BODY_ALPHA: 0.2,+ STRIPPED_CAP_MAX_FRACTION: 0.85,+ STRIPPED_FALLBACK_FRACTION: 0.12,+ GRID_LINE_OPACITY: 1,+ LOADING_SHIMMER_MAX_OPACITY: 0.22,+ LOADING_SHIMMER_BAND: 0.2,+ LOADING_SHIMMER_FEATHER: 0.2,+ BRUSH_FILL_OPACITY: 0.5,+ BRUSH_FILLER_OPACITY: 0,+ GRAY: "rgba(120, 120, 120, 1)",+ },+ pie: {+ REVEAL_DURATION: SECOND_MS,+ LOADING_ANIMATION_DURATION: 2 * SECOND_MS,+ LOADING_SECTORS: 5,+ DEFAULT_INNER_RADIUS: 0,+ DEFAULT_OUTER_RADIUS: "80%",+ DEFAULT_CORNER_RADIUS: 0,+ DEFAULT_PADDING_ANGLE: 0,+ DEFAULT_START_ANGLE: 0,+ DEFAULT_END_ANGLE: 360,+ FALLBACK_COLOR: "rgba(120, 120, 120, 1)",+ OVERLAP_BORDER_WIDTH: 5,+ SELECTED_OFFSET: 12,+ DIMMED_OPACITY: 0.15,+ LOADING_BASE_OPACITY: 0.15,+ LOADING_PEAK_OPACITY: 0.5,+ LOADING_SHIMMER_BAND: 0.28,+ LOADING_SHIMMER_FEATHER: 0.22,+ },+ brush: { BRUSH_BORDER_OPACITY: 1 },+ tooltip: { edgeInset: 8 },+} as const;diff --git a/packages/ui/src/components/evilcharts/ui/echarts-dot.tsx b/packages/ui/src/components/evilcharts/ui/echarts-dot.tsxnew file mode 100644index 00000000..02676ebb--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-dot.tsx@@ -0,0 +1,70 @@+import type * as echarts from "echarts/core";+import { withAlpha } from "./echarts-chart";+export type DotVariant =+ | "none"+ | "default"+ | "border"+ | "colored-border"+ | "ping";+export type DotItemStyleOption = {+ color?: string | echarts.graphic.LinearGradient;+ borderColor?: string | echarts.graphic.LinearGradient;+ borderWidth?: number;+ opacity?: number;+};+export type DotStyle = {+ size: number;+ itemStyle: DotItemStyleOption;+};+export function dotItemStyle(+ variant: DotVariant,+ paint: string | echarts.graphic.LinearGradient,+ background: string,+): DotItemStyleOption {+ switch (variant) {+ case "border":+ return { color: paint, borderColor: background, borderWidth: 2 };+ case "colored-border":+ return { color: background, borderColor: paint, borderWidth: 1 };+ case "ping": {+ const halo = typeof paint === "string" ? withAlpha(paint, 0.28) : paint;+ return { color: paint, borderColor: halo, borderWidth: 10 };+ }+ case "default":+ return { color: paint, borderWidth: 0 };+ default:+ return {};+ }+}+export const DOT_SIZES: Record<DotVariant, number> = {+ none: 0,+ default: 6,+ border: 8,+ "colored-border": 6,+ ping: 8,+};+export function dotStyle(+ variant: DotVariant,+ paint: string | echarts.graphic.LinearGradient,+ background: string,+): DotStyle {+ return {+ size: DOT_SIZES[variant],+ itemStyle: dotItemStyle(variant, paint, background),+ };+}+export function sampleGradient(slots: string[], t: number): string {+ if (slots.length <= 1) return slots[0] ?? "rgba(120, 120, 120, 1)";+ const parse = (color: string) =>+ color+ .match(/rgba?\(([^)]+)\)/)?.[1]+ ?.split(",")+ .map(Number) ?? [120, 120, 120, 1];+ const position = t * (slots.length - 1);+ const index = Math.min(Math.floor(position), slots.length - 2);+ const fraction = position - index;+ const [r1 = 0, g1 = 0, b1 = 0, a1 = 1] = parse(slots[index] ?? "");+ const [r2 = 0, g2 = 0, b2 = 0, a2 = 1] = parse(slots[index + 1] ?? "");+ const lerp = (from: number, to: number) => from + (to - from) * fraction;+ return `rgba(${Math.round(lerp(r1, r2))}, ${Math.round(lerp(g1, g2))}, ${Math.round(lerp(b1, b2))}, ${lerp(a1, a2).toFixed(3)})`;+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-legend.tsx b/packages/ui/src/components/evilcharts/ui/echarts-legend.tsxnew file mode 100644index 00000000..7f9ef7d3--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-legend.tsx@@ -0,0 +1,136 @@+"use client";+import type { CSSProperties } from "react";+import {+ type ChartConfig,+ getColorsCount,+ indicatorBackground,+} from "./echarts-chart";+export type LegendVariant =+ | "square"+ | "circle"+ | "circle-outline"+ | "rounded-square"+ | "rounded-square-outline"+ | "vertical-bar"+ | "horizontal-bar";+export function legendFillStyle(+ key: string,+ colorsCount: number,+): CSSProperties {+ if (colorsCount <= 1) return { backgroundColor: `var(--color-${key}-0)` };+ return { background: indicatorBackground(key, colorsCount) };+}+export function legendOutlineStyle(+ key: string,+ colorsCount: number,+): CSSProperties {+ const mask: CSSProperties = {+ WebkitMask:+ "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)",+ WebkitMaskComposite: "xor",+ mask: "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)",+ maskComposite: "exclude",+ };+ return { ...legendFillStyle(key, colorsCount), ...mask };+}+export function LegendIndicator({+ variant,+ dataKey,+ colorsCount,+}: {+ variant: LegendVariant;+ dataKey: string;+ colorsCount: number;+}) {+ const fill = legendFillStyle(dataKey, colorsCount);+ const outline = legendOutlineStyle(dataKey, colorsCount);+ switch (variant) {+ case "square":+ return <div className="h-2 w-2 shrink-0" style={fill} />;+ case "circle":+ return <div className="h-2 w-2 shrink-0 rounded-full" style={fill} />;+ case "circle-outline":+ return (+ <div+ className="h-2.5 w-2.5 shrink-0 rounded-full p-[1.5px]"+ style={outline}+ />+ );+ case "vertical-bar":+ return <div className="h-3 w-1 shrink-0 rounded-[2px]" style={fill} />;+ case "horizontal-bar":+ return <div className="h-1 w-3 shrink-0 rounded-[2px]" style={fill} />;+ case "rounded-square-outline":+ return (+ <div+ className="h-2.5 w-2.5 shrink-0 rounded-[3px] p-[1.5px]"+ style={outline}+ />+ );+ default:+ return <div className="h-2 w-2 shrink-0 rounded-[2px]" style={fill} />;+ }+}+type LegendOverlayProps = {+ seriesKeys: string[];+ config: ChartConfig;+ variant: LegendVariant;+ align: "left" | "center" | "right";+ verticalAlign: "top" | "middle" | "bottom";+ selectedKey: string | null;+ hoveredKey: string | null;+ isClickable: boolean;+ onToggle: (key: string) => void;+ style: CSSProperties;+};+export function LegendOverlay({+ seriesKeys,+ config,+ variant,+ align,+ selectedKey,+ hoveredKey,+ isClickable,+ onToggle,+ style,+}: LegendOverlayProps) {+ const legendJustify =+ align === "left"+ ? "justify-start"+ : align === "center"+ ? "justify-center"+ : "justify-end";+ return (+ <div+ style={style}+ className={`flex items-center gap-4 select-none ${legendJustify}`}+ >+ {seriesKeys.map((key) => {+ const item = config[key];+ const colorsCount = item ? getColorsCount(item) : 1;+ const isSelected =+ (selectedKey === null || selectedKey === key) &&+ (hoveredKey === null || hoveredKey === key);+ return (+ <button+ type="button"+ disabled={!isClickable}+ aria-pressed={isClickable ? selectedKey === key : undefined}+ key={key}+ className={`flex items-center gap-1.5 transition-opacity ${!isSelected ? "opacity-30" : ""} ${isClickable ? "cursor-pointer" : ""}`}+ onClick={() => {+ if (isClickable) onToggle(key);+ }}+ >+ <LegendIndicator+ variant={variant}+ dataKey={key}+ colorsCount={colorsCount}+ />+ {item?.label ?? key}+ </button>+ );+ })}+ </div>+ );+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-lifecycle.tsx b/packages/ui/src/components/evilcharts/ui/echarts-lifecycle.tsxnew file mode 100644index 00000000..20259441--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-lifecycle.tsx@@ -0,0 +1,197 @@+"use client";++import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import type { EChartsType } from "echarts/core";+import {+ type RefObject,+ useCallback,+ useRef,+ useSyncExternalStore,+} from "react";++import { seriesIndexForId } from "./echarts-options";++type Cleanup = (() => void) | undefined;+type LifecycleTask = (() => void) | (() => () => void);+type LifecycleProps = {+ prepare: () => void;+ setup: LifecycleTask;+ synchronize: LifecycleTask;+ animate: readonly LifecycleTask[];+};++class ChartLifecycle {+ private current: LifecycleProps | null = null;+ private initialized = false;+ private disposeChart: Cleanup;+ private disposeSynchronization: Cleanup;+ private animations: Cleanup[] = [];++ resume() {+ if (this.current && !this.initialized) this.commit(this.current);+ }++ commit(next: LifecycleProps) {+ const previous = this.current;+ this.current = next;+ next.prepare();+ if (!this.initialized || !previous) {+ this.initialized = true;+ this.disposeChart = next.setup() || undefined;+ this.disposeSynchronization = next.synchronize() || undefined;+ this.animations = next.animate.map((task) => task() || undefined);+ return;+ }+ const recreate = previous.setup !== next.setup;+ const synchronize = recreate || previous.synchronize !== next.synchronize;+ for (let index = 0; index < this.animations.length; index++) {+ if (recreate || previous.animate[index] !== next.animate[index]) {+ this.animations[index]?.();+ this.animations[index] = undefined;+ }+ }+ if (synchronize) {+ this.disposeSynchronization?.();+ this.disposeSynchronization = undefined;+ }+ if (recreate) {+ this.disposeChart?.();+ this.disposeChart = next.setup() || undefined;+ }+ if (synchronize)+ this.disposeSynchronization = next.synchronize() || undefined;+ next.animate.forEach((task, index) => {+ if (recreate || previous.animate[index] !== task)+ this.animations[index] = task() || undefined;+ });+ }++ dispose() {+ this.animations.forEach((cleanup) => {+ cleanup?.();+ });+ this.animations = [];+ this.disposeSynchronization?.();+ this.disposeSynchronization = undefined;+ this.disposeChart?.();+ this.disposeChart = undefined;+ this.initialized = false;+ }+}++export function useChartLifecycle(+ props: LifecycleProps,+ container: RefObject<HTMLDivElement | null>,+) {+ const lifecycleRef = useRef<ChartLifecycle | null>(null);+ const mountedNode = useRef<HTMLDivElement | null>(null);+ if (!lifecycleRef.current) lifecycleRef.current = new ChartLifecycle();+ const lifecycle = lifecycleRef.current;+ useMountEffect(() => {+ lifecycle.resume();+ return () => lifecycle.dispose();+ });+ return useCallback(+ (node: HTMLDivElement | null) => {+ container.current = node;+ if (node) {+ if (mountedNode.current !== null && mountedNode.current !== node)+ lifecycle.dispose();+ mountedNode.current = node;+ lifecycle.commit(props);+ }+ },+ [container, lifecycle, mountedNode, props],+ );+}++export function observeChartTheme(container: HTMLElement, refresh: () => void) {+ const observer = new MutationObserver(refresh);+ for (+ let element: HTMLElement | null = container;+ element;+ element = element.parentElement+ ) {+ observer.observe(element, {+ attributes: true,+ attributeFilter: ["class", "style", "data-theme"],+ });+ }+ return observer;+}++export function boundedIndex(+ index: number | null | undefined,+ length: number,+): number | null {+ return typeof index === "number" &&+ Number.isInteger(index) &&+ index >= 0 &&+ index < length+ ? index+ : null;+}++const activeTooltipTimers = new WeakMap<+ EChartsType,+ ReturnType<typeof setTimeout>+>();++export function cancelActiveTooltip(chart: EChartsType) {+ const timer = activeTooltipTimers.get(chart);+ if (timer !== undefined) clearTimeout(timer);+ activeTooltipTimers.delete(chart);+}++export function showActiveIndex(+ chart: EChartsType,+ index: number | null,+ seriesId?: string,+) {+ cancelActiveTooltip(chart);+ chart.dispatchAction({ type: "downplay", seriesId }, { silent: true });+ chart.dispatchAction({ type: "hideTip" }, { silent: true });+ if (index === null) return;+ const seriesIndex = seriesId ? seriesIndexForId(chart, seriesId) : 0;+ if (seriesIndex < 0) return;+ const target = seriesId ? { seriesId } : { seriesIndex };+ chart.dispatchAction(+ { type: "highlight", ...target, dataIndex: index },+ { silent: true },+ );+ const show = () => {+ chart.dispatchAction(+ { type: "showTip", seriesIndex, dataIndex: index },+ { silent: true },+ );+ };+ show();+ activeTooltipTimers.set(+ chart,+ setTimeout(() => {+ activeTooltipTimers.delete(chart);+ if (!chart.isDisposed()) show();+ }, 0),+ );+}++function readReducedMotion() {+ return (+ typeof window === "undefined" ||+ window.matchMedia("(prefers-reduced-motion: reduce)").matches+ );+}++function subscribeReducedMotion(notify: () => void) {+ const media = window.matchMedia("(prefers-reduced-motion: reduce)");+ media.addEventListener("change", notify);+ return () => media.removeEventListener("change", notify);+}++export function useReducedMotion() {+ return useSyncExternalStore(+ subscribeReducedMotion,+ readReducedMotion,+ readReducedMotion,+ );+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-options.ts b/packages/ui/src/components/evilcharts/ui/echarts-options.tsnew file mode 100644index 00000000..bd4d5621--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-options.ts@@ -0,0 +1,64 @@+import type {+ BarSeriesOption,+ LineSeriesOption,+ PieSeriesOption,+} from "echarts/charts";+import type {+ DataZoomComponentOption,+ GridComponentOption,+ TooltipComponentOption,+} from "echarts/components";+import type { ComposeOption, EChartsType } from "echarts/core";++type EngineOption = ComposeOption<+ | BarSeriesOption+ | LineSeriesOption+ | PieSeriesOption+ | DataZoomComponentOption+ | GridComponentOption+ | TooltipComponentOption+>;++function keyedComponents<T extends { id?: string | number }>(+ value: T | T[] | undefined,+ prefix: string,+): T[] {+ const components = Array.isArray(value) ? value : value ? [value] : [];+ return components.map((component, index) => ({+ ...component,+ id: component.id ?? `__${prefix}-${index}`,+ }));+}++export function setChartOption(chart: EChartsType, option: EngineOption) {+ const cartesian =+ option.grid !== undefined ||+ option.xAxis !== undefined ||+ option.yAxis !== undefined;+ const components = cartesian+ ? {+ grid: keyedComponents(option.grid, "grid"),+ xAxis: keyedComponents(option.xAxis, "x-axis"),+ yAxis: keyedComponents(option.yAxis, "y-axis"),+ dataZoom: keyedComponents(option.dataZoom, "zoom"),+ }+ : {};+ chart.setOption(+ {+ ...option,+ ...components,+ series: keyedComponents(option.series, "series"),+ },+ {+ replaceMerge: cartesian+ ? ["series", "grid", "xAxis", "yAxis", "dataZoom"]+ : ["series"],+ },+ );+}++export function seriesIndexForId(chart: EChartsType, id: string) {+ const option: EngineOption = chart.getOption();+ const series = Array.isArray(option.series) ? option.series : [option.series];+ return series.findIndex((component) => component?.id === id);+}diff --git a/packages/ui/src/components/evilcharts/ui/echarts-tooltip.tsx b/packages/ui/src/components/evilcharts/ui/echarts-tooltip.tsxnew file mode 100644index 00000000..8c754b4f--- /dev/null+++ b/packages/ui/src/components/evilcharts/ui/echarts-tooltip.tsx@@ -0,0 +1,150 @@+import type { TooltipComponentOption } from "echarts/components";+import { indicatorBackground, type ResolvedColors } from "./echarts-chart";+import { ECHARTS_CONFIG } from "./echarts-config";+export type TooltipVariant = "default" | "frosted-glass";+export type TooltipRoundness = "sm" | "md" | "lg" | "xl";+export type TooltipPosition = "fixed" | "variable" | "bottom";+export const roundnessClass: Record<TooltipRoundness, string> = {+ sm: "rounded-sm",+ md: "rounded-md",+ lg: "rounded-lg",+ xl: "rounded-xl",+};+export const tooltipVariantClass: Record<TooltipVariant, string> = {+ default: "bg-background",+ "frosted-glass": "bg-background/50 backdrop-blur-md",+};+export function escapeTooltipText(value: string): string {+ return value.replace(+ /[&<>"']/g,+ (character) =>+ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[+ character+ ] ?? character,+ );+}++export function tooltipIndicatorHtml(key: string, colorsCount: number): string {+ return `<div class="h-2.5 w-2.5 shrink-0 rounded-[2px]" style="background:${escapeTooltipText(indicatorBackground(key, colorsCount))}"></div>`;+}+export function tooltipRow({+ indicatorHtml,+ labelText,+ valueText,+ dimmed,+}: {+ indicatorHtml: string;+ labelText: string;+ valueText: string;+ dimmed: string;+}): string {+ return `<div class="flex w-full items-center gap-2 whitespace-nowrap${dimmed}">+ ${indicatorHtml}+ <div class="flex flex-1 items-center justify-between gap-4 leading-none">+ <span class="text-muted-foreground">${escapeTooltipText(labelText)}</span>+ <span class="text-foreground font-mono font-medium tabular-nums">${escapeTooltipText(valueText)}</span>+ </div>+ </div>`;+}+export function tooltipShell({+ label,+ body,+ roundness,+ variant,+}: {+ label: string;+ body: string;+ roundness: TooltipRoundness;+ variant: TooltipVariant;+}): string {+ return `<div class="grid min-w-32 items-start gap-1.5 border border-border/50 px-2.5 py-1.5 text-xs shadow-xl ${roundnessClass[roundness]} ${tooltipVariantClass[variant]}">+ <div class="font-medium text-primary">${escapeTooltipText(label)}</div>+ <div class="grid gap-1.5">${body}</div>+ </div>`;+}+function clippingBounds(dom: HTMLElement): { left: number; right: number } {+ const view = dom.ownerDocument.defaultView;+ const viewportRight = view?.innerWidth ?? Number.POSITIVE_INFINITY;+ let node = dom.parentElement?.parentElement ?? null;+ while (node && view?.getComputedStyle(node).overflowX === "visible") {+ node = node.parentElement;+ }+ const rect = node?.getBoundingClientRect();+ return {+ left: Math.max(0, rect?.left ?? 0),+ right: Math.min(viewportRight, rect?.right ?? viewportRight),+ };+}+function oversizedTooltipX(+ dom: HTMLElement | object | null,+ width: number,+ viewWidth: number,+): number {+ const centered = (viewWidth - width) / 2;+ if (!dom || !("parentElement" in dom)) return centered;+ const origin = dom.parentElement?.getBoundingClientRect();+ if (!origin) return centered;+ const bounds = clippingBounds(dom);+ const inset = ECHARTS_CONFIG.tooltip.edgeInset;+ const min = bounds.left + inset - origin.left;+ const max = bounds.right - inset - width - origin.left;+ if (max < min) return min;+ return Math.min(Math.max(centered, min), max);+}+export function resolveTooltipPosition(+ position: TooltipPosition,+): TooltipComponentOption["position"] {+ if (position === "variable") return undefined;+ if (position === "bottom") {+ return (point, _params, dom, _rect, size) => {+ const [width, height] = size.contentSize;+ const [viewWidth, viewHeight] = size.viewSize;+ const y = Math.max(+ 0,+ viewHeight - height - ECHARTS_CONFIG.tooltip.edgeInset,+ );+ if (width <= viewWidth) {+ return [+ Math.max(0, Math.min(point[0] - width / 2, viewWidth - width)),+ y,+ ];+ }+ return [oversizedTooltipX(dom, width, viewWidth), y];+ };+ }+ return (point, _params, _dom, _rect, size) => [+ point[0] - size.contentSize[0] / 2,+ 8,+ ];+}+export function tooltipBaseOption(params: {+ present: boolean;+ cursor: boolean;+ tokens: ResolvedColors["tokens"];+ position: TooltipPosition;+ axisPointerColor: string;+ strokeWidth: number;+}): TooltipComponentOption {+ const { present, cursor, position, axisPointerColor, strokeWidth } = params;+ return {+ show: present,+ trigger: "axis",+ confine: true,+ displayTransition: false,+ backgroundColor: "transparent",+ borderWidth: 0,+ padding: 0,+ extraCssText: "box-shadow:none;",+ axisPointer: cursor+ ? {+ type: "line",+ lineStyle: {+ color: axisPointerColor,+ width: strokeWidth,+ type: [3, 3] as [number, number],+ },+ }+ : { type: "none" },+ position: resolveTooltipPosition(position),+ };+}diff --git a/packages/ui/src/components/field.tsx b/packages/ui/src/components/field.tsxindex 0b29c35f..685eb65d 100644--- a/packages/ui/src/components/field.tsx+++ b/packages/ui/src/components/field.tsx@@ -12,7 +12,7 @@ function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {<fieldsetdata-slot="field-set"className={cn(- "flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",+ "flex flex-col gap-6 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",className,)}{...props}@@ -30,7 +30,7 @@ function FieldLegend({data-slot="field-legend"data-variant={variant}className={cn(- "mb-2.5 font-medium data-[variant=label]:text-xs data-[variant=legend]:text-sm",+ "mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",className,)}{...props}@@ -43,7 +43,7 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="field-group"className={cn(- "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",+ "group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",className,)}{...props}@@ -52,7 +52,7 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {}const fieldVariants = cva(- "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",+ "group/field flex w-full gap-3 data-[invalid=true]:text-destructive",{variants: {orientation: {@@ -90,7 +90,7 @@ function FieldContent({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="field-content"className={cn(- "group/field-content flex flex-1 flex-col gap-0.5 leading-snug",+ "group/field-content flex flex-1 flex-col gap-1 leading-snug",className,)}{...props}@@ -106,7 +106,7 @@ function FieldLabel({<Labeldata-slot="field-label"className={cn(- "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",+ "group/field-label peer/field-label flex w-fit gap-2 leading-snug transition-[color,background-color,border-color,box-shadow] group-data-[disabled=true]/field:opacity-50 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-data-checked:not-has-[:disabled,[data-disabled]]:hover:border-input has-[>[data-slot=field]]:not-has-data-checked:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-data-checked:border-brand/60 has-[>[data-slot=field]]:has-data-checked:bg-brand/5 has-[>[data-slot=field]]:has-[:focus-visible]:shadow-focus *:data-[slot=field]:p-3 dark:has-[>[data-slot=field]]:has-data-checked:bg-brand/10","has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",className,)}@@ -120,7 +120,7 @@ function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="field-label"className={cn(- "flex w-fit items-center gap-2 text-xs/relaxed group-data-[disabled=true]/field:opacity-50",+ "flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",className,)}{...props}@@ -133,7 +133,7 @@ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {<pdata-slot="field-description"className={cn(- "text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",+ "text-left text-13 font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5","last:mt-0 nth-last-2:-mt-1","[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",className,@@ -155,7 +155,7 @@ function FieldSeparator({data-slot="field-separator"data-content={!!children}className={cn(- "relative -my-2 h-5 text-xs group-data-[variant=outline]/field-group:-mb-2",+ "relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",className,)}{...props}@@ -216,7 +216,7 @@ function FieldError({<divrole="alert"data-slot="field-error"- className={cn("text-xs font-normal text-destructive", className)}+ className={cn("text-13 font-normal text-destructive", className)}{...props}>{content}diff --git a/packages/ui/src/components/form-sheet.tsx b/packages/ui/src/components/form-sheet.tsxnew file mode 100644index 00000000..4130e9b2--- /dev/null+++ b/packages/ui/src/components/form-sheet.tsx@@ -0,0 +1,206 @@+"use client";++import { Button } from "@crm/ui/components/button";+import { useDiscardChanges } from "@crm/ui/components/discard-changes";+import { FieldGroup } from "@crm/ui/components/field";+import {+ Sheet,+ SheetClose,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@crm/ui/components/sheet";+import {+ type ComponentProps,+ createContext,+ type FormEvent,+ type ReactNode,+ useContext,+ useState,+} from "react";++const FormSheetContext = createContext<{+ pending: boolean;+ cancel: () => void;+} | null>(null);++function FormSheet({+ children,+ open: controlledOpen,+ defaultOpen = false,+ onOpenChange,+ dirty = false,+ pending = false,+ onDiscard,+ ...props+}: ComponentProps<typeof Sheet> & {+ dirty?: boolean;+ pending?: boolean;+ onDiscard: () => void;+}) {+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);+ const open = controlledOpen ?? uncontrolledOpen;++ const changeOpen = (next: boolean) => {+ setUncontrolledOpen(next);+ onOpenChange?.(next);+ };++ const guard = useDiscardChanges({+ open,+ dirty,+ pending,+ onOpenChange: changeOpen,+ onDiscard,+ });++ return (+ <Sheet {...props} open={open} onOpenChange={guard.onOpenChange}>+ <FormSheetContext value={{ pending, cancel: guard.discard }}>+ {children}+ {guard.dialog}+ </FormSheetContext>+ </Sheet>+ );+}++function FormSheetContent({+ onPointerDownOutside,+ ...props+}: ComponentProps<typeof SheetContent>) {+ return (+ <SheetContent+ {...props}+ onPointerDownOutside={(event) => {+ onPointerDownOutside?.(event);+ event.preventDefault();+ }}+ />+ );+}++function useFormSheetValidation() {+ const [errors, setErrors] = useState<Record<string, string>>({});++ const clearError = (id: string) => {+ setErrors((current) => {+ if (!current[id]) return current;+ const next = { ...current };+ delete next[id];+ return next;+ });+ };++ const validate = (+ form: HTMLFormElement,+ additionalErrors: Record<string, string> = {},+ ) => {+ const next = { ...additionalErrors };+ for (const control of Array.from(form.elements)) {+ if (+ (control instanceof HTMLInputElement ||+ control instanceof HTMLSelectElement ||+ control instanceof HTMLTextAreaElement) &&+ !control.validity.valid+ ) {+ next[control.id] = control.validationMessage;+ }+ }+ setErrors(next);+ const firstInvalid = form.querySelector<HTMLElement>(+ Object.keys(next)+ .map((id) => `[id="${CSS.escape(id)}"]`)+ .join(",") || ":not(*)",+ );+ firstInvalid?.focus();+ return Object.keys(next).length === 0;+ };++ const onInput = (event: FormEvent<HTMLFormElement>) => {+ if (event.target instanceof HTMLElement) clearError(event.target.id);+ };++ return { errors, validate, clearError, onInput, reset: () => setErrors({}) };+}++function FormSheetHeader({+ title,+ description,+}: {+ title: ReactNode;+ description?: ReactNode;+}) {+ return (+ <SheetHeader>+ <SheetTitle>{title}</SheetTitle>+ {description ? <SheetDescription>{description}</SheetDescription> : null}+ </SheetHeader>+ );+}++function FormSheetForm({+ children,+ onSubmit,+ ...props+}: Omit<ComponentProps<"form">, "className">) {+ const guard = useContext(FormSheetContext);+ return (+ <form+ data-slot="form-sheet-form"+ className="min-h-0 flex-1 overflow-y-auto px-6 py-6"+ {...props}+ aria-busy={guard?.pending || undefined}+ onSubmit={(event) => {+ if (guard?.pending) {+ event.preventDefault();+ return;+ }+ onSubmit?.(event);+ }}+ >+ <FieldGroup>{children}</FieldGroup>+ </form>+ );+}++function FormSheetFooter({+ cancelLabel = "Cancel",+ children,+}: {+ cancelLabel?: string;+ children: ReactNode;+}) {+ const guard = useContext(FormSheetContext);+ return (+ <SheetFooter className="flex-row justify-end">+ {guard ? (+ <Button+ type="button"+ variant="ghost"+ disabled={guard.pending}+ onClick={guard.cancel}+ >+ {cancelLabel}+ </Button>+ ) : (+ <SheetClose asChild>+ <Button type="button" variant="ghost">+ {cancelLabel}+ </Button>+ </SheetClose>+ )}+ {children}+ </SheetFooter>+ );+}++export {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ FormSheetHeader,+ useFormSheetValidation,+};diff --git a/packages/ui/src/components/generated-avatar.tsx b/packages/ui/src/components/generated-avatar.tsxnew file mode 100644index 00000000..6ba28c10--- /dev/null+++ b/packages/ui/src/components/generated-avatar.tsx@@ -0,0 +1,98 @@+import { seedHash, seedPalette } from "@crm/ui/lib/seed-palette";+import { cn } from "@crm/ui/lib/utils";++export type GeneratedAvatarSize = "xs" | "sm" | "md" | "lg" | "xl" | "fill";++const SIZE: Record<GeneratedAvatarSize, string> = {+ fill: "size-full",+ xs: "size-4",+ sm: "size-5",+ md: "size-6",+ lg: "size-8",+ xl: "size-12",+};++const BOX = 50;++type Dot = { x: number; y: number; r: number; tone: 1 | 2 };++function glyphDots(value: number, inset: number): Dot[] {+ let bits = value & 0x7fff;+ let count = 0;++ for (let bit = 0; bit < 15; bit += 1) {+ count += (bits >> bit) & 1;+ }++ if (count < 6) {+ bits = ~bits & 0x7fff;+ }++ const cell = (BOX - inset * 2) / 5;+ const dots: Dot[] = [];++ for (let y = 0; y < 5; y += 1) {+ for (let x = 0; x < 5; x += 1) {+ const column = x > 2 ? 4 - x : x;++ if ((bits >> (y * 3 + column)) & 1) {+ dots.push({+ x: inset + (x + 0.5) * cell,+ y: inset + (y + 0.5) * cell,+ r: cell * 0.42,+ tone: x === 2 ? 2 : 1,+ });+ }+ }+ }++ const xs = dots.map((dot) => dot.x);+ const ys = dots.map((dot) => dot.y);+ const shiftX = BOX / 2 - (Math.min(...xs) + Math.max(...xs)) / 2;+ const shiftY = BOX / 2 - (Math.min(...ys) + Math.max(...ys)) / 2;++ return dots.map((dot) => ({ ...dot, x: dot.x + shiftX, y: dot.y + shiftY }));+}++function GeneratedAvatar({+ seed,+ kind = "person",+ size = "md",+}: {+ seed: string;+ kind?: "person" | "workspace";+ size?: GeneratedAvatarSize;+}) {+ const value = seedHash(seed);+ const palette = seedPalette(value);+ const person = kind === "person";+ const dots = glyphDots(value, person ? 7 : 5);++ return (+ <svg+ aria-hidden+ className={cn(+ "shrink-0 overflow-hidden",+ SIZE[size],+ person ? "rounded-full" : "rounded-md",+ )}+ data-kind={kind}+ data-slot="generated-avatar"+ focusable={false}+ viewBox={`0 0 ${BOX} ${BOX}`}+ >+ <rect fill={palette[0]} height={BOX} width={BOX} />+ {dots.map((dot) => (+ <circle+ cx={dot.x}+ cy={dot.y}+ fill={palette[dot.tone]}+ key={`${dot.x}-${dot.y}`}+ r={dot.r}+ />+ ))}+ </svg>+ );+}++export { GeneratedAvatar };diff --git a/packages/ui/src/components/icon.tsx b/packages/ui/src/components/icon.tsxindex 0c51b92f..ef78ae0b 100644--- a/packages/ui/src/components/icon.tsx+++ b/packages/ui/src/components/icon.tsx@@ -23,74 +23,97 @@ export const ICON_MOTIONS = [export type IconMotion = (typeof ICON_MOTIONS)[number];-export type CarbonIconProps = React.SVGProps<SVGSVGElement> & {+export type IconComponentProps = React.SVGProps<SVGSVGElement> & {size?: number | string;};-export type CarbonIcon = React.ComponentType<CarbonIconProps> & {+export type IconComponent = React.ComponentType<IconComponentProps> & {displayName?: string;- render?: { displayName?: string; name?: string };};-const MOTION_BY_ICON: Record<string, IconMotion> = {- ArrowRight: "nudge-right",- ChevronRight: "nudge-right",- Play: "nudge-right",- SendAlt: "nudge-right",- Logout: "nudge-right",- ArrowLeft: "nudge-left",- ChevronLeft: "nudge-left",- ArrowUp: "nudge-up",- ArrowDown: "nudge-down",- ChevronDown: "nudge-down",- Download: "bounce",- Launch: "launch",- Settings: "spin",- Renew: "spin",- Restart: "spin",- RecentlyViewed: "spin",- Earth: "spin",- Add: "turn",- Close: "turn",- TrashCan: "wiggle",- Tools: "wiggle",- Locked: "wiggle",- Password: "wiggle",- MagicWand: "wiggle",- Search: "wiggle",- WarningAlt: "wiggle",- Misuse: "pulse",- Information: "pulse",- Security: "pulse",- Light: "pulse",- Ai: "pulse",- Chip: "pulse",- Asleep: "swing",-};+const MOTION_BY_ICON = new Map(+ Object.entries({+ ArrowRight: "nudge-right",+ ChevronRight: "nudge-right",+ LogOut: "nudge-right",+ ArrowLeft: "nudge-left",+ ChevronLeft: "nudge-left",+ ArrowUp: "nudge-up",+ ArrowDown: "nudge-down",+ ChevronDown: "nudge-down",+ Download: "bounce",+ ExternalLink: "launch",+ ArrowUpRight: "launch",+ Settings: "spin",+ RefreshCw: "spin",+ Plus: "turn",+ X: "turn",+ Trash: "wiggle",+ Lock: "wiggle",+ Search: "wiggle",+ TriangleAlert: "wiggle",+ Info: "pulse",+ CircleAlert: "pulse",+ Shield: "pulse",+ Sun: "pulse",+ Moon: "swing",+ ChevronUp: "nudge-up",+ Play: "nudge-right",+ WandSparkles: "wiggle",+ } satisfies Record<string, IconMotion>),+);-function iconName(icon: CarbonIcon): string | undefined {- return icon.displayName ?? icon.render?.displayName ?? icon.render?.name;-}+export function iconMotionFor(icon: IconComponent): IconMotion {+ const name = icon.displayName;-export function iconMotionFor(icon: CarbonIcon): IconMotion {- const name = iconName(icon);- return (name && MOTION_BY_ICON[name]) || "pop";+ return (name && MOTION_BY_ICON.get(name)) || "pop";}-export type IconProps = CarbonIconProps & {- icon: CarbonIcon;+export type IconProps = IconComponentProps & {+ icon: IconComponent;motion?: IconMotion;+ tone?: "default" | "muted" | "destructive" | "success";+ size?: number | string;};-export function Icon({ icon: Glyph, motion, className, ...props }: IconProps) {+const ICON_SIZES = {+ xs: "size-3",+ sm: "size-3.5",+ md: "size-4",+ lg: "size-5",+} as const;++const ICON_SIZE_CLASSES = new Map(Object.entries(ICON_SIZES));++export function Icon({+ icon: Glyph,+ motion,+ tone = "default",+ size,+ className,+ ...props+}: IconProps) {const resolved = motion ?? iconMotionFor(Glyph);+ const sizeClass =+ typeof size === "string" ? ICON_SIZE_CLASSES.get(size) : undefined;+return (<Glypharia-hiddenfocusable={false}+ width={sizeClass ? undefined : (size ?? 16)}+ height={sizeClass ? undefined : (size ?? 16)}{...props}+ size={sizeClass ? undefined : (size ?? 16)}data-motion={resolved}- className={cn("cds-icon", className)}+ className={cn(+ "ds-icon",+ tone === "muted" && "text-muted-foreground",+ tone === "destructive" && "text-destructive",+ tone === "success" && "text-status-success",+ sizeClass,+ className,+ )}/>);}diff --git a/packages/ui/src/components/ink-field.tsx b/packages/ui/src/components/ink-field.tsxnew file mode 100644index 00000000..f1189bb8--- /dev/null+++ b/packages/ui/src/components/ink-field.tsx@@ -0,0 +1,108 @@+"use client";++import { SHELL } from "@crm/ui/lib/shell-config";+import { cn } from "@crm/ui/lib/utils";+import { MeshGradient } from "@paper-design/shaders-react";+import { Component, type ReactNode, useSyncExternalStore } from "react";++const MOTION_QUERY = "(prefers-reduced-motion: reduce)";++let webGlSupport: boolean | undefined;++function supportsWebGl(): boolean {+ if (webGlSupport === undefined) {+ try {+ webGlSupport = Boolean(+ document.createElement("canvas").getContext("webgl2"),+ );+ } catch {+ webGlSupport = false;+ }+ }+ return webGlSupport;+}++function subscribeToNothing() {+ return () => undefined;+}++function subscribeToTheme(onChange: () => void) {+ const observer = new MutationObserver(onChange);++ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class"],+ });++ return () => observer.disconnect();+}++function readColors() {+ const style = getComputedStyle(document.documentElement);++ return SHELL.ink.tokens+ .map((token) => style.getPropertyValue(token).trim())+ .join(" ");+}++function subscribeToMotion(onChange: () => void) {+ const query = window.matchMedia(MOTION_QUERY);++ query.addEventListener("change", onChange);++ return () => query.removeEventListener("change", onChange);+}++class InkFieldBoundary extends Component<+ { children: ReactNode },+ { failed: boolean }+> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ render() {+ return this.state.failed ? null : this.props.children;+ }+}++function InkField({ className }: { className?: string }) {+ const webGl = useSyncExternalStore(subscribeToNothing, supportsWebGl, () => false);+ const colors = useSyncExternalStore(subscribeToTheme, readColors, () => "");+ const reduced = useSyncExternalStore(+ subscribeToMotion,+ () => window.matchMedia(MOTION_QUERY).matches,+ () => true,+ );++ const mesh = colors.split(" ").filter(Boolean);++ return (+ <div+ aria-hidden+ data-slot="ink-field"+ className={cn(+ "pointer-events-none absolute inset-y-0 left-0 overflow-hidden bg-[var(--rail,#0c1712)]",+ className,+ )}+ >+ {webGl && mesh.length === SHELL.ink.tokens.length ? (+ <InkFieldBoundary>+ <MeshGradient+ className="size-full"+ colors={mesh}+ distortion={SHELL.ink.distortion}+ maxPixelCount={SHELL.ink.maxPixelCount}+ scale={SHELL.ink.scale}+ speed={reduced ? 0 : SHELL.ink.speed}+ swirl={SHELL.ink.swirl}+ />+ </InkFieldBoundary>+ ) : null}+ </div>+ );+}++export { InkField };diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsxindex 732be0cd..875d0d61 100644--- a/packages/ui/src/components/input-group.tsx+++ b/packages/ui/src/components/input-group.tsx@@ -13,7 +13,7 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {data-slot="input-group"role="group"className={cn(- "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-md border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-1 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-1 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-muted dark:shadow-[inset_0_1px_1px_rgb(0_0_0/0.30)] dark:has-disabled:bg-muted dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",+ "group/input-group relative flex h-9 w-full min-w-0 items-center rounded-md border border-border transition-[color,background-color,border-color,box-shadow] outline-none in-data-[slot=combobox-content]:shadow-none! hover:border-input has-[[data-slot=input-group-control]:disabled]:pointer-events-none has-[[data-slot=input-group-control]:disabled]:bg-muted has-[[data-slot=input-group-control]:disabled]:text-muted-foreground data-[disabled=true]:bg-muted data-[disabled=true]:text-muted-foreground has-[[data-slot=input-group-control]:focus-visible]:shadow-focus has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-4 has-[[data-slot][aria-invalid=true]]:ring-destructive/15 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",className,)}{...props}@@ -22,14 +22,14 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {}const inputGroupAddonVariants = cva(- "flex h-auto items-center justify-center gap-2 py-1.5 text-xs font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-none [&>svg:not([class*='size-'])]:size-4",+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm text-muted-foreground select-none group-data-[disabled=true]/input-group:bg-transparent group-has-[[data-slot=input-group-control]:disabled]/input-group:bg-transparent [&>svg:not([class*='size-'])]:size-3.5",{variants: {align: {"inline-start":- "order-first cursor-text pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",+ "order-first pl-2.5 has-[>button]:-ml-1.5 has-[>kbd]:ml-[-0.15rem] has-[>[data-slot=input-group-text]]:mr-1 has-[>[data-slot=input-group-text]]:self-stretch has-[>[data-slot=input-group-text]]:rounded-l-md has-[>[data-slot=input-group-text]]:border-r has-[>[data-slot=input-group-text]]:bg-sidebar has-[>[data-slot=input-group-text]]:px-3","inline-end":- "order-last cursor-text pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",+ "order-last pr-2.5 has-[>button]:-mr-1.5 has-[>kbd]:mr-[-0.15rem] has-[>[data-slot=input-group-text]]:ml-1 has-[>[data-slot=input-group-text]]:self-stretch has-[>[data-slot=input-group-text]]:rounded-r-md has-[>[data-slot=input-group-text]]:border-l has-[>[data-slot=input-group-text]]:bg-sidebar has-[>[data-slot=input-group-text]]:px-3","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2","block-end":@@ -66,14 +66,14 @@ function InputGroupAddon({}const inputGroupButtonVariants = cva(- "flex items-center gap-2 text-xs shadow-none",+ "flex items-center gap-2 text-sm shadow-none",{variants: {size: {- xs: "h-6 gap-1 rounded-none px-1.5 [&>svg:not([class*='size-'])]:size-3.5",- sm: "gap-1",- "icon-xs": "size-6 rounded-none p-0 has-[>svg]:p-0",- "icon-sm": "size-7 p-0 has-[>svg]:p-0",+ xs: "h-6 gap-1 rounded-sm px-1.5 [&>svg:not([class*='size-'])]:size-3.5",+ sm: "",+ "icon-xs": "size-6 rounded-sm p-0 has-[>svg]:p-0",+ "icon-sm": "size-8 rounded-sm p-0 has-[>svg]:p-0",},},defaultVariants: {@@ -104,8 +104,9 @@ function InputGroupButton({function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {return (<span+ data-slot="input-group-text"className={cn(- "flex items-center gap-2 text-xs text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",+ "flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-3.5",className,)}{...props}@@ -121,7 +122,7 @@ function InputGroupInput({<Inputdata-slot="input-group-control"className={cn(- "flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",+ "h-full min-h-0 flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 hover:border-transparent focus-visible:shadow-none focus-visible:ring-0 disabled:bg-transparent aria-invalid:border-0 aria-invalid:ring-0",className,)}{...props}@@ -139,7 +140,7 @@ function InputGroupTextarea({data-slot="input-group-control"size={size}className={cn(- "flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",+ "flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 hover:border-transparent focus-visible:shadow-none focus-visible:ring-0 disabled:bg-transparent aria-invalid:border-0 aria-invalid:ring-0",className,)}{...props}diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsxindex 911975c1..da8b2df7 100644--- a/packages/ui/src/components/input.tsx+++ b/packages/ui/src/components/input.tsx@@ -7,7 +7,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {type={type}data-slot="input"className={cn(- "h-8 w-full min-w-0 rounded-md border border-input bg-background px-2.5 py-1 text-xs transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-xs file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none 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",+ "h-9 w-full min-w-0 rounded-md border border-border bg-transparent px-2.5 py-1 text-base transition-[color,background-color,border-color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-input focus-visible:shadow-focus disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground aria-invalid:border-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15 md:text-sm",className,)}{...props}diff --git a/packages/ui/src/components/kbd.tsx b/packages/ui/src/components/kbd.tsxnew file mode 100644index 00000000..d8df0c45--- /dev/null+++ b/packages/ui/src/components/kbd.tsx@@ -0,0 +1,41 @@+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";++function Kbd({+ className,+ size = "default",+ variant = "default",+ ...props+}: React.ComponentProps<"kbd"> & {+ size?: "default" | "sm";+ variant?: "default" | "hint";+}) {+ return (+ <kbd+ data-slot="kbd"+ data-size={size}+ data-variant={variant}+ className={cn(+ "pointer-events-none inline-flex h-5 w-fit min-w-5 select-none items-center justify-center gap-1 rounded-sm bg-background px-1 font-medium font-sans text-foreground text-xs shadow-border in-data-[slot=button]:bg-transparent in-data-[slot=input-group]:text-muted-foreground in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=button]:text-current in-data-[slot=tooltip-content]:text-background in-data-[slot=button]:shadow-none in-data-[slot=tooltip-content]:shadow-none in-data-[slot=button]:ring-1 in-data-[slot=button]:ring-current/20 dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3",+ size === "sm" &&+ "h-4 min-w-4 rounded-xs px-0.5 [&_svg:not([class*='size-'])]:size-2.5!",+ variant === "hint" &&+ "bg-muted/50 px-1.5 font-mono font-normal text-11 text-muted-foreground shadow-none ring-1 ring-input/60",+ className,+ )}+ {...props}+ />+ );+}++function KbdGroup({ className, ...props }: React.ComponentProps<"kbd">) {+ return (+ <kbd+ data-slot="kbd-group"+ className={cn("inline-flex items-center gap-0.5", className)}+ {...props}+ />+ );+}++export { Kbd, KbdGroup };diff --git a/packages/ui/src/components/label.tsx b/packages/ui/src/components/label.tsxindex 1a0b0652..92146fe0 100644--- a/packages/ui/src/components/label.tsx+++ b/packages/ui/src/components/label.tsx@@ -12,7 +12,7 @@ function Label({<LabelPrimitive.Rootdata-slot="label"className={cn(- "flex items-center gap-2 text-xs leading-none select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",+ "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",className,)}{...props}diff --git a/packages/ui/src/components/logo-spinner.tsx b/packages/ui/src/components/logo-spinner.tsxnew file mode 100644index 00000000..791f9e59--- /dev/null+++ b/packages/ui/src/components/logo-spinner.tsx@@ -0,0 +1,54 @@+import { cn } from "@crm/ui/lib/utils";+import { cva, type VariantProps } from "class-variance-authority";++const SILHOUETTE =+ "M384 99.548 367.934 87.04 256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096Z";++const MARK =+ "m384 99.548 -16.066 -12.508L256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096zm-127.98 -49.419 79.695 61.975 -40.944 31.803 -3.661 2.837 -35.091 -27.287 -102.399 79.638 35.09 27.287 32.218 25.088 35.09 27.288L358.4 199.074l-35.047 -27.288 3.659 -2.837 40.943 -31.803 79.651 61.952 -40.943 31.852 -150.62 117.163 -79.695 -61.974 -32.218 -25.041 -38.752 -30.125 -40.922 -31.849z";++const logoSpinnerVariants = cva("shrink-0", {+ variants: {+ size: {+ default: "size-4",+ lg: "size-10",+ },+ },+ defaultVariants: {+ size: "default",+ },+});++function LogoSpinner({+ className,+ size,+ ...props+}: React.ComponentProps<"svg"> & VariantProps<typeof logoSpinnerVariants>) {+ return (+ <svg+ data-slot="logo-spinner"+ role="status"+ aria-label="Loading"+ xmlns="http://www.w3.org/2000/svg"+ viewBox="-68 -68 648 648"+ fill="none"+ className={cn(logoSpinnerVariants({ size }), className)}+ {...props}+ >+ <path d={MARK} fill="currentColor" fillOpacity={0.85} />+ <path+ d={SILHOUETTE}+ transform="translate(256 256) scale(1.16) translate(-256 -256)"+ stroke="var(--ring)"+ strokeWidth={32}+ strokeLinejoin="round"+ strokeLinecap="round"+ pathLength={100}+ strokeDasharray="40 60"+ className="animate-spinner-trace"+ />+ </svg>+ );+}++export { LogoSpinner };diff --git a/packages/ui/src/components/meta-row.tsx b/packages/ui/src/components/meta-row.tsxnew file mode 100644index 00000000..b7eaea3f--- /dev/null+++ b/packages/ui/src/components/meta-row.tsx@@ -0,0 +1,17 @@+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";++function MetaRow({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="meta-row"+ className={cn(+ "flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-13 text-muted-foreground",+ className,+ )}+ {...props}+ />+ );+}++export { MetaRow };diff --git a/packages/ui/src/components/option-label.tsx b/packages/ui/src/components/option-label.tsxnew file mode 100644index 00000000..932aceb5--- /dev/null+++ b/packages/ui/src/components/option-label.tsx@@ -0,0 +1,26 @@+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";++function OptionLabel({+ label,+ detail,+ className,+}: {+ label: React.ReactNode;+ detail?: React.ReactNode;+ className?: string;+}) {+ return (+ <span+ data-slot="option-label"+ className={cn("flex min-w-0 items-baseline gap-2", className)}+ >+ <span className="shrink-0">{label}</span>+ {detail ? (+ <span className="min-w-0 truncate text-muted-foreground">{detail}</span>+ ) : null}+ </span>+ );+}++export { OptionLabel };diff --git a/packages/ui/src/components/overflow-tooltip.tsx b/packages/ui/src/components/overflow-tooltip.tsxnew file mode 100644index 00000000..791d2a13--- /dev/null+++ b/packages/ui/src/components/overflow-tooltip.tsx@@ -0,0 +1,90 @@+"use client";++import {+ AnchoredTooltipContent,+ type TooltipAnchor,+} from "@crm/ui/components/anchored-tooltip";+import { Tooltip } from "@crm/ui/components/tooltip";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { type PointerEvent, type ReactNode, useState } from "react";++type Hint = { element: HTMLElement; text: string; anchor: TooltipAnchor };++const CELL_TAGS: ReadonlySet<string> = new Set(["TD", "TH"]);++function isTruncated(element: HTMLElement): boolean {+ const style = getComputedStyle(element);++ return (+ (element.scrollWidth > element.clientWidth &&+ style.textOverflow === "ellipsis") ||+ (element.scrollHeight > element.clientHeight &&+ style.webkitLineClamp !== "none")+ );+}++function hintFor(target: EventTarget, container: Element): Hint | null {+ let node = target instanceof HTMLElement ? target : null;++ while (node && node !== container) {+ const text = node.textContent?.trim() ?? "";++ if (text && isTruncated(node)) {+ const { top, left, width, height } = node.getBoundingClientRect();+ return { element: node, text, anchor: { top, left, width, height } };+ }++ if (CELL_TAGS.has(node.tagName)) return null;++ node = node.parentElement;+ }++ return null;+}++export type OverflowTooltip = {+ handlers: {+ onPointerOver: (event: PointerEvent<HTMLElement>) => void;+ onPointerLeave: () => void;+ };+ tooltip: ReactNode;+};++export function useOverflowTooltip(): OverflowTooltip {+ const [hint, setHint] = useState<Hint | null>(null);++ useMountEffect(() => {+ const dismiss = () => setHint(null);+ window.addEventListener("scroll", dismiss, true);+ window.addEventListener("resize", dismiss);+ return () => {+ window.removeEventListener("scroll", dismiss, true);+ window.removeEventListener("resize", dismiss);+ };+ });++ return {+ handlers: {+ onPointerOver: (event) => {+ const next = hintFor(event.target, event.currentTarget);++ setHint((current) =>+ current?.element === next?.element ? current : next,+ );+ },+ onPointerLeave: () => setHint(null),+ },+ tooltip: (+ <Tooltip+ open={hint !== null}+ onOpenChange={(open) => {+ if (!open) setHint(null);+ }}+ >+ <AnchoredTooltipContent anchor={hint?.anchor}>+ {hint?.text}+ </AnchoredTooltipContent>+ </Tooltip>+ ),+ };+}diff --git a/packages/ui/src/components/page-section.tsx b/packages/ui/src/components/page-section.tsxnew file mode 100644index 00000000..3d7f3e3e--- /dev/null+++ b/packages/ui/src/components/page-section.tsx@@ -0,0 +1,52 @@+import { type ReactNode, type Ref, useId } from "react";++function PageSection({+ title,+ description,+ action,+ anchor,+ headingRef,+ children,+}: {+ title: ReactNode;+ description?: ReactNode;+ action?: ReactNode;+ anchor?: string;+ headingRef?: Ref<HTMLHeadingElement>;+ children?: ReactNode;+}) {+ const headingId = useId();++ return (+ <section+ aria-labelledby={headingId}+ className="flex min-w-0 scroll-mt-6 flex-col gap-4"+ data-slot="page-section"+ id={anchor}+ >+ <div className="flex min-w-0 items-start justify-between gap-4">+ <div className="flex min-w-0 flex-col gap-2">+ <h2+ className="text-balance font-semibold text-base tracking-tight outline-none"+ id={headingId}+ ref={headingRef}+ tabIndex={-1}+ >+ {title}+ </h2>+ {description ? (+ <p className="max-w-prose text-pretty text-muted-foreground text-sm">+ {description}+ </p>+ ) : null}+ </div>+ {action ? (+ <div className="-my-1 flex shrink-0 gap-2">{action}</div>+ ) : null}+ </div>+ {children}+ </section>+ );+}++export { PageSection };diff --git a/packages/ui/src/components/page-shell.tsx b/packages/ui/src/components/page-shell.tsxnew file mode 100644index 00000000..6e44818e--- /dev/null+++ b/packages/ui/src/components/page-shell.tsx@@ -0,0 +1,310 @@+import { StatGroup } from "@crm/ui/components/dashboard";+import {+ SkeletonBlock,+ SkeletonControl,+ SkeletonLine,+} from "@crm/ui/components/skeleton-lines";+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";+import { ViewTransition } from "react";+import type {} from "react/canary";++const transition = {+ "nav-forward": "nav-forward",+ "nav-back": "nav-back",+ "nav-lateral": "nav-lateral",+ default: "none",+} as const;++type PageWidth = "full" | "narrow";++function PageTransition({ children }: { children: React.ReactNode }) {+ return (+ <ViewTransition+ enter={transition}+ exit={transition}+ update={transition}+ default="none"+ >+ {children}+ </ViewTransition>+ );+}++function PageShell({+ className,+ contained = false,+ width = "full",+ ...props+}: React.ComponentProps<"div"> & { contained?: boolean; width?: PageWidth }) {+ return (+ <PageTransition>+ <main+ data-slot="page-shell-scroll"+ className={cn(+ "relative flex min-w-0 flex-1 flex-col px-4 pt-5 pb-6 md:px-8 md:pt-8 md:pb-10",+ contained ? "min-h-0 overflow-hidden" : "overflow-y-auto",+ )}+ >+ <div+ data-slot="page-shell"+ data-width={width}+ className={cn(+ "flex w-full min-w-0 flex-1 flex-col gap-6",+ width === "narrow" && "mx-auto max-w-3xl",+ contained && "min-h-0",+ className,+ )}+ {...props}+ />+ </main>+ </PageTransition>+ );+}++function PageShellHeader({+ className,+ children,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <header+ data-slot="page-shell-header"+ className={cn(+ "flex flex-col gap-3 [view-transition-name:page-header]",+ className,+ )}+ {...props}+ >+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5 sm:gap-x-4">+ {children}+ </div>+ </header>+ );+}++function PageShellHeading({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="page-shell-heading"+ className={cn("contents", className)}+ {...props}+ />+ );+}++function PageShellTitle({ className, ...props }: React.ComponentProps<"h1">) {+ return (+ <h1+ data-slot="page-shell-title"+ className={cn(+ "col-start-1 row-start-1 min-w-0 self-center text-balance font-semibold text-2xl tracking-tight",+ className,+ )}+ {...props}+ />+ );+}++function PageShellDescription({+ className,+ ...props+}: React.ComponentProps<"p">) {+ return (+ <p+ data-slot="page-shell-description"+ className={cn(+ "col-span-full row-start-2 max-w-prose text-pretty text-muted-foreground text-sm",+ className,+ )}+ {...props}+ />+ );+}++function PageShellActions({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="page-shell-actions"+ className={cn(+ "col-start-2 row-start-1 flex flex-wrap items-center justify-end gap-2 self-center max-sm:[&_:is([data-slot=button],[data-slot$=-trigger])[data-size]:not([data-size^=icon])]:h-8 max-sm:[&_:is([data-slot=button],[data-slot$=-trigger])[data-size]:not([data-size^=icon])]:px-3",+ className,+ )}+ {...props}+ />+ );+}++function PageShellContent({+ className,+ children,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="page-shell-content"+ className={cn(+ "@container/page-content flex flex-1 flex-col gap-6",+ className,+ )}+ {...props}+ >+ {children}+ </div>+ );+}++const TABLE_CONTROL_WIDTHS = ["32", "24", "20", "28"] as const;++const TABLE_SKELETON_ROWS = 5;++const STAT_SKELETON_TILES = 4;++function TableSkeleton({ controls }: { controls: number }) {+ return (+ <div className="flex min-h-0 flex-1 flex-col gap-3">+ <div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">+ <div className="w-full sm:w-64">+ <SkeletonControl width="full" />+ </div>+ <div className="hidden flex-wrap items-center gap-2 sm:flex">+ {TABLE_CONTROL_WIDTHS.slice(+ TABLE_CONTROL_WIDTHS.length - controls,+ ).map((width) => (+ <SkeletonControl key={width} width={width} />+ ))}+ </div>+ </div>+ <div className="flex flex-col rounded-md bg-card shadow-border">+ <div className="flex h-10 items-center px-4 shadow-divider">+ <SkeletonLine width="24" />+ </div>+ {Array.from({ length: TABLE_SKELETON_ROWS }, (_, index) => (+ <div+ key={index}+ className="flex items-center gap-6 px-4 py-4 not-last:shadow-divider"+ >+ <div className="flex-1">+ <SkeletonLine width="72" />+ </div>+ <div className="hidden w-64 gap-6 md:flex">+ <SkeletonLine width="24" />+ <SkeletonLine width="24" />+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}++function DashboardSkeleton() {+ return (+ <div className="flex flex-col gap-6">+ <StatGroup>+ {Array.from({ length: STAT_SKELETON_TILES }, (_, index) => (+ <div key={index} className="flex flex-col gap-2 p-4 md:p-6">+ <SkeletonLine width="24" />+ <SkeletonLine size="2xl" width="24" />+ <SkeletonLine width="40" />+ </div>+ ))}+ </StatGroup>+ <div className="@container/dashboard">+ <div className="grid grid-cols-1 gap-4 @3xl/dashboard:grid-cols-[2fr_1fr]">+ <div className="flex flex-col gap-3">+ <SkeletonLine width="48" />+ <SkeletonBlock height="56" />+ </div>+ <div className="flex flex-col gap-3">+ <SkeletonLine width="40" />+ <SkeletonBlock height="56" />+ </div>+ </div>+ </div>+ </div>+ );+}++function SettingsSkeleton() {+ return (+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-3">+ <SkeletonLine width="40" />+ <SkeletonBlock height="40" />+ </div>+ <div className="flex flex-col gap-3">+ <SkeletonLine width="24" />+ <SkeletonBlock height="24" />+ </div>+ </div>+ );+}++type LoadingShape = "block" | "table" | "dashboard" | "settings";++function PageShellLoading({ shape = "block" }: { shape?: LoadingShape }) {+ return (+ <div aria-busy="true" className="flex min-h-0 flex-1 flex-col">+ <div aria-hidden="true" className="flex min-h-0 flex-1 flex-col">+ {shape === "table" ? (+ <TableSkeleton controls={3} />+ ) : shape === "dashboard" ? (+ <DashboardSkeleton />+ ) : shape === "settings" ? (+ <SettingsSkeleton />+ ) : (+ <SkeletonBlock height="56" />+ )}+ </div>+ <span role="status" className="sr-only">+ Loading page…+ </span>+ </div>+ );+}++function PageShellFallback({+ width = "full",+ shape = "block",+}: {+ width?: PageWidth;+ shape?: LoadingShape;+}) {+ return (+ <PageShell aria-busy="true" width={width}>+ <PageShellHeader aria-hidden="true">+ <PageShellHeading>+ <div className="col-start-1 row-start-1">+ <SkeletonLine size="2xl" width="48" />+ </div>+ <div className="col-span-full row-start-2 flex h-5 items-center">+ <SkeletonLine width="96" />+ </div>+ </PageShellHeading>+ </PageShellHeader>+ <PageShellContent>+ <PageShellLoading shape={shape} />+ </PageShellContent>+ </PageShell>+ );+}++export type { PageWidth };+export {+ PageShell,+ PageShellActions,+ PageShellContent,+ PageShellDescription,+ PageShellFallback,+ PageShellHeader,+ PageShellHeading,+ PageShellLoading,+ PageShellTitle,+};diff --git a/packages/ui/src/components/person-avatar.tsx b/packages/ui/src/components/person-avatar.tsxindex ca9db46c..d22a6cf6 100644--- a/packages/ui/src/components/person-avatar.tsx+++ b/packages/ui/src/components/person-avatar.tsx@@ -1,7 +1,7 @@"use client";import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";-import { initialsFromName } from "@crm/ui/lib/format";+import { GeneratedAvatar } from "@crm/ui/components/generated-avatar";import type * as React from "react";export type PersonAvatarSize = "sm" | "default" | "lg";@@ -19,12 +19,14 @@ export function PersonAvatar({size?: PersonAvatarSize;}) {const url = src?.trim() ? src : undefined;- const label = name?.trim() || email?.trim() || "";+ const seed = email?.trim() || name?.trim() || "";return (<Avatar size={size} {...props}>{url ? <AvatarImage src={url} alt="" /> : null}- <AvatarFallback>{initialsFromName(label)}</AvatarFallback>+ <AvatarFallback>+ <GeneratedAvatar seed={seed} size="fill" />+ </AvatarFallback></Avatar>);}diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsxindex b43c12ef..c2a3d7f1 100644--- a/packages/ui/src/components/popover.tsx+++ b/packages/ui/src/components/popover.tsx@@ -19,11 +19,11 @@ function PopoverTrigger({}const popoverContentVariants = cva(- "z-50 flex origin-(--radix-popover-content-transform-origin) flex-col rounded-lg bg-popover text-xs text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 flex origin-(--radix-popover-content-transform-origin) flex-col rounded-xl bg-popover text-sm text-popover-foreground shadow-menu outline-hidden duration-200 ease-spring data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",{variants: {size: {- default: "w-72 gap-2.5 p-2.5",+ default: "w-72 gap-4 p-4",fit: "w-auto overflow-hidden p-0",panel: "w-90 overflow-hidden p-0",},@@ -63,7 +63,7 @@ function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="popover-header"- className={cn("flex flex-col gap-0.5 text-xs", className)}+ className={cn("flex flex-col gap-1 text-sm", className)}{...props}/>)diff --git a/packages/ui/src/components/questionnaire.tsx b/packages/ui/src/components/questionnaire.tsxindex 10456641..740a8234 100644--- a/packages/ui/src/components/questionnaire.tsx+++ b/packages/ui/src/components/questionnaire.tsx@@ -1,11 +1,11 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";import { Questionnaire as QuestionnairePrimitive } from "@shadcn/react/questionnaire";+import { CheckIcon } from "lucide-react";import type * as React from "react";-import { buttonVariants, type Button } from "./button";-import { Icon } from "./icon";import { cn } from "../lib/utils";+import { type Button, buttonVariants } from "./button";+import { Icon } from "./icon";function Questionnaire({className,@@ -125,7 +125,7 @@ function QuestionnaireChoice({className="hidden size-2 rounded-full bg-primary-foreground group-data-[type=checkbox]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"/><Icon- icon={Checkmark}+ icon={CheckIcon}motion="none"data-slot="questionnaire-choice-indicator-check"className="hidden group-data-[type=radio]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"diff --git a/packages/ui/src/components/radio-group.tsx b/packages/ui/src/components/radio-group.tsxindex a69f011f..9c921157 100644--- a/packages/ui/src/components/radio-group.tsx+++ b/packages/ui/src/components/radio-group.tsx@@ -11,7 +11,7 @@ function RadioGroup({return (<RadioGroupPrimitive.Rootdata-slot="radio-group"- className={cn("grid w-full gap-2", className)}+ className={cn("grid w-full gap-3", className)}{...props}/>);@@ -25,7 +25,7 @@ function RadioGroupItem({<RadioGroupPrimitive.Itemdata-slot="radio-group-item"className={cn(- "group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary",+ "group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-muted-foreground/70 transition-[color,background-color,border-color,box-shadow] outline-none group-has-[>[data-slot=field]]/field-label:focus-visible:shadow-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive data-checked:border-primary",className,)}{...props}@@ -34,7 +34,7 @@ function RadioGroupItem({data-slot="radio-group-indicator"className="flex size-4 items-center justify-center">- <span className="absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground" />+ <span className="absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary" /></RadioGroupPrimitive.Indicator></RadioGroupPrimitive.Item>);diff --git a/packages/ui/src/components/record-sheet.tsx b/packages/ui/src/components/record-sheet.tsxnew file mode 100644index 00000000..704c872a--- /dev/null+++ b/packages/ui/src/components/record-sheet.tsx@@ -0,0 +1,442 @@+"use client";++import { Button } from "@crm/ui/components/button";+import { Skeleton } from "@crm/ui/components/skeleton";+import { SkeletonBlock, SkeletonLine } from "@crm/ui/components/skeleton-lines";+import { SheetTitle } from "@crm/ui/components/sheet";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@crm/ui/components/tabs";+import { SKELETON, skeletonRows } from "@crm/ui/lib/skeleton-config";+import { cn } from "@crm/ui/lib/utils";+import {+ ArrowLeftIcon,+ ChevronDownIcon,+ ChevronUpIcon,+ XIcon,+} from "lucide-react";+import { type ReactNode, useState } from "react";++export const RECORD_TITLE_SELECTOR = "[data-slot='record-title']";++export function focusRecordTitle(container: HTMLElement | null) {+ const title = container?.querySelector<HTMLElement>(RECORD_TITLE_SELECTOR);+ (title ?? container)?.focus();+}++function claimFocus(title: HTMLHeadingElement | null) {+ if (!title) return;+ const popup = title.closest<HTMLElement>("[data-slot='sheet-content']");+ const focused = document.activeElement;+ if (popup && (focused === popup || focused === document.body)) {+ title.focus();+ }+}++export type RecordSheetNavigation = {+ index: number;+ total: number;+ onPrevious: () => void;+ onNext: () => void;+};++function RecordQueue({+ label,+ navigation,+}: {+ label: string;+ navigation: RecordSheetNavigation;+}) {+ const { index, total, onPrevious, onNext } = navigation;+ const inQueue = index >= 0 && index < total;++ return (+ <div data-slot="record-queue" className="flex shrink-0 items-center gap-0.5">+ <Button+ aria-label={`Previous ${label.toLowerCase()}`}+ disabled={!inQueue || index === 0}+ onClick={onPrevious}+ size="icon-xs"+ variant="secondary"+ >+ <ChevronUpIcon />+ </Button>+ <Button+ aria-label={`Next ${label.toLowerCase()}`}+ disabled={!inQueue || index >= total - 1}+ onClick={onNext}+ size="icon-xs"+ variant="secondary"+ >+ <ChevronDownIcon />+ </Button>+ <output className="pl-2 text-muted-foreground text-sm tabular-nums">+ {inQueue ? `${label} ${index + 1} of ${total}` : label}+ </output>+ </div>+ );+}++export function RecordSheetBar({+ label,+ back,+ navigation,+ onClose,+}: {+ label: string;+ back?: { label: string; onBack: () => void };+ navigation?: RecordSheetNavigation;+ onClose: () => void;+}) {+ return (+ <div+ data-slot="record-sheet-bar"+ className="flex h-13 shrink-0 items-center justify-between gap-3 border-b px-4 md:pl-6"+ >+ <div className="flex min-w-0 items-center gap-2">+ {back ? (+ <Button+ variant="ghost"+ size="sm"+ className="-ml-2 min-w-0"+ onClick={back.onBack}+ >+ <ArrowLeftIcon data-icon="inline-start" />+ <span className="truncate">{back.label}</span>+ </Button>+ ) : null}+ {navigation && navigation.total > 0 ? (+ <RecordQueue label={label} navigation={navigation} />+ ) : (+ <span+ className={cn(+ "shrink-0 text-muted-foreground text-sm",+ !back && "pl-1",+ )}+ >+ {label}+ </span>+ )}+ </div>+ <Button variant="ghost" size="icon-sm" onClick={onClose}>+ <XIcon />+ <span className="sr-only">Close</span>+ </Button>+ </div>+ );+}++export function RecordSheetHeader({+ title,+ loading = false,+ media,+ pills,+ actions,+}: {+ title: string;+ loading?: boolean;+ media?: ReactNode;+ pills?: ReactNode;+ actions?: ReactNode;+}) {+ return (+ <header+ data-slot="record-sheet-header"+ aria-busy={loading || undefined}+ className="shrink-0 border-b px-4 py-3 md:px-6"+ >+ <div className="flex min-h-8 items-start justify-between gap-3">+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 pt-0.5">+ <div className="flex min-w-0 items-start gap-2.5">+ {media && !loading ? (+ <span className="flex h-7 shrink-0 items-center">{media}</span>+ ) : null}+ <SheetTitle+ ref={claimFocus}+ data-slot="record-title"+ tabIndex={-1}+ className={cn(+ "min-w-0 wrap-anywhere leading-7",+ loading && "sr-only",+ )}+ >+ {loading ? `Loading ${title.toLowerCase()}` : title}+ </SheetTitle>+ {loading ? (+ <Skeleton aria-hidden className="my-1 h-5 w-64 max-w-full" />+ ) : null}+ </div>+ {pills && !loading ? (+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground text-sm">+ {pills}+ </div>+ ) : null}+ </div>+ {actions && !loading ? (+ <div className="flex shrink-0 items-center gap-1">{actions}</div>+ ) : null}+ </div>+ </header>+ );+}++export type RecordSheetTab = {+ value: string;+ label: string;+ count?: number | null;+ content: ReactNode;+ fills?: boolean;+ keepMounted?: boolean;+};++export function RecordSheetBody({+ tabs,+ value,+ onValueChange,+ rail,+}: {+ tabs: RecordSheetTab[];+ value: string;+ onValueChange: (value: string) => void;+ rail?: ReactNode;+}) {+ const [opened] = useState(() => new Set<string>());+ opened.add(value);++ const active = tabs.find((tab) => tab.value === value) ?? tabs[0];+ const fills = active?.fills ?? false;+ const first = active?.value === tabs[0]?.value;++ return (+ <div+ data-slot="record-sheet-body"+ data-fills={fills || undefined}+ className={cn(+ "flex min-h-0 flex-1 flex-col items-stretch gap-6 overflow-x-hidden px-4 md:flex-row md:overflow-hidden md:px-6 md:pt-5",+ fills ? "max-md:overflow-hidden" : "overflow-y-auto pb-6 md:pb-0",+ )}+ >+ <Tabs+ value={active?.value ?? value}+ onValueChange={onValueChange}+ className={cn(+ "flex w-full min-w-0 flex-col gap-4.5 pt-4 md:min-h-0 md:flex-1 md:self-stretch md:pt-0",+ fills && "min-h-0 flex-1",+ )}+ >+ {tabs.length > 1 ? (+ <div className="no-scrollbar w-full min-w-0 shrink-0 overflow-x-auto">+ <TabsList variant="line" className="max-md:gap-3">+ {tabs.map((tab) => (+ <TabsTrigger key={tab.value} value={tab.value}>+ {tab.label}+ {tab.count ? (+ <span className="text-muted-foreground tabular-nums">+ {tab.count}+ </span>+ ) : null}+ </TabsTrigger>+ ))}+ </TabsList>+ </div>+ ) : null}++ {tabs.map((tab) => (+ <TabsContent+ key={tab.value}+ value={tab.value}+ forceMount={+ tab.keepMounted && opened.has(tab.value) ? true : undefined+ }+ className={cn(+ "min-w-0 data-[state=inactive]:hidden",+ tab.fills+ ? "flex min-h-0 flex-1 flex-col overflow-hidden pb-4 md:pb-6"+ : "scroll-gutter flex flex-col gap-4.5 *:shrink-0 md:min-h-0 md:flex-1 md:overflow-y-auto md:overflow-x-hidden md:pt-1 md:pb-6",+ )}+ >+ {tab.content}+ </TabsContent>+ ))}+ </Tabs>++ {rail ? (+ <RecordRail className={cn(!first && "max-md:hidden")}>{rail}</RecordRail>+ ) : null}+ </div>+ );+}++export function RecordSectionSkeleton() {+ return (+ <div className="flex min-w-0 flex-col gap-2.5">+ <div className="flex min-h-7 items-center">+ <SkeletonLine width="24" />+ </div>+ <SkeletonBlock height="40" />+ </div>+ );+}++export function RecordRailSkeleton() {+ return (+ <div className="flex min-w-0 flex-col gap-2.5">+ <div className="flex min-h-7 items-center">+ <SkeletonLine width="24" />+ </div>+ <div className="flex min-w-0 flex-col">+ {skeletonRows(SKELETON.rows.rail).map((row) => (+ <div+ className="flex min-w-0 items-center justify-between gap-3 py-1.5"+ key={row}+ >+ <SkeletonLine width="24" />+ <Skeleton className="h-8 w-40 min-w-0" />+ </div>+ ))}+ </div>+ </div>+ );+}++export function RecordSheetLoading({ tabs }: { tabs: number }) {+ const triggers = skeletonRows(tabs);++ return (+ <div+ aria-busy+ data-slot="record-sheet-body"+ className="flex min-h-0 flex-1 flex-col items-stretch gap-6 overflow-hidden px-4 md:flex-row md:px-6 md:pt-5"+ >+ <div className="flex w-full min-w-0 flex-col gap-4.5 pt-4 md:flex-1 md:pt-0">+ {tabs > 1 ? (+ <Tabs+ aria-hidden+ inert+ value={triggers[0]}+ className="w-full min-w-0 shrink-0 overflow-hidden"+ >+ <TabsList variant="line" className="max-md:gap-3">+ {triggers.map((trigger) => (+ <TabsTrigger key={trigger} value={trigger}>+ <Skeleton className="h-4 w-14" />+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ ) : null}+ <RecordSectionSkeleton />+ <RecordSectionSkeleton />+ </div>+ <RecordRail>+ <RecordRailSkeleton />+ </RecordRail>+ </div>+ );+}++export function RecordRail({+ className,+ children,+}: {+ className?: string;+ children: ReactNode;+}) {+ return (+ <div+ data-slot="record-rail"+ className={cn(+ "scroll-gutter flex w-full min-w-0 max-w-full flex-col gap-4.5 *:shrink-0 max-md:border-t max-md:pt-4.5 md:h-full md:w-83 md:shrink-0 md:self-stretch md:overflow-y-auto md:overflow-x-hidden md:pb-6",+ className,+ )}+ >+ {children}+ </div>+ );+}++export function RecordSection({+ label,+ count,+ action,+ className,+ children,+}: {+ label?: ReactNode;+ count?: number;+ action?: ReactNode;+ className?: string;+ children: ReactNode;+}) {+ return (+ <section+ data-slot="record-section"+ className={cn(+ "flex min-w-0 flex-col gap-2.5 border-t pt-4.5 first:border-t-0 first:pt-0",+ className,+ )}+ >+ {label || action ? (+ <div className="flex min-h-7 min-w-0 items-center justify-between gap-4">+ <h3 className="flex min-w-0 items-center gap-2 text-sm">+ <span className="truncate font-medium text-muted-foreground">+ {label}+ </span>+ {count === undefined ? null : (+ <span className="text-muted-foreground tabular-nums">+ {count}+ </span>+ )}+ </h3>+ {action}+ </div>+ ) : null}+ {children}+ </section>+ );+}++export function RecordFigure({+ value,+ children,+}: {+ value: ReactNode;+ children?: ReactNode;+}) {+ return (+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">+ <span className="font-semibold text-[2rem] text-foreground leading-9 tracking-[-0.04em] tabular-nums">+ {value}+ </span>+ {children ? (+ <span className="flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-0.5 text-muted-foreground text-sm">+ {children}+ </span>+ ) : null}+ </div>+ );+}++export function RecordFact({+ label,+ children,+}: {+ label: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="flex min-h-9 min-w-0 items-center justify-between gap-3 py-1.5 text-sm">+ <span className="shrink-0 truncate text-muted-foreground">{label}</span>+ <span className="flex min-w-0 justify-end text-right text-foreground">+ {children}+ </span>+ </div>+ );+}++export function RecordEmpty({ children }: { children: ReactNode }) {+ return <p className="text-pretty text-muted-foreground text-sm">{children}</p>;+}diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsxindex 1306cdaf..4ff457cf 100644--- a/packages/ui/src/components/select.tsx+++ b/packages/ui/src/components/select.tsx@@ -19,7 +19,7 @@ function SelectGroup({return (<SelectPrimitive.Groupdata-slot="select-group"- className={cn("scroll-my-1", className)}+ className={cn("scroll-my-1.5", className)}{...props}/>);@@ -32,14 +32,14 @@ function SelectValue({}const selectTriggerVariants = cva(- "flex w-fit items-center justify-between gap-1.5 rounded-md text-xs whitespace-nowrap transition-colors outline-none select-none disabled:cursor-not-allowed disabled:opacity-50 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "flex w-fit items-center justify-between gap-1.5 rounded-md text-sm whitespace-nowrap transition-[color,background-color,border-color,box-shadow] outline-none select-none focus-visible:shadow-focus disabled:pointer-events-none disabled:cursor-not-allowed aria-invalid:border-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {default:- "border border-input bg-background py-2 pr-2 pl-2.5 hover:border-ring/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/25 dark:bg-muted dark:hover:bg-accent",+ "border border-border bg-transparent py-2 pr-2 pl-2.5 hover:border-input disabled:bg-muted disabled:text-muted-foreground",ghost:- "border border-transparent bg-transparent px-2 hover:border-input hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 data-[state=open]:border-input data-[state=open]:bg-muted/40 [&_svg]:opacity-0 hover:[&_svg]:opacity-100 focus-visible:[&_svg]:opacity-100 data-[state=open]:[&_svg]:opacity-100",+ "border border-transparent bg-transparent px-2 hover:border-input hover:bg-muted/40 disabled:opacity-50 data-[state=open]:border-input data-[state=open]:bg-muted/40 [&_svg]:opacity-0 hover:[&_svg]:opacity-100 focus-visible:[&_svg]:opacity-100 data-[state=open]:[&_svg]:opacity-100",},},defaultVariants: {@@ -87,7 +87,7 @@ function SelectContent({data-slot="select-content"data-align-trigger={position === "item-aligned"}className={cn(- "relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "relative isolate z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-xl bg-popover text-popover-foreground shadow-menu duration-200 ease-spring data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:duration-100 data-closed:ease-out",className,)}position={position}@@ -98,7 +98,7 @@ function SelectContent({<SelectScrollUpButton /><SelectPrimitive.Viewportdata-position={position}- className="data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)"+ className="p-1.5 data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)">{children}</SelectPrimitive.Viewport>@@ -115,7 +115,7 @@ function SelectLabel({return (<SelectPrimitive.Labeldata-slot="select-label"- className={cn("px-2 py-2 text-xs text-muted-foreground", className)}+ className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}{...props}/>);@@ -130,7 +130,7 @@ function SelectItem({<SelectPrimitive.Itemdata-slot="select-item"className={cn(- "relative flex w-full cursor-default items-center gap-2 rounded-sm py-2 pr-8 pl-2 text-xs outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",+ "relative flex w-full cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",className,)}{...props}@@ -152,7 +152,7 @@ function SelectSeparator({return (<SelectPrimitive.Separatordata-slot="select-separator"- className={cn("pointer-events-none -mx-1 h-px bg-border", className)}+ className={cn("pointer-events-none -mx-1.5 my-1 h-px bg-border", className)}{...props}/>);diff --git a/packages/ui/src/components/setting-rows.tsx b/packages/ui/src/components/setting-rows.tsxnew file mode 100644index 00000000..b97f00e1--- /dev/null+++ b/packages/ui/src/components/setting-rows.tsx@@ -0,0 +1,64 @@+import {+ Field,+ FieldContent,+ FieldDescription,+ FieldLabel,+} from "@crm/ui/components/field";+import { Skeleton } from "@crm/ui/components/skeleton";+import type * as React from "react";+import { useId } from "react";++function SettingRows({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex flex-col divide-y" data-slot="setting-rows">+ {children}+ </div>+ );+}++function SettingRow({+ title,+ description,+ control,+ loading = false,+ loadingControl = "switch",+}: {+ title: React.ReactNode;+ description?: React.ReactNode;+ control: (id: string, describedBy: string | undefined) => React.ReactNode;+ loading?: boolean;+ loadingControl?: "switch" | "select";+}) {+ const id = useId();+ const descriptionId = `${id}-description`;++ return (+ <Field+ className="justify-between gap-6 py-4 first:pt-0 last:pb-0"+ data-slot="setting-row"+ orientation="horizontal"+ >+ <FieldContent>+ <FieldLabel htmlFor={id}>{title}</FieldLabel>+ {description ? (+ <FieldDescription id={descriptionId}>{description}</FieldDescription>+ ) : null}+ </FieldContent>+ <div className="flex shrink-0 items-center">+ {loading ? (+ <Skeleton+ className={+ loadingControl === "switch"+ ? "h-4.5 w-8 rounded-full"+ : "h-8 w-40 rounded-md"+ }+ />+ ) : (+ control(id, description ? descriptionId : undefined)+ )}+ </div>+ </Field>+ );+}++export { SettingRow, SettingRows };diff --git a/packages/ui/src/components/settings-card.tsx b/packages/ui/src/components/settings-card.tsxnew file mode 100644index 00000000..55e31afa--- /dev/null+++ b/packages/ui/src/components/settings-card.tsx@@ -0,0 +1,119 @@+import { SkeletonField } from "@crm/ui/components/skeleton-lines";+import { cn } from "@crm/ui/lib/utils";+import type * as React from "react";++type SettingsCardProps = {+ title: React.ReactNode;+ description?: React.ReactNode;+ status?: React.ReactNode;+ hint?: React.ReactNode;+ action?: React.ReactNode;+ tone?: "default" | "destructive";+ control?: "compact" | "full" | "table";+ loading?: boolean;+ loadingFallback?: React.ReactNode;+ titleId?: string;+ descriptionId?: string;+ children?: React.ReactNode;+};++function SettingsCard({+ title,+ description,+ status,+ hint,+ action,+ tone = "default",+ control = "full",+ loading = false,+ loadingFallback,+ titleId,+ descriptionId,+ children,+}: SettingsCardProps) {+ const destructive = tone === "destructive";+ const table = control === "table";++ return (+ <section+ aria-labelledby={titleId}+ className={cn(+ "overflow-hidden rounded-md bg-card text-card-foreground",+ destructive ? "ring-1 ring-destructive/30" : "shadow-border",+ )}+ data-slot="settings-card"+ >+ <div className="flex flex-col gap-5 p-5">+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <h2+ className="text-balance font-semibold text-xl tracking-tight"+ id={titleId}+ >+ {title}+ </h2>+ {status}+ </div>+ {description ? (+ <p+ className="text-pretty text-muted-foreground text-sm"+ id={descriptionId}+ >+ {description}+ </p>+ ) : null}+ </div>+ {children && !table ? (+ <div+ aria-busy={loading || undefined}+ className={cn(control === "compact" && "max-w-xs")}+ >+ {loading ? (loadingFallback ?? <SkeletonField />) : children}+ </div>+ ) : null}+ </div>+ {children && table ? (+ <div+ aria-busy={loading || undefined}+ className={cn(+ "border-t [&_[data-slot=table-container]]:rounded-none [&_[data-slot=table-container]]:border-0 [&_[data-slot=table-container]]:shadow-none",+ "[&_[data-slot=table-container]_:is(th,td):first-child]:pl-5 [&_[data-slot=table-container]_:is(th,td):last-child]:pr-5",+ )}+ >+ {loading ? (loadingFallback ?? <SkeletonField />) : children}+ </div>+ ) : null}+ {hint || action ? (+ <div+ className={cn(+ "flex min-h-14 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t py-3 pr-3 pl-5",+ destructive+ ? "border-destructive/30 bg-destructive/5"+ : "bg-sidebar",+ )}+ >+ <div className="text-pretty text-muted-foreground text-sm [&_a]:underline [&_a]:underline-offset-4 [&_a:hover]:text-foreground">+ {hint}+ </div>+ {loading && action ? (+ <div className="pointer-events-none opacity-50" inert>+ {action}+ </div>+ ) : (+ action+ )}+ </div>+ ) : null}+ </section>+ );+}++function SettingsColumn({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex flex-col gap-8" data-slot="settings-column">+ {children}+ </div>+ );+}++export { SettingsCard, SettingsColumn };diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsxindex db98a2b2..9948c659 100644--- a/packages/ui/src/components/sheet.tsx+++ b/packages/ui/src/components/sheet.tsx@@ -8,7 +8,7 @@ import { Dialog as SheetPrimitive } from "radix-ui";import type * as React from "react";const sheetContentVariants = cva(- "fixed z-50 flex flex-col bg-popover bg-clip-padding text-xs/relaxed text-popover-foreground shadow-lg duration-300 ease-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-open:animate-in data-[side=bottom]:data-open:slide-in-from-bottom-full data-[side=left]:data-open:slide-in-from-left-full data-[side=right]:data-open:slide-in-from-right-full data-[side=top]:data-open:slide-in-from-top-full data-closed:animate-out data-[side=bottom]:data-closed:slide-out-to-bottom-full data-[side=left]:data-closed:slide-out-to-left-full data-[side=right]:data-closed:slide-out-to-right-full data-[side=top]:data-closed:slide-out-to-top-full",+ "sheet-motion fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-modal outline-none data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-full data-[side=right]:md:w-3/4 data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=right]:md:corner-cut data-[side=right]:md:shadow-none",{variants: {size: {@@ -18,6 +18,8 @@ const sheetContentVariants = cva(xl: "data-[side=left]:sm:max-w-4xl data-[side=right]:sm:max-w-4xl","2xl":"data-[side=left]:sm:max-w-5xl data-[side=right]:sm:max-w-5xl data-[side=left]:lg:w-[68vw] data-[side=right]:lg:w-[68vw]",+ record:+ "data-[side=right]:md:w-[calc(100%-3.5rem)] data-[side=right]:lg:w-[max(75%,calc(100%-(--spacing(86))))] data-[side=right]:md:max-w-274",},},defaultVariants: {@@ -60,7 +62,7 @@ function SheetOverlay({<SheetPrimitive.Overlaydata-slot="sheet-overlay"className={cn(- "fixed inset-0 z-50 bg-overlay text-xs/relaxed duration-300 ease-out supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "sheet-overlay-motion fixed inset-0 z-50 bg-overlay",className,)}{...props}@@ -89,12 +91,27 @@ function SheetContent({className={cn(sheetContentVariants({ size }), className)}{...props}>+ {side === "right" ? (+ <svg+ aria-hidden+ data-slot="sheet-cut-edge"+ className="pointer-events-none absolute inset-y-0 left-0 z-10 hidden h-full w-6 text-border md:block"+ >+ <path+ d="M26 0.5Q22.17 0.5 19.15 2.85L3.47 15.03Q0.5 17.34 0.5 21.1V100000"+ fill="none"+ stroke="currentColor"+ strokeLinejoin="round"+ strokeWidth={1}+ />+ </svg>+ ) : null}{children}{showCloseButton && (<SheetPrimitive.Close data-slot="sheet-close" asChild><Buttonvariant="ghost"- className="absolute top-3 right-3"+ className="absolute top-4.5 right-4"size="icon-sm"><XIcon />@@ -111,7 +128,7 @@ function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="sheet-header"- className={cn("flex flex-col gap-0.5 p-4", className)}+ className={cn("flex flex-col gap-1 border-b px-6 py-5", className)}{...props}/>);@@ -121,23 +138,26 @@ function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {return (<divdata-slot="sheet-footer"- className={cn("mt-auto flex flex-col gap-2 p-4", className)}+ className={cn("mt-auto flex flex-col gap-2 border-t bg-sidebar px-6 py-3", className)}{...props}/>);}-const sheetTitleVariants = cva("font-heading font-medium text-foreground", {- variants: {- size: {- default: "text-sm",- lg: "text-lg leading-tight tracking-tight",+const sheetTitleVariants = cva(+ "font-heading font-semibold tracking-tight text-balance text-foreground outline-none",+ {+ variants: {+ size: {+ default: "text-lg",+ lg: "text-lg leading-tight",+ },+ },+ defaultVariants: {+ size: "default",},},- defaultVariants: {- size: "default",- },-});+);function SheetTitle({className,@@ -161,7 +181,7 @@ function SheetDescription({return (<SheetPrimitive.Descriptiondata-slot="sheet-description"- className={cn("text-xs/relaxed text-muted-foreground", className)}+ className={cn("text-sm text-pretty text-muted-foreground", className)}{...props}/>);diff --git a/packages/ui/src/components/simple-table.tsx b/packages/ui/src/components/simple-table.tsxindex 96734093..28aef68a 100644--- a/packages/ui/src/components/simple-table.tsx+++ b/packages/ui/src/components/simple-table.tsx@@ -32,6 +32,7 @@ const ALIGN_CLASS = {const PANEL_SURFACE = {popover: "bg-popover [&_th]:bg-popover",page: "bg-background [&_th]:bg-background",+ card: "bg-card [&_th]:bg-card",} as const;export function SimpleTable({@@ -59,9 +60,14 @@ export function SimpleTable({return (<Table- className={cn("w-full", panel && "table-fixed", className)}+ className={cn(+ "w-full",+ panel && "table-fixed [&_td>*]:max-w-full",+ className,+ )}containerClassName={cn(- panel && "min-h-0 flex-1 overflow-x-hidden overflow-y-auto",+ panel &&+ "@container/simple-table min-h-0 flex-1 overflow-x-hidden overflow-y-auto",!panel && "rounded-lg border bg-card",containerClassName,)}@@ -109,8 +115,11 @@ export function SimpleTableRow({return (<TableRowclassName={cn(- "hover:bg-transparent",- clickable && (expandable ? ROW_ACCENT_EXPANDABLE : ROW_ACCENT),+ clickable+ ? expandable+ ? ROW_ACCENT_EXPANDABLE+ : ROW_ACCENT+ : "hover:bg-transparent",className,)}{...props}diff --git a/packages/ui/src/components/skeleton-lines.tsx b/packages/ui/src/components/skeleton-lines.tsxnew file mode 100644index 00000000..9b454299--- /dev/null+++ b/packages/ui/src/components/skeleton-lines.tsx@@ -0,0 +1,93 @@+import { Skeleton } from "@crm/ui/components/skeleton";++export const SKELETON_LINE_SIZES = ["sm", "base", "lg", "2xl"] as const;++export type SkeletonLineSize = (typeof SKELETON_LINE_SIZES)[number];++export const SKELETON_LINE_WIDTHS = [+ "24",+ "40",+ "48",+ "64",+ "72",+ "96",+ "two-thirds",+ "full",+] as const;++export type SkeletonLineWidth = (typeof SKELETON_LINE_WIDTHS)[number];++export const SKELETON_BLOCK_HEIGHTS = ["24", "40", "56"] as const;++export type SkeletonBlockHeight = (typeof SKELETON_BLOCK_HEIGHTS)[number];++const LINE_CLASS =+ "max-w-full data-[size=sm]:h-4 data-[size=base]:h-5 data-[size=lg]:h-6 data-[size=2xl]:h-8 data-[width=24]:w-24 data-[width=40]:w-40 data-[width=48]:w-48 data-[width=64]:w-64 data-[width=72]:w-72 data-[width=96]:w-96 data-[width=two-thirds]:w-2/3 data-[width=full]:w-full";++const BLOCK_CLASS =+ "w-full data-[height=24]:h-24 data-[height=40]:h-40 data-[height=56]:h-56";++function SkeletonLine({+ size = "sm",+ width = "full",+}: {+ size?: SkeletonLineSize;+ width?: SkeletonLineWidth;+}) {+ return (+ <Skeleton className={LINE_CLASS} data-size={size} data-width={width} />+ );+}++function SkeletonBlock({ height }: { height: SkeletonBlockHeight }) {+ return <Skeleton className={BLOCK_CLASS} data-height={height} />;+}++const MARK_CLASS =+ "shrink-0 data-[kind=person]:rounded-full data-[kind=workspace]:rounded-md data-[size=sm]:size-5 data-[size=md]:size-6 data-[size=lg]:size-8 data-[size=xl]:size-12";++function SkeletonMark({+ size = "md",+ kind = "person",+}: {+ size?: "sm" | "md" | "lg" | "xl";+ kind?: "person" | "workspace";+}) {+ return <Skeleton className={MARK_CLASS} data-kind={kind} data-size={size} />;+}++function SkeletonField() {+ return <Skeleton className="h-9 w-full" data-slot="field-skeleton" />;+}++export const SKELETON_CONTROL_WIDTHS = [+ "20",+ "24",+ "28",+ "32",+ "48",+ "full",+] as const;++export type SkeletonControlWidth = (typeof SKELETON_CONTROL_WIDTHS)[number];++const CONTROL_CLASS =+ "h-9 max-w-full shrink-0 data-[width=20]:w-20 data-[width=24]:w-24 data-[width=28]:w-28 data-[width=32]:w-32 data-[width=48]:w-48 data-[width=full]:w-full";++function SkeletonControl({ width = "24" }: { width?: SkeletonControlWidth }) {+ return (+ <Skeleton+ className={CONTROL_CLASS}+ data-slot="control-skeleton"+ data-width={width}+ />+ );+}++export {+ SkeletonBlock,+ SkeletonControl,+ SkeletonField,+ SkeletonLine,+ SkeletonMark,+};diff --git a/packages/ui/src/components/skeleton-swap.tsx b/packages/ui/src/components/skeleton-swap.tsxindex ce19974c..e7d3083d 100644--- a/packages/ui/src/components/skeleton-swap.tsx+++ b/packages/ui/src/components/skeleton-swap.tsx@@ -1,15 +1,10 @@"use client";import { Skeleton } from "@crm/ui/components/skeleton";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";import { cn } from "@crm/ui/lib/utils";import { domAnimation, LazyMotion, m, useReducedMotion } from "motion/react";-import {- type ReactNode,- useCallback,- useEffect,- useRef,- useState,-} from "react";+import { type ReactNode, useCallback, useRef, useState } from "react";const CROSSFADE = {type: "spring",@@ -75,7 +70,7 @@ export function SkeletonSwap({[clear, delay, loading, minVisible, showSkeleton],);- useEffect(() => clear, [clear]);+ useMountEffect(() => clear);return (<LazyMotion features={domAnimation}>diff --git a/packages/ui/src/components/skeleton.tsx b/packages/ui/src/components/skeleton.tsxindex 1d5a1820..5e69721b 100644--- a/packages/ui/src/components/skeleton.tsx+++ b/packages/ui/src/components/skeleton.tsx@@ -5,7 +5,7 @@ function Skeleton({ className, ...props }: React.ComponentProps<"div">) {<divdata-slot="skeleton"className={cn(- "animate-pulse rounded-sm bg-muted motion-reduce:animate-none",+ "animate-[tw-shimmer_2s_linear_infinite] rounded-md bg-muted bg-[linear-gradient(90deg,transparent_40%,color-mix(in_oklab,var(--foreground)_5%,transparent)_50%,transparent_60%)] bg-size-[300%_100%] bg-no-repeat motion-reduce:animate-none",className,)}{...props}diff --git a/packages/ui/src/components/sonner.tsx b/packages/ui/src/components/sonner.tsxindex e37dcdea..4dfbb609 100644--- a/packages/ui/src/components/sonner.tsx+++ b/packages/ui/src/components/sonner.tsx@@ -1,5 +1,6 @@"use client";+import { Spinner } from "@crm/ui/components/spinner";import {CircleCheckIcon,InfoIcon,@@ -8,31 +9,121 @@ import {TriangleAlertIcon,} from "lucide-react";import { useTheme } from "next-themes";+import { useSyncExternalStore } from "react";import { Toaster as Sonner, type ToasterProps } from "sonner";-const Toaster = ({ ...props }: ToasterProps) => {+const NEO_STYLE = {+ "--width": "420px",+ "--normal-bg": "var(--popover)",+ "--normal-text": "var(--popover-foreground)",+ "--normal-border": "var(--border)",+ "--border-radius": "var(--radius-xl)",+ "--success-bg": "color-mix(in oklab, var(--brand) 6%, var(--popover))",+ "--success-border": "transparent",+ "--success-text": "var(--popover-foreground)",+ "--info-bg": "color-mix(in oklab, var(--status-info) 6%, var(--popover))",+ "--info-border": "transparent",+ "--info-text": "var(--popover-foreground)",+ "--warning-bg":+ "color-mix(in oklab, var(--status-warning) 8%, var(--popover))",+ "--warning-border": "transparent",+ "--warning-text": "var(--popover-foreground)",+ "--error-bg": "color-mix(in oklab, var(--destructive) 6%, var(--popover))",+ "--error-border": "transparent",+ "--error-text": "var(--popover-foreground)",+} as React.CSSProperties;++const CLASSIC_CLASS_NAME = [+ "theme-classic toaster group [--border-radius:5px]!",+ "data-[sonner-theme=light]:[--normal-bg:#ffffff]!",+ "data-[sonner-theme=light]:[--normal-text:#171717]!",+ "data-[sonner-theme=light]:[--normal-border:#e2e2e2]!",+ "data-[sonner-theme=dark]:[--normal-bg:#171717]!",+ "data-[sonner-theme=dark]:[--normal-text:#f5f5f5]!",+ "data-[sonner-theme=dark]:[--normal-border:#2a2a2a]!",+].join(" ");++type ToasterVariant = "default" | "classic";++function subscribeStoredTheme(onChange: () => void) {+ window.addEventListener("storage", onChange);+ return () => window.removeEventListener("storage", onChange);+}++function readStoredTheme(): string | null {+ try {+ return window.localStorage.getItem("theme");+ } catch {+ return null;+ }+}++function noStoredTheme(): null {+ return null;+}++function NeoToaster(props: ToasterProps) {const { theme = "system" } = useTheme();return (<Sonnertheme={theme as ToasterProps["theme"]}- position="bottom-left"+ position="bottom-right"className="toaster group"icons={{- success: <CircleCheckIcon className="size-4" />,- info: <InfoIcon className="size-4" />,- warning: <TriangleAlertIcon className="size-4" />,- error: <OctagonXIcon className="size-4" />,- loading: <Loader2Icon className="size-4 animate-spin" />,+ success: <CircleCheckIcon className="size-4 text-brand" />,+ info: <InfoIcon className="size-4 text-status-info" />,+ warning: <TriangleAlertIcon className="size-4 text-status-warning" />,+ error: <OctagonXIcon className="size-4 text-destructive" />,+ loading: (+ <Spinner+ aria-hidden+ aria-label={undefined}+ className="text-muted-foreground"+ role="presentation"+ />+ ),+ }}+ style={NEO_STYLE}+ toastOptions={{+ classNames: {+ toast:+ "cn-toast gap-3! border-0! text-sm! shadow-menu! has-[[data-close-button]]:pr-12!",+ icon: "mx-0! mt-0.5 self-start",+ description: "text-13 text-muted-foreground!",+ actionButton:+ "h-8! rounded-md! bg-primary! px-3! text-sm! text-primary-foreground! hover:bg-primary/80! focus-visible:shadow-focus!",+ cancelButton:+ "h-8! rounded-md! bg-transparent! px-3! text-sm! text-foreground! hover:bg-muted! focus-visible:shadow-focus!",+ closeButton:+ "top-1/2! right-2! left-auto! size-8! -translate-y-1/2 transform-none! rounded-md! border-0! bg-transparent! text-muted-foreground! hover:bg-muted! hover:text-foreground! focus-visible:shadow-focus! [&_svg]:size-4",+ },+ }}+ {...props}+ />+ );+}++function ClassicToaster(props: ToasterProps) {+ const { theme = "system" } = useTheme();+ const storedTheme = useSyncExternalStore(+ subscribeStoredTheme,+ readStoredTheme,+ noStoredTheme,+ );++ return (+ <Sonner+ theme={(storedTheme ? theme : "system") as ToasterProps["theme"]}+ position="bottom-left"+ className={CLASSIC_CLASS_NAME}+ icons={{+ success: <CircleCheckIcon className="size-4 stroke-2" />,+ info: <InfoIcon className="size-4 stroke-2" />,+ warning: <TriangleAlertIcon className="size-4 stroke-2" />,+ error: <OctagonXIcon className="size-4 stroke-2" />,+ loading: <Loader2Icon className="size-4 animate-spin stroke-2" />,}}- style={- {- "--normal-bg": "var(--popover)",- "--normal-text": "var(--popover-foreground)",- "--normal-border": "var(--border)",- "--border-radius": "var(--radius)",- } as React.CSSProperties- }toastOptions={{classNames: {toast: "cn-toast",@@ -41,6 +132,17 @@ const Toaster = ({ ...props }: ToasterProps) => {{...props}/>);-};+}++function Toaster({+ variant = "default",+ ...props+}: ToasterProps & { variant?: ToasterVariant }) {+ if (variant === "classic") {+ return <ClassicToaster {...props} />;+ }++ return <NeoToaster {...props} />;+}-export { Toaster };+export { Toaster, type ToasterVariant };diff --git a/packages/ui/src/components/sortable-list.tsx b/packages/ui/src/components/sortable-list.tsxindex bb215f10..55f2900b 100644--- a/packages/ui/src/components/sortable-list.tsx+++ b/packages/ui/src/components/sortable-list.tsx@@ -1,6 +1,8 @@"use client";-import Draggable from "@carbon/icons-react/es/Draggable";+import { Button } from "@crm/ui/components/button";+import { Icon } from "@crm/ui/components/icon";+import { cn } from "@crm/ui/lib/utils";import {closestCenter,DndContext,@@ -22,10 +24,8 @@ import {verticalListSortingStrategy,} from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";+import { GripVerticalIcon } from "lucide-react";import type { ReactNode } from "react";-import { Button } from "@crm/ui/components/button";-import { Icon } from "@crm/ui/components/icon";-import { cn } from "@crm/ui/lib/utils";export function SortableList({ids,@@ -108,7 +108,7 @@ export function SortableItem({{...attributes}{...listeners}>- <Icon icon={Draggable} />+ <Icon icon={GripVerticalIcon} motion="none" /><span className="sr-only">Reorder {label}</span></Button>{children}diff --git a/packages/ui/src/components/spinner.tsx b/packages/ui/src/components/spinner.tsxindex acc4f6d6..7b821e60 100644--- a/packages/ui/src/components/spinner.tsx+++ b/packages/ui/src/components/spinner.tsx@@ -1,16 +1,15 @@import { cn } from "@crm/ui/lib/utils";import { cva, type VariantProps } from "class-variance-authority";-const SILHOUETTE =- "M384 99.548 367.934 87.04 256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096Z";+const BARS = Array.from({ length: 10 }, (_, index) => ({+ angle: index * 36,+ opacity: 0.15 + (0.85 * index) / 9,+}));-const MARK =- "m384 99.548 -16.066 -12.508L256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096zm-127.98 -49.419 79.695 61.975 -40.944 31.803 -3.661 2.837 -35.091 -27.287 -102.399 79.638 35.09 27.287 32.218 25.088 35.09 27.288L358.4 199.074l-35.047 -27.288 3.659 -2.837 40.943 -31.803 79.651 61.952 -40.943 31.852 -150.62 117.163 -79.695 -61.974 -32.218 -25.041 -38.752 -30.125 -40.922 -31.849z";--const spinnerVariants = cva("shrink-0", {+const spinnerVariants = cva("shrink-0 animate-spinner", {variants: {size: {- default: "size-4",+ default: "",lg: "size-10",},},@@ -30,23 +29,27 @@ function Spinner({role="status"aria-label="Loading"xmlns="http://www.w3.org/2000/svg"- viewBox="-68 -68 648 648"+ viewBox="0 0 24 24"+ width={16}+ height={16}fill="none"className={cn(spinnerVariants({ size }), className)}{...props}>- <path d={MARK} fill="currentColor" fillOpacity={0.85} />- <path- d={SILHOUETTE}- transform="translate(256 256) scale(1.16) translate(-256 -256)"- stroke="var(--ring)"- strokeWidth={32}- strokeLinejoin="round"- strokeLinecap="round"- pathLength={100}- strokeDasharray="40 60"- className="animate-spinner-trace"- />+ {BARS.map((bar) => (+ <line+ key={bar.angle}+ opacity={bar.opacity}+ stroke="currentColor"+ strokeLinecap="round"+ strokeWidth={2}+ transform={`rotate(${bar.angle} 12 12)`}+ x1={12}+ x2={12}+ y1={2.5}+ y2={7}+ />+ ))}</svg>);}diff --git a/packages/ui/src/components/stat-card.tsx b/packages/ui/src/components/stat-card.tsxindex 36440b67..a802348f 100644--- a/packages/ui/src/components/stat-card.tsx+++ b/packages/ui/src/components/stat-card.tsx@@ -39,7 +39,7 @@ function StatDeltaText({<span className={cn("inline-flex items-baseline gap-1.5", className)}><spanclassName={cn(- "inline-flex items-baseline gap-0.5 font-medium text-xs tabular-nums",+ "inline-flex items-baseline gap-0.5 font-medium text-13 tabular-nums",TREND_COLOR[direction],)}>@@ -49,7 +49,7 @@ function StatDeltaText({{delta.value}</span>{delta.label ? (- <span className="text-muted-foreground text-xs">{delta.label}</span>+ <span className="text-muted-foreground text-13">{delta.label}</span>) : null}</span>);@@ -72,24 +72,24 @@ function StatCard({return (<divdata-slot="stat-card"- className={cn("flex flex-col gap-2.5 p-4 md:p-6", className)}+ className={cn("flex min-w-0 flex-col gap-1 p-4 md:p-6", className)}{...props}>{label != null ? (- <span className="truncate text-sm font-medium text-muted-foreground">+ <span className="truncate text-13 text-muted-foreground">{label}</span>) : null}<div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">- <span className="font-medium text-3xl tracking-tight tabular-nums">+ <span className="font-semibold text-2xl tracking-tight tabular-nums">{value}</span>{delta ? <StatDeltaText delta={delta} /> : null}</div>{description ? (- <p className="text-pretty text-muted-foreground text-xs/relaxed">+ <div className="text-pretty text-muted-foreground text-13">{description}- </p>+ </div>) : null}{children}</div>diff --git a/packages/ui/src/components/status-indicator.tsx b/packages/ui/src/components/status-indicator.tsxindex 008e8022..2839e5d1 100644--- a/packages/ui/src/components/status-indicator.tsx+++ b/packages/ui/src/components/status-indicator.tsx@@ -1,5 +1,5 @@import { Spinner } from "@crm/ui/components/spinner";-import { type Bloom, bloomClass } from "@crm/ui/lib/dither";+import { type Bloom, bloomClass } from "@crm/ui/lib/bloom";import { cn } from "@crm/ui/lib/utils";import type * as React from "react";@@ -73,6 +73,7 @@ function StatusIndicator({busy = false,bloom = "low",size = "default",+ iconOnlyBelowSm = false,className,...props}: Omit<React.ComponentProps<"span">, "color"> & {@@ -83,6 +84,7 @@ function StatusIndicator({busy?: boolean;bloom?: Bloom;size?: StatusSize;+ iconOnlyBelowSm?: boolean;}) {return (<span@@ -106,7 +108,14 @@ function StatusIndicator({aria-hidden="true"/>)}- <span className="truncate">{label}</span>+ <span+ className={cn(+ "min-w-0 truncate",+ iconOnlyBelowSm && "hidden sm:inline",+ )}+ >+ {label}+ </span></span>);}diff --git a/packages/ui/src/components/suggestion.tsx b/packages/ui/src/components/suggestion.tsxindex a679e4a5..03554ccd 100644--- a/packages/ui/src/components/suggestion.tsx+++ b/packages/ui/src/components/suggestion.tsx@@ -1,10 +1,9 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import Close from "@carbon/icons-react/es/Close";import { Button } from "@crm/ui/components/button";import { Icon } from "@crm/ui/components/icon";import { Spinner } from "@crm/ui/components/spinner";+import { CheckIcon, XIcon } from "lucide-react";import type * as React from "react";export function Suggestion({@@ -43,7 +42,7 @@ export function Suggestion({onClick={onAccept}aria-label="Accept">- <Icon icon={Checkmark} />+ <Icon icon={CheckIcon} /></Button><Buttonvariant="ghost"@@ -51,7 +50,7 @@ export function Suggestion({onClick={onDismiss}aria-label="Dismiss">- <Icon icon={Close} />+ <Icon icon={XIcon} /></Button></>)}diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsxindex 82e743bc..61fb9fe6 100644--- a/packages/ui/src/components/switch.tsx+++ b/packages/ui/src/components/switch.tsx@@ -17,14 +17,14 @@ function Switch({data-slot="switch"data-size={size}className={cn(- "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 data-[size=default]:h-[18px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",+ "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-[color,background-color,border-color,box-shadow] outline-none group-has-[>[data-slot=field]]/field-label:focus-visible:shadow-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:shadow-focus aria-invalid:ring-2 aria-invalid:ring-destructive/40 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] data-checked:bg-brand data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",className)}{...props}><SwitchPrimitive.Thumbdata-slot="switch-thumb"- className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"+ className="pointer-events-none block rounded-full bg-background ring-0 transition-transform duration-300 ease-spring-bouncy group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:bg-foreground"/></SwitchPrimitive.Root>)diff --git a/packages/ui/src/components/table-empty.tsx b/packages/ui/src/components/table-empty.tsxnew file mode 100644index 00000000..2e2c011f--- /dev/null+++ b/packages/ui/src/components/table-empty.tsx@@ -0,0 +1,37 @@+import {+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@crm/ui/components/empty";+import { Spinner } from "@crm/ui/components/spinner";+import type { ReactNode } from "react";++export function TableEmpty({+ title,+ description,+ action,+ busy = false,+}: {+ title: string;+ description: string;+ action?: ReactNode;+ busy?: boolean;+}) {+ return (+ <Empty aria-busy={busy || undefined}>+ <EmptyHeader>+ {busy ? (+ <EmptyMedia>+ <Spinner />+ </EmptyMedia>+ ) : null}+ <EmptyTitle>{title}</EmptyTitle>+ <EmptyDescription>{description}</EmptyDescription>+ </EmptyHeader>+ {action ? <EmptyContent>{action}</EmptyContent> : null}+ </Empty>+ );+}diff --git a/packages/ui/src/components/table-pagination.tsx b/packages/ui/src/components/table-pagination.tsxindex 1a6c535e..a4a6194a 100644--- a/packages/ui/src/components/table-pagination.tsx+++ b/packages/ui/src/components/table-pagination.tsx@@ -1,10 +1,9 @@"use client";-import ChevronLeft from "@carbon/icons-react/es/ChevronLeft";-import ChevronRight from "@carbon/icons-react/es/ChevronRight";import { Button } from "@crm/ui/components/button";-import { Spinner } from "@crm/ui/components/spinner";-import type { ReactNode } from "react";+import { SkeletonLine } from "@crm/ui/components/skeleton-lines";+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";+import { type ReactNode, useCallback, useRef } from "react";const numberFormat = new Intl.NumberFormat();@@ -27,40 +26,84 @@ export function TablePagination({}) {const rangeStart = total === 0 ? 0 : (page - 1) * pageSize + 1;const rangeEnd = Math.min(page * pageSize, total);+ const previous = useRef<HTMLButtonElement>(null);+ const next = useRef<HTMLButtonElement>(null);+ const returnFocus = useRef<{+ page: number;+ control: "previous" | "next";+ } | null>(null);+ const restoreFocus = useCallback(+ (node: HTMLDivElement | null) => {+ if (!node || returnFocus.current?.page !== page) return;+ const target =+ returnFocus.current.control === "previous" ? previous : next;+ const source =+ returnFocus.current.control === "previous" ? next : previous;+ returnFocus.current = null;+ if (+ (document.activeElement === source.current ||+ document.activeElement === document.body) &&+ !target.current?.disabled+ )+ target.current?.focus();+ },+ [page],+ );return (<div className="flex shrink-0 flex-wrap items-center justify-between gap-3">- <span className="flex items-center gap-2 text-muted-foreground text-xs tabular-nums">- {loading && <Spinner />}- {meta ??+ <span className="flex items-center gap-2 text-13 text-muted-foreground tabular-nums">+ {loading && total === 0 ? (+ <SkeletonLine width="48" />+ ) : (+ (meta ??(total === 0? "No results": `Showing ${numberFormat.format(rangeStart)}–${numberFormat.format(rangeEnd,- )} of ${numberFormat.format(total)}`)}+ )} of ${numberFormat.format(total)}`))+ )}</span>{totalPages > 1 && (- <div className="flex items-center gap-2">+ <div ref={restoreFocus} className="flex items-center gap-2"><Button+ ref={previous}variant="ghost"size="sm"disabled={page <= 1}- onClick={() => onPageChange(Math.max(1, page - 1))}+ onClick={(event) => {+ const targetPage = Math.max(1, page - 1);+ returnFocus.current =+ targetPage === 1 &&+ document.activeElement === event.currentTarget+ ? { page: targetPage, control: "next" }+ : null;+ onPageChange(targetPage);+ }}>- <ChevronLeft data-icon="inline-start" />+ <ChevronLeftIcon data-icon="inline-start" />Previous</Button>- <span className="text-muted-foreground text-xs tabular-nums">+ <span className="text-muted-foreground text-sm tabular-nums">{page} / {totalPages}</span><Button- variant="contrast"+ ref={next}+ variant="ghost"size="sm"disabled={page >= totalPages}- onClick={() => onPageChange(page + 1)}+ onClick={(event) => {+ const targetPage = page + 1;+ returnFocus.current =+ targetPage >= totalPages &&+ document.activeElement === event.currentTarget+ ? { page: targetPage, control: "previous" }+ : null;+ onPageChange(targetPage);+ }}>Next- <ChevronRight data-icon="inline-end" />+ <ChevronRightIcon data-icon="inline-end" /></Button></div>)}diff --git a/packages/ui/src/components/table.tsx b/packages/ui/src/components/table.tsxindex a45b59b5..863d8609 100644--- a/packages/ui/src/components/table.tsx+++ b/packages/ui/src/components/table.tsx@@ -19,7 +19,7 @@ function Table({><tabledata-slot="table"- className={cn("w-full caption-bottom text-xs", className)}+ className={cn("w-full caption-bottom text-sm", className)}{...props}/>{overlay}@@ -60,12 +60,39 @@ function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {);}-function TableRow({ className, ...props }: React.ComponentProps<"tr">) {+function TableRow({+ className,+ onClick,+ onKeyDown,+ tabIndex,+ ...props+}: React.ComponentProps<"tr">) {return (<trdata-slot="table-row"+ tabIndex={tabIndex ?? (onClick ? 0 : undefined)}+ onClick={+ onClick+ ? (event) => {+ event.currentTarget.focus();+ onClick(event);+ }+ : undefined+ }+ onKeyDown={(event) => {+ onKeyDown?.(event);+ if (+ onClick &&+ !event.defaultPrevented &&+ event.target === event.currentTarget &&+ (event.key === "Enter" || event.key === " ")+ ) {+ event.preventDefault();+ event.currentTarget.click();+ }+ }}className={cn(- "border-b transition-colors hover:bg-muted/60 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",+ "border-b outline-hidden transition-colors hover:bg-muted/50 focus-visible:not-in-data-pointer:outline-2 focus-visible:not-in-data-pointer:outline-solid focus-visible:not-in-data-pointer:-outline-offset-2 focus-visible:not-in-data-pointer:outline-ring has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",className,)}{...props}@@ -78,7 +105,7 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {<thdata-slot="table-head"className={cn(- "h-9 px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground [&:has([role=checkbox])]:pr-0",+ "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",className,)}{...props}@@ -91,7 +118,7 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) {<tddata-slot="table-cell"className={cn(- "px-2 py-2.5 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",+ "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",className,)}{...props}@@ -106,7 +133,7 @@ function TableCaption({return (<captiondata-slot="table-caption"- className={cn("mt-4 text-xs text-muted-foreground", className)}+ className={cn("mt-4 text-sm text-muted-foreground", className)}{...props}/>);diff --git a/packages/ui/src/components/tabs.tsx b/packages/ui/src/components/tabs.tsxindex 4c85bc6c..29cacfb1 100644--- a/packages/ui/src/components/tabs.tsx+++ b/packages/ui/src/components/tabs.tsx@@ -24,12 +24,12 @@ function Tabs({}const tabsListVariants = cva(- "group/tabs-list inline-flex w-fit items-center justify-center rounded-md p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",+ "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-0.5 text-muted-foreground group-data-horizontal/tabs:h-9 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",{variants: {variant: {default: "bg-muted",- line: "gap-1 bg-transparent",+ line: "w-full justify-start gap-6 bg-transparent p-0 shadow-divider group-data-vertical/tabs:w-fit group-data-vertical/tabs:gap-1 group-data-vertical/tabs:shadow-none",},},defaultVariants: {@@ -62,10 +62,10 @@ function TabsTrigger({<TabsPrimitive.Triggerdata-slot="tabs-trigger"className={cn(- "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-1.5 py-0.5 text-xs font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start group-data-vertical/tabs:py-[calc(--spacing(1.25))] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",- "group-data-[variant=line]/tabs-list:flex-none group-data-[variant=line]/tabs-list:px-0 group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",- "data-active:bg-background data-active:text-foreground data-active:shadow-2xs dark:data-active:border-border dark:data-active:bg-accent dark:data-active:text-foreground",- "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",+ "relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-muted-foreground transition-[color,background-color,box-shadow] outline-none group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:not-focus-visible:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group-data-horizontal/tabs:group-data-[variant=line]/tabs-list:h-full group-data-[variant=line]/tabs-list:flex-none group-data-[variant=line]/tabs-list:rounded-none group-data-[variant=line]/tabs-list:px-0.5 group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",+ "data-active:bg-background data-active:text-foreground dark:data-active:bg-input/30 dark:data-active:text-foreground",+ "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-0 group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",className,)}{...props}@@ -80,7 +80,7 @@ function TabsContent({return (<TabsPrimitive.Contentdata-slot="tabs-content"- className={cn("flex-1 text-xs/relaxed outline-none", className)}+ className={cn("flex-1 text-sm outline-none", className)}{...props}/>);diff --git a/packages/ui/src/components/textarea.tsx b/packages/ui/src/components/textarea.tsxindex 27cc72ac..7c6dcd29 100644--- a/packages/ui/src/components/textarea.tsx+++ b/packages/ui/src/components/textarea.tsx@@ -3,16 +3,18 @@ import { cva, type VariantProps } from "class-variance-authority";import type * as React from "react";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",+ "flex field-sizing-content w-full rounded-md border border-border bg-transparent px-2.5 py-2 text-base transition-[color,background-color,border-color,box-shadow] outline-none placeholder:text-muted-foreground supports-[field-sizing:content]:resize-none hover:border-input focus-visible:shadow-focus disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground aria-invalid:border-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15 md:text-sm",{variants: {variant: {default: "",+ flush:+ "-mx-1 w-[calc(100%+--spacing(2))] px-1 [--focus-outline-offset:-2px] focus-visible:border-ring focus-visible:shadow-[inset_0_0_0_1px_var(--ring)]",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",+ "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:shadow-none focus-visible:ring-0 disabled:bg-transparent sm:text-15",},size: {- default: "min-h-16",+ default: "min-h-24",sm: "min-h-8",composer: "max-h-40 min-h-6",},diff --git a/packages/ui/src/components/toggle-group.tsx b/packages/ui/src/components/toggle-group.tsxindex 2fa84fda..ba0425fe 100644--- a/packages/ui/src/components/toggle-group.tsx+++ b/packages/ui/src/components/toggle-group.tsx@@ -45,7 +45,7 @@ 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:w-full 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-[spacing=0]:data-[variant=outline]:shadow-xs data-vertical:w-full data-vertical:flex-col data-vertical:items-stretch aria-invalid:outline aria-invalid:outline-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15",className,)}{...props}@@ -74,7 +74,7 @@ function ToggleGroupItem({data-size={context.size || size}data-spacing={context.spacing}className={cn(- "shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",+ "shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 group-data-[spacing=0]/toggle-group:shadow-none focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-md group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-md group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-md group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-md data-[state=on]:bg-muted group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",toggleVariants({variant: context.variant || variant,size: context.size || size,diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsxindex b7ef1b78..f448c1bd 100644--- a/packages/ui/src/components/toggle.tsx+++ b/packages/ui/src/components/toggle.tsx@@ -6,19 +6,19 @@ import { Toggle as TogglePrimitive } from "radix-ui";import type * as React from "react";const toggleVariants = cva(- "group/toggle inline-flex items-center justify-center gap-1 rounded-md text-muted-foreground text-xs font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted aria-pressed:text-foreground data-[state=on]:bg-muted data-[state=on]:text-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ "group/toggle inline-flex items-center justify-center gap-1 rounded-md text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow] outline-none hover:bg-muted hover:text-foreground focus-visible:shadow-focus disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-4 aria-invalid:ring-destructive/15 aria-pressed:bg-muted data-[state=on]:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants: {variant: {default: "bg-transparent",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",+ "border border-border bg-transparent shadow-xs hover:border-input hover:bg-muted",},size: {default:- "h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- sm: "h-7 min-w-7 rounded-md px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",- lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",+ "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",+ sm: "h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",+ lg: "h-10 min-w-10 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",},},defaultVariants: {diff --git a/packages/ui/src/components/token-field.tsx b/packages/ui/src/components/token-field.tsxindex 7216415d..4a052cb2 100644--- a/packages/ui/src/components/token-field.tsx+++ b/packages/ui/src/components/token-field.tsx@@ -73,7 +73,7 @@ function TokenField({aria-disabled={inactive || undefined}tabIndex={inactive ? -1 : tabIndex}className={cn(- "max-h-40 min-h-6 w-full min-w-0 cursor-text overflow-y-auto whitespace-pre-wrap break-words px-1 text-base leading-6 outline-none data-[empty=true]:before:pointer-events-none data-[empty=true]:before:text-muted-foreground data-[empty=true]:before:content-[attr(data-placeholder)] data-[loading=true]:cursor-wait focus-within:before:hidden aria-disabled:cursor-not-allowed aria-disabled:opacity-60 sm:text-[15px] md:text-xs [&>[contenteditable]]:outline-none",+ "max-h-40 min-h-6 w-full min-w-0 cursor-text overflow-y-auto whitespace-pre-wrap break-words px-1 text-base leading-6 outline-none data-[empty=true]:before:pointer-events-none data-[empty=true]:before:text-muted-foreground data-[empty=true]:before:content-[attr(data-placeholder)] data-[loading=true]:cursor-wait focus-within:before:hidden aria-disabled:cursor-not-allowed aria-disabled:opacity-60 md:text-sm [&>[contenteditable]]:outline-none",className,)}{...props}diff --git a/packages/ui/src/components/tool-step.tsx b/packages/ui/src/components/tool-step.tsxindex 6be2d5a7..697b175a 100644--- a/packages/ui/src/components/tool-step.tsx+++ b/packages/ui/src/components/tool-step.tsx@@ -1,10 +1,9 @@"use client";-import Checkmark from "@carbon/icons-react/es/Checkmark";-import WarningAlt from "@carbon/icons-react/es/WarningAlt";import { DotMatrix } from "@crm/ui/components/dot-matrix";import { Icon } from "@crm/ui/components/icon";import { Shimmer } from "@crm/ui/components/shimmer";+import { CheckIcon, TriangleAlertIcon } from "lucide-react";import type * as React from "react";export const TOOL_STEP_STATES = ["pending", "done", "failed"] as const;@@ -36,10 +35,14 @@ export function ToolStep({<span className="flex h-5 shrink-0 items-center">{state === "pending" ? <DotMatrix decorative /> : null}{state === "done" ? (- <Icon className="text-primary" icon={Checkmark} motion="none" />+ <Icon className="text-primary" icon={CheckIcon} motion="none" />) : null}{state === "failed" ? (- <Icon className="text-destructive" icon={WarningAlt} motion="none" />+ <Icon+ className="text-destructive"+ icon={TriangleAlertIcon}+ motion="none"+ />) : null}</span><span className="min-w-0 wrap-break-word">@@ -48,7 +51,10 @@ export function ToolStep({</span></div>{state === "failed" && error ? (- <p className="wrap-break-word pl-5.5 text-destructive text-xs/5" role="alert">+ <p+ className="wrap-break-word pl-5.5 text-destructive text-xs/5"+ role="alert"+ >{error}</p>) : null}diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsxindex 7d0d2be8..c021daee 100644--- a/packages/ui/src/components/tooltip.tsx+++ b/packages/ui/src/components/tooltip.tsx@@ -5,7 +5,7 @@ import { Tooltip as TooltipPrimitive } from "radix-ui";import type * as React from "react";function TooltipProvider({- delayDuration = 0,+ delayDuration = 400,...props}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {return (@@ -31,7 +31,7 @@ function TooltipTrigger({function TooltipContent({className,- sideOffset = 0,+ sideOffset = 8,children,...props}: React.ComponentProps<typeof TooltipPrimitive.Content>) {@@ -41,13 +41,13 @@ function TooltipContent({data-slot="tooltip-content"sideOffset={sideOffset}className={cn(- "z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-none data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-lg bg-foreground px-2 py-1.5 text-center text-13 text-balance text-background duration-100 has-data-[slot=kbd]:pr-1 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=instant-open]:animate-in data-[state=instant-open]:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className,)}{...props}>{children}- <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-none bg-foreground fill-foreground" />+ <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" /></TooltipPrimitive.Content></TooltipPrimitive.Portal>);diff --git a/packages/ui/src/components/user-menu.tsx b/packages/ui/src/components/user-menu.tsxnew file mode 100644index 00000000..59ce8c61--- /dev/null+++ b/packages/ui/src/components/user-menu.tsx@@ -0,0 +1,161 @@+"use client";++import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";+import { GeneratedAvatar } from "@crm/ui/components/generated-avatar";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@crm/ui/components/dropdown-menu";+import { Skeleton } from "@crm/ui/components/skeleton";+import { LogOutIcon, MonitorIcon, MoonIcon, SunIcon } from "lucide-react";+import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";+import { type ReactNode, useTransition } from "react";++export type UserMenuUser = {+ name: string;+ email: string;+ avatar: string | null;+};++export type ThemePreference = "light" | "dark" | "system";++const THEMES = [+ { value: "light", label: "Light", icon: SunIcon },+ { value: "dark", label: "Dark", icon: MoonIcon },+ { value: "system", label: "System", icon: MonitorIcon },+] as const;++function isThemePreference(value: string): value is ThemePreference {+ return THEMES.some((theme) => theme.value === value);+}++function UserAvatar({+ user,+ trigger = false,+}: {+ user: UserMenuUser;+ trigger?: boolean;+}) {+ return (+ <Avatar className={trigger ? "size-7" : undefined}>+ {user.avatar ? <AvatarImage alt={user.name} src={user.avatar} /> : null}+ <AvatarFallback>+ <GeneratedAvatar seed={user.email || user.name} size="fill" />+ </AvatarFallback>+ </Avatar>+ );+}++function ThemeSwitcher({+ value,+ onValueChange,+ label,+}: {+ value: ThemePreference;+ onValueChange: (theme: ThemePreference) => void;+ label: string;+}) {+ return (+ <DropdownMenuPrimitive.RadioGroup+ aria-label={label}+ className="flex rounded-md shadow-xs"+ data-slot="theme-switcher"+ onValueChange={(next) => {+ if (isThemePreference(next)) onValueChange(next);+ }}+ value={value}+ >+ {THEMES.map(({ value: theme, label: themeLabel, icon: ThemeIcon }) => (+ <DropdownMenuPrimitive.RadioItem+ aria-label={themeLabel}+ className="relative -ml-px flex h-8 min-w-8 cursor-default items-center justify-center border border-border px-2 text-foreground outline-none transition-[color,background-color,box-shadow] first:ml-0 first:rounded-l-md last:rounded-r-md hover:bg-muted focus-visible:z-10 focus-visible:shadow-focus data-[state=checked]:bg-muted [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"+ key={theme}+ onSelect={(event) => event.preventDefault()}+ value={theme}+ >+ <ThemeIcon aria-hidden />+ </DropdownMenuPrimitive.RadioItem>+ ))}+ </DropdownMenuPrimitive.RadioGroup>+ );+}++function UserMenu({+ user,+ actions,+ theme,+ onThemeChange,+ onSignOut,+ menuLabel = "Account menu",+ themeLabel = "Theme",+ signOutLabel = "Log out",+}: {+ user: UserMenuUser;+ actions?: ReactNode;+ theme: ThemePreference;+ onThemeChange: (theme: ThemePreference) => void;+ onSignOut: () => Promise<void>;+ menuLabel?: string;+ themeLabel?: string;+ signOutLabel?: string;+}) {+ const [isSigningOut, startSignOut] = useTransition();++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={menuLabel}+ className="flex shrink-0 rounded-full outline-none focus-visible:shadow-focus"+ >+ <UserAvatar trigger user={user} />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="min-w-60"+ side="bottom"+ sideOffset={4}+ >+ <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">+ <UserAvatar user={user} />+ <div className="grid min-w-0 flex-1 leading-tight">+ <span className="truncate font-medium">{user.name}</span>+ <span className="truncate text-muted-foreground text-xs">+ {user.email}+ </span>+ </div>+ </div>+ <DropdownMenuSeparator />+ {actions ? <DropdownMenuGroup>{actions}</DropdownMenuGroup> : null}+ <div className="flex items-center justify-between gap-4 py-1 pr-1 pl-2 text-sm">+ <span className="text-muted-foreground">{themeLabel}</span>+ <ThemeSwitcher+ label={themeLabel}+ onValueChange={onThemeChange}+ value={theme}+ />+ </div>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={isSigningOut}+ onSelect={(event) => {+ event.preventDefault();+ startSignOut(onSignOut);+ }}+ >+ <LogOutIcon aria-hidden />+ {signOutLabel}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function UserMenuSkeleton() {+ return <Skeleton className="size-7 shrink-0 rounded-full" />;+}++export { UserMenu, UserMenuSkeleton };diff --git a/packages/ui/src/components/value-meter.tsx b/packages/ui/src/components/value-meter.tsxnew file mode 100644index 00000000..57fb8059--- /dev/null+++ b/packages/ui/src/components/value-meter.tsx@@ -0,0 +1,24 @@+import type { CSSProperties } from "react";+import { type ChartColor, chartSwatch } from "../lib/chart-config";++function ValueMeter({ share, color }: { share: number; color: ChartColor }) {+ return (+ <span+ data-slot="value-meter"+ className="flex h-1.5 w-full overflow-hidden bg-muted forced-colors:outline-1 forced-colors:-outline-offset-1 forced-colors:outline-[CanvasText] forced-colors:outline-solid"+ >+ <span+ data-slot="value-meter-fill"+ className="h-full w-(--share) forced-colors:outline-1 forced-colors:-outline-offset-1 forced-colors:outline-[CanvasText] forced-colors:outline-solid forced-colors:forced-color-adjust-none"+ style={+ {+ backgroundColor: chartSwatch(color),+ "--share": `${Math.round(Math.max(Math.min(share, 100), 0))}%`,+ } as CSSProperties+ }+ />+ </span>+ );+}++export { ValueMeter };diff --git a/packages/ui/src/components/workspace-switcher.tsx b/packages/ui/src/components/workspace-switcher.tsxnew file mode 100644index 00000000..3474cedd--- /dev/null+++ b/packages/ui/src/components/workspace-switcher.tsx@@ -0,0 +1,152 @@+"use client";++import { Button } from "@crm/ui/components/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuTrigger,+} from "@crm/ui/components/dropdown-menu";+import { EntityLogo } from "@crm/ui/components/entity-logo";+import { GeneratedAvatar } from "@crm/ui/components/generated-avatar";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { INTERACTION_CONFIG } from "@crm/ui/lib/interaction-config";+import { CheckIcon, ChevronsUpDownIcon } from "lucide-react";+import { type ReactNode, useEffectEvent } from "react";++export type SwitcherWorkspace = {+ id: string;+ name: string;+ slug: string;+ logo: string | null;+};++function WorkspaceLogo({+ workspace,+ size = "default",+}: {+ workspace: SwitcherWorkspace;+ size?: "sm" | "default";+}) {+ if (workspace.logo?.trim()) {+ return (+ <EntityLogo name={workspace.name} size={size} src={workspace.logo} />+ );+ }++ return (+ <GeneratedAvatar+ kind="workspace"+ seed={workspace.name}+ size={size === "sm" ? "sm" : "md"}+ />+ );+}++function WorkspaceSwitcher({+ workspaces,+ activeSlug,+ onSwitch,+ actions,+ label = "Workspaces",+}: {+ workspaces: SwitcherWorkspace[];+ activeSlug: string | null;+ onSwitch: (slug: string) => void;+ actions?: ReactNode;+ label?: string;+}) {+ const onShortcut = useEffectEvent((event: KeyboardEvent) => {+ if (!event.metaKey && !event.ctrlKey) return;+ if (event.altKey || event.shiftKey) return;++ const position = Number.parseInt(event.key, 10);++ if (Number.isNaN(position) || position < 1) return;+ if (position > INTERACTION_CONFIG.workspaceShortcuts) return;++ const workspace = workspaces[position - 1];++ if (!workspace) return;++ event.preventDefault();+ onSwitch(workspace.slug);+ });++ useMountEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => onShortcut(event);++ window.addEventListener("keydown", onKeyDown);++ return () => window.removeEventListener("keydown", onKeyDown);+ });++ const activeWorkspace =+ workspaces.find((workspace) => workspace.slug === activeSlug) ??+ workspaces[0];++ if (!activeWorkspace) return null;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ data-slot="workspace-switcher"+ className="h-10 w-full justify-start gap-2 px-2"+ variant="ghost"+ >+ <span aria-hidden className="flex shrink-0">+ <WorkspaceLogo size="sm" workspace={activeWorkspace} />+ </span>+ <span className="min-w-0 flex-1 truncate text-left font-medium text-sm">+ {activeWorkspace.name}+ </span>+ <ChevronsUpDownIcon aria-hidden className="text-muted-foreground" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="w-(--radix-dropdown-menu-trigger-width) min-w-60"+ sideOffset={4}+ >+ <DropdownMenuGroup>+ <DropdownMenuLabel>{label}</DropdownMenuLabel>+ {workspaces.map((workspace, index) => (+ <DropdownMenuItem+ aria-current={+ workspace.slug === activeWorkspace.slug ? "true" : undefined+ }+ key={workspace.id}+ onSelect={() => onSwitch(workspace.slug)}+ >+ <span aria-hidden className="flex shrink-0">+ <WorkspaceLogo workspace={workspace} />+ </span>+ <span className="min-w-0 flex-1 truncate">{workspace.name}</span>+ {workspace.slug === activeWorkspace.slug ? (+ <CheckIcon aria-hidden className="text-foreground" />+ ) : null}+ {index < INTERACTION_CONFIG.workspaceShortcuts ? (+ <DropdownMenuShortcut className="ml-0">+ ⌘{index + 1}+ </DropdownMenuShortcut>+ ) : null}+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ {actions ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>{actions}</DropdownMenuGroup>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++export { WorkspaceSwitcher };diff --git a/packages/ui/src/hooks/use-mobile.ts b/packages/ui/src/hooks/use-mobile.tsindex 0a892310..9620bdee 100644--- a/packages/ui/src/hooks/use-mobile.ts+++ b/packages/ui/src/hooks/use-mobile.ts@@ -1,21 +1,20 @@-import * as React from "react";+import { LAYOUT } from "@crm/ui/lib/layout-config";+import { useSyncExternalStore } from "react";-const MOBILE_BREAKPOINT = 768;+function subscribe(onChange: () => void) {+ const query = window.matchMedia(LAYOUT.mobileMediaQuery);+ query.addEventListener("change", onChange);+ return () => query.removeEventListener("change", onChange);+}-export function useIsMobile() {- const [isMobile, setIsMobile] = React.useState<boolean | undefined>(- undefined,- );+function getSnapshot(): boolean {+ return window.matchMedia(LAYOUT.mobileMediaQuery).matches;+}- React.useEffect(() => {- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);- const onChange = () => {- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);- };- mql.addEventListener("change", onChange);- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);- return () => mql.removeEventListener("change", onChange);- }, []);+function getServerSnapshot(): boolean {+ return false;+}- return !!isMobile;+export function useIsMobile() {+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);}diff --git a/packages/ui/src/hooks/use-search-input.ts b/packages/ui/src/hooks/use-search-input.tsindex 2593b1a8..f5320c7f 100644--- a/packages/ui/src/hooks/use-search-input.ts+++ b/packages/ui/src/hooks/use-search-input.ts@@ -1,6 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";+import { useRef, useState } from "react";export function useSearchInput(committed: string,@@ -16,12 +17,9 @@ export function useSearchInput(setState({ committed, value: committed });}- useEffect(- () => () => {- if (timer.current) clearTimeout(timer.current);- },- [],- );+ useMountEffect(() => () => {+ if (timer.current) clearTimeout(timer.current);+ });const change = (next: string) => {setState({ committed, value: next });diff --git a/packages/ui/src/lib/dither.ts b/packages/ui/src/lib/bloom.tssimilarity index 100%rename from packages/ui/src/lib/dither.tsrename to packages/ui/src/lib/bloom.tsdiff --git a/packages/ui/src/lib/chart-config.ts b/packages/ui/src/lib/chart-config.tsnew file mode 100644index 00000000..d104d638--- /dev/null+++ b/packages/ui/src/lib/chart-config.ts@@ -0,0 +1,65 @@+export type ChartColor = { light: string; dark: string };++const COLORS = {+ emerald: { light: "#059669", dark: "#34d399" },+ neutral: { light: "#71717a", dark: "#a1a1aa" },+ stage1: { light: "#a7f3d0", dark: "#065f46" },+ stage2: { light: "#6ee7b7", dark: "#047857" },+ stage3: { light: "#10b981", dark: "#10b981" },+ stage4: { light: "#047857", dark: "#6ee7b7" },+} as const satisfies Record<string, ChartColor>;++export const CHART_CONFIG = {+ trend: {+ won: COLORS.emerald,+ created: COLORS.neutral,+ },+ stages: [COLORS.stage1, COLORS.stage2, COLORS.stage3, COLORS.stage4],+ fallback: COLORS.neutral,+ height: {+ area: 200,+ bar: 180,+ donut: 200,+ dashboardTrend: 196,+ dashboardDonut: 168,+ },+ area: {+ curve: "monotone",+ stroke: "solid",+ strokeWidth: 1.5,+ },+ bar: {+ radius: 4,+ },+ donut: {+ innerRadius: "72%",+ outerRadius: "100%",+ cornerRadius: 4,+ paddingAngle: 2,+ },+} as const satisfies {+ trend: Record<string, ChartColor>;+ stages: readonly ChartColor[];+ fallback: ChartColor;+ height: Record<string, number>;+ area: { curve: string; stroke: string; strokeWidth: number };+ bar: { radius: number };+ donut: {+ innerRadius: string;+ outerRadius: string;+ cornerRadius: number;+ paddingAngle: number;+ };+};++export function chartSwatch(color: ChartColor): string {+ return `light-dark(${color.light}, ${color.dark})`;+}++export function chartThemeColors(color: ChartColor) {+ return { light: [color.light], dark: [color.dark] };+}++export function stageChartColor(index: number): ChartColor {+ return CHART_CONFIG.stages[index] ?? CHART_CONFIG.fallback;+}diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.tsindex de4a95c3..820ad1d4 100644--- a/packages/ui/src/lib/format.ts+++ b/packages/ui/src/lib/format.ts@@ -84,7 +84,7 @@ export function fromDay(value: string | null | undefined): Date | undefined {export function formatDay(value: string | null | undefined): string {const date = fromDay(value);- return date ? dayFormat.format(date) : (value ?? "—");+ return date ? dayFormat.format(date) : (value ?? "");}export function initialsFromName(name: string | null | undefined): string {diff --git a/packages/ui/src/lib/interaction-config.ts b/packages/ui/src/lib/interaction-config.tsnew file mode 100644index 00000000..b5f84478--- /dev/null+++ b/packages/ui/src/lib/interaction-config.ts@@ -0,0 +1,3 @@+export const INTERACTION_CONFIG = {+ workspaceShortcuts: 9,+} as const;diff --git a/packages/ui/src/lib/layout-config.ts b/packages/ui/src/lib/layout-config.tsnew file mode 100644index 00000000..26f840f8--- /dev/null+++ b/packages/ui/src/lib/layout-config.ts@@ -0,0 +1,6 @@+const MOBILE_BREAKPOINT_PX = 768;++export const LAYOUT = {+ mobileMediaQuery: `(width < ${MOBILE_BREAKPOINT_PX}px)`,+ desktopMediaQuery: `(width >= ${MOBILE_BREAKPOINT_PX}px)`,+} as const;diff --git a/packages/ui/src/lib/row-accent.ts b/packages/ui/src/lib/row-accent.tsindex 27f23036..84a29b21 100644--- a/packages/ui/src/lib/row-accent.ts+++ b/packages/ui/src/lib/row-accent.ts@@ -1,21 +1,3 @@-const BAR = [- "[&>td:first-child]:relative",- "[&>td:first-child]:before:pointer-events-none [&>td:first-child]:before:absolute",- "[&>td:first-child]:before:inset-y-0 [&>td:first-child]:before:left-0 [&>td:first-child]:before:w-0.5",- "[&>td:first-child]:before:bg-foreground [&>td:first-child]:before:opacity-0",- "[&:hover>td:first-child]:before:opacity-100",-].join(" ");+export const ROW_ACCENT = "cursor-pointer focus-visible:bg-muted/50";-export const ROW_ACCENT = [- "cursor-pointer",- BAR,- "[&>td:first-child]:transition-[padding] [&>td:first-child]:duration-200 [&>td:first-child]:ease-out",- "[&:hover>td:first-child]:pl-5",-].join(" ");--export const ROW_ACCENT_EXPANDABLE = [- "cursor-pointer",- BAR,- "[&>td:nth-child(2)]:transition-[padding] [&>td:nth-child(2)]:duration-200 [&>td:nth-child(2)]:ease-out",- "[&:hover>td:nth-child(2)]:pl-5",-].join(" ");+export const ROW_ACCENT_EXPANDABLE = ROW_ACCENT;diff --git a/packages/ui/src/lib/seed-palette.ts b/packages/ui/src/lib/seed-palette.tsnew file mode 100644index 00000000..2ed5b02c--- /dev/null+++ b/packages/ui/src/lib/seed-palette.ts@@ -0,0 +1,30 @@+const PALETTES = [+ ["#d1fae5", "#34d399", "#047857"],+ ["#dcfce7", "#4ade80", "#166534"],+ ["#ccfbf1", "#2dd4bf", "#0f766e"],+ ["#e4ece6", "#8fb39b", "#3e6a4f"],+ ["#e7ebe9", "#98a6a0", "#3c4a45"],+] as const;++export type SeedPalette = (typeof PALETTES)[number];++export function seedHash(seed: string): number {+ let value = 0x811c9dc5;++ for (const char of seed.trim().toLowerCase()) {+ value ^= char.codePointAt(0) ?? 0;+ value = Math.imul(value, 0x01000193);+ }++ value ^= value >>> 16;+ value = Math.imul(value, 0x85ebca6b);+ value ^= value >>> 13;+ value = Math.imul(value, 0xc2b2ae35);+ value ^= value >>> 16;++ return value >>> 0;+}++export function seedPalette(value: number): SeedPalette {+ return PALETTES[value % PALETTES.length] ?? PALETTES[0];+}diff --git a/packages/ui/src/lib/shell-config.ts b/packages/ui/src/lib/shell-config.tsnew file mode 100644index 00000000..31f46dc9--- /dev/null+++ b/packages/ui/src/lib/shell-config.ts@@ -0,0 +1,15 @@+export const SHELL = {+ ink: {+ tokens: [+ "--rail-mesh-1",+ "--rail-mesh-2",+ "--rail-mesh-3",+ "--rail-mesh-4",+ ],+ distortion: 1,+ maxPixelCount: 360_000,+ scale: 1.2,+ speed: 0.34,+ swirl: 0.55,+ },+} as const;diff --git a/packages/ui/src/lib/skeleton-config.ts b/packages/ui/src/lib/skeleton-config.tsnew file mode 100644index 00000000..de864652--- /dev/null+++ b/packages/ui/src/lib/skeleton-config.ts@@ -0,0 +1,13 @@+export const SKELETON = {+ rows: {+ feed: 4,+ rail: 5,+ fields: 4,+ messages: 3,+ editor: 3,+ },+} as const;++export function skeletonRows(count: number): string[] {+ return Array.from({ length: count }, (_, index) => `row-${index}`);+}diff --git a/packages/ui/src/lib/utils.ts b/packages/ui/src/lib/utils.tsindex ac680b30..1d3defdf 100644--- a/packages/ui/src/lib/utils.ts+++ b/packages/ui/src/lib/utils.ts@@ -1,5 +1,28 @@import { type ClassValue, clsx } from "clsx";-import { twMerge } from "tailwind-merge";+import { extendTailwindMerge } from "tailwind-merge";++const twMerge = extendTailwindMerge({+ extend: {+ classGroups: {+ "font-size": [{ text: ["11", "13", "15", "26", "28", "32"] }],+ shadow: [+ {+ shadow: [+ "border",+ "border-strong",+ "menu",+ "modal",+ "raised",+ "divider",+ "focus",+ "picker",+ ],+ },+ ],+ transition: [{ transition: ["size", "progress"] }],+ },+ },+});export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.cssindex 9d04731a..be853664 100644--- a/packages/ui/src/styles/globals.css+++ b/packages/ui/src/styles/globals.css@@ -1,44 +1,116 @@@import "tailwindcss";@import "tw-animate-css";+@import "./shell.css";+@import "./sheet.css";+@import "./reduced-motion.css";@source "../../**/*.{ts,tsx}";@custom-variant dark (&:is(.dark *));+@custom-variant data-open {+ &:where([data-state="open"]),+ &:where([data-open]:not([data-open="false"])) {+ @slot;+ }+}++@custom-variant data-closed {+ &:where([data-state="closed"]),+ &:where([data-closed]:not([data-closed="false"])) {+ @slot;+ }+}++@custom-variant data-checked {+ &:where([data-state="checked"]),+ &:where([data-checked]:not([data-checked="false"])) {+ @slot;+ }+}++@custom-variant data-unchecked {+ &:where([data-state="unchecked"]),+ &:where([data-unchecked]:not([data-unchecked="false"])) {+ @slot;+ }+}++@custom-variant data-selected {+ &:where([data-selected="true"]) {+ @slot;+ }+}++@custom-variant data-disabled {+ &:where([data-disabled="true"]),+ &:where([data-disabled]:not([data-disabled="false"])) {+ @slot;+ }+}++@custom-variant data-active {+ &:where([data-state="active"]),+ &:where([data-active]:not([data-active="false"])) {+ @slot;+ }+}++@custom-variant data-horizontal {+ &:where([data-orientation="horizontal"]) {+ @slot;+ }+}++@custom-variant data-vertical {+ &:where([data-orientation="vertical"]) {+ @slot;+ }+}+:root {- --background: #ffffff;- --foreground: #171717;- --card: #ffffff;- --card-foreground: #171717;- --popover: #ffffff;- --popover-foreground: #171717;- --primary: #006b4f;- --primary-foreground: #ffffff;- --secondary: #f4f4f4;- --secondary-foreground: #171717;- --muted: #f4f4f4;- --muted-foreground: #6b6b6b;- --accent: #f4f4f4;- --accent-foreground: #171717;- --tag: #ffffff;- --tag-foreground: #171717;- --destructive: #ae2e24;+ --background: oklch(1 0 0);+ --foreground: oklch(0.2046 0 0);+ --card: oklch(1 0 0);+ --card-foreground: oklch(0.2046 0 0);+ --popover: oklch(1 0 0);+ --popover-foreground: oklch(0.2046 0 0);+ --primary: oklch(0.2046 0 0);+ --primary-foreground: oklch(1 0 0);+ --brand: #059669;+ --brand-foreground: #ffffff;+ --secondary: oklch(0.9612 0 0);+ --secondary-foreground: oklch(0.2046 0 0);+ --muted: oklch(0.9612 0 0);+ --muted-foreground: oklch(0.4165 0 0);+ --accent: oklch(0 0 0 / 5%);+ --accent-foreground: oklch(0.2046 0 0);+ --tag: var(--background);+ --tag-foreground: var(--foreground);+ --destructive: #cb2a2f;--destructive-foreground: #ffffff;- --success: oklch(0.55 0.13 150);+ --destructive-solid: #da2f35;+ --border: oklch(0 0 0 / 8%);+ --input: oklch(0 0 0 / 21%);+ --overlay: oklch(0 0 0 / 20%);+ --ring: var(--brand);+ --chart-1: #a7f3d0;+ --chart-2: #6ee7b7;+ --chart-3: #34d399;+ --chart-4: #10b981;+ --chart-5: #047857;+ --status-info: #3d74d6;+ --status-warning: #ffb224;+ --status-warning-text: #a35200;+ --status-success: var(--brand);+ --status-success-text: #047857;+ --status-danger: #da2f35;+ --success: var(--status-success-text);--success-foreground: #ffffff;- --warning: oklch(0.62 0.14 65);+ --warning: var(--status-warning-text);--warning-foreground: #ffffff;- --info: oklch(0.55 0.16 255);+ --info: var(--status-info);--info-foreground: #ffffff;- --border: #e2e2e2;- --input: #e2e2e2;- --overlay: rgb(0 0 0 / 0.18);- --ring: #006b4f;- --chart-1: #00915f;- --chart-2: #2563eb;- --chart-3: #b45309;- --chart-4: #7c3aed;- --chart-5: #0891b2;--severity-critical: var(--destructive);--severity-high: oklch(0.646 0.222 41.116);--severity-medium: oklch(0.681 0.162 75.834);@@ -47,37 +119,125 @@--severity-unknown: oklch(0.75 0 0);--code-foreground: #2b2b2b;--code-accent: #b0402c;- --code-string: var(--primary);- --sidebar: #fafafa;- --sidebar-foreground: #171717;- --sidebar-primary: #006b4f;- --sidebar-primary-foreground: #ffffff;- --sidebar-accent: #f4f4f4;- --sidebar-accent-foreground: #171717;- --sidebar-border: #e2e2e2;- --sidebar-ring: #006b4f;+ --code-string: var(--status-success-text);+ --sidebar: oklch(0.9851 0 0);+ --sidebar-foreground: oklch(0.2046 0 0);+ --sidebar-primary: oklch(0.2046 0 0);+ --sidebar-primary-foreground: oklch(1 0 0);+ --sidebar-accent: oklch(0 0 0 / 5%);+ --sidebar-accent-foreground: oklch(0.2046 0 0);+ --sidebar-border: oklch(0 0 0 / 8%);+ --sidebar-ring: var(--brand);+ --rail: #0c1712;+ --rail-foreground: #f1f5f2;+ --rail-muted: #93a59c;+ --rail-accent: oklch(1 0 0 / 7%);+ --rail-border: oklch(1 0 0 / 14%);+ --rail-mesh-1: #0c1712;+ --rail-mesh-2: #10231a;+ --rail-mesh-3: #09130e;+ --rail-mesh-4: #12352a;+ --scrollbar-thumb: oklch(0 0 0 / 21%);+ --scrollbar-thumb-hover: oklch(0 0 0 / 34%);--font-sans: var(--font-geist-sans, "Geist", sans-serif);--font-mono: var(--font-geist-mono, "Geist Mono", monospace);- --radius: 5px;- --shadow-x: 0px;- --shadow-y: 1px;- --shadow-blur: 2px;- --shadow-spread: 0px;- --shadow-opacity: 0.08;- --shadow-color: hsl(0 0% 0%);- --shadow-2xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);- --shadow-xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);- --shadow-sm: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);- --shadow: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);- --shadow-md: 0px 2px 4px -1px hsl(0 0% 0% / 0.08);- --shadow-lg: 0px 4px 8px -2px hsl(0 0% 0% / 0.08);- --shadow-xl: 0px 8px 16px -4px hsl(0 0% 0% / 0.08);- --shadow-2xl: 0px 16px 32px -8px hsl(0 0% 0% / 0.12);+ --radius: 0.375rem;--tracking-normal: 0em;--spacing: 0.25rem;+ --shadow-2xs: 0px 1px 1px oklch(0 0 0 / 4%);+ --shadow-xs: 0px 1px 2px oklch(0 0 0 / 4%);+ --shadow-sm: 0px 2px 2px oklch(0 0 0 / 4%);+ --shadow: var(--shadow-sm);+ --shadow-md:+ 0px 2px 2px oklch(0 0 0 / 4%), 0px 8px 8px -8px oklch(0 0 0 / 4%);+ --shadow-lg:+ 0px 2px 2px oklch(0 0 0 / 4%), 0px 8px 16px -4px oklch(0 0 0 / 4%);+ --shadow-xl:+ 0px 1px 1px oklch(0 0 0 / 2%), 0px 4px 8px -4px oklch(0 0 0 / 4%),+ 0px 16px 24px -8px oklch(0 0 0 / 6%);+ --shadow-2xl:+ 0px 1px 1px oklch(0 0 0 / 2%), 0px 8px 16px -4px oklch(0 0 0 / 4%),+ 0px 24px 32px -8px oklch(0 0 0 / 6%);}.dark {+ --background: oklch(0.1448 0 0);+ --foreground: oklch(0.9461 0 0);+ --card: oklch(0.1448 0 0);+ --card-foreground: oklch(0.9461 0 0);+ --popover: oklch(0.1448 0 0);+ --popover-foreground: oklch(0.9461 0 0);+ --primary: oklch(0.9461 0 0);+ --primary-foreground: oklch(0.1448 0 0);+ --brand: #10b981;+ --brand-foreground: #022c22;+ --secondary: oklch(0.2178 0 0);+ --secondary-foreground: oklch(0.9461 0 0);+ --muted: oklch(0.2178 0 0);+ --muted-foreground: oklch(0.709 0 0);+ --accent: oklch(1 0 0 / 6%);+ --accent-foreground: oklch(0.9461 0 0);+ --tag: var(--secondary);+ --tag-foreground: var(--foreground);+ --destructive: #ff6166;+ --destructive-foreground: #ffffff;+ --destructive-solid: #d93036;+ --border: oklch(1 0 0 / 14%);+ --input: oklch(1 0 0 / 24%);+ --ring: var(--brand);+ --chart-1: #064e3b;+ --chart-2: #047857;+ --chart-3: #10b981;+ --chart-4: #34d399;+ --chart-5: #a7f3d0;+ --status-info: #5b8ee6;+ --status-warning-text: var(--status-warning);+ --status-success: var(--brand);+ --status-success-text: var(--brand);+ --status-danger: #d93036;+ --success: var(--status-success-text);+ --success-foreground: oklch(0.1448 0 0);+ --warning: var(--status-warning-text);+ --warning-foreground: oklch(0.1448 0 0);+ --info: var(--status-info);+ --info-foreground: oklch(0.1448 0 0);+ --severity-critical: oklch(0.637 0.237 25.331);+ --severity-high: oklch(0.705 0.213 47.604);+ --severity-medium: oklch(0.8 0.15 75);+ --severity-low: var(--muted-foreground);+ --severity-info: oklch(0.71 0.01 286);+ --severity-unknown: oklch(0.5 0 0);+ --code-foreground: #e3e3e3;+ --code-accent: #e5735b;+ --code-string: var(--status-success-text);+ --sidebar: oklch(0 0 0);+ --sidebar-foreground: oklch(0.9461 0 0);+ --sidebar-primary: oklch(0.9461 0 0);+ --sidebar-primary-foreground: oklch(0.1448 0 0);+ --sidebar-accent: oklch(1 0 0 / 6%);+ --sidebar-accent-foreground: oklch(0.9461 0 0);+ --sidebar-border: oklch(1 0 0 / 14%);+ --sidebar-ring: var(--brand);+ --rail: #000000;+ --rail-foreground: #ededed;+ --rail-muted: #8f8f8f;+ --rail-accent: oklch(1 0 0 / 8%);+ --rail-border: oklch(1 0 0 / 14%);+ --rail-mesh-1: #000000;+ --rail-mesh-2: #0b0b0b;+ --rail-mesh-3: #030303;+ --rail-mesh-4: #121212;+ --scrollbar-thumb: oklch(1 0 0 / 24%);+ --scrollbar-thumb-hover: oklch(1 0 0 / 51%);+ --shadow-2xs: 0px 1px 1px oklch(0 0 0 / 16%);+ --shadow-xs: 0px 1px 2px oklch(0 0 0 / 16%);+ --shadow-sm: 0px 1px 2px oklch(0 0 0 / 16%);+ --shadow: var(--shadow-sm);+ --shadow-md:+ 0px 2px 2px oklch(0 0 0 / 32%), 0px 8px 8px -8px oklch(0 0 0 / 16%);+}++.theme-classic {--background: #0f0f0f;--foreground: #f5f5f5;--card: #171717;@@ -96,30 +256,10 @@--tag-foreground: #f5f5f5;--destructive: #ae2e24;--destructive-foreground: #ffffff;- --success: oklch(0.72 0.16 155);- --success-foreground: oklch(0.205 0 0);- --warning: oklch(0.8 0.15 75);- --warning-foreground: oklch(0.205 0 0);- --info: oklch(0.7 0.15 250);- --info-foreground: oklch(0.205 0 0);--border: #2a2a2a;--input: #2a2a2a;--overlay: rgb(0 0 0 / 0.55);--ring: #40be96;- --chart-1: #0fa871;- --chart-2: #4b87f0;- --chart-3: #c07e22;- --chart-4: #9b7bf0;- --chart-5: #1e93b8;- --severity-critical: oklch(0.637 0.237 25.331);- --severity-high: oklch(0.705 0.213 47.604);- --severity-medium: var(--chart-2);- --severity-low: var(--muted-foreground);- --severity-info: oklch(0.71 0.01 286);- --severity-unknown: oklch(0.5 0 0);- --code-foreground: #e3e3e3;- --code-accent: #e5735b;- --code-string: #40be96;--sidebar: #171717;--sidebar-foreground: #f5f5f5;--sidebar-primary: #006b4f;@@ -128,15 +268,7 @@--sidebar-accent-foreground: #f5f5f5;--sidebar-border: #2a2a2a;--sidebar-ring: #40be96;- --font-sans: var(--font-geist-sans, "Geist", sans-serif);- --font-mono: var(--font-geist-mono, "Geist Mono", monospace);--radius: 5px;- --shadow-x: 0px;- --shadow-y: 1px;- --shadow-blur: 2px;- --shadow-spread: 0px;- --shadow-opacity: 0.08;- --shadow-color: hsl(0 0% 0%);--shadow-2xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);--shadow-xs: 0px 1px 2px 0px hsl(0 0% 0% / 0.04);--shadow-sm: 0px 1px 2px 0px hsl(0 0% 0% / 0.06);@@ -158,6 +290,7 @@--container-narrow: 560px;--container-sheet: 640px;--height-tool-panel: clamp(400px, calc(100dvh - 416px), 640px);+ --min-height-empty-page: 60svh;--color-dark-card: #171717;--color-dark-border: #2a2a2a;--color-dark-ring: #40be96;@@ -172,6 +305,8 @@--color-popover-foreground: var(--popover-foreground);--color-primary: var(--primary);--color-primary-foreground: var(--primary-foreground);+ --color-brand: var(--brand);+ --color-brand-foreground: var(--brand-foreground);--color-secondary: var(--secondary);--color-secondary-foreground: var(--secondary-foreground);--color-muted: var(--muted);@@ -182,12 +317,19 @@--color-tag-foreground: var(--tag-foreground);--color-destructive: var(--destructive);--color-destructive-foreground: var(--destructive-foreground);+ --color-destructive-solid: var(--destructive-solid);--color-success: var(--success);--color-success-foreground: var(--success-foreground);--color-warning: var(--warning);--color-warning-foreground: var(--warning-foreground);--color-info: var(--info);--color-info-foreground: var(--info-foreground);+ --color-status-info: var(--status-info);+ --color-status-warning: var(--status-warning);+ --color-status-warning-text: var(--status-warning-text);+ --color-status-success: var(--status-success);+ --color-status-success-text: var(--status-success-text);+ --color-status-danger: var(--status-danger);--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring);@@ -215,14 +357,27 @@--color-sidebar-border: var(--sidebar-border);--color-sidebar-ring: var(--sidebar-ring);+ --animate-spinner: spin 1s steps(10, end) infinite;--animate-spinner-trace: spinner-trace 1.4s linear infinite;+ --text-11: 0.6875rem;+ --text-11--line-height: 0.875rem;+ --text-13: 0.8125rem;+ --text-13--line-height: 1.125rem;+ --text-15: 0.9375rem;+ --text-15--line-height: 1.375rem;+--font-sans: var(--font-sans);--font-mono: var(--font-mono);- --radius-sm: 4px;+ --font-heading: var(--font-sans);++ --radius-sm: 0.25rem;--radius-md: var(--radius);- --radius-lg: 8px;- --radius-xl: 12px;+ --radius-lg: 0.5rem;+ --radius-xl: 0.75rem;+ --radius-2xl: 1rem;+ --radius-3xl: 1.5rem;+ --radius-4xl: 2rem;--shadow-2xs: var(--shadow-2xs);--shadow-xs: var(--shadow-xs);@@ -232,10 +387,62 @@--shadow-lg: var(--shadow-lg);--shadow-xl: var(--shadow-xl);--shadow-2xl: var(--shadow-2xl);- --font-heading: var(--font-sans);- --radius-2xl: calc(var(--radius) * 1.8);- --radius-3xl: calc(var(--radius) * 2.2);- --radius-4xl: calc(var(--radius) * 2.6);+ --shadow-border: 0 0 0 1px var(--border);+ --shadow-border-strong: 0 0 0 1px var(--input);+ --shadow-menu: 0 0 0 1px var(--border), var(--shadow-xl);+ --shadow-modal: 0 0 0 1px var(--border), var(--shadow-2xl);+ --shadow-raised: 0 0 0 1px var(--border), 0 1px 2px oklch(0 0 0 / 6%);+ --shadow-picker:+ 0 0 0 1px var(--border), 0 12px 28px -10px oklch(0 0 0 / 15%);+ --shadow-divider: inset 0 -1px 0 var(--border);+ --shadow-focus: 0 0 0 2px var(--background), 0 0 0 4px var(--ring);++ --ease-spring: linear(+ 0,+ 0.047,+ 0.155,+ 0.286,+ 0.418,+ 0.54,+ 0.646,+ 0.733,+ 0.804,+ 0.859,+ 0.9,+ 0.932,+ 0.955,+ 0.971,+ 0.982,+ 0.99,+ 0.995,+ 0.998,+ 1,+ 1.001,+ 1+ );+ --ease-spring-bouncy: linear(+ 0,+ 0.088,+ 0.284,+ 0.512,+ 0.721,+ 0.886,+ 0.999,+ 1.065,+ 1.092,+ 1.093,+ 1.078,+ 1.058,+ 1.036,+ 1.018,+ 1.005,+ 0.997,+ 0.992,+ 0.991,+ 0.992,+ 0.993,+ 1+ );}@layer base {@@ -245,32 +452,374 @@body {@apply bg-background text-foreground font-sans;}-- * {- scrollbar-width: thin;- scrollbar-color: var(--border) transparent;+ input[type="search"]::-webkit-search-cancel-button,+ input[type="search"]::-webkit-search-decoration {+ appearance: none;+ }+ :is(input, textarea, [contenteditable="true"]):not(.theme-classic *) {+ caret-color: var(--brand);+ }+ :not(.theme-classic *)::selection {+ background-color: color-mix(in oklab, var(--brand) 22%, transparent);+ }+ svg.lucide:not(.theme-classic *) {+ stroke-width: 1.5;}+ button:not(:disabled),+ [role="button"]:not(:disabled) {+ cursor: pointer;+ }+*::-webkit-scrollbar {- width: 10px;- height: 10px;+ width: 6px;+ height: 6px;}- *::-webkit-scrollbar-track {+ *::-webkit-scrollbar-track,+ *::-webkit-scrollbar-corner {background: transparent;}+ *::-webkit-scrollbar-track {+ margin-block: var(--scrollbar-inset, 0.5rem);+ }*::-webkit-scrollbar-thumb {- background-color: var(--border);- border: 2px solid transparent;+ background-color: var(--scrollbar-thumb);+ background-clip: content-box;+ border: 1.5px solid transparent;border-radius: 9999px;- background-clip: padding-box;+ transition: background-color 150ms ease;}*::-webkit-scrollbar-thumb:hover {- background-color: var(--muted-foreground);+ background-color: var(--scrollbar-thumb-hover);+ border-width: 0.5px;}- *::-webkit-scrollbar-corner {- background: transparent;++ @supports (-moz-appearance: none) {+ * {+ scrollbar-width: thin;+ scrollbar-color: var(--scrollbar-thumb) transparent;+ }+ }+}++@keyframes tw-shimmer {+ from {+ background-position: 100% 0;+ }+ to {+ background-position: 0 0;+ }+}++@utility no-scrollbar {+ -ms-overflow-style: none;+ scrollbar-width: none;++ &::-webkit-scrollbar {+ display: none;}}+@property --scroll-fade-t {+ syntax: "<length-percentage>";+ inherits: false;+ initial-value: 0px;+}+@property --scroll-fade-b {+ syntax: "<length-percentage>";+ inherits: false;+ initial-value: 0px;+}+@property --scroll-fade-s {+ syntax: "<length-percentage>";+ inherits: false;+ initial-value: 0px;+}+@property --scroll-fade-e {+ syntax: "<length-percentage>";+ inherits: false;+ initial-value: 0px;+}+@property --scroll-fade-mask {+ syntax: "*";+ inherits: false;+}++@keyframes scroll-fade-reveal-t {+ from {+ --scroll-fade-t: 0px;+ }+ to {+ --scroll-fade-t: var(+ --_scroll-fade-size-t,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ }+}+@keyframes scroll-fade-reveal-b {+ from {+ --scroll-fade-b: var(+ --_scroll-fade-size-b,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ }+ to {+ --scroll-fade-b: 0px;+ }+}+@keyframes scroll-fade-reveal-s {+ from {+ --scroll-fade-s: 0px;+ }+ to {+ --scroll-fade-s: var(+ --_scroll-fade-size-s,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ }+}+@keyframes scroll-fade-reveal-e {+ from {+ --scroll-fade-e: var(+ --_scroll-fade-size-e,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ }+ to {+ --scroll-fade-e: 0px;+ }+}++@utility scroll-fade-x {+ --_scroll-fade-size-s: var(+ --scroll-fade-s-size,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ --_scroll-fade-size-e: var(+ --scroll-fade-e-size,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ --scroll-fade-inline: linear-gradient(+ to right,+ transparent 0,+ #000 var(--scroll-fade-s, 0px),+ #000 calc(100% - var(--scroll-fade-e, 0px)),+ transparent 100%+ );+ &:where([dir="rtl"], [dir="rtl"] *) {+ --scroll-fade-inline: linear-gradient(+ to left,+ transparent 0,+ #000 var(--scroll-fade-s, 0px),+ #000 calc(100% - var(--scroll-fade-e, 0px)),+ transparent 100%+ );+ }+ -webkit-mask-image: var(--scroll-fade-mask, var(--scroll-fade-inline));+ mask-image: var(--scroll-fade-mask, var(--scroll-fade-inline));+ -webkit-mask-composite: source-in;+ mask-composite: intersect;+ -webkit-mask-repeat: no-repeat;+ mask-repeat: no-repeat;++ @supports (animation-timeline: scroll()) {+ animation:+ scroll-fade-reveal-s 1ms ease-in-out,+ scroll-fade-reveal-e 1ms ease-in-out;+ animation-timeline: scroll(self inline), scroll(self inline);+ animation-range:+ 0 var(--scroll-fade-reveal, calc(var(--spacing) * 24)),+ calc(100% - var(--scroll-fade-reveal, calc(var(--spacing) * 24))) 100%;+ animation-fill-mode: both;+ }++ @supports not (animation-timeline: scroll()) {+ --scroll-fade-s: var(--_scroll-fade-size-s);+ --scroll-fade-e: var(--_scroll-fade-size-e);+ }+}++@utility scroll-fade-b {+ --_scroll-fade-size-b: var(+ --scroll-fade-b-size,+ var(--scroll-fade-size, min(12%, calc(var(--spacing) * 10)))+ );+ --scroll-fade-mask: linear-gradient(+ to bottom,+ #000 0,+ #000 calc(100% - var(--scroll-fade-b, 0px)),+ transparent 100%+ );+ -webkit-mask-image: var(--scroll-fade-mask);+ mask-image: var(--scroll-fade-mask);+ -webkit-mask-composite: source-in;+ mask-composite: intersect;+ -webkit-mask-repeat: no-repeat;+ mask-repeat: no-repeat;++ @supports (animation-timeline: scroll()) {+ animation: scroll-fade-reveal-b 1ms ease-in-out;+ animation-timeline: scroll(self y);+ animation-range: calc(+ 100% -+ var(--scroll-fade-reveal, calc(var(--spacing) * 24))+ )+ 100%;+ animation-fill-mode: both;+ }++ @supports not (animation-timeline: scroll()) {+ --scroll-fade-b: var(--_scroll-fade-size-b);+ }+}++@utility scroll-gutter {+ margin-right: -0.5rem;+ margin-left: -0.25rem;+ padding-right: 0.5rem;+ padding-left: 0.25rem;+ scrollbar-gutter: stable;+}++@property --scroll-edge-fade {+ syntax: "<length>";+ inherits: false;+ initial-value: 0px;+}++@property --scroll-edge-fade-end {+ syntax: "<length>";+ inherits: false;+ initial-value: 0px;+}++@keyframes scroll-edge-fade {+ to {+ --scroll-edge-fade: 1rem;+ }+}++@keyframes scroll-edge-fade-end {+ from {+ --scroll-edge-fade-end: 1rem;+ }+ to {+ --scroll-edge-fade-end: 0px;+ }+}++@keyframes scroll-edge-line {+ to {+ box-shadow: 0 1px 0 var(--border);+ }+}++@utility scroll-edge-scope {+ timeline-scope: --scroll-edge;+}++@utility scroll-edge-source {+ @supports (animation-timeline: scroll()) {+ scroll-timeline: --scroll-edge y;+ mask-image: linear-gradient(+ to bottom,+ transparent 0,+ black var(--scroll-edge-fade),+ black calc(100% - var(--scroll-edge-fade-end)),+ transparent 100%+ );+ animation:+ scroll-edge-fade linear both,+ scroll-edge-fade-end linear both;+ animation-timeline: --scroll-edge, --scroll-edge;+ animation-range:+ 0 1.5rem,+ calc(100% - 1.5rem) 100%;+ }+}++@utility scroll-edge-line {+ @supports (animation-timeline: scroll()) {+ position: relative;+ z-index: 1;+ animation: scroll-edge-line linear both;+ animation-timeline: --scroll-edge;+ animation-range: 0 1.5rem;+ }+}++@property --roll {+ syntax: "<integer>";+ inherits: false;+ initial-value: 0;+}++@utility number-roll {+ transition: --roll 800ms cubic-bezier(0.22, 1, 0.36, 1);+ counter-set: roll var(--roll);+ &::after {+ content: counter(roll);+ }+}++@utility transition-progress {+ transition-property: width;+ transition-duration: 800ms;+ transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1);+}++@utility transition-size {+ transition-property: height, width, grid-template-rows;+ transition-timing-function: var(--ease-spring);+ transition-duration: 300ms;+}++@utility reveal-closed {+ display: grid;+ grid-template-rows: 0fr;+}++@utility reveal-open {+ display: grid;+ grid-template-rows: 1fr;+}++@keyframes feed-in {+ from {+ grid-template-rows: 0fr;+ opacity: 0;+ }+ to {+ grid-template-rows: 1fr;+ opacity: 1;+ }+}++@keyframes feed-out {+ from {+ grid-template-rows: 1fr;+ opacity: 1;+ }+ to {+ grid-template-rows: 0fr;+ opacity: 0;+ }+}++@utility feed-in {+ display: grid;+ animation: feed-in 450ms cubic-bezier(0.22, 1, 0.36, 1) both;+}++@utility feed-out {+ display: grid;+ animation: feed-out 450ms cubic-bezier(0.22, 1, 0.36, 1) both;+}++@utility dashed-edge {+ border-width: 1.5px;+ border-style: dashed;+}+@layer utilities {.bloom-low {box-shadow: 0 0 4px var(--bloom-color, currentColor);@@ -286,51 +835,51 @@}@layer utilities {- .cds-icon {+ .ds-icon {transform-origin: center;}@media (prefers-reduced-motion: no-preference) {- .cds-icon {+ .ds-icon {transition: transform 240ms cubic-bezier(0.34, 1.56, 0.64, 1);}- .cds-icon[data-motion="pop"] {- --cds-hover: scale(1.14);+ .ds-icon[data-motion="pop"] {+ --ds-hover: scale(1.14);}- .cds-icon[data-motion="scale"] {- --cds-hover: scale(1.1);+ .ds-icon[data-motion="scale"] {+ --ds-hover: scale(1.1);}- .cds-icon[data-motion="lift"] {- --cds-hover: translateY(-2px) scale(1.06);+ .ds-icon[data-motion="lift"] {+ --ds-hover: translateY(-2px) scale(1.06);}- .cds-icon[data-motion="turn"] {- --cds-hover: rotate(90deg);+ .ds-icon[data-motion="turn"] {+ --ds-hover: rotate(90deg);}- .cds-icon[data-motion="rotate"] {- --cds-hover: rotate(-12deg);+ .ds-icon[data-motion="rotate"] {+ --ds-hover: rotate(-12deg);}- .cds-icon[data-motion="flip"] {- --cds-hover: rotateY(180deg);+ .ds-icon[data-motion="flip"] {+ --ds-hover: rotateY(180deg);}- .cds-icon[data-motion="nudge-right"] {- --cds-hover: translateX(3px);+ .ds-icon[data-motion="nudge-right"] {+ --ds-hover: translateX(3px);}- .cds-icon[data-motion="nudge-left"] {- --cds-hover: translateX(-3px);+ .ds-icon[data-motion="nudge-left"] {+ --ds-hover: translateX(-3px);}- .cds-icon[data-motion="nudge-up"] {- --cds-hover: translateY(-3px);+ .ds-icon[data-motion="nudge-up"] {+ --ds-hover: translateY(-3px);}- .cds-icon[data-motion="nudge-down"] {- --cds-hover: translateY(3px);+ .ds-icon[data-motion="nudge-down"] {+ --ds-hover: translateY(3px);}- .cds-icon[data-motion="launch"] {- --cds-hover: translate(2px, -2px);+ .ds-icon[data-motion="launch"] {+ --ds-hover: translate(2px, -2px);}:where(- .cds-icon:hover,+ .ds-icon:hover,:where(button,a,@@ -341,31 +890,31 @@[data-slot="sidebar-menu-button"],.icon-hover):hover- .cds-icon+ .ds-icon) {- transform: var(--cds-hover, none);+ transform: var(--ds-hover, none);&[data-motion="spin"] {- animation: cds-spin 1.1s linear infinite;+ animation: ds-spin 1.1s linear infinite;}&[data-motion="wiggle"] {- animation: cds-wiggle 0.5s ease-in-out;+ animation: ds-wiggle 0.5s ease-in-out;}&[data-motion="swing"] {- animation: cds-swing 0.6s ease-in-out;+ animation: ds-swing 0.6s ease-in-out;transform-origin: top center;}&[data-motion="bounce"] {- animation: cds-bounce 0.6s ease;+ animation: ds-bounce 0.6s ease;}&[data-motion="pulse"] {- animation: cds-pulse 0.9s ease-in-out infinite;+ animation: ds-pulse 0.9s ease-in-out infinite;}}}}-@keyframes cds-spin {+@keyframes ds-spin {to {transform: rotate(360deg);}@@ -375,7 +924,7 @@stroke-dashoffset: -100;}}-@keyframes cds-wiggle {+@keyframes ds-wiggle {0%,100% {transform: rotate(0);@@ -393,7 +942,7 @@transform: rotate(3deg);}}-@keyframes cds-swing {+@keyframes ds-swing {0%,100% {transform: rotate(0);@@ -408,7 +957,7 @@transform: rotate(4deg);}}-@keyframes cds-bounce {+@keyframes ds-bounce {0%,100% {transform: translateY(0);@@ -423,7 +972,7 @@transform: translateY(-1px);}}-@keyframes cds-pulse {+@keyframes ds-pulse {0%,100% {transform: scale(1);@@ -478,6 +1027,13 @@opacity: 0;}+@media (forced-colors: active) {+ :focus-visible {+ outline: 2px solid Highlight;+ outline-offset: var(--focus-outline-offset, 2px);+ }+}+::view-transition-group(app-header),::view-transition-group(app-rail) {z-index: 100;diff --git a/packages/ui/src/styles/reduced-motion.css b/packages/ui/src/styles/reduced-motion.cssnew file mode 100644index 00000000..88014558--- /dev/null+++ b/packages/ui/src/styles/reduced-motion.css@@ -0,0 +1,11 @@+@layer base {+ @media (prefers-reduced-motion: reduce) {+ *,+ ::before,+ ::after {+ animation-duration: 1ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 1ms !important;+ }+ }+}diff --git a/packages/ui/src/styles/sheet.css b/packages/ui/src/styles/sheet.cssnew file mode 100644index 00000000..c49ee538--- /dev/null+++ b/packages/ui/src/styles/sheet.css@@ -0,0 +1,84 @@+@keyframes sheet-presence-open {+ from {+ --sheet-presence: 0;+ }+ to {+ --sheet-presence: 1;+ }+}++@keyframes sheet-presence-closed {+ from {+ --sheet-presence: 1;+ }+ to {+ --sheet-presence: 0;+ }+}++@layer components {+ .sheet-motion,+ .sheet-overlay-motion {+ --sheet-duration-open: 300ms;+ --sheet-duration-closed: 150ms;+ --sheet-offset: 2.5rem;+ --sheet-offset-x: 0px;+ --sheet-offset-y: 0px;+ opacity: 1;+ animation-name: sheet-presence-open;+ animation-duration: var(--sheet-duration-open);+ animation-timing-function: linear;+ transition-property: opacity, translate;+ transition-duration: var(--sheet-duration-open);+ transition-timing-function: var(--ease-spring);+ }++ .sheet-motion {+ translate: 0 0;+ }++ .sheet-motion[data-side="right"] {+ --sheet-offset-x: var(--sheet-offset);+ }++ .sheet-motion[data-side="left"] {+ --sheet-offset-x: calc(-1 * var(--sheet-offset));+ }++ .sheet-motion[data-side="bottom"] {+ --sheet-offset-y: var(--sheet-offset);+ }++ .sheet-motion[data-side="top"] {+ --sheet-offset-y: calc(-1 * var(--sheet-offset));+ }++ .sheet-overlay-motion {+ --sheet-duration-open: var(--sheet-duration-closed);+ transition-timing-function: ease-out;+ }++ .sheet-motion[data-state="closed"],+ .sheet-overlay-motion[data-state="closed"] {+ opacity: 0;+ animation-name: sheet-presence-closed;+ animation-duration: var(--sheet-duration-closed);+ transition-duration: var(--sheet-duration-closed);+ transition-timing-function: ease-out;+ }++ .sheet-motion[data-state="closed"] {+ translate: var(--sheet-offset-x) var(--sheet-offset-y);+ }++ @starting-style {+ .sheet-motion[data-state="open"],+ .sheet-overlay-motion[data-state="open"] {+ opacity: 0;+ }++ .sheet-motion[data-state="open"] {+ translate: var(--sheet-offset-x) var(--sheet-offset-y);+ }+ }+}diff --git a/packages/ui/src/styles/shell.css b/packages/ui/src/styles/shell.cssnew file mode 100644index 00000000..d1f06720--- /dev/null+++ b/packages/ui/src/styles/shell.css@@ -0,0 +1,31 @@+@utility shell-rail {+ --sidebar-foreground: var(--rail-foreground, #f1f5f2);+ --sidebar-accent: var(--rail-accent, oklch(1 0 0 / 7%));+ --sidebar-accent-foreground: var(--rail-foreground, #f1f5f2);+ --sidebar-border: var(--rail-border, oklch(1 0 0 / 14%));+ --foreground: var(--rail-foreground, #f1f5f2);+ --muted-foreground: var(--rail-muted, #93a59c);+ --accent: var(--rail-accent, oklch(1 0 0 / 7%));+ --accent-foreground: var(--rail-foreground, #f1f5f2);+ --border: var(--rail-border, oklch(1 0 0 / 14%));+ --muted: var(--rail-accent, oklch(1 0 0 / 7%));+ --ring: var(--rail-foreground, #f1f5f2);+ --sidebar: transparent;+ position: relative;+ z-index: 1;+ color: var(--rail-foreground, #f1f5f2);+}++@utility corner-cut {+ mask:+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32'%3E%3Cpath d='M26 0H32V32H0V21.1Q0 17.1 3.16 14.64L18.84 2.46Q22 0 26 0Z'/%3E%3C/svg%3E")+ left top / 32px 32px no-repeat,+ linear-gradient(#000, #000) right top / calc(100% - 32px) 32px no-repeat,+ linear-gradient(#000, #000) left bottom / 100% calc(100% - 32px) no-repeat;+}++@utility shell-cut {+ position: relative;+ z-index: 1;+ @apply corner-cut;+}diff --git a/packages/ui/test/dashboard-chart.spec.tsx b/packages/ui/test/dashboard-chart.spec.tsxnew file mode 100644index 00000000..22968ef3--- /dev/null+++ b/packages/ui/test/dashboard-chart.spec.tsx@@ -0,0 +1,334 @@+import { afterEach, expect, mock, test } from "bun:test";+import { Window } from "happy-dom";+import { act, type ReactNode } from "react";++if (process.env.CRM_DASHBOARD_CHART_TEST_CHILD !== "1") {+ test("dashboard chart wrappers run in an isolated DOM", () => {+ const result = Bun.spawnSync(["bun", "test", import.meta.path], {+ env: { ...process.env, CRM_DASHBOARD_CHART_TEST_CHILD: "1" },+ stdout: "pipe",+ stderr: "pipe",+ });+ const output = new TextDecoder().decode(result.stderr);+ expect(output).not.toContain("(fail)");+ expect(output).toContain(" 0 fail");+ expect(result.exitCode).toBe(0);+ });+} else {+ const browser = new Window({ url: "http://localhost" });+ Object.assign(globalThis, {+ window: browser,+ document: browser.document,+ navigator: browser.navigator,+ HTMLElement: browser.HTMLElement,+ IS_REACT_ACT_ENVIRONMENT: true,+ });++ type EngineProps = {+ activeIndex?: number | null;+ activeSector?: string | null;+ onHoverIndexChange?: (index: number | null) => void;+ onSelectionChange?: unknown;+ children?: ReactNode;+ };+ type EngineState = { last: EngineProps | null };+ const engine: EngineState = { last: null };+ const part = () => null;+ function stubChart(name: string, parts: string[]) {+ const Chart = (props: EngineProps) => {+ engine.last = props;+ return <div data-engine={name} />;+ };+ return Object.assign(+ Chart,+ Object.fromEntries(parts.map((key) => [key, part])),+ );+ }+ mock.module("../src/components/evilcharts/charts/echarts-area-chart", () => ({+ EChartsAreaChart: stubChart("area", ["Grid", "XAxis", "Tooltip", "Area"]),+ }));+ mock.module("../src/components/evilcharts/charts/echarts-bar-chart", () => ({+ EChartsBarChart: stubChart("bar", ["Grid", "XAxis", "Tooltip", "Bar"]),+ }));+ mock.module("../src/components/evilcharts/charts/echarts-pie-chart", () => ({+ EChartsPieChart: stubChart("pie", ["Tooltip", "Pie"]),+ }));++ const { createRoot } = await import("react-dom/client");+ const { AreaTrend, BarStat, BarTrend, DonutStat } = await import(+ "../src/components/dashboard-chart"+ );+ const { ChartSwatch } = await import("../src/components/chart-swatch");+ const { ValueMeter } = await import("../src/components/value-meter");+ const { CHART_CONFIG } = await import("../src/lib/chart-config");++ const roots: ReturnType<typeof createRoot>[] = [];+ afterEach(() => {+ for (const root of roots.splice(0)) act(() => root.unmount());+ document.body.innerHTML = "";+ engine.last = null;+ });++ function render(node: ReactNode) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container as unknown as Element);+ roots.push(root);+ act(() => root.render(node));+ return container;+ }++ function press(target: Element, key: string) {+ const event = new browser.KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ });+ act(() => {+ target.dispatchEvent(event as unknown as Event);+ });+ return event;+ }++ function liveRegions(container: Element) {+ return [...container.querySelectorAll("[aria-live]")];+ }++ function onlyLiveRegion(container: Element) {+ const regions = liveRegions(container);+ expect(regions).toHaveLength(1);+ const region = regions[0] as Element;+ expect(region.getAttribute("aria-live")).toBe("polite");+ expect(region.getAttribute("aria-atomic")).toBe("true");+ expect(region.className).toContain("sr-only");+ return region;+ }++ function group(container: Element) {+ const groups = [...container.querySelectorAll('[role="group"]')];+ expect(groups).toHaveLength(1);+ expect(container.querySelectorAll("[tabindex]")).toHaveLength(1);+ const element = groups[0] as Element;+ expect(element.getAttribute("tabindex")).toBe("0");+ return element;+ }++ const money = (value: number | string) => `$${Number(value).toFixed(0)}`;+ const trend = [+ { month: "2026-05", won: 0, created: 74000 },+ { month: "2026-06", won: 1200, created: null },+ ];+ const trendConfig = {+ won: { label: "Closed won", color: CHART_CONFIG.trend.won },+ created: { label: "New pipeline", color: CHART_CONFIG.trend.created },+ };+ const slices = [+ {+ key: "demo",+ label: "Demo booked",+ value: 75000,+ color: CHART_CONFIG.stages[0],+ },+ {+ key: "decision",+ label: "Decision maker in",+ value: 76000,+ color: CHART_CONFIG.stages[1],+ },+ ];++ for (const [name, Chart] of [+ ["AreaTrend", AreaTrend],+ ["BarTrend", BarTrend],+ ] as const) {+ test(`${name} announces only the keyboard period and clears on Escape`, () => {+ const container = render(+ <Chart+ data={trend}+ config={trendConfig}+ xKey="month"+ showLegend+ formatX={(value) => (value.endsWith("05") ? "May" : "Jun")}+ formatValue={money}+ label="Trend"+ />,+ );+ const region = onlyLiveRegion(container);+ const chart = group(container);+ expect(region.textContent).toBe("");++ press(chart, "ArrowRight");+ expect(region.textContent).toBe(+ "May, Closed won $0, New pipeline $74000",+ );+ expect(engine.last?.activeIndex).toBe(0);+ press(chart, "ArrowRight");+ expect(region.textContent).toBe(+ "Jun, Closed won $1200, New pipeline None",+ );+ expect(onlyLiveRegion(container)).toBe(region);++ press(chart, "Escape");+ expect(region.textContent).toBe("");+ expect(engine.last?.activeIndex).toBeNull();+ });+ }++ test("AreaTrend pointer hover updates the visible readout, not the live region", () => {+ const container = render(+ <AreaTrend+ data={trend}+ config={trendConfig}+ xKey="month"+ showLegend+ formatX={(value) => (value.endsWith("05") ? "May" : "Jun")}+ formatValue={money}+ />,+ );+ const region = onlyLiveRegion(container);+ act(() => engine.last?.onHoverIndexChange?.(1));+ expect(container.textContent).toContain("Jun");+ expect(region.textContent).toBe("");+ });++ test("BarStat legend is static and a stable region announces the keyboard bar", () => {+ const opened: string[] = [];+ const container = render(+ <BarStat+ data={slices}+ formatValue={money}+ onBarClick={(key) => opened.push(key)}+ label="Stages"+ />,+ );+ const legend = container.querySelector("ul");+ expect(legend?.hasAttribute("aria-live")).toBe(false);+ const region = onlyLiveRegion(container);+ const chart = group(container);+ expect(region.textContent).toBe("");++ press(chart, "Enter");+ expect(opened).toEqual([]);+ press(chart, "End");+ expect(region.textContent).toBe("Decision maker in: $76000");+ expect(engine.last?.activeIndex).toBe(1);+ press(chart, "Home");+ expect(region.textContent).toBe("Demo booked: $75000");+ press(chart, "Enter");+ expect(opened).toEqual(["demo"]);+ expect(onlyLiveRegion(container)).toBe(region);++ press(chart, "Escape");+ expect(region.textContent).toBe("");+ expect(engine.last?.activeIndex).toBeNull();+ expect(legend?.textContent).toContain("Demo booked$75000");+ });++ test("DonutStat announces the keyboard slice atomically and clears on Escape", () => {+ const opened: string[] = [];+ const container = render(+ <DonutStat+ data={slices}+ formatValue={money}+ onSliceClick={(key) => opened.push(key)}+ centerValue="$151K"+ label="Pipeline"+ />,+ );+ const region = onlyLiveRegion(container);+ const chart = group(container);+ expect(region.textContent).toBe("");+ press(chart, "ArrowLeft");+ expect(region.textContent).toBe("Decision maker in: $76000");+ expect(engine.last?.activeSector).toBe("decision");+ press(chart, " ");+ expect(opened).toEqual(["decision"]);+ press(chart, "Escape");+ expect(region.textContent).toBe("");+ expect(engine.last?.activeSector).toBeNull();+ });++ test("Space does not scroll or activate an actionable chart before a keyboard selection", () => {+ const opened: string[] = [];+ const container = render(+ <>+ <BarStat data={slices} onBarClick={(key) => opened.push(key)} />+ <DonutStat data={slices} onSliceClick={(key) => opened.push(key)} />+ </>,+ );+ const charts = [...container.querySelectorAll('[role="group"]')];+ expect(charts).toHaveLength(2);+ for (const chart of charts) {+ expect(press(chart, " ").defaultPrevented).toBe(true);+ }+ expect(opened).toEqual([]);+ });++ test("Readout swatches pair each label with a forced-colors outline", () => {+ const container = render(+ <BarStat data={slices} formatValue={money} label="Stages" />,+ );+ const swatches = [+ ...container.querySelectorAll('[data-slot="chart-swatch"]'),+ ];+ expect(swatches).toHaveLength(2);+ for (const [index, swatch] of swatches.entries()) {+ expect(swatch.getAttribute("aria-hidden")).toBe("true");+ for (const token of [+ "size-2",+ "forced-colors:forced-color-adjust-none",+ "forced-colors:outline-solid",+ "forced-colors:outline-1",+ "forced-colors:outline-[CanvasText]",+ ]) {+ expect(swatch.classList.contains(token)).toBe(true);+ }+ expect(swatch.nextElementSibling?.textContent).toBe(slices[index]?.label);+ }+ });++ test("ChartSwatch sm variant matches the stage legend square", () => {+ const container = render(+ <ChartSwatch color={CHART_CONFIG.stages[2]} size="sm" />,+ );+ const swatch = container.querySelector('[data-slot="chart-swatch"]');+ expect(swatch?.classList.contains("size-1.5")).toBe(true);+ expect(swatch?.classList.contains("rounded-[2px]")).toBe(false);+ expect(+ swatch?.classList.contains("forced-colors:forced-color-adjust-none"),+ ).toBe(true);+ });++ test("ValueMeter clamps the share and keeps a forced-colors track and fill", () => {+ const container = render(+ <>+ <ValueMeter share={-5} color={CHART_CONFIG.stages[0]} />+ <ValueMeter share={42.4} color={CHART_CONFIG.stages[1]} />+ <ValueMeter share={180} color={CHART_CONFIG.stages[2]} />+ </>,+ );+ const fills = [+ ...container.querySelectorAll('[data-slot="value-meter-fill"]'),+ ];+ expect(+ fills.map((fill) =>+ (fill as unknown as HTMLElement).style.getPropertyValue("--share"),+ ),+ ).toEqual(["0%", "42%", "100%"]);+ const track = container.querySelector('[data-slot="value-meter"]');+ for (const token of [+ "h-1.5",+ "bg-muted",+ "forced-colors:outline-1",+ "forced-colors:outline-[CanvasText]",+ ]) {+ expect(track?.classList.contains(token)).toBe(true);+ }+ expect(+ fills[0]?.classList.contains("forced-colors:forced-color-adjust-none"),+ ).toBe(true);+ expect(+ track?.classList.contains("forced-colors:forced-color-adjust-none"),+ ).toBe(false);+ });+}diff --git a/packages/ui/test/evilcharts-engine.spec.tsx b/packages/ui/test/evilcharts-engine.spec.tsxnew file mode 100644index 00000000..cbf704e8--- /dev/null+++ b/packages/ui/test/evilcharts-engine.spec.tsx@@ -0,0 +1,1082 @@+import { afterEach, expect, mock, test } from "bun:test";+import type { TooltipComponentPositionCallback } from "echarts";+import { Window } from "happy-dom";+import {+ act,+ type ReactNode,+ StrictMode,+ Suspense,+ startTransition,+ useCallback,+ useRef,+ useState,+} from "react";++if (process.env.CRM_EVILCHARTS_TEST_CHILD !== "1") {+ test("EvilCharts engine runs in an isolated DOM", () => {+ const result = Bun.spawnSync(["bun", "test", import.meta.path], {+ env: { ...process.env, CRM_EVILCHARTS_TEST_CHILD: "1" },+ stdout: "pipe",+ stderr: "pipe",+ });+ expect(new TextDecoder().decode(result.stderr)).not.toContain("(fail)");+ expect(result.exitCode).toBe(0);+ });+} else {+ const browser = new Window({ url: "http://localhost" });+ let width = 500;+ let height = 300;+ let reducedMotion = false;+ let nextFrame = 0;+ const frames = new Map<number, FrameRequestCallback>();+ const mediaSubscribers = new Set<() => void>();+ browser.matchMedia = () => ({+ matches: reducedMotion,+ addEventListener: (_name: string, callback: () => void) => {+ mediaSubscribers.add(callback);+ },+ removeEventListener: (_name: string, callback: () => void) => {+ mediaSubscribers.delete(callback);+ },+ });+ const resizeObservers = new Set<TestResizeObserver>();+ class TestResizeObserver {+ constructor(readonly callback: () => void) {}+ observe() {+ resizeObservers.add(this);+ }+ disconnect() {+ resizeObservers.delete(this);+ }+ }+ Object.assign(globalThis, {+ window: browser,+ document: browser.document,+ navigator: browser.navigator,+ HTMLElement: browser.HTMLElement,+ MutationObserver: browser.MutationObserver,+ ResizeObserver: TestResizeObserver,+ getComputedStyle: browser.getComputedStyle.bind(browser),+ IS_REACT_ACT_ENVIRONMENT: true,+ requestAnimationFrame: (callback: FrameRequestCallback) => {+ const id = ++nextFrame;+ frames.set(id, callback);+ return id;+ },+ cancelAnimationFrame: (id: number) => {+ frames.delete(id);+ },+ });+ Object.defineProperties(browser.HTMLElement.prototype, {+ clientWidth: { configurable: true, get: () => width },+ clientHeight: { configurable: true, get: () => height },+ });+ Object.defineProperty(browser.HTMLCanvasElement.prototype, "getContext", {+ configurable: true,+ value: () => null,+ });+ mock.module("motion/react", () => ({+ useReducedMotion: () => reducedMotion,+ }));+ const core = await import("echarts/core");+ const nativeInit = core.init;+ type EventData = {+ seriesId?: string;+ seriesIndex?: number;+ name?: string;+ offsetX?: number;+ offsetY?: number;+ };+ type Action = {+ type: string;+ dataIndex?: number;+ seriesId?: string;+ seriesIndex?: number;+ };+ type Series = {+ id?: string;+ type?: string;+ stack?: string;+ data?: (+ | number+ | string+ | null+ | {+ name?: string;+ value: number | string;+ itemStyle?: { opacity?: number };+ }+ )[];+ lineStyle?: { color?: string; width?: number; opacity?: number };+ itemStyle?: { opacity?: number };+ };+ type PixelFinder = {+ gridIndex?: number;+ xAxisIndex?: number;+ yAxisIndex?: number;+ };+ type TooltipValue = {+ seriesId?: string;+ value?: number | string | null;+ axisValue?: string;+ name?: string;+ };+ type Option = {+ animation?: boolean;+ backgroundColor?: string;+ series?: Series[];+ tooltip?: {+ show?: boolean;+ trigger?: string;+ formatter?: (params: TooltipValue | TooltipValue[]) => string;+ };+ dataZoom?: { start: number; end: number }[];+ };+ class Events {+ listeners = new Map<string, Set<(event: EventData) => void>>();+ on(name: string, callback: (event: EventData) => void) {+ const callbacks = this.listeners.get(name) ?? new Set();+ callbacks.add(callback);+ this.listeners.set(name, callbacks);+ }+ off(name?: string, callback?: (event: EventData) => void) {+ if (!name) this.listeners.clear();+ else if (callback) this.listeners.get(name)?.delete(callback);+ else this.listeners.delete(name);+ }+ emit(name: string, event: EventData = {}) {+ for (const callback of this.listeners.get(name) ?? []) callback(event);+ }+ add() {}+ remove() {}+ }+ class TestChart extends Events {+ zr = new Events();+ options: Option[] = [];+ updates: { notMerge?: boolean; replaceMerge?: string[] }[] = [];+ actions: Action[] = [];+ silent: boolean[] = [];+ disposed = false;+ resizes = 0;+ width = width;+ height = height;+ constructor(readonly renderer: string) {+ super();+ }+ setOption(+ option: Option,+ update: { notMerge?: boolean; replaceMerge?: string[] } = {},+ ) {+ if (this.disposed) throw new Error("Chart update follows disposal.");+ this.options.push(option);+ this.updates.push(update);+ }+ getOption() {+ return this.options.at(-1) ?? {};+ }+ dispatchAction(action: Action, options?: { silent?: boolean }) {+ if (this.disposed) throw new Error("Chart action follows disposal.");+ this.actions.push(action);+ this.silent.push(options?.silent ?? false);+ }+ getWidth() {+ return this.width;+ }+ getHeight() {+ return this.height;+ }+ resize() {+ this.width = width;+ this.height = height;+ this.resizes += 1;+ }+ getZr() {+ return this.zr;+ }+ containPixel(_finder: PixelFinder, point: number[]) {+ return (point[0] ?? -1) >= 0 && (point[1] ?? -1) >= 0;+ }+ convertFromPixel(_finder: PixelFinder, point: number[]) {+ return point;+ }+ convertToPixel(_finder: PixelFinder, point: number | number[]) {+ return Array.isArray(point) ? point : point * 10;+ }+ dispose() {+ this.disposed = true;+ }+ isDisposed() {+ return this.disposed;+ }+ }+ const charts: TestChart[] = [];+ let nativeFixtures = false;+ const nativeInstances = new Set<ReturnType<typeof nativeInit>>();+ mock.module("echarts/core", () => ({+ ...core,+ init: (+ _element: HTMLElement,+ _theme: null,+ options: { renderer: string },+ ) => {+ if (nativeFixtures) {+ const instance = nativeInit(_element, null, {+ ...options,+ width: 500,+ height: 300,+ });+ nativeInstances.add(instance);+ return instance;+ }+ const chart = new TestChart(options.renderer);+ charts.push(chart);+ return chart;+ },+ }));+ const { createRoot } = await import("react-dom/client");+ const { EChartsAreaChart: Area } = await import(+ "../src/components/evilcharts/charts/echarts-area-chart"+ );+ const { EChartsBarChart: Bar } = await import(+ "../src/components/evilcharts/charts/echarts-bar-chart"+ );+ const { EChartsPieChart: Pie } = await import(+ "../src/components/evilcharts/charts/echarts-pie-chart"+ );+ const { finiteSum, finiteValue, buildChartCss, normalizeColor } =+ await import("../src/components/evilcharts/ui/echarts-chart");+ const { tooltipRow, tooltipShell, resolveTooltipPosition } = await import(+ "../src/components/evilcharts/ui/echarts-tooltip"+ );+ const { setChartOption } = await import(+ "../src/components/evilcharts/ui/echarts-options"+ );+ const { showActiveIndex, useChartLifecycle } = await import(+ "../src/components/evilcharts/ui/echarts-lifecycle"+ );++ const config = {+ amount: {+ label: "Amount",+ colors: { light: ["#123456"], dark: ["#abcdef"] },+ },+ };+ const roots: ReturnType<typeof createRoot>[] = [];+ function mount(children: ReactNode) {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ act(() => root.render(children));+ return { root, container };+ }+ function chart() {+ const last = charts.at(-1);+ if (!last) throw new Error("Chart is missing.");+ return last;+ }+ function fullOption() {+ const option = chart().options.findLast((option) =>+ option.series?.some((series) => series.type),+ );+ if (!option) throw new Error("Full chart option is missing.");+ return option;+ }+ function values(id: string) {+ return fullOption().series?.find((series) => series.id === id)?.data;+ }+ function flushFrames() {+ const callbacks = [...frames.values()];+ frames.clear();+ act(() => {+ callbacks.forEach((callback) => {+ callback(performance.now() + 100);+ });+ });+ }+ afterEach(() => {+ act(() => {+ roots.splice(0).forEach((root) => {+ root.unmount();+ });+ });+ expect(resizeObservers.size).toBe(0);+ expect(frames.size).toBe(0);+ expect(mediaSubscribers.size).toBe(0);+ for (const chart of charts) {+ expect(chart.disposed).toBe(true);+ expect(chart.listeners.size).toBe(0);+ expect(chart.zr.listeners.size).toBe(0);+ }+ nativeInstances.forEach((instance) => {+ expect(instance.isDisposed()).toBe(true);+ });+ nativeInstances.clear();+ nativeFixtures = false;+ charts.length = 0;+ document.body.replaceChildren();+ document.documentElement.className = "";+ reducedMotion = false;+ width = 500;+ height = 300;+ });++ test("area preserves missing values, finite numbers, and real zero", () => {+ mount(+ <Area+ data={[+ { day: "a", amount: 0 },+ { day: "b", amount: null },+ { day: "c", amount: Infinity },+ { day: "d", amount: Number.NaN },+ { day: "e", amount: 125 },+ ]}+ config={config}+ xDataKey="day"+ >+ <Area.Area dataKey="amount" />+ <Area.Tooltip+ valueFormatter={(value) => `$${(value / 100).toFixed(2)}`}+ />+ </Area>,+ );+ expect(values("amount")).toEqual([0, null, null, null, 125]);+ const formatter = fullOption().tooltip?.formatter;+ expect(+ formatter?.([{ seriesId: "amount", value: 125, axisValue: "a" }]),+ ).toContain("$1.25");+ expect(+ formatter?.([{ seriesId: "amount", value: null, axisValue: "a" }]),+ ).not.toContain("Amount");+ expect(chart().renderer).toBe("canvas");+ });++ test("committed props update options without replacing the chart or repeating entrance", () => {+ const view = (amount: number, formatter: (value: number) => string) => (+ <Area+ data={[{ day: "a", amount }]}+ config={config}+ chartOptions={{ backgroundColor: "transparent" }}+ >+ <Area.Area dataKey="amount" />+ <Area.Tooltip valueFormatter={formatter} />+ </Area>+ );+ const { root } = mount(view(100, () => "first"));+ expect(fullOption().animation).toBe(true);+ act(() => root.render(view(200, () => "second")));+ expect(charts.length).toBe(1);+ expect(values("amount")).toEqual([200]);+ expect(fullOption().animation).toBe(false);+ expect(fullOption().backgroundColor).toBe("transparent");+ expect(+ fullOption().tooltip?.formatter?.([{ seriesId: "amount", value: 200 }]),+ ).toContain("second");+ });++ test("renderer changes dispose callbacks and StrictMode preserves entrance on the surviving chart", () => {+ const view = (renderer: "canvas" | "svg") => (+ <StrictMode>+ <Bar+ data={[{ day: "a", amount: 2 }]}+ config={config}+ renderer={renderer}+ >+ <Bar.Bar dataKey="amount" isClickable />+ <Bar.Tooltip />+ </Bar>+ </StrictMode>+ );+ const { root } = mount(view("canvas"));+ expect(charts.length).toBe(2);+ expect(charts[0]?.disposed).toBe(true);+ expect(fullOption().animation).toBe(true);+ const previous = chart();+ act(() => root.render(view("svg")));+ expect(previous.disposed).toBe(true);+ expect(previous.listeners.size).toBe(0);+ expect(previous.zr.listeners.size).toBe(0);+ expect(chart().renderer).toBe("svg");+ expect(resizeObservers.size).toBe(1);+ });++ test("resize and theme changes use current committed options", async () => {+ const view = (amount: number) => (+ <Area data={[{ day: "a", amount }]} config={config}>+ <Area.Area dataKey="amount" />+ </Area>+ );+ const { root } = mount(view(1));+ act(() => root.render(view(7)));+ width = 650;+ height = 350;+ act(() => {+ resizeObservers.forEach((observer) => {+ observer.callback();+ });+ });+ expect(chart().resizes).toBe(1);+ expect(values("amount")).toEqual([7]);+ const before = chart().options.length;+ await act(async () => {+ document.documentElement.className = "dark";+ await browser.happyDOM.waitUntilComplete();+ });+ expect(chart().options.length).toBeGreaterThan(before);+ expect(values("amount")).toEqual([7]);+ expect(+ fullOption().series?.find((series) => series.id === "amount")?.lineStyle+ ?.color,+ ).toBe("#abcdef");+ });++ test("controlled active indices reject invalid values and clear without selection callbacks", () => {+ const selections: (string | null)[] = [];+ const view = (activeIndex: number | null) => (+ <Bar+ data={[+ { day: "a", amount: 0 },+ { day: "b", amount: 8 },+ ]}+ config={config}+ activeIndex={activeIndex}+ onSelectionChange={(key) => selections.push(key)}+ >+ <Bar.Bar dataKey="amount" isClickable />+ <Bar.Tooltip />+ </Bar>+ );+ const { root } = mount(view(1));+ expect(chart().actions.at(-1)).toMatchObject({+ type: "showTip",+ dataIndex: 1,+ });+ for (const index of [null, -1, 2, 0.5, Infinity]) {+ act(() => root.render(view(index)));+ expect(chart().actions.at(-1)?.type).toBe("hideTip");+ }+ expect(chart().silent.every(Boolean)).toBe(true);+ expect(selections).toEqual([]);+ });++ test("pointer hover survives first category render and restores keyboard focus on leave", () => {+ const hovered: (number | null)[] = [];+ function Interactive() {+ const [, setHovered] = useState<number | null>(null);+ return (+ <Area+ data={[+ { day: "a", amount: 5 },+ { day: "b", amount: 8 },+ ]}+ config={config}+ activeIndex={1}+ onHoverIndexChange={(index) => {+ hovered.push(index);+ setHovered(index);+ }}+ >+ <Area.Area dataKey="amount" />+ <Area.Tooltip />+ </Area>+ );+ }+ mount(<Interactive />);+ act(() => chart().zr.emit("mousemove", { offsetX: 0, offsetY: 5 }));+ expect(hovered).toEqual([0]);+ expect(chart().actions.at(-1)).toMatchObject({+ type: "showTip",+ dataIndex: 0,+ });+ expect(fullOption().animation).toBe(false);+ expect(chart().updates.at(-1)?.notMerge).not.toBe(true);+ expect(chart().updates.at(-1)?.replaceMerge).toContain("series");+ act(() => chart().zr.emit("mousemove", { offsetX: 0, offsetY: 5 }));+ expect(hovered).toEqual([0]);+ act(() => chart().zr.emit("globalout"));+ expect(hovered).toEqual([0, null]);+ expect(chart().actions.at(-1)).toMatchObject({+ type: "showTip",+ dataIndex: 1,+ });+ });++ test("bar selection uses the current callback once under StrictMode", () => {+ const first: (string | null)[] = [];+ const current: (string | null)[] = [];+ const view = (select: (key: string | null) => void) => (+ <StrictMode>+ <Bar+ data={[{ day: "a", amount: 5 }]}+ config={config}+ onSelectionChange={select}+ >+ <Bar.Bar dataKey="amount" isClickable />+ </Bar>+ </StrictMode>+ );+ const { root } = mount(view((key) => first.push(key)));+ act(() => root.render(view((key) => current.push(key))));+ act(() => chart().emit("click", { seriesId: "amount" }));+ act(() => chart().emit("click", { seriesId: "amount" }));+ expect(first).toEqual([]);+ expect(current).toEqual(["amount", null]);+ });++ test("bar and pie preserve missing values and pie active sectors stay bounded", () => {+ mount(+ <Bar+ data={[+ { day: "a", amount: 0 },+ { day: "b", amount: null },+ { day: "c", amount: Infinity },+ ]}+ config={config}+ >+ <Bar.Bar dataKey="amount" />+ </Bar>,+ );+ expect(values("amount")).toEqual([0, null, null]);+ const view = (activeSector: string | null) => (+ <Pie+ data={[+ { name: "amount", value: 125 },+ { name: "missing", value: null },+ { name: "zero", value: 0 },+ ]}+ config={config}+ dataKey="value"+ nameKey="name"+ activeSector={activeSector}+ >+ <Pie.Pie />+ <Pie.Tooltip+ valueFormatter={(value) => `$${(value / 100).toFixed(2)}`}+ />+ </Pie>+ );+ const { root } = mount(view("amount"));+ expect(fullOption().series?.[0]?.data).toMatchObject([+ { value: 125 },+ { value: "-" },+ { value: 0 },+ ]);+ expect(chart().actions.at(-1)).toMatchObject({+ type: "showTip",+ dataIndex: 0,+ });+ expect(+ fullOption().tooltip?.formatter?.({ name: "amount", value: 125 }),+ ).toContain("$1.25");+ act(() => root.render(view("absent")));+ expect(chart().actions.at(-1)?.type).toBe("hideTip");+ act(() => root.render(view(null)));+ expect(chart().actions.at(-1)?.type).toBe("hideTip");+ });++ test("pie selection preserves zero and rejects missing values", () => {+ const selected: ({ dataKey: string; value: number } | null)[] = [];+ mount(+ <Pie+ data={[+ { name: "zero", value: 0 },+ { name: "missing", value: null },+ { name: "invalid", value: Infinity },+ ]}+ config={config}+ nameKey="name"+ dataKey="value"+ onSelectionChange={(value) => selected.push(value)}+ >+ <Pie.Pie isClickable />+ </Pie>,+ );+ act(() => chart().emit("click", { name: "missing" }));+ act(() => chart().emit("click", { name: "invalid" }));+ expect(selected).toEqual([]);+ act(() => chart().emit("click", { name: "zero" }));+ expect(selected).toEqual([{ dataKey: "zero", value: 0 }]);+ });++ test("reduced motion stops native skeleton and animated dash loops", () => {+ reducedMotion = true;+ const view = (loading: boolean) => (+ <Area+ data={[{ day: "a", amount: 5 }]}+ config={config}+ isLoading={loading}+ >+ <Area.Area dataKey="amount" strokeVariant="animated-dashed" />+ </Area>+ );+ const { root, container } = mount(view(true));+ expect(values("__loading")?.length).toBeGreaterThan(0);+ expect(container.textContent).not.toContain("Loading");+ expect(container.querySelector(".animate-spin")).toBeNull();+ expect(frames.size).toBe(0);+ act(() => root.render(view(false)));+ expect(fullOption().animation).toBe(false);+ expect(frames.size).toBe(0);+ });++ test("reduced motion changes stop a running skeleton without a parent render", () => {+ mount(+ <Bar data={[{ day: "a", amount: 2 }]} config={config} isLoading>+ <Bar.Bar dataKey="amount" />+ </Bar>,+ );+ expect(frames.size).toBe(1);+ act(() => {+ reducedMotion = true;+ mediaSubscribers.forEach((notify) => {+ notify();+ });+ });+ expect(frames.size).toBe(0);+ expect(fullOption().animation).toBe(false);+ });++ test("suspended renders never expose speculative props to chart callbacks", () => {+ const committed: (string | null)[] = [];+ const speculative: (string | null)[] = [];+ const blocked = new Promise<never>(() => {});+ function Block({ suspend }: { suspend: boolean }) {+ if (suspend) throw blocked;+ return null;+ }+ const view = (suspend: boolean, select: (key: string | null) => void) => (+ <Suspense fallback={null}>+ <Bar+ data={[{ day: "a", amount: suspend ? 9 : 2 }]}+ config={config}+ onSelectionChange={select}+ >+ <Bar.Bar dataKey="amount" isClickable />+ </Bar>+ <Block suspend={suspend} />+ </Suspense>+ );+ const { root } = mount(view(false, (key) => committed.push(key)));+ act(() => {+ startTransition(() =>+ root.render(view(true, (key) => speculative.push(key))),+ );+ });+ expect(values("amount")).toEqual([2]);+ act(() => chart().emit("click", { seriesId: "amount" }));+ expect(committed).toEqual(["amount"]);+ expect(speculative).toEqual([]);+ });++ test("loading loops clean up after updates, renderer changes, and unmount", () => {+ const view = (renderer: "canvas" | "svg") => (+ <Pie+ data={[{ name: "amount", value: 2 }]}+ config={config}+ nameKey="name"+ dataKey="value"+ renderer={renderer}+ isLoading+ >+ <Pie.Pie />+ </Pie>+ );+ const { root } = mount(view("canvas"));+ expect(frames.size).toBe(1);+ flushFrames();+ act(() => root.render(view("svg")));+ expect(frames.size).toBe(1);+ expect(charts[0]?.disposed).toBe(true);+ flushFrames();+ });++ test("tooltip HTML escapes plain labels, values, and titles", () => {+ const text = `<img src=x onerror="alert('x')">&`;+ const row = tooltipRow({+ indicatorHtml: "<i></i>",+ labelText: text,+ valueText: text,+ dimmed: "",+ });+ const html = tooltipShell({+ label: text,+ body: row,+ roundness: "lg",+ variant: "default",+ });+ const container = document.createElement("div");+ container.innerHTML = html;+ expect(container.querySelector("img")).toBeNull();+ expect(container.querySelector("i")).not.toBeNull();+ expect(container.textContent?.split(text).length).toBe(4);+ mount(+ <Pie+ data={[{ name: text, value: 1 }]}+ config={{ [text]: { label: text } }}+ dataKey="value"+ nameKey="name"+ >+ <Pie.Pie />+ <Pie.Tooltip valueFormatter={() => text} />+ </Pie>,+ );+ container.innerHTML =+ fullOption().tooltip?.formatter?.({ name: text, value: 1 }) ?? "";+ expect(container.querySelector("img")).toBeNull();+ expect(container.textContent).toContain(text);+ });++ test("real ECharts renders generated area, bar, and pie options as SVG", () => {+ const views = [+ <Area+ key="area"+ data={[+ { day: "a", amount: 0 },+ { day: "b", amount: 3 },+ ]}+ config={config}+ >+ <Area.Area dataKey="amount" />+ <Area.XAxis dataKey="day" />+ <Area.YAxis />+ <Area.Grid />+ <Area.Tooltip />+ </Area>,+ <Bar+ key="bar"+ data={[+ { day: "a", amount: 0 },+ { day: "b", amount: 3 },+ ]}+ config={config}+ >+ <Bar.Bar dataKey="amount" variant="stripped" />+ <Bar.XAxis dataKey="day" />+ <Bar.YAxis />+ <Bar.Tooltip />+ </Bar>,+ <Pie+ key="pie"+ data={[{ name: "amount", value: 3 }]}+ config={config}+ nameKey="name"+ dataKey="value"+ >+ <Pie.Pie innerRadius="60%" />+ <Pie.Tooltip />+ </Pie>,+ ];+ for (const view of views) {+ mount(view);+ const instance = nativeInit(null, null, {+ renderer: "svg",+ ssr: true,+ width: 500,+ height: 300,+ });+ try {+ instance.setOption({ ...fullOption(), animation: false });+ const svg = instance.renderToSVGString();+ expect(svg).toContain("<svg");+ expect(svg).toContain("<path");+ expect(svg).not.toContain("NaN");+ expect(svg).not.toContain("undefined");+ } finally {+ instance.dispose();+ }+ }+ });++ test("keyboard tooltip actions resolve series IDs after inserted companion series", () => {+ mount(+ <Area+ data={[+ { day: "a", amount: 1 },+ { day: "b", amount: 2 },+ ]}+ config={config}+ activeIndex={1}+ enableHoverReveal+ >+ <Area.Area dataKey="amount" />+ <Area.Tooltip />+ </Area>,+ );+ expect(fullOption().series?.[0]?.id).toBe("__reveal-amount");+ expect(chart().actions.at(-1)).toMatchObject({+ type: "showTip",+ seriesIndex: 1,+ dataIndex: 1,+ });+ expect(chart().actions.at(-2)).toMatchObject({+ type: "highlight",+ seriesId: "amount",+ dataIndex: 1,+ });+ });++ test("replacing a container recreates the chart without remounting its hooks", () => {+ function Container({ revision }: { revision: number }) {+ const container = useRef<HTMLDivElement | null>(null);+ const setup = useCallback(() => {+ const instance = new TestChart("canvas");+ charts.push(instance);+ return () => {+ instance.dispose();+ };+ }, []);+ const ref = useChartLifecycle(+ { prepare: () => {}, setup, synchronize: () => {}, animate: [] },+ container,+ );+ return <div key={revision} ref={ref} />;+ }+ const { root } = mount(<Container revision={0} />);+ const previous = chart();+ act(() => root.render(<Container revision={1} />));+ expect(charts.length).toBe(2);+ expect(previous.disposed).toBe(true);+ expect(chart().disposed).toBe(false);+ });++ test("native updates preserve the tooltip view and remove obsolete series and brush axes", () => {+ const view = (extra: boolean) => (+ <Area+ data={[+ { day: "a", amount: 1, second: 2 },+ { day: "b", amount: 2, second: 3 },+ ]}+ config={{ ...config, second: config.amount }}+ >+ <Area.Area dataKey="amount" />+ {extra && <Area.Area dataKey="second" />}+ <Area.XAxis dataKey="day" />+ <Area.Tooltip />+ {extra && <Area.Brush />}+ </Area>+ );+ const { root } = mount(view(true));+ const instance = nativeInit(null, null, {+ renderer: "svg",+ ssr: true,+ width: 500,+ height: 300,+ });+ try {+ setChartOption(instance, { ...fullOption(), animation: false });+ const tooltip = instance.getModel().getComponent("tooltip");+ expect(instance.getOption().series.length).toBe(4);+ act(() => root.render(view(false)));+ setChartOption(instance, { ...fullOption(), animation: false });+ expect(instance.getModel().getComponent("tooltip")).toBe(tooltip);+ expect(+ instance+ .getOption()+ .series.filter(Boolean)+ .map((series: Series) => series.id),+ ).toEqual(["amount"]);+ expect(instance.getOption().xAxis.filter(Boolean).length).toBe(1);+ expect(instance.getOption().dataZoom.filter(Boolean).length).toBe(0);+ } finally {+ instance.dispose();+ }+ });++ test("native showTip actions display axis tooltip content through resolved series indices", () => {+ mount(+ <Area+ data={[+ { day: "a", amount: 125 },+ { day: "b", amount: 250 },+ ]}+ config={config}+ >+ <Area.Area dataKey="amount" />+ <Area.XAxis dataKey="day" />+ <Area.Tooltip+ valueFormatter={(value) => `USD ${(value / 100).toFixed(2)}`}+ />+ </Area>,+ );+ const container = document.createElement("div");+ document.body.append(container);+ const instance = nativeInit(container, null, {+ renderer: "svg",+ width: 500,+ height: 300,+ });+ try {+ setChartOption(instance, { ...fullOption(), animation: false });+ showActiveIndex(instance, 1, "amount");+ expect(container.textContent).toContain("USD 2.50");+ expect(instance.getOption().xAxis[0].axisPointer.status).toBe("show");+ } finally {+ instance.dispose();+ }+ });++ test("native pie keyboard navigation keeps every donut sector tooltip visible after refresh", async () => {+ nativeFixtures = true;+ const rows = [+ { name: "first", value: 6200000 },+ { name: "second", value: 3800000 },+ { name: "Decision maker in", value: 7600000 },+ { name: "fourth", value: 2400000 },+ ];+ function KeyboardPie() {+ const [index, setIndex] = useState<number | null>(null);+ return (+ <div+ role="application"+ aria-label="Donut keyboard test"+ onKeyDown={(event) => {+ if (event.key === "Home") setIndex(0);+ if (event.key === "ArrowRight")+ setIndex((previous) => ((previous ?? -1) + 1) % rows.length);+ if (event.key === "ArrowLeft")+ setIndex(+ (previous) => ((previous ?? 1) + rows.length - 1) % rows.length,+ );+ }}+ >+ <Pie+ data={rows}+ config={{}}+ nameKey="name"+ dataKey="value"+ renderer="svg"+ animation={false}+ activeSector={index === null ? null : rows[index]?.name}+ >+ <Pie.Pie+ innerRadius="72%"+ outerRadius="100%"+ cornerRadius={4}+ paddingAngle={2}+ />+ <Pie.Tooltip+ position="bottom"+ valueFormatter={(value) =>+ `$${(value / 100).toLocaleString("en-US")}`+ }+ />+ </Pie>+ </div>+ );+ }+ const { container } = mount(<KeyboardPie />);+ const host = container.firstElementChild;+ if (!host) throw new Error("Keyboard host is missing.");+ let expectedIndex = 0;+ for (const key of [+ "Home",+ "ArrowRight",+ "ArrowRight",+ "ArrowRight",+ "ArrowLeft",+ ]) {+ await act(async () => {+ host.dispatchEvent(+ new browser.KeyboardEvent("keydown", { key, bubbles: true }),+ );+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 150));+ const tooltip = container.querySelector(".grid.min-w-32")?.parentElement;+ expect(tooltip).not.toBeNull();+ expect(tooltip?.style.display).not.toBe("none");+ if (key === "Home") expectedIndex = 0;+ if (key === "ArrowRight")+ expectedIndex = (expectedIndex + 1) % rows.length;+ if (key === "ArrowLeft")+ expectedIndex = (expectedIndex + rows.length - 1) % rows.length;+ const expected = rows[expectedIndex];+ expect(tooltip?.textContent).toContain(expected?.name);+ expect(tooltip?.textContent).toContain(+ `$${((expected?.value ?? 0) / 100).toLocaleString("en-US")}`,+ );+ expect(tooltip?.querySelector(".font-medium.text-primary")).toBeNull();+ for (const label of tooltip?.querySelectorAll("span") ?? [])+ expect(label.textContent?.trim()).not.toBe("");+ }+ expect(container.textContent).toContain("$76,000");+ });++ test("native area pointer leave restores the keyboard tooltip after globalout", async () => {+ nativeFixtures = true;+ const rows = [+ { day: "Jun", amount: 11800000 },+ { day: "Jul", amount: 5000000 },+ ];+ const parts = [+ <Area.Area key="area" dataKey="amount" />,+ <Area.XAxis key="axis" dataKey="day" />,+ <Area.Tooltip key="tooltip" />,+ ];+ function PointerArea() {+ const [, setPointer] = useState<number | null>(null);+ return (+ <Area+ data={rows}+ config={config}+ renderer="svg"+ animation={false}+ activeIndex={0}+ onHoverIndexChange={setPointer}+ >+ {parts}+ </Area>+ );+ }+ const { container } = mount(<PointerArea />);+ const instance = [...nativeInstances].at(-1);+ if (!instance) throw new Error("Native chart is missing.");+ const point = instance.convertToPixel({ gridIndex: 0 }, [1, 5000000]);+ act(() =>+ instance+ .getZr()+ .trigger("mousemove", { offsetX: point[0], offsetY: point[1] }),+ );+ act(() => instance.getZr().trigger("globalout", {}));+ await new Promise<void>((resolve) => setTimeout(resolve, 150));+ expect(instance.getOption().xAxis[0].axisPointer.status).toBe("show");+ const tooltip = container.querySelector(".grid.min-w-32")?.parentElement;+ expect(tooltip?.style.display).not.toBe("none");+ expect(tooltip?.textContent).toContain("Jun");+ });++ test("bottom tooltip positions stay bounded and preserve fixed and variable modes", () => {+ const bottom = resolveTooltipPosition(+ "bottom",+ ) as TooltipComponentPositionCallback;+ const fixed = resolveTooltipPosition(+ "fixed",+ ) as TooltipComponentPositionCallback;+ const dom = document.createElement("div");+ const size = { contentSize: [120, 40], viewSize: [200, 168] };+ expect(bottom([10, 50], [], dom, null, size)).toEqual([0, 120]);+ expect(bottom([190, 50], [], dom, null, size)).toEqual([80, 120]);+ expect(+ bottom([50, 50], [], dom, null, {+ contentSize: [300, 200],+ viewSize: [200, 168],+ }),+ ).toEqual([-50, 0]);+ expect(fixed([100, 50], [], dom, null, size)).toEqual([40, 8]);+ expect(resolveTooltipPosition("variable")).toBeUndefined();+ });++ test("primitive values and theme arrays keep finite values and upstream color slots", () => {+ expect(+ [0, null, undefined, "5", false, Infinity, Number.NaN].map(finiteValue),+ ).toEqual([0, null, null, null, null, null, null]);+ expect(+ Number.isFinite(finiteSum([Number.MAX_VALUE, Number.MAX_VALUE])),+ ).toBe(true);+ expect(+ buildChartCss("chart-test", {+ amount: { colors: { light: ["red", "blue"], dark: ["white"] } },+ }),+ ).toContain("--color-amount-1: white;");+ expect(normalizeColor("oklch(0.6 0.1 150)")).toBe("oklch(0.6 0.1 150)");+ });+}diff --git a/packages/ui/test/form-sheet.spec.tsx b/packages/ui/test/form-sheet.spec.tsxnew file mode 100644index 00000000..220ed2b3--- /dev/null+++ b/packages/ui/test/form-sheet.spec.tsx@@ -0,0 +1,340 @@+import { afterEach, expect, test } from "bun:test";+import { Window } from "happy-dom";+import { type ReactNode, StrictMode, useState } from "react";++if (process.env.CRM_FORM_SHEET_TEST_CHILD !== "1") {+ test("form sheet behaviors pass in an isolated DOM", () => {+ const result = Bun.spawnSync(["bun", "test", import.meta.path], {+ env: { ...process.env, CRM_FORM_SHEET_TEST_CHILD: "1" },+ stdout: "pipe",+ stderr: "pipe",+ });+ expect(new TextDecoder().decode(result.stderr)).not.toContain("(fail)");+ expect(result.exitCode).toBe(0);+ });+} else {+ const browser = new Window({ url: "http://localhost" });+ Object.assign(globalThis, {+ window: browser,+ document: browser.document,+ navigator: browser.navigator,+ HTMLElement: browser.HTMLElement,+ HTMLInputElement: browser.HTMLInputElement,+ HTMLSelectElement: browser.HTMLSelectElement,+ HTMLTextAreaElement: browser.HTMLTextAreaElement,+ Node: browser.Node,+ NodeFilter: browser.NodeFilter,+ Element: browser.Element,+ Event: browser.Event,+ CustomEvent: browser.CustomEvent,+ MutationObserver: browser.MutationObserver,+ getComputedStyle: browser.getComputedStyle.bind(browser),+ CSS: browser.CSS,+ requestAnimationFrame: browser.requestAnimationFrame.bind(browser),+ cancelAnimationFrame: browser.cancelAnimationFrame.bind(browser),+ });++ const { createRoot } = await import("react-dom/client");+ const {+ FormSheet,+ FormSheetContent,+ FormSheetFooter,+ FormSheetForm,+ FormSheetHeader,+ useFormSheetValidation,+ } = await import("../src/components/form-sheet");+ const { SheetTrigger } = await import("../src/components/sheet");+ const { Field, FieldError, FieldLabel } = await import(+ "../src/components/field"+ );+ const { Input } = await import("../src/components/input");+ const roots: Array<ReturnType<typeof createRoot>> = [];++ afterEach(async () => {+ for (const root of roots.splice(0)) root.unmount();+ await settle();+ document.body.innerHTML = "";+ });++ function Fixture({ pending = false }: { pending?: boolean }) {+ const [open, setOpen] = useState(false);+ const [value, setValue] = useState("");+ return (+ <FormSheet+ open={open}+ onOpenChange={setOpen}+ dirty={value !== ""}+ pending={pending}+ onDiscard={() => setValue("")}+ >+ <SheetTrigger>New item</SheetTrigger>+ <FormSheetContent>+ <FormSheetHeader title="Create item" description="Add an item." />+ <FormSheetForm id="create-item">+ <Input+ aria-label="Name"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ <button type="button" onClick={() => setValue("Draft")}>+ Fill draft+ </button>+ <button type="button" onClick={() => setValue("")}>+ Clear draft+ </button>+ </FormSheetForm>+ <FormSheetFooter>+ <button type="submit" form="create-item">+ Save+ </button>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>+ );+ }++ async function render(element: ReactNode) {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ root.render(<StrictMode>{element}</StrictMode>);+ await settle();+ return root;+ }++ async function settle() {+ await new Promise((resolve) => setTimeout(resolve, 25));+ }++ async function click(label: string) {+ const button = [+ ...document.querySelectorAll<HTMLButtonElement>("button"),+ ].find((item) => item.textContent === label);+ expect(button).toBeDefined();+ button?.click();+ await settle();+ }++ async function pressEscape() {+ document.activeElement?.dispatchEvent(+ new browser.KeyboardEvent("keydown", {+ key: "Escape",+ bubbles: true,+ cancelable: true,+ }),+ );+ await settle();+ }++ function sheetOpen() {+ return (+ document.querySelector(+ '[data-slot="sheet-content"][data-state="open"]',+ ) !== null+ );+ }++ function questionOpen() {+ return (+ document.querySelector('[role="alertdialog"][data-state="open"]') !== null+ );+ }++ test("Escape closes a clean form and returns focus to its trigger", async () => {+ await render(<Fixture />);+ await click("New item");+ expect(sheetOpen()).toBe(true);+ await pressEscape();+ expect(sheetOpen()).toBe(false);+ expect(document.activeElement?.textContent).toBe("New item");+ });++ test("dirty close asks; Keep editing and confirmation Escape retain the draft", async () => {+ await render(<Fixture />);+ await click("New item");+ await click("Fill draft");+ await click("Close");+ expect(questionOpen()).toBe(true);+ expect(document.activeElement?.textContent).toBe("Keep editing");+ await click("Keep editing");+ expect(+ document.activeElement?.closest("[data-slot=sheet-content]"),+ ).not.toBeNull();+ expect(sheetOpen()).toBe(true);+ expect(+ document.querySelector<HTMLInputElement>('input[aria-label="Name"]')+ ?.value,+ ).toBe("Draft");+ await pressEscape();+ expect(questionOpen()).toBe(true);+ await pressEscape();+ expect(questionOpen()).toBe(false);+ expect(sheetOpen()).toBe(true);+ expect(+ document.querySelector<HTMLInputElement>('input[aria-label="Name"]')+ ?.value,+ ).toBe("Draft");+ });++ test("confirmed discard clears the draft before reopening", async () => {+ await render(<Fixture />);+ await click("New item");+ await click("Fill draft");+ await pressEscape();+ await click("Discard");+ expect(sheetOpen()).toBe(false);+ await click("New item");+ expect(+ document.querySelector<HTMLInputElement>('input[aria-label="Name"]')+ ?.value,+ ).toBe("");+ });++ test("Cancel clears a dirty draft without asking", async () => {+ await render(<Fixture />);+ await click("New item");+ await click("Fill draft");+ await click("Cancel");+ expect(sheetOpen()).toBe(false);+ expect(questionOpen()).toBe(false);+ await click("New item");+ expect(+ document.querySelector<HTMLInputElement>('input[aria-label="Name"]')+ ?.value,+ ).toBe("");+ });++ test("reverting the actual value removes the discard prompt", async () => {+ await render(<Fixture />);+ await click("New item");+ await click("Fill draft");+ await click("Clear draft");+ await pressEscape();+ expect(sheetOpen()).toBe(false);+ expect(questionOpen()).toBe(false);+ });++ test("pending forms block Close, Escape, Cancel, and duplicate submission", async () => {+ let submitted = 0;+ await render(+ <FormSheet+ defaultOpen+ pending+ dirty+ onDiscard={() => {+ throw new Error("Unexpected discard");+ }}+ >+ <FormSheetContent>+ <FormSheetHeader title="Pending form" description="Saving item." />+ <FormSheetForm+ id="pending"+ onSubmit={(event) => {+ event.preventDefault();+ submitted += 1;+ }}+ >+ <Input aria-label="Name" defaultValue="Draft" />+ </FormSheetForm>+ <FormSheetFooter>+ <button type="submit" form="pending">+ Save+ </button>+ </FormSheetFooter>+ </FormSheetContent>+ </FormSheet>,+ );+ await click("Close");+ await pressEscape();+ await click("Cancel");+ await click("Save");+ expect(sheetOpen()).toBe(true);+ expect(questionOpen()).toBe(false);+ expect(submitted).toBe(0);+ });++ test("outside pointer presses never close a clean or dirty form", async () => {+ await render(<Fixture />);+ await click("New item");+ for (const dirty of [false, true]) {+ if (dirty) await click("Fill draft");+ document.body.dispatchEvent(+ new browser.PointerEvent("pointerdown", {+ bubbles: true,+ cancelable: true,+ button: 0,+ }),+ );+ await settle();+ expect(sheetOpen()).toBe(true);+ expect(questionOpen()).toBe(false);+ }+ });++ function ValidationFixture({ onSubmit }: { onSubmit: () => void }) {+ const validation = useFormSheetValidation();+ return (+ <FormSheetForm+ noValidate+ onInput={validation.onInput}+ onSubmit={(event) => {+ event.preventDefault();+ if (validation.validate(event.currentTarget)) onSubmit();+ }}+ >+ <Field data-invalid={!!validation.errors.name}>+ <FieldLabel htmlFor="name">Name</FieldLabel>+ <Input+ id="name"+ required+ pattern=".*\S.*"+ aria-invalid={!!validation.errors.name}+ aria-describedby={validation.errors.name ? "name-error" : undefined}+ />+ <FieldError id="name-error">{validation.errors.name}</FieldError>+ </Field>+ <Field>+ <FieldLabel htmlFor="email">Email</FieldLabel>+ <Input id="email" type="email" />+ <FieldError>{validation.errors.email}</FieldError>+ </Field>+ <button type="submit">Save</button>+ </FormSheetForm>+ );+ }++ test("invalid submission shows native constraint errors, focuses the first field, and never calls submit", async () => {+ let submitted = 0;+ await render(+ <ValidationFixture+ onSubmit={() => {+ submitted += 1;+ }}+ />,+ );+ await click("Save");+ expect(submitted).toBe(0);+ expect(document.activeElement?.id).toBe("name");+ expect(document.querySelector('[id="name-error"]')?.textContent).not.toBe(+ "",+ );+ expect(+ document.querySelector('[id="name"]')?.getAttribute("aria-invalid"),+ ).toBe("true");+ const name = document.querySelector<HTMLInputElement>('[id="name"]');+ const email = document.querySelector<HTMLInputElement>('[id="email"]');+ if (!name || !email) throw new Error("Missing fields");+ name.value = " ";+ await click("Save");+ expect(submitted).toBe(0);+ name.value = "New item";+ email.value = "invalid";+ await click("Save");+ expect(submitted).toBe(0);+ expect(document.activeElement?.id).toBe("email");+ email.value = "[email protected]";+ await click("Save");+ expect(submitted).toBe(1);+ });+}diff --git a/packages/ui/test/settings-form-parity.spec.tsx b/packages/ui/test/settings-form-parity.spec.tsxnew file mode 100644index 00000000..cd9fceae--- /dev/null+++ b/packages/ui/test/settings-form-parity.spec.tsx@@ -0,0 +1,599 @@+import { afterEach, expect, mock, test } from "bun:test";+import { Window } from "happy-dom";+import {+ type ComponentProps,+ type ReactNode,+ StrictMode,+ useRef,+ useState,+} from "react";++if (process.env.CRM_SETTINGS_FORM_TEST_CHILD !== "1") {+ test("settings form behaviors pass in an isolated DOM", () => {+ const result = Bun.spawnSync(["bun", "test", import.meta.path], {+ env: { ...process.env, CRM_SETTINGS_FORM_TEST_CHILD: "1" },+ stdout: "pipe",+ stderr: "pipe",+ });+ expect(new TextDecoder().decode(result.stderr)).not.toContain("(fail)");+ expect(result.exitCode).toBe(0);+ });+} else {+ const browser = new Window({ url: "http://localhost" });+ Object.assign(globalThis, {+ window: browser,+ document: browser.document,+ navigator: browser.navigator,+ location: browser.location,+ history: browser.history,+ HTMLElement: browser.HTMLElement,+ HTMLInputElement: browser.HTMLInputElement,+ HTMLFormElement: browser.HTMLFormElement,+ HTMLSelectElement: browser.HTMLSelectElement,+ HTMLTextAreaElement: browser.HTMLTextAreaElement,+ Node: browser.Node,+ DocumentFragment: browser.DocumentFragment,+ NodeFilter: browser.NodeFilter,+ Element: browser.Element,+ Event: browser.Event,+ CustomEvent: browser.CustomEvent,+ MutationObserver: browser.MutationObserver,+ getComputedStyle: browser.getComputedStyle.bind(browser),+ CSS: browser.CSS,+ requestAnimationFrame: browser.requestAnimationFrame.bind(browser),+ cancelAnimationFrame: browser.cancelAnimationFrame.bind(browser),+ });+ const successes: string[] = [];+ const failures: string[] = [];+ const permission = { canConfigure: true, canManage: true, pending: false };+ const manualRates: Array<{ currency: string; rate: number }> = [];+ const submitted: Array<{+ providerId: string;+ issuer: string;+ domain: string;+ clientId: string;+ clientSecret: string;+ }> = [];+ mock.module("sonner", () => ({+ toast: {+ success: (message: string) => successes.push(message),+ error: (message: string) => failures.push(message),+ },+ }));+ mock.module("../../../apps/app/lib/trpc/client", () => ({+ useTRPC: () => ({+ sso: {+ settings: { queryOptions: () => ({}) },+ register: { mutationOptions: () => ({}) },+ },+ currency: {+ settings: { queryOptions: () => ({ kind: "currency" }) },+ setReportingCurrency: {+ mutationOptions: () => ({ kind: "currency-other" }),+ },+ setManualRate: {+ mutationOptions: (options: { onSuccess: () => Promise<void> }) => ({+ ...options,+ kind: "manual-rate",+ }),+ },+ removeManualRate: {+ mutationOptions: () => ({ kind: "currency-other" }),+ },+ refreshRates: { mutationOptions: () => ({ kind: "currency-other" }) },+ },+ apiKeys: {+ create: {+ mutationOptions: (options: {+ onSuccess: (key: typeof fixtureKey) => Promise<void>;+ }) => options,+ },+ },+ }),+ }));+ mock.module("../../../apps/app/lib/trpc/cache", () => ({+ useCrmCache: () => ({+ sso: async () => undefined,+ apiKeys: async () => undefined,+ currency: async () => undefined,+ }),+ }));+ mock.module("@tanstack/react-query", () => ({+ useQuery: (options: { kind?: string }) => ({+ data:+ options.kind === "currency"+ ? {+ reportingCurrency: "USD",+ refreshedAt: null,+ rates: [],+ inUse: [],+ unconverted: { count: 0, currencies: [] },+ catalog: [],+ canManage: permission.canManage,+ }+ : {+ canConfigure: permission.canConfigure,+ callbackBase: "https://example.test/sso",+ },+ }),+ useMutation: (options: {+ kind?: string;+ onSuccess?: (key: typeof fixtureKey) => Promise<void>;+ }) => ({+ isPending: permission.pending,+ mutate: (+ input: (typeof submitted)[number] | (typeof manualRates)[number],+ ) => {+ if (options.kind === "currency-other")+ throw new Error("Unexpected currency operation");+ if (options.kind === "manual-rate" && "currency" in input) {+ manualRates.push(input);+ void options.onSuccess?.(fixtureKey);+ } else if (options.onSuccess) void options.onSuccess(fixtureKey);+ else if ("providerId" in input) submitted.push(input);+ },+ }),+ }));+ const { createRoot } = await import("react-dom/client");+ const { NuqsTestingAdapter } = await import("nuqs/adapters/testing");+ const { CreatedApiKeyDialog } = await import(+ "../../../apps/app/app/(app)/[slug]/settings/api-keys/created-api-key-dialog"+ );+ const { CreateApiKeySheet } = await import(+ "../../../apps/app/app/(app)/[slug]/settings/api-keys/create-api-key-sheet"+ );+ const { CopyValue } = await import(+ "../../../apps/app/app/(app)/[slug]/settings/copy-value"+ );+ const { AddSsoProviderSheet } = await import(+ "../../../apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet"+ );+ const { CurrencySettings } = await import(+ "../../../apps/app/app/(app)/[slug]/settings/currencies/currency-settings"+ );+ const roots: Array<ReturnType<typeof createRoot>> = [];+ const fixtureKey = {+ id: "fixture-key-1",+ name: "Fixture key",+ start: "fixture",+ enabled: true,+ createdAt: "2026-10-26T00:00:00.000Z",+ lastRequest: null,+ expiresAt: null,+ key: "fixture-only-key",+ } satisfies NonNullable<ComponentProps<typeof CreatedApiKeyDialog>["apiKey"]>;++ afterEach(async () => {+ for (const root of roots.splice(0)) root.unmount();+ await settle();+ document.body.innerHTML = "";+ successes.length = 0;+ failures.length = 0;+ submitted.length = 0;+ manualRates.length = 0;+ permission.canConfigure = true;+ permission.canManage = true;+ permission.pending = false;+ clipboard(async () => undefined);+ });++ function clipboard(writeText: ((value: string) => Promise<void>) | null) {+ Object.defineProperty(browser.navigator, "clipboard", {+ configurable: true,+ value: writeText ? { writeText } : undefined,+ });+ }++ async function settle() {+ await new Promise((resolve) => setTimeout(resolve, 25));+ }++ async function render(element: ReactNode) {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ root.render(<StrictMode>{element}</StrictMode>);+ await settle();+ return root;+ }++ function button(label: string) {+ const scope =+ document.querySelector('[role="alertdialog"][data-state="open"]') ??+ document.querySelector(+ '[data-slot="dialog-content"][data-state="open"], [data-slot="sheet-content"][data-state="open"]',+ ) ??+ document;+ const found = [...scope.querySelectorAll<HTMLButtonElement>("button")].find(+ (item) => item.textContent?.trim() === label,+ );+ if (!found) throw new Error(`Missing button: ${label}`);+ return found;+ }++ async function click(label: string) {+ button(label).click();+ await settle();+ }++ async function pressEscape() {+ document.activeElement?.dispatchEvent(+ new browser.KeyboardEvent("keydown", {+ key: "Escape",+ bubbles: true,+ cancelable: true,+ }),+ );+ await settle();+ }++ function revealOpen() {+ return (+ document.querySelector(+ '[data-slot="dialog-content"][data-state="open"]',+ ) !== null+ );+ }++ function confirmationOpen() {+ return (+ document.querySelector('[role="alertdialog"][data-state="open"]') !== null+ );+ }++ function RevealFixture() {+ const [key, setKey] = useState<typeof fixtureKey | null>(fixtureKey);+ const trigger = useRef<HTMLButtonElement>(null);+ return (+ <>+ <button ref={trigger} type="button" onClick={() => setKey(fixtureKey)}>+ New API key+ </button>+ <CreatedApiKeyDialog+ apiKey={key}+ onOpenChange={(open) => {+ if (!open) setKey(null);+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ trigger.current?.focus();+ }}+ />+ </>+ );+ }++ for (const close of ["Done", "Close", "Escape"]) {+ test(`uncopied ${close} asks; Go back and confirmation Escape retain the fixture key`, async () => {+ await render(<RevealFixture />);+ if (close === "Escape") await pressEscape();+ else await click(close);+ expect(revealOpen()).toBe(true);+ expect(confirmationOpen()).toBe(true);+ expect(document.activeElement?.textContent).toBe("Go back to the key");+ await pressEscape();+ expect(confirmationOpen()).toBe(false);+ expect(revealOpen()).toBe(true);+ expect(+ document.activeElement?.closest('[data-slot="dialog-content"]'),+ ).not.toBeNull();+ expect(document.querySelector<HTMLInputElement>("input")?.value).toBe(+ fixtureKey.key,+ );+ await click("Done");+ await click("Go back to the key");+ expect(revealOpen()).toBe(true);+ await click("Done");+ await click("Close anyway");+ expect(revealOpen()).toBe(false);+ expect(document.activeElement?.textContent).toBe("New API key");+ });+ }++ test("outside presses never dismiss the one-time key", async () => {+ await render(<RevealFixture />);+ document.body.dispatchEvent(+ new browser.PointerEvent("pointerdown", {+ bubbles: true,+ cancelable: true,+ button: 0,+ }),+ );+ await settle();+ expect(revealOpen()).toBe(true);+ expect(confirmationOpen()).toBe(false);+ });++ for (const close of ["Done", "Close", "Escape"]) {+ test(`successful clipboard copying releases the ${close} guard`, async () => {+ const copied: string[] = [];+ clipboard(async (value) => {+ copied.push(value);+ });+ await render(<RevealFixture />);+ await click("Copy api key");+ expect(copied).toEqual([fixtureKey.key]);+ expect(successes).toEqual(["API key copied."]);+ if (close === "Escape") await pressEscape();+ else await click(close);+ expect(revealOpen()).toBe(false);+ expect(confirmationOpen()).toBe(false);+ expect(document.activeElement?.textContent).toBe("New API key");+ });+ }++ for (const failure of ["rejected", "unavailable"]) {+ test(`${failure} clipboard copying keeps the reveal guard active`, async () => {+ clipboard(+ failure === "rejected"+ ? async () => {+ throw new Error("Fixture clipboard failure");+ }+ : null,+ );+ await render(<RevealFixture />);+ await click("Copy api key");+ expect(successes).toHaveLength(0);+ expect(failures).toEqual([+ "Could not copy the api key. Select it instead.",+ ]);+ await click("Done");+ expect(revealOpen()).toBe(true);+ expect(confirmationOpen()).toBe(true);+ });+ }++ test("the guard remains active until the clipboard promise succeeds", async () => {+ let resolveCopy: (() => void) | undefined;+ clipboard(+ () =>+ new Promise<void>((resolve) => {+ resolveCopy = resolve;+ }),+ );+ await render(<RevealFixture />);+ await click("Copy api key");+ await click("Done");+ expect(confirmationOpen()).toBe(true);+ await click("Go back to the key");+ resolveCopy?.();+ await settle();+ await click("Done");+ expect(revealOpen()).toBe(false);+ });++ test("a newly revealed key requires its own successful copy", async () => {+ clipboard(async () => undefined);+ const root = await render(+ <CreatedApiKeyDialog+ apiKey={fixtureKey}+ onOpenChange={() => undefined}+ />,+ );+ await click("Copy api key");+ root.render(+ <StrictMode>+ <CreatedApiKeyDialog+ apiKey={{+ ...fixtureKey,+ id: "fixture-key-2",+ key: "second-fixture-only-key",+ }}+ onOpenChange={() => undefined}+ />+ </StrictMode>,+ );+ await settle();+ await click("Done");+ expect(confirmationOpen()).toBe(true);+ });++ test("existing copy consumers work without a callback; callbacks run only after successful copying", async () => {+ const copied: string[] = [];+ clipboard(async (value) => {+ copied.push(value);+ });+ await render(+ <>+ <CopyValue value="first fixture" label="First" />+ <CopyValue+ value="second fixture"+ label="Second"+ onCopied={() => copied.push("callback")}+ />+ </>,+ );+ await click("Copy first");+ await click("Copy second");+ expect(copied).toEqual(["first fixture", "second fixture", "callback"]);+ expect(successes).toEqual(["First copied.", "Second copied."]);+ });++ async function renderSso(canConfigure = true) {+ permission.canConfigure = canConfigure;+ await render(+ <NuqsTestingAdapter searchParams="?new=true" hasMemory>+ <AddSsoProviderSheet />+ </NuqsTestingAdapter>,+ );+ expect(+ document.querySelector('[data-slot="sheet-content"][data-state="open"]'),+ ).not.toBeNull();+ }++ function input(label: string) {+ const fieldLabel = [+ ...document.querySelectorAll<HTMLLabelElement>("label"),+ ].find((item) => item.textContent === label);+ const field = fieldLabel?.htmlFor+ ? document.getElementById(fieldLabel.htmlFor)+ : null;+ if (!(field instanceof HTMLInputElement))+ throw new Error(`Missing input: ${label}`);+ return field;+ }++ async function fill(label: string, value: string) {+ const field = input(label);+ const setter = Object.getOwnPropertyDescriptor(+ browser.HTMLInputElement.prototype,+ "value",+ )?.set;+ setter?.call(field, value);+ field.dispatchEvent(new browser.Event("input", { bubbles: true }));+ field.dispatchEvent(new browser.Event("change", { bubbles: true }));+ await settle();+ }++ for (const copied of [false, true]) {+ test(`actual API-key creation returns focus to its trigger after ${copied ? "copied" : "confirmed uncopied"} close`, async () => {+ clipboard(async () => undefined);+ await render(+ <NuqsTestingAdapter hasMemory>+ <CreateApiKeySheet />+ </NuqsTestingAdapter>,+ );+ await click("New API key");+ await fill("Name", "Fixture key");+ await click("Create key");+ expect(revealOpen()).toBe(true);+ if (copied) await click("Copy api key");+ await click("Done");+ if (!copied) await click("Close anyway");+ expect(revealOpen()).toBe(false);+ expect(document.activeElement?.textContent).toBe("New API key");+ });+ }++ test("actual SSO form enables invalid submission, shows adjacent errors, focuses Name, and sends no registration", async () => {+ await renderSso();+ expect(button("Add provider").disabled).toBe(false);+ await click("Add provider");+ expect(submitted).toHaveLength(0);+ expect(document.querySelectorAll('[data-slot="field-error"]')).toHaveLength(+ 5,+ );+ expect(document.activeElement).toBe(input("Name"));+ for (const label of [+ "Name",+ "Issuer URL",+ "Email domain",+ "Client ID",+ "Client secret",+ ]) {+ const field = input(label);+ expect(field.getAttribute("aria-invalid")).toBe("true");+ expect(+ document.getElementById(field.getAttribute("aria-describedby") ?? "")+ ?.textContent,+ ).not.toBe("");+ }+ });++ test("actual SSO form blocks invalid URL and whitespace; valid fixture values reach only the mocked mutation", async () => {+ await renderSso();+ await fill("Name", " Fixture-Provider ");+ await fill("Issuer URL", "invalid-url");+ await fill("Email domain", " example.test ");+ await fill("Client ID", " fixture-client ");+ await fill("Client secret", "fixture-secret");+ await click("Add provider");+ expect(submitted).toHaveLength(0);+ expect(document.activeElement).toBe(input("Issuer URL"));+ await fill("Issuer URL", "https://issuer.example.test");+ await fill("Client secret", " ");+ await click("Add provider");+ expect(submitted).toHaveLength(0);+ expect(document.activeElement).toBe(input("Client secret"));+ await fill("Client secret", " fixture-secret ");+ await click("Add provider");+ expect(submitted).toEqual([+ {+ providerId: "fixture-provider",+ issuer: "https://issuer.example.test",+ domain: "example.test",+ clientId: "fixture-client",+ clientSecret: "fixture-secret",+ },+ ]);+ });++ test("actual SSO permission gate blocks both the button and direct form submission", async () => {+ await renderSso(false);+ expect(button("Add provider").disabled).toBe(true);+ await fill("Name", "fixture-provider");+ await fill("Issuer URL", "https://issuer.example.test");+ await fill("Email domain", "example.test");+ await fill("Client ID", "fixture-client");+ await fill("Client secret", "fixture-secret");+ document+ .querySelector("form")+ ?.dispatchEvent(+ new browser.Event("submit", { bubbles: true, cancelable: true }),+ );+ await settle();+ expect(submitted).toHaveLength(0);+ });+ async function chooseRateCurrency() {+ const form = document.getElementById("manual-rate");+ const trigger = form?.querySelector<HTMLButtonElement>('[role="combobox"]');+ if (!trigger) throw new Error("Missing currency picker");+ trigger.click();+ await settle();+ const option = [+ ...document.querySelectorAll<HTMLElement>('[role="option"]'),+ ].find((item) => item.textContent?.startsWith("EUR"));+ if (!option) throw new Error("Missing EUR option");+ option.click();+ await settle();+ }++ test("actual manual-rate form enables empty submit and shows adjacent currency and rate errors", async () => {+ await render(<CurrencySettings />);+ expect(button("Save rate").disabled).toBe(false);+ await click("Save rate");+ expect(manualRates).toHaveLength(0);+ expect(document.querySelectorAll('[data-slot="field-error"]')).toHaveLength(+ 2,+ );+ expect(document.activeElement).toBe(+ document.querySelector('#manual-rate [role="combobox"]'),+ );+ });++ test("actual manual-rate form blocks nonpositive and nonfinite rates; valid input reaches only the mock", async () => {+ await render(<CurrencySettings />);+ await chooseRateCurrency();+ for (const value of ["", " ", "bad-rate", "0", "-1", "Infinity"]) {+ await fill("1 EUR = ? USD", value);+ await click("Save rate");+ expect(manualRates).toHaveLength(0);+ expect(input("1 EUR = ? USD").getAttribute("aria-invalid")).toBe("true");+ expect(document.activeElement).toBe(input("1 EUR = ? USD"));+ }+ await fill("1 EUR = ? USD", "1.09");+ await click("Save rate");+ expect(manualRates).toEqual([{ currency: "EUR", rate: 1.09 }]);+ expect(input("1 unit = ? USD").value).toBe("");+ expect(document.querySelectorAll('[data-slot="field-error"]')).toHaveLength(+ 0,+ );+ });++ for (const denied of ["permission", "pending"]) {+ test(`actual manual-rate ${denied} restriction blocks direct submission`, async () => {+ permission.canManage = denied !== "permission";+ permission.pending = denied === "pending";+ await render(<CurrencySettings />);+ expect(button("Save rate").disabled).toBe(true);+ document+ .getElementById("manual-rate")+ ?.dispatchEvent(+ new browser.Event("submit", { bubbles: true, cancelable: true }),+ );+ await settle();+ expect(manualRates).toHaveLength(0);+ });+ }+}diff --git a/packages/ui/test/table-controls.spec.tsx b/packages/ui/test/table-controls.spec.tsxnew file mode 100644index 00000000..66a62c6f--- /dev/null+++ b/packages/ui/test/table-controls.spec.tsx@@ -0,0 +1,72 @@+import { expect, test } from "bun:test";+import { NuqsTestingAdapter } from "nuqs/adapters/testing";+import { renderToStaticMarkup } from "react-dom/server";+import { DataTable } from "../src/components/data-table";+import { TooltipProvider } from "../src/components/tooltip";+import type { TableQueryState } from "../src/lib/table-query";++const query: TableQueryState = {+ sort: "name",+ dir: "asc",+ page: 1,+ pageSize: 25,+ tab: "all",+ filters: {},+ toggleSort: () => undefined,+ setSort: () => undefined,+ setDir: () => undefined,+ setPage: async () => undefined,+ setTab: () => undefined,+ setFilter: () => undefined,+};++test("empty archived lists keep status, filters, sort, and column controls", () => {+ const html = renderToStaticMarkup(+ <TooltipProvider>+ <NuqsTestingAdapter searchParams="?archived=true">+ <DataTable+ label="Deals"+ query={query}+ columns={[+ {+ id: "name",+ header: "Name",+ sortable: true,+ cell: (row: { id: string; name: string }) => row.name,+ },+ ]}+ getRowId={(row) => row.id}+ rows={[]}+ total={0}+ tabs={{+ id: "status",+ label: "Status",+ options: [+ { value: "open", label: "Open" },+ { value: "closed", label: "Closed" },+ ],+ }}+ facets={[+ {+ id: "stage",+ label: "Stage",+ options: [],+ },+ ]}+ actions={+ <button type="button" aria-pressed>+ Archived+ </button>+ }+ />+ </NuqsTestingAdapter>+ </TooltipProvider>,+ );+ for (const label of ["Status", "Filters", "Sort", "Columns", "Archived"]) {+ expect(html).toContain(label);+ }+ expect(html).toContain('aria-pressed="true"');+ expect(html).toMatch(+ /<button(?=[^>]*disabled="")[^>]*>(?:(?!<\/button>).)*Filters/s,+ );+});diff --git a/packages/ui/test/table-pagination.spec.tsx b/packages/ui/test/table-pagination.spec.tsxnew file mode 100644index 00000000..96b1cd12--- /dev/null+++ b/packages/ui/test/table-pagination.spec.tsx@@ -0,0 +1,141 @@+import { afterEach, expect, test } from "bun:test";+import { Window } from "happy-dom";+import { StrictMode, useState } from "react";++if (process.env.CRM_PAGINATION_TEST_CHILD !== "1") {+ test("pagination focus passes in an isolated DOM", () => {+ const result = Bun.spawnSync(["bun", "test", import.meta.path], {+ env: { ...process.env, CRM_PAGINATION_TEST_CHILD: "1" },+ stdout: "pipe",+ stderr: "pipe",+ });+ expect(new TextDecoder().decode(result.stderr)).not.toContain("(fail)");+ expect(result.exitCode).toBe(0);+ });+} else {+ const browser = new Window({ url: "http://localhost" });+ Object.assign(globalThis, {+ window: browser,+ document: browser.document,+ navigator: browser.navigator,+ HTMLElement: browser.HTMLElement,+ });+ const { createRoot } = await import("react-dom/client");+ const { flushSync } = await import("react-dom");+ const { TablePagination } = await import(+ "../src/components/table-pagination"+ );+ const roots: Array<ReturnType<typeof createRoot>> = [];++ afterEach(() => {+ flushSync(() => {+ for (const root of roots.splice(0)) root.unmount();+ });+ document.body.innerHTML = "";+ });++ function Fixture({+ initialPage,+ pages,+ }: {+ initialPage: number;+ pages: number;+ }) {+ const [page, setPage] = useState(initialPage);+ return (+ <TablePagination+ page={page}+ totalPages={pages}+ pageSize={25}+ total={pages * 25}+ onPageChange={setPage}+ />+ );+ }++ function render(initialPage: number, pages: number) {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ flushSync(() => {+ root.render(+ <StrictMode>+ <Fixture initialPage={initialPage} pages={pages} />+ </StrictMode>,+ );+ });+ const [previous, next] = container.querySelectorAll("button");+ if (!previous || !next) throw new Error("Paging controls are missing.");+ return { previous, next };+ }++ test("reaching the final page moves focus from disabled Next to Previous", () => {+ const { previous, next } = render(1, 2);+ next.focus();+ flushSync(() => next.click());+ expect(next.disabled).toBe(true);+ expect(previous.disabled).toBe(false);+ expect(document.activeElement).toBe(previous);+ });++ test("reaching the first page moves focus from disabled Previous to Next", () => {+ const { previous, next } = render(2, 2);+ previous.focus();+ flushSync(() => previous.click());+ expect(previous.disabled).toBe(true);+ expect(next.disabled).toBe(false);+ expect(document.activeElement).toBe(next);+ });++ test("intermediate pages keep focus on the active paging control", () => {+ const { next } = render(1, 3);+ next.focus();+ flushSync(() => next.click());+ expect(next.disabled).toBe(false);+ expect(document.activeElement).toBe(next);+ });++ test("programmatic page changes preserve focus outside pagination", () => {+ const { next } = render(1, 2);+ const input = document.createElement("input");+ document.body.append(input);+ input.focus();+ flushSync(() => next.click());+ expect(next.disabled).toBe(true);+ expect(document.activeElement).toBe(input);+ });++ test("delayed page changes preserve a newer focus choice", () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ let requested = 1;+ const renderPage = (page: number) =>+ flushSync(() => {+ root.render(+ <TablePagination+ page={page}+ totalPages={2}+ pageSize={25}+ total={45}+ onPageChange={(next) => {+ requested = next;+ }}+ />,+ );+ });+ renderPage(1);+ const next = container.querySelectorAll("button")[1];+ if (!next) throw new Error("Next is missing.");+ next.focus();+ next.click();+ const input = document.createElement("input");+ document.body.append(input);+ input.focus();+ renderPage(requested);+ expect(next.disabled).toBe(true);+ expect(document.activeElement).toBe(input);+ });+}diff --git a/packages/validation/package.json b/packages/validation/package.jsonindex dd659a48..ce55c4b3 100644--- a/packages/validation/package.json+++ b/packages/validation/package.json@@ -19,7 +19,8 @@"./eve-tool": "./src/eve-tool.ts","./field-backfill": "./src/field-backfill.ts","./field-templates": "./src/field-templates.ts",- "./saved-view": "./src/saved-view.ts"+ "./saved-view": "./src/saved-view.ts",+ "./search-config": "./src/search-config.ts"},"scripts": {"check-types": "tsc --noEmit",diff --git a/packages/validation/src/search-config.ts b/packages/validation/src/search-config.tsnew file mode 100644index 00000000..0ee0f2eb--- /dev/null+++ b/packages/validation/src/search-config.ts@@ -0,0 +1,4 @@+export const QUICK_SEARCH = {+ query: { minLength: 2, maxLength: 120 },+ results: { perKind: 5 },+} as const;