OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): new realtime map, modals and form fields (#582)
Carl-Gerhard Lindesvärd8ecb30492f5e
diff --git a/apps/start/e2e/auth-login.spec.ts b/apps/start/e2e/auth-login.spec.tsindex be8694061..161beb6b7 100644--- a/apps/start/e2e/auth-login.spec.ts+++ b/apps/start/e2e/auth-login.spec.ts@@ -62,22 +62,20 @@ test('the login form validates before it calls the API', async ({ page }) => {});await gotoHydrated(page, '/login');+ const fieldErrors = page.locator('[data-slot="field-error"]');await page.getByRole('button', { name: 'Sign in', exact: true }).click();- await expect(page.getByText('Issues')).toHaveCount(2);- await page.getByText('Issues').first().hover();- await expect(page.getByRole('tooltip')).toContainText(- 'Invalid email address'- );+ await expect(fieldErrors).toHaveCount(2);+ await expect(fieldErrors.first()).toHaveText('Invalid email address');await page.getByLabel('Email').fill('not-an-email');await page.getByLabel('Password').fill('short');await page.getByLabel('Password').press('Enter');- await expect(page.getByText('Issues')).toHaveCount(2);+ await expect(fieldErrors).toHaveCount(2);await page.getByLabel('Email').fill('[email protected]');await page.getByLabel('Password').fill('long-enough-password');await page.getByLabel('Email').press('Tab');- await expect(page.getByText('Issues')).toHaveCount(0);+ await expect(fieldErrors).toHaveCount(0);await expect(page.getByRole('link', { name: 'Create one today' })diff --git a/apps/start/e2e/org-members.spec.ts b/apps/start/e2e/org-members.spec.tsindex e77074622..44ab84004 100644--- a/apps/start/e2e/org-members.spec.ts+++ b/apps/start/e2e/org-members.spec.ts@@ -191,11 +191,12 @@ test('invite validation: bad email, existing member, duplicate', async ({await gotoHydrated(page, `/${seed.organizationId}/members/invitations`);const sheet = await openInviteSheet(page);+ const emailError = sheet.locator('[data-slot="field-error"]');await sendInvite(sheet);- await expect(sheet.getByText('Issues')).toBeVisible();+ await expect(emailError).toBeVisible();await sheet.getByLabel('Email').fill('not-an-email');await sendInvite(sheet);- await expect(sheet.getByText('Issues')).toBeVisible();+ await expect(emailError).toBeVisible();await sheet.getByLabel('Email').fill(seed.user.email.toUpperCase());await sendInvite(sheet);diff --git a/apps/start/e2e/org-settings.spec.ts b/apps/start/e2e/org-settings.spec.tsindex eb4469007..015872db4 100644--- a/apps/start/e2e/org-settings.spec.ts+++ b/apps/start/e2e/org-settings.spec.ts@@ -105,7 +105,7 @@ test('a too short name gets a readable validation message', async ({await page.getByLabel('Name').fill('A');await saveButton(page).click();const toast = page.locator('[data-sonner-toast]').first();- const inlineError = page.getByText('Issues');+ const inlineError = page.locator('[data-slot="field-error"]');await expect(toast.or(inlineError).first()).toBeVisible();await shot(page, 'settings-short-name');expect((await getOrganization(page, seed.organizationId)).name).toBe(diff --git a/apps/start/e2e/reports-builder.spec.ts b/apps/start/e2e/reports-builder.spec.tsindex 53f012507..0fdebf51b 100644--- a/apps/start/e2e/reports-builder.spec.ts+++ b/apps/start/e2e/reports-builder.spec.ts@@ -53,7 +53,7 @@ test('linear report: build, compare with the API, save, reload, edit, update', aawait addEvent(page, 'purchase');await addEvent(page, 'add_to_cart');const sheet = await openSidebar(page);- await sheet.getByRole('button', { name: 'Select breakdown' }).click();+ await sheet.getByRole('button', { name: 'Add breakdown' }).click();await page.getByRole('menuitem', { name: 'Event properties' }).click();await page.getByPlaceholder('Search').last().fill('device');await pagediff --git a/apps/start/e2e/reports-funnel-step-breakdown.spec.ts b/apps/start/e2e/reports-funnel-step-breakdown.spec.tsindex 1cbc29df9..8c451dc97 100644--- a/apps/start/e2e/reports-funnel-step-breakdown.spec.ts+++ b/apps/start/e2e/reports-funnel-step-breakdown.spec.ts@@ -39,7 +39,7 @@ test('a funnel breaks down by a property that only exists on its last step', asy}const sheet = await openSidebar(page);- await sheet.getByRole('button', { name: 'Select breakdown' }).click();+ await sheet.getByRole('button', { name: 'Add breakdown' }).click();await page.getByRole('menuitem', { name: 'Event properties' }).click();await page.getByPlaceholder('Search').last().fill('payment');await pagediff --git a/apps/start/package.json b/apps/start/package.jsonindex 688e49036..fde6ae85a 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -108,7 +108,10 @@"d3-array": "3.2.4","d3-geo": "3.1.1","d3-sankey": "0.12.3",+ "d3-selection": "3.0.0","d3-shape": "3.2.0",+ "d3-transition": "3.0.1",+ "d3-zoom": "3.0.0","date-fns": "3.3.1","debounce": "2.2.0","embla-carousel-autoplay": "8.6.0",@@ -143,7 +146,6 @@"react-markdown": "10.1.0","react-redux": "8.1.3","react-responsive": "9.0.2",- "react-simple-maps": "3.0.0","react-svg-worldmap": "2.0.0-alpha.16","react-syntax-highlighter": "15.5.0","react-use-websocket": "4.7.0",@@ -161,10 +163,12 @@"tailwind-merge": "3.3.1","tailwindcss": "4.1.12","tailwindcss-animate": "1.0.7",+ "topojson-client": "3.1.0","tw-animate-css": "1.3.7","use-stick-to-bottom": "1.1.3","usehooks-ts": "2.14.0","vite-tsconfig-paths": "5.1.4",+ "world-atlas": "2.0.2","zod": "catalog:"},"devDependencies": {@@ -179,7 +183,10 @@"@types/d3-array": "3.2.2","@types/d3-geo": "3.1.1","@types/d3-sankey": "0.12.5",+ "@types/d3-selection": "3.0.11","@types/d3-shape": "3.2.0",+ "@types/d3-transition": "3.0.9",+ "@types/d3-zoom": "3.0.8","@types/geojson": "7946.0.16","@types/lodash.debounce": "4.0.9","@types/lodash.isequal": "4.5.8",@@ -187,8 +194,9 @@"@types/ramda": "0.31.0","@types/react": "catalog:","@types/react-dom": "catalog:",- "@types/react-simple-maps": "3.0.4","@types/react-syntax-highlighter": "15.5.11",+ "@types/topojson-client": "3.1.5",+ "@types/topojson-specification": "1.0.5","@vitejs/plugin-react": "5.2.0","jsdom": "26.1.0","typescript": "catalog:",diff --git a/apps/start/src/components/auth/sign-in-email-form.tsx b/apps/start/src/components/auth/sign-in-email-form.tsxindex 942dcde14..116e831ea 100644--- a/apps/start/src/components/auth/sign-in-email-form.tsx+++ b/apps/start/src/components/auth/sign-in-email-form.tsx@@ -57,13 +57,11 @@ export function SignInEmailForm({><InputWithLabel{...form.register('email')}- className="border-def-300 bg-def-100/50 focus:border-highlight focus:ring-highlight/20"error={form.formState.errors.email?.message}label="Email"/><InputWithLabel{...form.register('password')}- className="border-def-300 bg-def-100/50 focus:border-highlight focus:ring-highlight/20"error={form.formState.errors.password?.message}label="Password"type="password"diff --git a/apps/start/src/components/forms/input-with-label.test.tsx b/apps/start/src/components/forms/input-with-label.test.tsxnew file mode 100644index 000000000..49e0c9728--- /dev/null+++ b/apps/start/src/components/forms/input-with-label.test.tsx@@ -0,0 +1,75 @@+// @vitest-environment jsdom++// A label with spaces used to become the field's id, and aria-describedby+// splits on spaces, so the input never pointed at its hint or error.++import { render } from '@testing-library/react';+import { describe, expect, test } from 'vitest';+import { fieldMessageId, InputWithLabel, WithLabel } from './input-with-label';++describe('InputWithLabel', () => {+ test('ties the label and the message to the input with single-token ids', () => {+ const { container } = render(+ <InputWithLabel error="Required" label="Client name" />+ );+ const input = container.querySelector('input');+ const label = container.querySelector('label');+ const message = container.querySelector('[data-slot="field-error"]');++ expect(input?.id).toBeTruthy();+ expect(input?.id).not.toMatch(/\s/);+ expect(label?.getAttribute('for')).toBe(input?.id);+ expect(input?.getAttribute('aria-describedby')).toBe(message?.id);+ expect(message?.id).not.toMatch(/\s/);+ });++ test('keeps a caller-supplied id and description and adds the message to them', () => {+ const { container } = render(+ <InputWithLabel+ aria-describedby="outside-note"+ error="Required"+ id="client-name"+ label="Client name"+ />+ );+ const input = container.querySelector('input');+ expect(input?.id).toBe('client-name');+ expect(container.querySelector('label')?.getAttribute('for')).toBe(+ 'client-name'+ );+ expect(input?.getAttribute('aria-describedby')).toBe(+ 'outside-note client-name-message'+ );+ });++ test('omits aria-describedby when there is nothing to describe', () => {+ const { container } = render(<InputWithLabel label="Client name" />);+ expect(+ container.querySelector('input')?.hasAttribute('aria-describedby')+ ).toBe(false);+ });+});++describe('WithLabel', () => {+ test('lets a caller point its own control at the label and hint', () => {+ const { container } = render(+ <WithLabel+ hint="Shown under the field"+ id="client-type"+ label="Type of client"+ >+ <button+ aria-describedby={fieldMessageId('client-type')}+ id="client-type"+ type="button"+ />+ </WithLabel>+ );+ expect(container.querySelector('label')?.getAttribute('for')).toBe(+ 'client-type'+ );+ expect(container.querySelector('[data-slot="field-hint"]')?.id).toBe(+ container.querySelector('button')?.getAttribute('aria-describedby')+ );+ });+});diff --git a/apps/start/src/components/forms/input-with-label.tsx b/apps/start/src/components/forms/input-with-label.tsxindex 828a02a4d..9e43aa782 100644--- a/apps/start/src/components/forms/input-with-label.tsx+++ b/apps/start/src/components/forms/input-with-label.tsx@@ -1,64 +1,94 @@-import { BanIcon, InfoIcon } from 'lucide-react';-import { forwardRef } from 'react';+import { InfoIcon } from 'lucide-react';+import { forwardRef, useId } from 'react';import type { InputProps } from '../ui/input';import { Input } from '../ui/input';import { Label } from '../ui/label';import { Tooltiper } from '../ui/tooltip';+import { cn } from '@/utils/cn';interface WithLabel {children: React.ReactNode;label: string;+ /** The control's id, so the label and message point at it; defaults to the label text. */+ id?: string;error?: string | undefined;+ /** Shown under the field; replaced by the error while there is one. */+ hint?: React.ReactNode;info?: React.ReactNode;className?: string;}type InputWithLabelProps = InputProps & Omit<WithLabel, 'children'>;+/** Spaces would split an aria-describedby reference, so the id is made of one token. */+export function fieldMessageId(fieldId: string) {+ return `${fieldId.replace(/\s+/g, '-')}-message`;+}+export const WithLabel = ({children,className,label,+ id,+ hint,info,error,}: WithLabel) => {+ const message = error ?? hint;+ const fieldId = id ?? label;return (- <div className={className}>- <div className="mb-2 flex items-end justify-between">- <Label- className="mb-0 flex flex-1 shrink-0 items-center gap-1 whitespace-nowrap"- htmlFor={label}- >- {label}- {info && (- <Tooltiper content={info}>- <InfoIcon size={14} />- </Tooltiper>- )}- </Label>- {error && (- <Tooltiper- align="end"- asChild- content={error}- tooltipClassName="max-w-80"- >- <div className="flex items-center gap-1 text-destructive">- Issues- <BanIcon size={14} />- </div>+ <div className={cn('flex flex-col gap-1.5', className)}>+ <Label className="mb-0 flex items-center gap-1" htmlFor={fieldId}>+ {label}+ {info && (+ <Tooltiper content={info}>+ <InfoIcon className="text-muted-foreground" size={14} /></Tooltiper>)}- </div>+ </Label>{children}+ {message && (+ <p+ aria-live="polite"+ className={cn(+ 'text-xs',+ error ? 'text-destructive' : 'text-muted-foreground'+ )}+ data-slot={error ? 'field-error' : 'field-hint'}+ id={fieldMessageId(fieldId)}+ >+ {message}+ </p>+ )}</div>);};export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(- (props, ref) => {+ ({ className, label, hint, info, error, ...inputProps }, ref) => {+ const hasMessage = Boolean(error ?? hint);+ const generatedId = useId();+ // A caller's own id and description are kept; the message is added to them.+ const fieldId = inputProps.id ?? generatedId;+ const describedBy =+ [inputProps['aria-describedby'], hasMessage && fieldMessageId(fieldId)]+ .filter(Boolean)+ .join(' ') || undefined;return (- <WithLabel {...props}>- <Input id={props.label} ref={ref} {...props} />+ <WithLabel+ className={className}+ error={error}+ hint={hint}+ id={fieldId}+ info={info}+ label={label}+ >+ <Input+ error={error}+ ref={ref}+ {...inputProps}+ aria-describedby={describedBy}+ id={fieldId}+ /></WithLabel>);}diff --git a/apps/start/src/components/forms/tag-input.tsx b/apps/start/src/components/forms/tag-input.tsxindex 33688bf8e..74f678f5f 100644--- a/apps/start/src/components/forms/tag-input.tsx+++ b/apps/start/src/components/forms/tag-input.tsx@@ -5,6 +5,7 @@ import { XIcon } from 'lucide-react';import type { ElementRef } from 'react';import { useEffect, useRef, useState } from 'react';import { Button } from '@/components/ui/button';+import { fieldSurface } from '@/components/ui/input';import { cn } from '@/utils/cn';interface Props {@@ -101,8 +102,9 @@ const TagInput = ({return (<divclassName={cn(- 'inline-flex w-full flex-wrap items-center gap-2 rounded-md border border-input bg-card p-1 px-3 ring-offset-background has-[input:focus]:ring-2 has-[input:focus]:ring-ring has-[input:focus]:ring-offset-1',- !!error && 'border-destructive'+ fieldSurface,+ 'inline-flex min-h-9 w-full flex-wrap items-center gap-2 px-3 py-1 has-[input:focus]:ring-2 has-[input:focus]:ring-ring',+ !!error && 'ring-1 ring-destructive')}ref={scope}>@@ -112,7 +114,7 @@ const TagInput = ({return (<spanclassName={cn(- 'inline-flex items-center gap-2 rounded bg-def-200 px-2 py-1',+ 'inline-flex items-center gap-2 rounded bg-card px-2 py-1 shadow-xs',isMarkedForDeletion &&i === value.length - 1 &&'bg-destructive/15 ring-2 ring-destructive ring-offset-2 ring-offset-card',@@ -136,7 +138,7 @@ const TagInput = ({})}<input- className="min-w-20 flex-1 bg-card py-1 focus-visible:outline-none"+ className="min-w-20 flex-1 bg-transparent py-1 focus-visible:outline-none"id={id}onBlur={handleBlur}onChange={(e) => setInputValue(e.target.value)}diff --git a/apps/start/src/components/integrations/forms/webhook-integration.tsx b/apps/start/src/components/integrations/forms/webhook-integration.tsxindex 36f506cd6..f655361d0 100644--- a/apps/start/src/components/integrations/forms/webhook-integration.tsx+++ b/apps/start/src/components/integrations/forms/webhook-integration.tsx@@ -213,6 +213,7 @@ export function WebhookIntegrationForm({label="Payload Format"><Combobox+ variant="input"{...field}className="w-full"items={[diff --git a/apps/start/src/components/organization/edit-organization.tsx b/apps/start/src/components/organization/edit-organization.tsxindex b6d64818f..946bd78b9 100644--- a/apps/start/src/components/organization/edit-organization.tsx+++ b/apps/start/src/components/organization/edit-organization.tsx@@ -79,6 +79,7 @@ export default function EditOrganization({onChange={field.onChange}placeholder="Select timezone"value={field.value}+ variant="input"/></WithLabel>)}diff --git a/apps/start/src/components/overview/overview-list-modal.tsx b/apps/start/src/components/overview/overview-list-modal.tsxindex 3cff13e66..2e95aa998 100644--- a/apps/start/src/components/overview/overview-list-modal.tsx+++ b/apps/start/src/components/overview/overview-list-modal.tsx@@ -117,7 +117,10 @@ export function OverviewListModal<T extends OverviewListItem>({const virtualItems = virtualizer.getVirtualItems();return (- <ModalContent className="!max-h-[90vh] flex flex-col gap-0 p-0 sm:max-w-2xl">+ <ModalContent+ bodyClassName="flex flex-col gap-0 p-0"+ className="sm:max-w-2xl"+ ><div className="flex-shrink-0 border-border border-b"><div className="p-6 pb-4"><DialogTitle className="mb-4 font-semibold text-lg">diff --git a/apps/start/src/components/overview/overview-widget.tsx b/apps/start/src/components/overview/overview-widget.tsxindex c6a75e608..bf4d61836 100644--- a/apps/start/src/components/overview/overview-widget.tsx+++ b/apps/start/src/components/overview/overview-widget.tsx@@ -276,6 +276,7 @@ export function WidgetHeadSearchable<T extends string>({className="rounded-none border-0 border-y bg-transparent pl-9 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"onChange={(e) => onSearchChange(e.target.value)}placeholder={searchPlaceholder}+ size="sm"type="search"value={searchValue ?? ''}/>diff --git a/apps/start/src/components/page/gsc-cannibalization.tsx b/apps/start/src/components/page/gsc-cannibalization.tsxindex eda89fb9b..3ab1c5f5d 100644--- a/apps/start/src/components/page/gsc-cannibalization.tsx+++ b/apps/start/src/components/page/gsc-cannibalization.tsx@@ -126,6 +126,7 @@ export function GscCannibalization({setPage(0);}}placeholder="Search keywords"+ size="sm"type="search"value={search}/>diff --git a/apps/start/src/components/page/pages-insights.tsx b/apps/start/src/components/page/pages-insights.tsxindex 531dbd47e..35e55059c 100644--- a/apps/start/src/components/page/pages-insights.tsx+++ b/apps/start/src/components/page/pages-insights.tsx@@ -281,6 +281,7 @@ export function PagesInsights({ projectId }: PagesInsightsProps) {setPage(0);}}placeholder="Search pages"+ size="sm"type="search"value={search}/>diff --git a/apps/start/src/components/project-mapper.tsx b/apps/start/src/components/project-mapper.tsxindex 25b29dbe3..f46151bcf 100644--- a/apps/start/src/components/project-mapper.tsx+++ b/apps/start/src/components/project-mapper.tsx@@ -70,6 +70,7 @@ export function ProjectMapper({</Label><Inputplaceholder="e.g., abc123"+ size="sm"{...register(`projectMapper.${index}.from`)}className="mt-1"/>diff --git a/apps/start/src/components/realtime/live/live-constants.ts b/apps/start/src/components/realtime/live/live-constants.tsnew file mode 100644index 000000000..9b6e6138c--- /dev/null+++ b/apps/start/src/components/realtime/live/live-constants.ts@@ -0,0 +1,8 @@+/** Gap between two feed items arriving, so a burst reads like a chat stream. */+export const FEED_RELEASE_MS = 400;+export const FEED_MAX_ITEMS = 24;+/** Forget ids beyond this; the feed only needs to recognise recent ones. */+export const FEED_SEEN_LIMIT = 1000;+export const FEED_CLOCK_MS = 10_000;++export const ISLAND_TOP_COUNT = 5;diff --git a/apps/start/src/components/realtime/live/live-counter.tsx b/apps/start/src/components/realtime/live/live-counter.tsxnew file mode 100644index 000000000..86396eec3--- /dev/null+++ b/apps/start/src/components/realtime/live/live-counter.tsx@@ -0,0 +1,19 @@+import { AnimatedNumber } from '@/components/animated-number';+import { Ping } from '@/components/ping';+import { useLiveCounter } from '@/hooks/use-live-counter';++export function LiveCounter({ projectId }: { projectId: string }) {+ const counter = useLiveCounter({ projectId });++ return (+ <div className="flex flex-col">+ <div className="font-semibold text-6xl tabular-nums tracking-tight">+ <AnimatedNumber value={counter.debounced} />+ </div>+ <div className="flex items-center gap-2 font-medium text-2xs text-muted-foreground uppercase tracking-widest">+ <Ping />+ Online now+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/realtime/live/live-event-feed.tsx b/apps/start/src/components/realtime/live/live-event-feed.tsxnew file mode 100644index 000000000..71c21b72c--- /dev/null+++ b/apps/start/src/components/realtime/live/live-event-feed.tsx@@ -0,0 +1,51 @@+import { useQuery } from '@tanstack/react-query';+import { useMemo } from 'react';+import { FEED_CLOCK_MS } from './live-constants';+import { formatAge, LiveFeed, LiveFeedItem } from './live-feed';+import { useLiveFeed, useNow } from './use-live-feed';+import { EventIcon } from '@/components/events/event-icon';+import { SerieIcon } from '@/components/report-chart/common/serie-icon';+import { useTRPC } from '@/integrations/trpc/react';+import { getCountry } from '@/translations/countries';++const PAGE_VIEW_EVENT = 'screen_view';+/** Session boundaries already show in the sessions feed. */+const SESSION_EVENTS = new Set(['session_start', 'session_end']);++export function LiveEventFeed({ projectId }: { projectId: string }) {+ const trpc = useTRPC();+ const query = useQuery(+ trpc.realtime.activeSessions.queryOptions({ projectId })+ );+ const visibleEvents = useMemo(+ () => query.data?.filter((event) => !SESSION_EVENTS.has(event.name)),+ [query.data]+ );+ const events = useLiveFeed(visibleEvents);+ const now = useNow(FEED_CLOCK_MS);++ return (+ <LiveFeed+ items={events}+ renderItem={(event) => {+ const isPageView = event.name === PAGE_VIEW_EVENT;+ return (+ <LiveFeedItem+ detail={event.city || getCountry(event.country)}+ icon={<EventIcon className="size-4" name={event.name} size="xs" />}+ sessionId={event.sessionId}+ title={isPageView ? event.path || '/' : event.name}+ trailing={+ <>+ <SerieIcon name={event.country} />+ <span>{formatAge(event.createdAt, now)}</span>+ </>+ }+ />+ );+ }}+ storageKey="events"+ title="Events"+ />+ );+}diff --git a/apps/start/src/components/realtime/live/live-feed.tsx b/apps/start/src/components/realtime/live/live-feed.tsxnew file mode 100644index 000000000..e849fae12--- /dev/null+++ b/apps/start/src/components/realtime/live/live-feed.tsx@@ -0,0 +1,119 @@+import { ChevronDownIcon } from 'lucide-react';+import { useStoredToggle } from './use-stored-toggle';+import { ProjectLink } from '@/components/links';+import { cn } from '@/utils/cn';++const SECONDS_PER_MINUTE = 60;+const SECONDS_PER_HOUR = 3600;++export function formatAge(date: Date, now: number) {+ const seconds = Math.max(+ 0,+ Math.round((now - new Date(date).getTime()) / 1000)+ );+ if (seconds < SECONDS_PER_MINUTE) {+ return 'now';+ }+ if (seconds < SECONDS_PER_HOUR) {+ return `${Math.floor(seconds / SECONDS_PER_MINUTE)}m`;+ }+ return `${Math.floor(seconds / SECONDS_PER_HOUR)}h`;+}++export function LiveFeed<T extends { id: string }>({+ title,+ storageKey,+ items,+ renderItem,+ className,+}: {+ title: string;+ /** Remembers per browser whether this feed is shown. */+ storageKey: string;+ items: T[];+ renderItem: (item: T) => React.ReactNode;+ className?: string;+}) {+ const [isOpen, toggleOpen] = useStoredToggle(+ `realtime-feed-${storageKey}-open`,+ true+ );++ return (+ <section+ aria-label={title}+ className={cn(+ 'flex min-h-0 flex-col gap-2 overflow-hidden',+ isOpen &&+ 'flex-1 [mask-image:linear-gradient(to_bottom,black_55%,transparent)]',+ className+ )}+ >+ <h2>+ <button+ aria-expanded={isOpen}+ className="pointer-events-auto flex items-center gap-1 font-medium text-2xs text-muted-foreground uppercase tracking-widest transition-colors hover:text-foreground"+ onClick={toggleOpen}+ title={+ isOpen+ ? `Hide ${title.toLowerCase()}`+ : `Show ${title.toLowerCase()}`+ }+ type="button"+ >+ {title}+ <ChevronDownIcon+ className={cn(+ 'size-3 transition-transform',+ isOpen ? 'rotate-0' : '-rotate-90'+ )}+ />+ </button>+ </h2>+ {isOpen ? (+ <ul className="flex flex-col gap-1">+ {items.map((item) => (+ <li className="animate-live-feed-in" key={item.id}>+ {renderItem(item)}+ </li>+ ))}+ </ul>+ ) : null}+ </section>+ );+}++export function LiveFeedItem({+ sessionId,+ icon,+ title,+ detail,+ trailing,+}: {+ sessionId: string;+ icon: React.ReactNode;+ title: string;+ detail?: string;+ trailing?: React.ReactNode;+}) {+ return (+ <ProjectLink+ className="pointer-events-auto flex h-7 items-center gap-2 rounded-md border bg-card/70 px-2 text-xs backdrop-blur-md transition-colors hover:bg-card"+ params={{ sessionId }}+ to="/sessions/$sessionId"+ >+ <span className="flex size-4 shrink-0 items-center justify-center">+ {icon}+ </span>+ <span className="max-w-[55%] shrink-0 truncate font-medium">{title}</span>+ <span className="min-w-0 flex-1 truncate text-muted-foreground">+ {detail}+ </span>+ {trailing ? (+ <span className="flex shrink-0 items-center gap-1.5 text-muted-foreground tabular-nums">+ {trailing}+ </span>+ ) : null}+ </ProjectLink>+ );+}diff --git a/apps/start/src/components/realtime/live/live-session-feed.tsx b/apps/start/src/components/realtime/live/live-session-feed.tsxnew file mode 100644index 000000000..a6711a3ed--- /dev/null+++ b/apps/start/src/components/realtime/live/live-session-feed.tsx@@ -0,0 +1,48 @@+import { useQuery } from '@tanstack/react-query';+import { GlobeIcon } from 'lucide-react';+import { FEED_CLOCK_MS } from './live-constants';+import { formatAge, LiveFeed, LiveFeedItem } from './live-feed';+import { useLiveFeed, useNow } from './use-live-feed';+import { SerieIcon } from '@/components/report-chart/common/serie-icon';+import { useTRPC } from '@/integrations/trpc/react';+import { getCountry } from '@/translations/countries';++export function LiveSessionFeed({ projectId }: { projectId: string }) {+ const trpc = useTRPC();+ const query = useQuery(+ trpc.realtime.recentSessions.queryOptions({ projectId })+ );+ const sessions = useLiveFeed(query.data);+ const now = useNow(FEED_CLOCK_MS);++ return (+ <LiveFeed+ items={sessions}+ renderItem={(session) => (+ <LiveFeedItem+ detail={session.path || undefined}+ icon={+ session.country ? (+ <SerieIcon name={session.country} />+ ) : (+ <GlobeIcon className="size-3.5 text-muted-foreground" />+ )+ }+ sessionId={session.sessionId}+ title={+ session.city || getCountry(session.country) || 'Unknown location'+ }+ trailing={+ <>+ <SerieIcon name={session.referrerName} />+ <SerieIcon name={session.device} />+ <span>{formatAge(session.createdAt, now)}</span>+ </>+ }+ />+ )}+ storageKey="sessions"+ title="New sessions"+ />+ );+}diff --git a/apps/start/src/components/realtime/live/live-top-island.tsx b/apps/start/src/components/realtime/live/live-top-island.tsxnew file mode 100644index 000000000..91ca66d84--- /dev/null+++ b/apps/start/src/components/realtime/live/live-top-island.tsx@@ -0,0 +1,78 @@+import { useQuery } from '@tanstack/react-query';+import { ISLAND_TOP_COUNT } from './live-constants';+import { SerieIcon } from '@/components/report-chart/common/serie-icon';+import { useNumber } from '@/hooks/use-numer-formatter';+import { useTRPC } from '@/integrations/trpc/react';+import { getCountry } from '@/translations/countries';++interface IslandItem {+ key: string;+ icon: string;+ label: string;+ count: number;+}++export function LiveTopIsland({ projectId }: { projectId: string }) {+ const trpc = useTRPC();+ const { data } = useQuery(+ trpc.realtime.topSources.queryOptions({ projectId })+ );++ const referrers: IslandItem[] = (data?.referrers ?? [])+ .slice(0, ISLAND_TOP_COUNT)+ .map((row) => ({+ key: row.name,+ icon: row.name,+ label: row.name,+ count: row.sessions,+ }));+ const countries: IslandItem[] = (data?.countries ?? [])+ .slice(0, ISLAND_TOP_COUNT)+ .map((row) => ({+ key: row.country,+ icon: row.country,+ label: getCountry(row.country) ?? row.country,+ count: row.sessions,+ }));++ if (referrers.length === 0 && countries.length === 0) {+ return null;+ }++ return (+ <div className="pointer-events-auto flex max-w-[calc(100vw-2rem)] flex-col gap-2 rounded-2xl border bg-card/85 px-4 py-3 shadow-lg backdrop-blur-md">+ <IslandRow items={referrers} label="Referrers" />+ <IslandRow items={countries} label="Countries" />+ </div>+ );+}++function IslandRow({ label, items }: { label: string; items: IslandItem[] }) {+ const number = useNumber();++ if (items.length === 0) {+ return null;+ }++ return (+ <div className="flex items-center gap-4">+ <span className="w-20 shrink-0 font-medium text-2xs text-muted-foreground uppercase tracking-widest">+ {label}+ </span>+ <ul className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1 text-sm">+ {items.map((item) => (+ <li+ className="flex items-center gap-1.5 whitespace-nowrap"+ key={item.key}+ >+ <SerieIcon name={item.icon} />+ <span>{item.label}</span>+ <span className="text-muted-foreground tabular-nums">+ {number.format(item.count)}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/apps/start/src/components/realtime/live/live-visitor-bars.tsx b/apps/start/src/components/realtime/live/live-visitor-bars.tsxnew file mode 100644index 000000000..7cc1ef9a6--- /dev/null+++ b/apps/start/src/components/realtime/live/live-visitor-bars.tsx@@ -0,0 +1,86 @@+import { useQuery } from '@tanstack/react-query';+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { useNumber } from '@/hooks/use-numer-formatter';+import { useTRPC } from '@/integrations/trpc/react';+import type { RouterOutputs } from '@/trpc/client';++/** Matches the dots on the map, so everything live reads as one colour. */+const BAR_COLOR = 'var(--color-emerald-500)';+const BAR_RADIUS = 1;+const BAR_GAP = 0.25;+const NO_MARGIN = { top: 0, right: 0, bottom: 0, left: 0 };++type MinutePoint = RouterOutputs['realtime']['histogram']['minutes'][number] & {+ time: string;+ [key: string]: unknown;+};++function formatMinute(minute: string) {+ return new Date(minute).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit',+ });+}++export function LiveVisitorBars({ projectId }: { projectId: string }) {+ const trpc = useTRPC();+ const number = useNumber();+ const { data } = useQuery(+ trpc.realtime.histogram.queryOptions({ projectId })+ );+ const points: MinutePoint[] = (data?.minutes ?? []).map((point) => ({+ ...point,+ time: formatMinute(point.minute),+ }));++ return (+ <div className="pointer-events-auto flex flex-col gap-2 rounded-xl border bg-card/80 p-3 shadow-sm backdrop-blur-md">+ <div className="flex items-baseline justify-between gap-2">+ <span className="font-medium text-2xs text-muted-foreground uppercase tracking-widest">+ Last 30 minutes+ </span>+ <span className="font-semibold text-sm tabular-nums">+ {number.format(data?.totalSessions ?? 0)}+ <span className="ml-1 font-normal text-muted-foreground text-xs">+ sessions+ </span>+ </span>+ </div>+ <div className="h-14 w-full">+ {points.length > 0 ? (+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BAR_GAP}+ className="h-full"+ data={points}+ margin={NO_MARGIN}+ xDataKey="time"+ >+ <Bar+ animate={false}+ dataKey="visitors"+ fill={BAR_COLOR}+ lineCap={BAR_RADIUS}+ />+ <OPChartTooltip<MinutePoint>+ datePill={false}+ rows={(point) => [+ {+ color: BAR_COLOR,+ label: 'Visitors',+ value: point.visitors,+ format: number.format,+ },+ ]}+ showDots={false}+ title={(point) => point.time}+ />+ </BarChart>+ ) : null}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/realtime/live/realtime-live-overlays.tsx b/apps/start/src/components/realtime/live/realtime-live-overlays.tsxnew file mode 100644index 000000000..f956ef399--- /dev/null+++ b/apps/start/src/components/realtime/live/realtime-live-overlays.tsx@@ -0,0 +1,26 @@+import { LiveCounter } from './live-counter';+import { LiveEventFeed } from './live-event-feed';+import { LiveSessionFeed } from './live-session-feed';+import { LiveTopIsland } from './live-top-island';+import { LiveVisitorBars } from './live-visitor-bars';++/** Sits over the map; only the cards take pointer events so the map still pans. */+export function RealtimeLiveOverlays({ projectId }: { projectId: string }) {+ return (+ <div className="pointer-events-none absolute inset-0 z-10">+ <div className="absolute top-6 bottom-36 left-6 hidden w-72 flex-col gap-6 md:flex">+ <LiveCounter projectId={projectId} />+ <LiveSessionFeed projectId={projectId} />+ </div>++ <div className="absolute top-6 right-6 bottom-36 hidden w-72 flex-col gap-6 md:flex">+ <LiveVisitorBars projectId={projectId} />+ <LiveEventFeed projectId={projectId} />+ </div>++ <div className="absolute inset-x-0 bottom-6 flex justify-center px-4">+ <LiveTopIsland projectId={projectId} />+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/realtime/live/use-live-feed.ts b/apps/start/src/components/realtime/live/use-live-feed.tsnew file mode 100644index 000000000..ce6ace468--- /dev/null+++ b/apps/start/src/components/realtime/live/use-live-feed.ts@@ -0,0 +1,68 @@+import { useEffect, useRef, useState } from 'react';+import {+ FEED_MAX_ITEMS,+ FEED_RELEASE_MS,+ FEED_SEEN_LIMIT,+} from './live-constants';++/**+ * Turns a newest-first list that is refetched in bursts into a feed that+ * gains one item at a time. The first load shows at once; later arrivals+ * queue up and drop in on a steady beat.+ */+export function useLiveFeed<T extends { id: string }>(items: T[] | undefined) {+ const [shown, setShown] = useState<T[]>([]);+ const seenIds = useRef(new Set<string>());+ const queue = useRef<T[]>([]);+ const isPrimed = useRef(false);++ useEffect(() => {+ if (!items) {+ return;+ }++ if (!isPrimed.current) {+ isPrimed.current = true;+ seenIds.current = new Set(items.map((item) => item.id));+ setShown(items.slice(0, FEED_MAX_ITEMS));+ return;+ }++ if (seenIds.current.size > FEED_SEEN_LIMIT) {+ seenIds.current = new Set(items.map((item) => item.id));+ return;+ }++ const arrivals = items.filter((item) => !seenIds.current.has(item.id));+ for (const item of arrivals) {+ seenIds.current.add(item.id);+ }+ // Oldest first, and only as many as the feed can show anyway.+ queue.current = [...queue.current, ...arrivals.reverse()].slice(+ -FEED_MAX_ITEMS+ );+ }, [items]);++ useEffect(() => {+ const interval = setInterval(() => {+ const next = queue.current.shift();+ if (next) {+ setShown((previous) => [next, ...previous].slice(0, FEED_MAX_ITEMS));+ }+ }, FEED_RELEASE_MS);+ return () => clearInterval(interval);+ }, []);++ return shown;+}++export function useNow(intervalMs: number) {+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ const interval = setInterval(() => setNow(Date.now()), intervalMs);+ return () => clearInterval(interval);+ }, [intervalMs]);++ return now;+}diff --git a/apps/start/src/components/realtime/live/use-stored-toggle.ts b/apps/start/src/components/realtime/live/use-stored-toggle.tsnew file mode 100644index 000000000..3e3ef0a09--- /dev/null+++ b/apps/start/src/components/realtime/live/use-stored-toggle.ts@@ -0,0 +1,27 @@+import { useCallback, useEffect, useState } from 'react';++/**+ * A boolean remembered in localStorage. It starts at the default and reads+ * storage after mount, so the server-rendered HTML and the first client+ * render always agree.+ */+export function useStoredToggle(key: string, defaultValue: boolean) {+ const [value, setValue] = useState(defaultValue);++ useEffect(() => {+ const stored = window.localStorage.getItem(key);+ if (stored !== null) {+ setValue(stored === 'true');+ }+ }, [key]);++ const toggle = useCallback(() => {+ setValue((previous) => {+ const next = !previous;+ window.localStorage.setItem(key, String(next));+ return next;+ });+ }, [key]);++ return [value, toggle] as const;+}diff --git a/apps/start/src/components/realtime/map/coordinates.ts b/apps/start/src/components/realtime/map/coordinates.tsdeleted file mode 100644index ad48c3507..000000000--- a/apps/start/src/components/realtime/map/coordinates.ts+++ /dev/null@@ -1,527 +0,0 @@-export interface Coordinate {- lat: number;- long: number;- city?: string;- country?: string;- count?: number;-}--export type ClusterDetailLevel = 'country' | 'city' | 'coordinate';--export interface CoordinateCluster {- center: Coordinate;- count: number;- members: Coordinate[];- location: {- city?: string;- country?: string;- };-}--const COUNTRY_GROUP_MAX_ZOOM = 2;-const CITY_GROUP_MAX_ZOOM = 4.5;--function normalizeLocationValue(value?: string) {- const trimmed = value?.trim();- return trimmed ? trimmed : undefined;-}--export function getClusterDetailLevel(zoom: number): ClusterDetailLevel {- if (zoom <= COUNTRY_GROUP_MAX_ZOOM) {- return 'country';- }-- if (zoom <= CITY_GROUP_MAX_ZOOM) {- return 'city';- }-- return 'coordinate';-}--function getLocationSummary(members: Coordinate[]) {- const cityCounts = new Map<string, number>();- const countryCounts = new Map<string, number>();-- for (const member of members) {- const city = normalizeLocationValue(member.city);- const country = normalizeLocationValue(member.country);- const weight = member.count ?? 1;-- if (city) {- cityCounts.set(city, (cityCounts.get(city) ?? 0) + weight);- }-- if (country) {- countryCounts.set(country, (countryCounts.get(country) ?? 0) + weight);- }- }-- const getTopLocation = (counts: Map<string, number>) =>- [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];-- return {- city: getTopLocation(cityCounts),- country: getTopLocation(countryCounts),- };-}--function getAggregationKey(- member: Coordinate,- detailLevel: Exclude<ClusterDetailLevel, 'coordinate'>-) {- const city = normalizeLocationValue(member.city);- const country = normalizeLocationValue(member.country);-- if (detailLevel === 'country') {- return country ?? city;- }-- if (country && city) {- return `${country}::${city}`;- }-- return city ?? country;-}--function regroupClustersByDetail(- clusters: CoordinateCluster[],- detailLevel: Exclude<ClusterDetailLevel, 'coordinate'>-): CoordinateCluster[] {- const grouped = new Map<string, Coordinate[]>();- const ungrouped: CoordinateCluster[] = [];-- for (const cluster of clusters) {- for (const member of cluster.members) {- const key = getAggregationKey(member, detailLevel);-- if (!key) {- ungrouped.push({- members: [member],- center: calculateClusterCenter([member]),- count: member.count ?? 1,- location: {- city: normalizeLocationValue(member.city),- country: normalizeLocationValue(member.country),- },- });- continue;- }-- grouped.set(key, [...(grouped.get(key) ?? []), member]);- }- }-- const regrouped = [...grouped.values()].map((members) => {- const location = getLocationSummary(members);-- return {- members,- center: calculateClusterCenter(members),- count: members.reduce((sum, member) => sum + (member.count ?? 1), 0),- location,- };- });-- return [...regrouped, ...ungrouped];-}--export function haversineDistance(- coord1: Coordinate,- coord2: Coordinate-): number {- const R = 6371; // Earth's radius in kilometers- const lat1Rad = coord1.lat * (Math.PI / 180);- const lat2Rad = coord2.lat * (Math.PI / 180);- const deltaLatRad = (coord2.lat - coord1.lat) * (Math.PI / 180);- const deltaLonRad = (coord2.long - coord1.long) * (Math.PI / 180);-- const a =- Math.sin(deltaLatRad / 2) * Math.sin(deltaLatRad / 2) +- Math.cos(lat1Rad) *- Math.cos(lat2Rad) *- Math.sin(deltaLonRad / 2) *- Math.sin(deltaLonRad / 2);- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));-- return R * c; // Distance in kilometers-}--export function findFarthestPoints(- coordinates: Coordinate[]-): [Coordinate, Coordinate] {- if (coordinates.length < 2) {- throw new Error('At least two coordinates are required');- }-- let maxDistance = 0;- let point1: Coordinate = coordinates[0]!;- let point2: Coordinate = coordinates[1]!;-- for (let i = 0; i < coordinates.length; i++) {- for (let j = i + 1; j < coordinates.length; j++) {- const distance = haversineDistance(coordinates[i]!, coordinates[j]!);- if (distance > maxDistance) {- maxDistance = distance;- point1 = coordinates[i]!;- point2 = coordinates[j]!;- }- }- }-- return [point1, point2];-}--export function getAverageCenter(coordinates: Coordinate[]): Coordinate {- if (coordinates.length === 0) {- return { long: 0, lat: 20 };- }-- let sumLong = 0;- let sumLat = 0;- let totalWeight = 0;-- for (const coord of coordinates) {- const weight = coord.count ?? 1;- sumLong += coord.long * weight;- sumLat += coord.lat * weight;- totalWeight += weight;- }-- const avgLat = sumLat / totalWeight;- const avgLong = sumLong / totalWeight;-- return { long: avgLong, lat: avgLat };-}--function sortCoordinates(a: Coordinate, b: Coordinate): number {- return a.long === b.long ? a.lat - b.lat : a.long - b.long;-}--function cross(o: Coordinate, a: Coordinate, b: Coordinate): number {- return (- (a.long - o.long) * (b.lat - o.lat) - (a.lat - o.lat) * (b.long - o.long)- );-}--// convex hull-export function getOuterMarkers(coordinates: Coordinate[]): Coordinate[] {- const sorted = [...coordinates].sort(sortCoordinates);-- if (sorted.length <= 3) {- return sorted;- }-- const lower: Coordinate[] = [];- for (const coord of sorted) {- while (- lower.length >= 2 &&- cross(lower.at(-2)!, lower.at(-1)!, coord) <= 0- ) {- lower.pop();- }- lower.push(coord);- }-- const upper: Coordinate[] = [];- for (let i = coordinates.length - 1; i >= 0; i--) {- while (- upper.length >= 2 &&- cross(upper.at(-2)!, upper.at(-1)!, sorted[i]!) <= 0- ) {- upper.pop();- }- upper.push(sorted[i]!);- }-- upper.pop();- lower.pop();- return lower.concat(upper);-}--export function calculateCentroid(polygon: Coordinate[]): Coordinate {- if (polygon.length < 3) {- throw new Error('At least three points are required to form a polygon.');- }-- let area = 0;- let centroidLat = 0;- let centroidLong = 0;-- for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {- const x0 = polygon[j]!.long;- const y0 = polygon[j]!.lat;- const x1 = polygon[i]!.long;- const y1 = polygon[i]!.lat;- const a = x0 * y1 - x1 * y0;- area += a;- centroidLong += (x0 + x1) * a;- centroidLat += (y0 + y1) * a;- }-- area /= 2;- if (area === 0) {- // This should not happen for a proper convex hull- throw new Error('Area of the polygon is zero, check the coordinates.');- }-- centroidLat /= 6 * area;- centroidLong /= 6 * area;-- return { lat: centroidLat, long: centroidLong };-}--export function calculateGeographicMidpoint(- coordinate: Coordinate[]-): Coordinate {- let minLat = Number.POSITIVE_INFINITY;- let maxLat = Number.NEGATIVE_INFINITY;- let minLong = Number.POSITIVE_INFINITY;- let maxLong = Number.NEGATIVE_INFINITY;-- for (const { lat, long } of coordinate) {- if (lat < minLat) {- minLat = lat;- }- if (lat > maxLat) {- maxLat = lat;- }- if (long < minLong) {- minLong = long;- }- if (long > maxLong) {- maxLong = long;- }- }-- // Handling the wrap around the international date line- let midLong: number;- if (maxLong > minLong) {- midLong = (maxLong + minLong) / 2;- } else {- // Adjust calculation when spanning the dateline- midLong = ((maxLong + 360 + minLong) / 2) % 360;- }-- const midLat = (maxLat + minLat) / 2;-- return { lat: midLat, long: midLong };-}--export function clusterCoordinates(- coordinates: Coordinate[],- radius = 25,- options: {- useOptimizedClustering?: boolean;- zoom?: number;- stability?: boolean;- adaptiveRadius?: boolean;- viewport?: {- center: Coordinate;- bounds: {- minLat: number;- maxLat: number;- minLong: number;- maxLong: number;- };- };- } = {}-) {- const { zoom = 1, adaptiveRadius = true, viewport } = options;- const detailLevel = getClusterDetailLevel(zoom);-- let adjustedRadius = radius;-- if (adaptiveRadius) {- // More aggressive clustering at lower zoom levels: the radius shrinks- // roughly with 4 / (zoom + 1), e.g. ~3x at zoom 1 down to ~0.2x by zoom 8.- const zoomFactor = Math.max(0.1, 4 / (zoom + 1));- adjustedRadius = radius * zoomFactor;-- if (viewport && coordinates.length > 0) {- const viewportCoords = coordinates.filter(- (coord) =>- coord.lat >= viewport.bounds.minLat &&- coord.lat <= viewport.bounds.maxLat &&- coord.long >= viewport.bounds.minLong &&- coord.long <= viewport.bounds.maxLong- );-- if (viewportCoords.length > 0) {- const viewportArea =- (viewport.bounds.maxLat - viewport.bounds.minLat) *- (viewport.bounds.maxLong - viewport.bounds.minLong);-- const density = viewportCoords.length / viewportArea;-- // Adjust radius based on density - higher density = larger radius for more aggressive clustering- const densityFactor = Math.max(- 0.5,- Math.min(5, Math.sqrt(density * 1000) + 1)- );- adjustedRadius *= densityFactor;- }- }- } else {- adjustedRadius = radius * Math.max(0.5, 1 / Math.sqrt(zoom));- }-- const result = basicClusterCoordinates(coordinates, adjustedRadius);-- if (detailLevel === 'coordinate') {- return result;- }-- return regroupClustersByDetail(result, detailLevel);-}--// Aggressive clustering algorithm with iterative expansion-function basicClusterCoordinates(coordinates: Coordinate[], radius: number) {- if (coordinates.length === 0) {- return [];- }-- const clusters: CoordinateCluster[] = [];- const visited = new Set<number>();-- // Sort coordinates by density (coordinates near others first)- const coordinatesWithDensity = coordinates- .map((coord, idx) => {- const nearbyCount = coordinates.filter(- (other) => haversineDistance(coord, other) <= radius * 0.5- ).length;- return { ...coord, originalIdx: idx, nearbyCount };- })- .sort((a, b) => b.nearbyCount - a.nearbyCount);-- coordinatesWithDensity.forEach(- ({ lat, long, city, country, count, originalIdx }) => {- if (!visited.has(originalIdx)) {- const initialCount = count ?? 1;- const cluster = {- members: [{ lat, long, city, country, count: initialCount }],- center: { lat, long },- count: initialCount,- location: {- city: normalizeLocationValue(city),- country: normalizeLocationValue(country),- },- };-- visited.add(originalIdx);-- // Iteratively expand the cluster to include nearby points- let expandedInLastIteration = true;- while (expandedInLastIteration) {- expandedInLastIteration = false;-- for (const member of [...cluster.members]) {- coordinatesWithDensity.forEach(- ({- lat: otherLat,- long: otherLong,- city: otherCity,- country: otherCountry,- count: otherCount,- originalIdx: otherIdx,- }) => {- if (!visited.has(otherIdx)) {- const distance = haversineDistance(member, {- lat: otherLat,- long: otherLong,- });-- if (distance <= radius) {- const memberCount = otherCount ?? 1;- cluster.members.push({- lat: otherLat,- long: otherLong,- city: otherCity,- country: otherCountry,- count: memberCount,- });- visited.add(otherIdx);- cluster.count += memberCount;- expandedInLastIteration = true;- }- }- }- );- }- }-- cluster.center = calculateClusterCenter(cluster.members);- cluster.location = getLocationSummary(cluster.members);-- clusters.push(cluster);- }- }- );-- return clusters;-}--export function getClusteringStats(- coordinates: Coordinate[],- clusters: ReturnType<typeof clusterCoordinates>-) {- const totalPoints = coordinates.reduce(- (sum, coordinate) => sum + (coordinate.count ?? 1),- 0- );- const totalClusters = clusters.length;- const singletonClusters = clusters.filter((c) => c.count === 1).length;- const avgClusterSize = totalPoints > 0 ? totalPoints / totalClusters : 0;- const maxClusterSize = Math.max(...clusters.map((c) => c.count));- const compressionRatio = totalClusters > 0 ? totalPoints / totalClusters : 1;-- return {- totalPoints,- totalClusters,- singletonClusters,- avgClusterSize: Math.round(avgClusterSize * 100) / 100,- maxClusterSize,- compressionRatio: Math.round(compressionRatio * 100) / 100,- };-}--// Helper function to calculate cluster center with longitude wrapping-function calculateClusterCenter(members: Coordinate[]): Coordinate {- if (members.length === 1) {- return { ...members[0]! };- }-- const longitudes = members.map((m) => m.long);- const minLong = Math.min(...longitudes);- const maxLong = Math.max(...longitudes);-- let avgLat = 0;- let avgLong = 0;- let totalWeight = 0;-- if (maxLong - minLong > 180) {- let adjustedLongSum = 0;- for (const member of members) {- const weight = member.count ?? 1;- avgLat += member.lat * weight;- const adjustedLong = member.long < 0 ? member.long + 360 : member.long;- adjustedLongSum += adjustedLong * weight;- totalWeight += weight;- }- avgLat /= totalWeight;- avgLong = (adjustedLongSum / totalWeight) % 360;- if (avgLong > 180) {- avgLong -= 360;- }- } else {- for (const member of members) {- const weight = member.count ?? 1;- avgLat += member.lat * weight;- avgLong += member.long * weight;- totalWeight += weight;- }- avgLat /= totalWeight;- avgLong /= totalWeight;- }-- return { lat: avgLat, long: avgLong };-}diff --git a/apps/start/src/components/realtime/map/index.tsx b/apps/start/src/components/realtime/map/index.tsxindex 7dc74d856..5c9fe0c86 100644--- a/apps/start/src/components/realtime/map/index.tsx+++ b/apps/start/src/components/realtime/map/index.tsx@@ -1,19 +1,14 @@import { useRef } from 'react';import { MapBadgeDetails } from './map-badge-details';-import { MapCanvas } from './map-canvas';import type { RealtimeMapProps } from './map-types';+import { RealtimeMap } from './realtime-map';-const Map = ({ projectId, markers, sidebarConfig }: RealtimeMapProps) => {+const Map = ({ projectId, markers }: RealtimeMapProps) => {const containerRef = useRef<HTMLDivElement>(null);return (<div className="relative h-full w-full" ref={containerRef}>- <MapCanvas- markers={markers}- projectId={projectId}- sidebarConfig={sidebarConfig}- />-+ <RealtimeMap markers={markers} projectId={projectId} /><MapBadgeDetails containerRef={containerRef} /></div>);diff --git a/apps/start/src/components/realtime/map/map-badge-detail-card.tsx b/apps/start/src/components/realtime/map/map-badge-detail-card.tsxindex 25c204beb..ac575d719 100644--- a/apps/start/src/components/realtime/map/map-badge-detail-card.tsx+++ b/apps/start/src/components/realtime/map/map-badge-detail-card.tsx@@ -3,12 +3,7 @@ import { motion } from 'framer-motion';import { XIcon } from 'lucide-react';import type { RefObject } from 'react';import type { DisplayMarker } from './map-types';-import {- getBadgeOverlayPosition,- getProfileDisplayName,- getUniqueCoordinateDetailLocations,- getUniquePlaceDetailLocations,-} from './map-utils';+import { getBadgeOverlayPosition, getProfileDisplayName } from './map-utils';import { ProjectLink } from '@/components/links';import { ProfileAvatar } from '@/components/profiles/profile-avatar';import { SerieIcon } from '@/components/report-chart/common/serie-icon';@@ -31,10 +26,7 @@ export function MapBadgeDetailCard({const input = {detailScope: marker.detailScope,projectId,- locations:- marker.detailScope === 'coordinate'- ? getUniqueCoordinateDetailLocations(marker.members)- : getUniquePlaceDetailLocations(marker.members),+ locations: marker.locations,};const query = useQuery(trpc.realtime.mapBadgeDetails.queryOptions(input, {@@ -66,7 +58,7 @@ export function MapBadgeDetailCard({<div className="flex items-start justify-between gap-4 border-b p-4"><div className="min-w-0"><div className="mb-2 text-muted-foreground text-xs uppercase tracking-wide">- Realtime cluster+ Online now</div><div className="truncate text-lg" style={{ fontWeight: 600 }}>{marker.label}@@ -94,7 +86,7 @@ export function MapBadgeDetailCard({<div className="col gap-1 rounded-lg bg-def-200 p-3"><div className="text-muted-foreground text-xs">Locations</div><div className="font-semibold">- {query.data?.summary.totalLocations ?? marker.members.length}+ {query.data?.summary.totalLocations ?? marker.locations.length}</div></div><div className="col gap-1 rounded-lg bg-def-200 p-3">diff --git a/apps/start/src/components/realtime/map/map-canvas.tsx b/apps/start/src/components/realtime/map/map-canvas.tsxdeleted file mode 100644index 50657e493..000000000--- a/apps/start/src/components/realtime/map/map-canvas.tsx+++ /dev/null@@ -1,314 +0,0 @@-import { bind } from 'bind-event-listener';-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import {- ComposableMap,- Geographies,- Geography,- Marker,- ZoomableGroup,-} from 'react-simple-maps';-import {- calculateGeographicMidpoint,- clusterCoordinates,- getAverageCenter,- getOuterMarkers,-} from './coordinates';-import { determineZoom, GEO_MAP_URL, getBoundingBox } from './map.helpers';-import { createDisplayMarkers } from './map-display-markers';-import { MapMarkerPill } from './map-marker-pill';-import type {- DisplayMarkerCache,- GeographyFeature,- MapCanvasProps,- MapProjection,- ZoomMoveEndPosition,- ZoomMovePosition,-} from './map-types';-import {- ANCHOR_R,- isValidCoordinate,- PILL_GAP,- PILL_H,- PILL_W,-} from './map-utils';-import {- closeMapBadgeDetails,- openMapBadgeDetails,-} from './realtime-map-badge-slice';-import { useTheme } from '@/hooks/use-theme';-import { useDispatch } from '@/redux';--export const MapCanvas = memo(function MapCanvas({- projectId,- markers,- sidebarConfig,-}: MapCanvasProps) {- const dispatch = useDispatch();- const ref = useRef<HTMLDivElement>(null);- const [size, setSize] = useState<{ width: number; height: number } | null>(- null- );- const [currentZoom, setCurrentZoom] = useState(1);- const [debouncedZoom, setDebouncedZoom] = useState(1);- const [viewCenter, setViewCenter] = useState<[number, number]>([0, 20]);- const zoomTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const displayMarkersCacheRef = useRef<DisplayMarkerCache>({- markers: [],- projection: null,- viewportCenter: [0, 20],- zoom: 1,- size: null,- result: [],- });-- const { center, initialZoom } = useMemo(() => {- const hull = getOuterMarkers(markers);- const center =- hull.length < 2- ? getAverageCenter(markers)- : calculateGeographicMidpoint(hull);-- const boundingBox = getBoundingBox(hull.length > 0 ? hull : markers);- const aspectRatio = size ? size.width / size.height : 1;- const autoZoom = Math.max(- 1,- Math.min(20, determineZoom(boundingBox, aspectRatio) * 0.4)- );- const initialZoom = markers.length > 0 ? autoZoom : 1;-- return { center, initialZoom };- }, [markers, size]);-- const updateDebouncedZoom = useCallback((newZoom: number) => {- if (zoomTimeoutRef.current) {- clearTimeout(zoomTimeoutRef.current);- }- zoomTimeoutRef.current = setTimeout(() => {- setDebouncedZoom(newZoom);- }, 100);- }, []);-- useEffect(() => {- return () => {- if (zoomTimeoutRef.current) {- clearTimeout(zoomTimeoutRef.current);- }- };- }, []);-- const { long, lat } = useMemo(() => {- let adjustedLong = center.long;- if (sidebarConfig && size) {- const sidebarOffset =- sidebarConfig.position === 'left'- ? sidebarConfig.width / 2- : -sidebarConfig.width / 2;- const longitudePerPixel = 360 / (size.width * initialZoom);- const longitudeOffset = sidebarOffset * longitudePerPixel;- adjustedLong = center.long - longitudeOffset;- }- return { long: adjustedLong, lat: center.lat };- }, [center.long, center.lat, sidebarConfig, size, initialZoom]);-- useEffect(() => {- setViewCenter([long, lat]);- setCurrentZoom(initialZoom);- setDebouncedZoom(initialZoom);- }, [long, lat, initialZoom]);-- useEffect(() => {- return bind(window, {- type: 'resize',- listener() {- if (ref.current) {- const parentRect = ref.current.getBoundingClientRect();- setSize({- width: parentRect.width ?? 0,- height: parentRect.height ?? 0,- });- }- },- });- }, []);-- useEffect(() => {- if (ref.current) {- const parentRect = ref.current.getBoundingClientRect();- setSize({- width: parentRect.width ?? 0,- height: parentRect.height ?? 0,- });- }- }, []);-- const theme = useTheme();-- const clusteredMarkers = useMemo(() => {- return clusterCoordinates(markers, 150, {- zoom: debouncedZoom,- adaptiveRadius: true,- });- }, [markers, debouncedZoom]);-- const invScale = Number.isNaN(1 / currentZoom) ? 1 : 1 / currentZoom;-- return (- <div className="relative h-full w-full" ref={ref}>- <div className="absolute inset-x-0 bottom-0 h-1/10 bg-gradient-to-t from-def-100 to-transparent" />- {size !== null && (- <ComposableMap- height={size.height}- projection="geoMercator"- width={size.width}- >- <ZoomableGroup- center={[long, lat]}- // key={`${long}-${lat}-${initialZoom}`}- maxZoom={20}- minZoom={1}- onMove={(position: ZoomMovePosition) => {- dispatch(closeMapBadgeDetails());- if (currentZoom !== position.zoom) {- setCurrentZoom(position.zoom);- updateDebouncedZoom(position.zoom);- }- }}- onMoveEnd={(position: ZoomMoveEndPosition) => {- setViewCenter(position.coordinates);-- if (currentZoom !== position.zoom) {- setCurrentZoom(position.zoom);- updateDebouncedZoom(position.zoom);- }- }}- zoom={initialZoom}- >- <Geographies geography={GEO_MAP_URL}>- {({- geographies,- projection,- }: {- geographies: GeographyFeature[];- projection: MapProjection;- }) => {- const cachedDisplayMarkers = displayMarkersCacheRef.current;- const cacheMatches =- cachedDisplayMarkers.markers === clusteredMarkers &&- cachedDisplayMarkers.projection === projection &&- cachedDisplayMarkers.viewportCenter[0] === viewCenter[0] &&- cachedDisplayMarkers.viewportCenter[1] === viewCenter[1] &&- cachedDisplayMarkers.zoom === debouncedZoom &&- cachedDisplayMarkers.size?.width === size.width &&- cachedDisplayMarkers.size?.height === size.height;-- const displayMarkers = cacheMatches- ? cachedDisplayMarkers.result- : createDisplayMarkers({- markers: clusteredMarkers,- projection,- viewportCenter: viewCenter,- zoom: debouncedZoom,- labelZoom: debouncedZoom,- size,- });-- if (!cacheMatches) {- displayMarkersCacheRef.current = {- markers: clusteredMarkers,- projection,- viewportCenter: viewCenter,- zoom: debouncedZoom,- size,- result: displayMarkers,- };- }-- return (- <>- {geographies- .filter(- (geo: GeographyFeature) =>- geo.properties.name !== 'Antarctica'- )- .map((geo: GeographyFeature) => (- <Geography- fill={theme.theme === 'dark' ? '#000' : '#f0f0f0'}- geography={geo}- key={geo.rsmKey}- pointerEvents="none"- stroke={theme.theme === 'dark' ? '#333' : '#999'}- strokeWidth={0.5}- vectorEffect="non-scaling-stroke"- />- ))}-- {markers.filter(isValidCoordinate).map((marker, index) => (- <Marker- coordinates={[marker.long, marker.lat]}- key={`point-${index}-${marker.long}-${marker.lat}`}- >- <g transform={`scale(${invScale})`}>- <circle- fill="var(--primary)"- fillOpacity={0.9}- pointerEvents="none"- r={ANCHOR_R}- />- </g>- </Marker>- ))}-- {displayMarkers.map((marker, index) => {- const coordinates: [number, number] = [- marker.center.long,- marker.center.lat,- ];-- return (- <Marker- coordinates={coordinates}- key={`cluster-${index}-${marker.center.long}-${marker.center.lat}-${marker.mergedVisualClusters}`}- >- <g transform={`scale(${invScale})`}>- <foreignObject- height={PILL_H}- overflow="visible"- width={PILL_W}- x={-PILL_W / 2}- y={-(PILL_H + ANCHOR_R + PILL_GAP)}- >- <div- style={{- display: 'flex',- justifyContent: 'center',- height: '100%',- alignItems: 'center',- }}- >- <MapMarkerPill- marker={marker}- onClick={() => {- dispatch(- openMapBadgeDetails({- marker,- projectId,- })- );- }}- />- </div>- </foreignObject>- </g>- </Marker>- );- })}- </>- );- }}- </Geographies>- </ZoomableGroup>- </ComposableMap>- )}- </div>- );-});diff --git a/apps/start/src/components/realtime/map/map-constants.ts b/apps/start/src/components/realtime/map/map-constants.tsnew file mode 100644index 000000000..d8cd35ac0--- /dev/null+++ b/apps/start/src/components/realtime/map/map-constants.ts@@ -0,0 +1,51 @@+export const MAP_MIN_ZOOM = 1;+export const MAP_MAX_ZOOM = 24;+export const MAP_ZOOM_BUTTON_FACTOR = 1.8;+export const MAP_ZOOM_ANIMATION_MS = 300;+export const NIGHT_REFRESH_MS = 60_000;++/** A country gets its name once it covers this many square pixels on screen. */+export const LABEL_MIN_SCREEN_AREA = 9000;+export const LABEL_MAX_COUNT = 40;+/** Twilight: the night shade fades in over this many degrees past the terminator. */+export const NIGHT_FEATHER_DEGREES = 18;+export const NIGHT_FEATHER_STEPS = 12;+export const NIGHT_MAX_ALPHA_DARK = 0.22;+export const NIGHT_MAX_ALPHA_LIGHT = 0.05;++export const MARKER_MIN_RADIUS = 3.5;+export const MARKER_MAX_RADIUS = 10;+export const MARKER_RADIUS_PER_SQRT_VISITOR = 1.2;+export const MARKER_HIT_RADIUS = 12;+export const MARKER_STROKE_WIDTH = 1.5;+export const MARKER_ACTIVE_RING_GAP = 4;+/** Dots this far off screen are still drawn, so none pops in at the edge. */+export const MARKER_VIEWPORT_MARGIN = 20;+/** Only the busiest dots pulse, so the ring animation stays cheap on big maps. */+export const MARKER_PULSE_LIMIT = 40;+export const MARKER_PULSE_DURATION_MS = 2400;+export const MARKER_PULSE_SPREAD = 3.2;+export const MARKER_PULSE_ALPHA = 0.45;++/** How long a pan or zoom must pause before the crisp world bitmap is rendered. */+export const RASTER_SETTLE_MS = 120;+/** The crisp bitmap extends this share of the viewport past each edge. */+export const RASTER_DETAIL_MARGIN = 0.25;+export const RASTER_DETAIL_MAX_PIXELS = 12_000_000;+export const RASTER_MAX_PIXEL_RATIO = 2;+/** From this zoom on, the crisp bitmap uses the detailed coastlines. */+export const RASTER_FINE_DETAIL_ZOOM = 3;+/** Size of the cells the detailed border lines are grouped into. */+export const BORDER_BUCKET_DEGREES = 10;+/** Rebuilding the geometry is heavy, so a window resize waits this long to settle. */+export const RESIZE_SETTLE_MS = 150;++/** The detail query accepts at most this many locations. */+export const PLACE_MAX_LOCATIONS = 200;++export const DETAIL_CARD_WIDTH = 380;+export const DETAIL_CARD_MIN_HEIGHT = 340;+export const DETAIL_CARD_INSET = 12;+export const DETAIL_CARD_GAP = 20;+/** How far above the dot the card's top edge starts. */+export const DETAIL_CARD_ANCHOR_OFFSET = 40;diff --git a/apps/start/src/components/realtime/map/map-display-markers.ts b/apps/start/src/components/realtime/map/map-display-markers.tsdeleted file mode 100644index 18ba17626..000000000--- a/apps/start/src/components/realtime/map/map-display-markers.ts+++ /dev/null@@ -1,309 +0,0 @@-import type { Coordinate, CoordinateCluster } from './coordinates';-import {- getAverageCenter,- getClusterDetailLevel,- haversineDistance,-} from './coordinates';-import type {- ContinentBucket,- DisplayMarker,- MapProjection,-} from './map-types';-import {- ANCHOR_R,- createDisplayLabel,- createMergedDisplayLabel,- getDetailQueryScope,- getDisplayMarkerId,- getMergedDetailQueryScope,- getWeightedScreenPoint,- isValidCoordinate,- normalizeLocationValue,- PILL_GAP,- PILL_H,- PILL_W,-} from './map-utils';--function projectToScreen(- projection: MapProjection,- coordinate: Coordinate,- viewportCenter: [number, number],- zoom: number,- size: { width: number; height: number }-) {- const projectedPoint = projection([coordinate.long, coordinate.lat]);- const projectedCenter = projection(viewportCenter);-- if (!(projectedPoint && projectedCenter)) {- return null;- }-- return {- x: (projectedPoint[0] - projectedCenter[0]) * zoom + size.width / 2,- y: (projectedPoint[1] - projectedCenter[1]) * zoom + size.height / 2,- };-}--function isOffscreen(- point: { x: number; y: number },- size: { width: number; height: number }-) {- const margin = PILL_W;-- return (- point.x < -margin ||- point.x > size.width + margin ||- point.y < -margin ||- point.y > size.height + margin- );-}--function doPillsOverlap(- left: { x: number; y: number },- right: { x: number; y: number },- padding: number-) {- const leftBox = {- left: left.x - PILL_W / 2 - padding,- right: left.x + PILL_W / 2 + padding,- top: left.y - (PILL_H + ANCHOR_R + PILL_GAP) - padding,- };- const rightBox = {- left: right.x - PILL_W / 2 - padding,- right: right.x + PILL_W / 2 + padding,- top: right.y - (PILL_H + ANCHOR_R + PILL_GAP) - padding,- };-- const leftBottom = leftBox.top + PILL_H + padding * 2;- const rightBottom = rightBox.top + PILL_H + padding * 2;-- return !(- leftBox.right < rightBox.left ||- leftBox.left > rightBox.right ||- leftBottom < rightBox.top ||- leftBox.top > rightBottom- );-}--function getVisualMergePadding(zoom: number) {- const detailLevel = getClusterDetailLevel(zoom);-- if (detailLevel === 'country') {- return 8;- }-- if (detailLevel === 'city') {- return 4;- }-- return 2;-}--function getContinentBucket(coordinate: Coordinate): ContinentBucket {- const { lat, long } = coordinate;-- if (lat >= 15 && long >= -170 && long <= -20) {- return 'north-america';- }-- if (lat < 15 && lat >= -60 && long >= -95 && long <= -30) {- return 'south-america';- }-- if (lat >= 35 && long >= -25 && long <= 45) {- return 'europe';- }-- if (lat >= -40 && lat <= 38 && long >= -20 && long <= 55) {- return 'africa';- }-- if (lat >= -10 && long >= 110 && long <= 180) {- return 'oceania';- }-- if (lat >= -10 && long >= 55 && long <= 180) {- return 'asia';- }-- if (lat >= 0 && long >= 45 && long <= 180) {- return 'asia';- }-- if (lat >= -10 && long >= 30 && long < 55) {- return 'asia';- }-- return 'unknown';-}--function getMaxVisualMergeDistanceKm(zoom: number) {- const detailLevel = getClusterDetailLevel(zoom);-- if (detailLevel === 'country') {- return 2200;- }-- if (detailLevel === 'city') {- return 900;- }-- return 500;-}--function canVisuallyMergeMarkers(- left: CoordinateCluster,- right: CoordinateCluster,- zoom: number-) {- const sameContinent =- getContinentBucket(left.center) === getContinentBucket(right.center);-- if (!sameContinent) {- return false;- }-- return (- haversineDistance(left.center, right.center) <=- getMaxVisualMergeDistanceKm(zoom)- );-}--export function createDisplayMarkers({- markers,- projection,- viewportCenter,- zoom,- labelZoom,- size,-}: {- markers: CoordinateCluster[];- projection: MapProjection;- viewportCenter: [number, number];- zoom: number;- labelZoom: number;- size: { width: number; height: number };-}): DisplayMarker[] {- const positionedMarkers = markers- .map((marker) => {- if (!isValidCoordinate(marker.center)) {- return null;- }-- const point = projectToScreen(- projection,- marker.center,- viewportCenter,- zoom,- size- );-- if (!point || isOffscreen(point, size)) {- return null;- }-- return { marker, point };- })- .filter((entry) => entry !== null);-- const entries = positionedMarkers.sort(- (left, right) => right.marker.count - left.marker.count- );- const consumed = new Set<number>();- const mergedMarkers: DisplayMarker[] = [];- const overlapPadding = getVisualMergePadding(labelZoom);-- for (let index = 0; index < entries.length; index++) {- if (consumed.has(index)) {- continue;- }-- const queue = [index];- const componentIndices: number[] = [];- consumed.add(index);-- while (queue.length > 0) {- const currentIndex = queue.shift()!;- componentIndices.push(currentIndex);-- for (- let candidateIndex = currentIndex + 1;- candidateIndex < entries.length;- candidateIndex++- ) {- if (consumed.has(candidateIndex)) {- continue;- }-- if (- doPillsOverlap(- entries[currentIndex]!.point,- entries[candidateIndex]!.point,- overlapPadding- ) &&- canVisuallyMergeMarkers(- entries[currentIndex]!.marker,- entries[candidateIndex]!.marker,- labelZoom- )- ) {- consumed.add(candidateIndex);- queue.push(candidateIndex);- }- }- }-- const componentEntries = componentIndices.map(- (componentIndex) => entries[componentIndex]!- );- const componentMarkers = componentEntries.map((entry) => entry.marker);-- if (componentMarkers.length === 1) {- const marker = componentMarkers[0]!;- mergedMarkers.push({- ...marker,- detailScope: getDetailQueryScope(marker, labelZoom),- id: getDisplayMarkerId(marker.members),- label: createDisplayLabel(marker, labelZoom),- mergedVisualClusters: 1,- screenPoint: entries[index]!.point,- });- continue;- }-- const members = componentMarkers.flatMap((marker) => marker.members);- const center = getAverageCenter(members);- const representativeCountry = normalizeLocationValue(- componentMarkers[0]?.location.country- );- const representativeCity = normalizeLocationValue(- componentMarkers[0]?.location.city- );-- const mergedMarker: CoordinateCluster = {- center,- count: componentMarkers.reduce((sum, marker) => sum + marker.count, 0),- members,- location: {- city: representativeCity,- country: representativeCountry,- },- };-- mergedMarkers.push({- ...mergedMarker,- detailScope: getMergedDetailQueryScope(labelZoom),- id: getDisplayMarkerId(mergedMarker.members),- label: createMergedDisplayLabel(mergedMarker, labelZoom),- mergedVisualClusters: componentMarkers.length,- screenPoint: getWeightedScreenPoint(- componentEntries.map((entry) => ({- count: entry.marker.count,- screenPoint: entry.point,- }))- ),- });- }-- return mergedMarkers;-}diff --git a/apps/start/src/components/realtime/map/map-geometry.ts b/apps/start/src/components/realtime/map/map-geometry.tsnew file mode 100644index 000000000..8019ac207--- /dev/null+++ b/apps/start/src/components/realtime/map/map-geometry.ts@@ -0,0 +1,288 @@+import type { GeoProjection } from 'd3-geo';+import { geoArea, geoCircle, geoMercator, geoPath } from 'd3-geo';+import type {+ Feature,+ FeatureCollection,+ MultiLineString,+ MultiPolygon,+ Polygon,+} from 'geojson';+import { feature, mesh } from 'topojson-client';+import type { GeometryCollection, Topology } from 'topojson-specification';+import fineAtlasUrl from 'world-atlas/countries-50m.json?url';+import coarseAtlasUrl from 'world-atlas/countries-110m.json?url';+import {+ BORDER_BUCKET_DEGREES,+ NIGHT_FEATHER_DEGREES,+ NIGHT_FEATHER_STEPS,+} from './map-constants';++/** Mercator runs to infinity at the poles; this band holds every inhabited place. */+const NORTH_LIMIT = 84;+const SOUTH_LIMIT = -58;+/** Where d3's Mercator clips; panning up or down stops here, so there is never an edge. */+const PAN_LATITUDE_LIMIT = 85;+const HIDDEN_COUNTRIES = new Set(['Antarctica']);+const COUNTRY_NAME_OVERRIDES: Record<string, string> = {+ 'United States of America': 'United States',+ 'Dem. Rep. Congo': 'DR Congo',+ 'Central African Rep.': 'CAR',+};+const EARTH_AXIAL_TILT = 23.44;+const DAYS_PER_YEAR = 365;+const DAYS_FROM_SOLSTICE_TO_YEAR_END = 10;+const MS_PER_DAY = 86_400_000;+const MINUTES_PER_DAY = 1440;++interface CountryProperties {+ name: string;+}+type CountryFeature = Feature<Polygon | MultiPolygon, CountryProperties>;+type CountriesTopology = Topology<{+ countries: GeometryCollection<CountryProperties>;+}>;++interface AtlasShapes {+ countries: CountryFeature[];+ borders: MultiLineString;+}++/** Two levels of detail: coarse for the whole world, fine for zoomed-in views. */+export interface WorldShapes {+ coarse: AtlasShapes;+ fine: AtlasShapes;+}++/** A projected box in world coordinates at zoom 1. */+export type WorldBox = [[number, number], [number, number]];++export interface BoundedPath {+ path: Path2D;+ bounds: WorldBox;+}++export interface CountryLabel {+ name: string;+ x: number;+ y: number;+ /** Projected area at zoom 1, so labels can appear as countries grow on screen. */+ area: number;+}++export interface MapGeometry {+ projection: GeoProjection;+ /** The whole world in one path each; cheap enough to fill in a few milliseconds. */+ coarseLand: Path2D;+ coarseBorders: Path2D;+ /** Per country, with bounds, so a zoomed-in view fills only what it shows. */+ fineCountries: BoundedPath[];+ fineBorders: BoundedPath[];+ labels: CountryLabel[];+ /** One world's projected width; the map repeats sideways at this interval. */+ worldWidth: number;+ /** Where the world starts horizontally, so copies line up with it. */+ worldLeft: number;+ /** Infinite sideways, Mercator's own limit up and down. */+ panBounds: [[number, number], [number, number]];+}++async function loadAtlas(url: string): Promise<AtlasShapes> {+ const response = await fetch(url);+ const topology: CountriesTopology = await response.json();+ const collection = feature(+ topology,+ topology.objects.countries+ ) as FeatureCollection<Polygon | MultiPolygon, CountryProperties>;++ return {+ countries: collection.features.filter(+ (country) => !HIDDEN_COUNTRIES.has(country.properties.name)+ ),+ borders: mesh(+ topology,+ topology.objects.countries,+ (a, b) => a !== b+ ) as MultiLineString,+ };+}++export async function loadWorldShapes(): Promise<WorldShapes> {+ const [coarse, fine] = await Promise.all([+ loadAtlas(coarseAtlasUrl),+ loadAtlas(fineAtlasUrl),+ ]);+ return { coarse, fine };+}++function projectMercatorY(latitude: number) {+ const radians = (latitude * Math.PI) / 180;+ return Math.log(Math.tan(Math.PI / 4 + radians / 2));+}++/** Scales the map so it covers the viewport edge to edge, like `object-fit: cover`. */+function createCoverProjection(width: number, height: number) {+ const top = projectMercatorY(NORTH_LIMIT);+ const bottom = projectMercatorY(SOUTH_LIMIT);+ const scale = Math.max(width / (2 * Math.PI), height / (top - bottom));+ const middle = (top + bottom) / 2;++ return geoMercator()+ .scale(scale)+ .translate([width / 2, height / 2 + middle * scale]);+}++function getLargestPolygon(country: CountryFeature): Feature<Polygon> {+ const polygons =+ country.geometry.type === 'Polygon'+ ? [country.geometry.coordinates]+ : country.geometry.coordinates;++ let largest: Feature<Polygon> | null = null;+ let largestArea = -1;+ for (const coordinates of polygons) {+ const candidate: Feature<Polygon> = {+ type: 'Feature',+ properties: {},+ geometry: { type: 'Polygon', coordinates },+ };+ const area = geoArea(candidate);+ if (area > largestArea) {+ largest = candidate;+ largestArea = area;+ }+ }++ return largest ?? (country as Feature<Polygon>);+}++function createCountryLabels(+ countries: CountryFeature[],+ path: ReturnType<typeof geoPath>+): CountryLabel[] {+ const labels: CountryLabel[] = [];+ for (const country of countries) {+ const mainland = getLargestPolygon(country);+ const [x, y] = path.centroid(mainland);+ if (!(Number.isFinite(x) && Number.isFinite(y))) {+ continue;+ }+ const name = country.properties.name;+ labels.push({+ name: COUNTRY_NAME_OVERRIDES[name] ?? name,+ x,+ y,+ area: path.area(mainland),+ });+ }++ return labels.sort((a, b) => b.area - a.area);+}++function toBoundedPath(+ path: ReturnType<typeof geoPath>,+ shape: Parameters<typeof path>[0]+): BoundedPath {+ return { path: new Path2D(path(shape) ?? ''), bounds: path.bounds(shape) };+}++/** Border lines grouped into lat/long cells, so zoomed-in views stroke only nearby ones. */+function bucketBorders(+ path: ReturnType<typeof geoPath>,+ borders: MultiLineString+): BoundedPath[] {+ const cells = new Map<string, MultiLineString>();+ for (const line of borders.coordinates) {+ const [longitude, latitude] = line[0] ?? [0, 0];+ const key = `${Math.floor(longitude / BORDER_BUCKET_DEGREES)}:${Math.floor(latitude / BORDER_BUCKET_DEGREES)}`;+ const cell = cells.get(key) ?? { type: 'MultiLineString', coordinates: [] };+ cell.coordinates.push(line);+ cells.set(key, cell);+ }+ return [...cells.values()].map((cell) => toBoundedPath(path, cell));+}++export function createMapGeometry(+ shapes: WorldShapes,+ size: { width: number; height: number }+): MapGeometry {+ const projection = createCoverProjection(size.width, size.height);+ const path = geoPath(projection);+ const [worldLeft, panTop] = projection([-180, PAN_LATITUDE_LIMIT]) ?? [0, 0];+ const [, panBottom] = projection([0, -PAN_LATITUDE_LIMIT]) ?? [+ 0,+ size.height,+ ];++ return {+ projection,+ coarseLand: new Path2D(+ path({ type: 'FeatureCollection', features: shapes.coarse.countries }) ??+ ''+ ),+ coarseBorders: new Path2D(path(shapes.coarse.borders) ?? ''),+ fineCountries: shapes.fine.countries.map((country) =>+ toBoundedPath(path, country)+ ),+ fineBorders: bucketBorders(path, shapes.fine.borders),+ labels: createCountryLabels(shapes.coarse.countries, path),+ worldWidth: 2 * Math.PI * projection.scale(),+ worldLeft,+ panBounds: [+ [Number.NEGATIVE_INFINITY, panTop],+ [Number.POSITIVE_INFINITY, panBottom],+ ],+ };+}++/** Where the sun is straight overhead; precise enough to shade night on a map. */+export function getSubsolarPoint(date: Date): [number, number] {+ const startOfYear = Date.UTC(date.getUTCFullYear(), 0, 0);+ const dayOfYear = (date.getTime() - startOfYear) / MS_PER_DAY;+ const latitude =+ -EARTH_AXIAL_TILT *+ Math.cos(+ ((2 * Math.PI) / DAYS_PER_YEAR) *+ (dayOfYear + DAYS_FROM_SOLSTICE_TO_YEAR_END)+ );+ const minutesIntoDay = date.getUTCHours() * 60 + date.getUTCMinutes();+ const longitude = 180 - (minutesIntoDay / MINUTES_PER_DAY) * 360;++ return [longitude, latitude];+}++export interface NightRing {+ path: Path2D;+ /** How dark this ring is, as a share of full night. */+ strength: number;+}++/**+ * Night as rings between concentric circles, each filled once with the+ * even-odd rule, so the shade covers the night area about once instead of+ * stacking a dozen overlapping fills.+ */+export function createNightRings(+ projection: GeoProjection,+ date: Date+): NightRing[] {+ const [sunLongitude, sunLatitude] = getSubsolarPoint(date);+ const antipode: [number, number] = [sunLongitude + 180, -sunLatitude];+ const path = geoPath(projection);+ const circle = geoCircle().center(antipode);+ const radiusAt = (step: number) =>+ 90 - (step * NIGHT_FEATHER_DEGREES) / NIGHT_FEATHER_STEPS;++ const rings: NightRing[] = [];+ for (let step = 0; step < NIGHT_FEATHER_STEPS; step++) {+ const ring = new Path2D(path(circle.radius(radiusAt(step))()) ?? '');+ ring.addPath(new Path2D(path(circle.radius(radiusAt(step + 1))()) ?? ''));+ rings.push({ path: ring, strength: (step + 1) / NIGHT_FEATHER_STEPS });+ }+ rings.push({+ path: new Path2D(+ path(circle.radius(radiusAt(NIGHT_FEATHER_STEPS))()) ?? ''+ ),+ strength: 1,+ });+ return rings;+}diff --git a/apps/start/src/components/realtime/map/map-marker-pill.tsx b/apps/start/src/components/realtime/map/map-marker-pill.tsxdeleted file mode 100644index 0a15642b5..000000000--- a/apps/start/src/components/realtime/map/map-marker-pill.tsx+++ /dev/null@@ -1,35 +0,0 @@-import type { DisplayMarker } from './map-types';-import { cn } from '@/lib/utils';--export function MapMarkerPill({- marker,- onClick,-}: {- marker: DisplayMarker;- onClick?: () => void;-}) {- return (- <button- className={cn(- 'inline-flex select-none items-center gap-1.5 whitespace-nowrap rounded-lg border border-border/10 bg-background px-[10px] py-[5px] font-medium text-2xs text-foreground shadow-[0_4px_16px] shadow-background/20',- onClick ? 'cursor-pointer' : 'cursor-default'- )}- onClick={onClick}- type="button"- >- <span className="relative flex size-[7px] shrink-0">- <span className="absolute inset-0 animate-ping rounded-full bg-emerald-300 opacity-75" />- <span className="relative inline-flex size-[7px] rounded-full bg-emerald-500" />- </span>-- <span className="tabular-nums">{marker.count.toLocaleString()}</span>-- {marker.label ? (- <>- <span className="h-4 w-px shrink-0 bg-foreground/20" />- <span className="max-w-[110px] truncate">{marker.label}</span>- </>- ) : null}- </button>- );-}diff --git a/apps/start/src/components/realtime/map/map-markers-canvas.ts b/apps/start/src/components/realtime/map/map-markers-canvas.tsnew file mode 100644index 000000000..9c81b7d94--- /dev/null+++ b/apps/start/src/components/realtime/map/map-markers-canvas.ts@@ -0,0 +1,133 @@+import type { ZoomTransform } from 'd3-zoom';+import {+ MARKER_ACTIVE_RING_GAP,+ MARKER_PULSE_ALPHA,+ MARKER_PULSE_DURATION_MS,+ MARKER_PULSE_SPREAD,+ MARKER_STROKE_WIDTH,+ MARKER_VIEWPORT_MARGIN,+} from './map-constants';++export interface MarkerStyle {+ fill: string;+ stroke: string;+ ring: string;+}++export interface DrawnMarker {+ id: string;+ /** World coordinates at zoom 1. */+ x: number;+ y: number;+ radius: number;+ pulses: boolean;+}++const FULL_TURN = 2 * Math.PI;+const HASH_MODULUS = 1_000_003;+const PHASE_STEPS = 1000;++/**+ * Draws every visible dot in one fill and one stroke. Hundreds of dots cost+ * about a millisecond this way, where hundreds of DOM nodes would each need+ * style and paint work on every frame of a zoom.+ */+export function drawMarkers({+ context,+ markers,+ transform,+ viewport,+ copyOffsets,+ activeId,+ style,+ now,+}: {+ context: CanvasRenderingContext2D;+ markers: DrawnMarker[];+ transform: ZoomTransform;+ viewport: { width: number; height: number; pixelRatio: number };+ copyOffsets: number[];+ activeId: string | null;+ style: MarkerStyle;+ /** Drives the pulse rings; pass the frame time. */+ now: number;+}) {+ const { pixelRatio } = viewport;+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(+ 0,+ 0,+ viewport.width * pixelRatio,+ viewport.height * pixelRatio+ );+ context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);++ const dots = new Path2D();+ const ring = new Path2D();+ const margin = MARKER_VIEWPORT_MARGIN;+ context.fillStyle = style.fill;+ for (const offset of copyOffsets) {+ for (const marker of markers) {+ const x = transform.applyX(marker.x + offset);+ const y = transform.applyY(marker.y);+ if (+ x < -margin ||+ x > viewport.width + margin ||+ y < -margin ||+ y > viewport.height + margin+ ) {+ continue;+ }+ if (marker.pulses) {+ drawPulse(context, marker, x, y, now);+ }+ dots.moveTo(x + marker.radius, y);+ dots.arc(x, y, marker.radius, 0, FULL_TURN);+ if (marker.id === activeId) {+ const ringRadius = marker.radius + MARKER_ACTIVE_RING_GAP;+ ring.moveTo(x + ringRadius, y);+ ring.arc(x, y, ringRadius, 0, FULL_TURN);+ }+ }+ }++ context.globalAlpha = 1;+ context.fillStyle = style.fill;+ context.fill(dots);+ context.strokeStyle = style.stroke;+ context.lineWidth = MARKER_STROKE_WIDTH;+ context.stroke(dots);++ if (activeId) {+ context.strokeStyle = style.ring;+ context.lineWidth = MARKER_STROKE_WIDTH;+ context.stroke(ring);+ }+}++/** A ring that grows out of the dot and fades, each dot on its own beat. */+function drawPulse(+ context: CanvasRenderingContext2D,+ marker: DrawnMarker,+ x: number,+ y: number,+ now: number+) {+ const offset = hashPhase(marker.id) * MARKER_PULSE_DURATION_MS;+ const phase =+ ((now + offset) % MARKER_PULSE_DURATION_MS) / MARKER_PULSE_DURATION_MS;+ const eased = 1 - (1 - phase) * (1 - phase);+ const radius = marker.radius * (1 + (MARKER_PULSE_SPREAD - 1) * eased);+ context.globalAlpha = MARKER_PULSE_ALPHA * (1 - eased);+ context.beginPath();+ context.arc(x, y, radius, 0, FULL_TURN);+ context.fill();+}++function hashPhase(id: string) {+ let hash = 0;+ for (let index = 0; index < id.length; index++) {+ hash = (hash * 31 + id.charCodeAt(index)) % HASH_MODULUS;+ }+ return (hash % PHASE_STEPS) / PHASE_STEPS;+}diff --git a/apps/start/src/components/realtime/map/map-raster.ts b/apps/start/src/components/realtime/map/map-raster.tsnew file mode 100644index 000000000..4f902dd7f--- /dev/null+++ b/apps/start/src/components/realtime/map/map-raster.ts@@ -0,0 +1,321 @@+import type { ZoomTransform } from 'd3-zoom';+import {+ RASTER_DETAIL_MARGIN,+ RASTER_DETAIL_MAX_PIXELS,+ RASTER_FINE_DETAIL_ZOOM,+ RASTER_MAX_PIXEL_RATIO,+ RASTER_SETTLE_MS,+} from './map-constants';+import type { MapGeometry, NightRing, WorldBox } from './map-geometry';++export interface WorldStyle {+ ocean: string;+ land: string;+ border: string;+ night: string;+ nightAlpha: number;+}++interface Viewport {+ width: number;+ height: number;+ pixelRatio: number;+}++/** A crisp bitmap of the area around the viewport at one exact zoom. */+interface DetailBitmap {+ canvas: HTMLCanvasElement;+ k: number;+ /** Top-left of the bitmap in world coordinates (zoom 1). */+ left: number;+ top: number;+ /** World units covered. */+ width: number;+ height: number;+ pixelRatio: number;+}++/**+ * Keeps the drawn world in bitmaps so a pan or zoom frame is a blit, not a+ * fill of every coastline. A low-res copy of the whole world always exists;+ * a crisp one for the current view is rendered once the gesture settles.+ */+export class WorldRaster {+ private base: HTMLCanvasElement | null = null;+ private basePixelRatio = 1;+ private detail: DetailBitmap | null = null;+ /** Reused between renders; allocating a bitmap this size each time was most of the cost. */+ private detailCanvas: HTMLCanvasElement | null = null;+ private settleTimer: ReturnType<typeof setTimeout> | null = null;++ constructor(+ private geometry: MapGeometry,+ private night: NightRing[],+ private style: WorldStyle,+ private readonly onDetailReady: () => void+ ) {}++ update(geometry: MapGeometry, night: NightRing[], style: WorldStyle) {+ this.geometry = geometry;+ this.night = night;+ this.style = style;+ this.base = null;+ this.detail = null;+ }++ dispose() {+ if (this.settleTimer) {+ clearTimeout(this.settleTimer);+ }+ }++ draw(+ context: CanvasRenderingContext2D,+ transform: ZoomTransform,+ viewport: Viewport+ ) {+ const { pixelRatio } = viewport;+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.fillStyle = this.style.ocean;+ context.fillRect(+ 0,+ 0,+ viewport.width * pixelRatio,+ viewport.height * pixelRatio+ );+ context.setTransform(+ pixelRatio * transform.k,+ 0,+ 0,+ pixelRatio * transform.k,+ pixelRatio * transform.x,+ pixelRatio * transform.y+ );++ const detailCovers = this.detailCovers(transform, viewport);+ if (!detailCovers) {+ const base = this.getBase();+ const { worldLeft, worldWidth, panBounds } = this.geometry;+ const panTop = panBounds[0][1];+ for (const offset of this.visibleCopies(transform, viewport)) {+ context.drawImage(+ base,+ worldLeft + offset,+ panTop,+ worldWidth,+ base.height / this.basePixelRatio+ );+ }+ this.scheduleDetail(transform, viewport);+ }++ if (this.detail && this.detail.k === transform.k) {+ const { canvas, left, top, width, height } = this.detail;+ context.drawImage(canvas, left, top, width, height);+ }+ }++ private detailCovers(transform: ZoomTransform, viewport: Viewport) {+ const detail = this.detail;+ if (!detail || detail.k !== transform.k) {+ return false;+ }+ const [[left, top], [right, bottom]] = this.visibleWorldBox(+ transform,+ viewport+ );+ return (+ left >= detail.left &&+ top >= detail.top &&+ right <= detail.left + detail.width &&+ bottom <= detail.top + detail.height+ );+ }++ private visibleWorldBox(+ transform: ZoomTransform,+ viewport: Viewport+ ): [[number, number], [number, number]] {+ return [+ [transform.invertX(0), transform.invertY(0)],+ [transform.invertX(viewport.width), transform.invertY(viewport.height)],+ ];+ }++ private visibleCopies(transform: ZoomTransform, viewport: Viewport) {+ const [[left], [right]] = this.visibleWorldBox(transform, viewport);+ return this.copiesInRange(left, right);+ }++ /** Offsets of every world copy overlapping a horizontal range in world coordinates. */+ private copiesInRange(left: number, right: number) {+ const { worldLeft, worldWidth } = this.geometry;+ const first = Math.floor((left - worldLeft) / worldWidth);+ const last = Math.floor((right - worldLeft) / worldWidth);+ const offsets: number[] = [];+ for (let copy = first; copy <= last; copy++) {+ offsets.push(copy * worldWidth);+ }+ return offsets;+ }++ /** The whole world at zoom 1, at screen resolution; the fallback while moving. */+ private getBase() {+ if (this.base) {+ return this.base;+ }+ const { worldLeft, worldWidth, panBounds } = this.geometry;+ const panTop = panBounds[0][1];+ const worldHeight = panBounds[1][1] - panTop;+ const pixelRatio = 1;+ const canvas = document.createElement('canvas');+ canvas.width = Math.ceil(worldWidth * pixelRatio);+ canvas.height = Math.ceil(worldHeight * pixelRatio);+ const context = canvas.getContext('2d');+ if (context) {+ context.setTransform(+ pixelRatio,+ 0,+ 0,+ pixelRatio,+ -worldLeft * pixelRatio,+ -panTop * pixelRatio+ );+ this.drawWorld(context, 1, [0], null);+ }+ this.base = canvas;+ this.basePixelRatio = pixelRatio;+ return canvas;+ }++ private scheduleDetail(transform: ZoomTransform, viewport: Viewport) {+ if (this.settleTimer) {+ clearTimeout(this.settleTimer);+ }+ this.settleTimer = setTimeout(() => {+ this.settleTimer = null;+ this.renderDetail(transform, viewport);+ this.onDetailReady();+ }, RASTER_SETTLE_MS);+ }++ private renderDetail(transform: ZoomTransform, viewport: Viewport) {+ const pixelRatio = Math.min(viewport.pixelRatio, RASTER_MAX_PIXEL_RATIO);+ const marginX = viewport.width * RASTER_DETAIL_MARGIN;+ const marginY = viewport.height * RASTER_DETAIL_MARGIN;+ let screenWidth = viewport.width + 2 * marginX;+ let screenHeight = viewport.height + 2 * marginY;+ const pixels = screenWidth * screenHeight * pixelRatio * pixelRatio;+ if (pixels > RASTER_DETAIL_MAX_PIXELS) {+ const shrink = Math.sqrt(RASTER_DETAIL_MAX_PIXELS / pixels);+ screenWidth *= shrink;+ screenHeight *= shrink;+ }+ const offsetX = (screenWidth - viewport.width) / 2;+ const offsetY = (screenHeight - viewport.height) / 2;+ const { k } = transform;+ const left = transform.invertX(-offsetX);+ const top = transform.invertY(-offsetY);++ const canvas = this.detailCanvas ?? document.createElement('canvas');+ this.detailCanvas = canvas;+ const width = Math.ceil(screenWidth * pixelRatio);+ const height = Math.ceil(screenHeight * pixelRatio);+ const context = canvas.getContext('2d');+ if (!context) {+ return;+ }+ if (canvas.width !== width || canvas.height !== height) {+ canvas.width = width;+ canvas.height = height;+ } else {+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, width, height);+ }+ context.setTransform(+ pixelRatio * k,+ 0,+ 0,+ pixelRatio * k,+ -left * pixelRatio * k,+ -top * pixelRatio * k+ );+ const area: WorldBox = [+ [left, top],+ [left + screenWidth / k, top + screenHeight / k],+ ];+ const copies = this.copiesInRange(area[0][0], area[1][0]);+ this.drawWorld(context, k, copies, area);++ this.detail = {+ canvas,+ k,+ left,+ top,+ width: screenWidth / k,+ height: screenHeight / k,+ pixelRatio,+ };+ }++ /** Fills the coarse world, or only the detailed countries inside `area` when zoomed in. */+ private drawWorld(+ context: CanvasRenderingContext2D,+ k: number,+ copies: number[],+ area: WorldBox | null+ ) {+ const { style, night, geometry } = this;+ const useFine = area !== null && k >= RASTER_FINE_DETAIL_ZOOM;+ const hairline = 1 / k;+ for (const offset of copies) {+ context.save();+ context.translate(offset, 0);+ const local: WorldBox | null = area && [+ [area[0][0] - offset, area[0][1]],+ [area[1][0] - offset, area[1][1]],+ ];++ context.fillStyle = style.land;+ if (useFine && local) {+ for (const country of geometry.fineCountries) {+ if (overlaps(country.bounds, local)) {+ context.fill(country.path);+ }+ }+ } else {+ context.fill(geometry.coarseLand);+ }++ context.strokeStyle = style.border;+ context.lineWidth = hairline;+ if (useFine && local) {+ for (const bucket of geometry.fineBorders) {+ if (overlaps(bucket.bounds, local)) {+ context.stroke(bucket.path);+ }+ }+ } else {+ context.stroke(geometry.coarseBorders);+ }++ // Night deepens ring by ring past the terminator.+ context.fillStyle = style.night;+ for (const ring of night) {+ context.globalAlpha = style.nightAlpha * ring.strength;+ context.fill(ring.path, 'evenodd');+ }+ context.globalAlpha = 1;+ context.restore();+ }+ }+}++function overlaps(a: WorldBox, b: WorldBox) {+ return (+ a[0][0] <= b[1][0] &&+ a[1][0] >= b[0][0] &&+ a[0][1] <= b[1][1] &&+ a[1][1] >= b[0][1]+ );+}diff --git a/apps/start/src/components/realtime/map/map-types.ts b/apps/start/src/components/realtime/map/map-types.tsindex b78e68dbf..d3f720171 100644--- a/apps/start/src/components/realtime/map/map-types.ts+++ b/apps/start/src/components/realtime/map/map-types.ts@@ -1,55 +1,30 @@-import type { Coordinate, CoordinateCluster } from './coordinates';-import type { MapBadgeDisplayMarker } from './realtime-map-badge-slice';+import type { RouterOutputs } from '@/trpc/client';-export type DisplayMarker = MapBadgeDisplayMarker;--export type ContinentBucket =- | 'north-america'- | 'south-america'- | 'europe'- | 'africa'- | 'asia'- | 'oceania'- | 'unknown';+export type RealtimeMapPoint = RouterOutputs['realtime']['coordinates'][number];-export type MapProjection = (- point: [number, number]-) => [number, number] | null;--export interface ZoomMovePosition {- zoom: number;+export interface RealtimeMapProps {+ projectId: string;+ markers: RealtimeMapPoint[];}-export interface ZoomMoveEndPosition {- coordinates: [number, number];- zoom: number;+export interface MapLocation {+ city?: string;+ country?: string;+ lat: number;+ long: number;}-export interface GeographyFeature {- rsmKey: string;- properties: {- name?: string;+/** What a clicked dot hands to the detail panel; must stay serializable. */+export interface MapBadgeDisplayMarker {+ id: string;+ label: string;+ count: number;+ detailScope: 'coordinate';+ locations: MapLocation[];+ screenPoint: {+ x: number;+ y: number;};}-export interface DisplayMarkerCache {- markers: CoordinateCluster[];- projection: MapProjection | null;- viewportCenter: [number, number];- zoom: number;- size: { width: number; height: number } | null;- result: DisplayMarker[];-}--export interface MapSidebarConfig {- width: number;- position: 'left' | 'right';-}--export interface RealtimeMapProps {- projectId: string;- markers: Coordinate[];- sidebarConfig?: MapSidebarConfig;-}--export interface MapCanvasProps extends RealtimeMapProps {}+export type DisplayMarker = MapBadgeDisplayMarker;diff --git a/apps/start/src/components/realtime/map/map-utils.ts b/apps/start/src/components/realtime/map/map-utils.tsindex 5b044e458..a3fa9dfbd 100644--- a/apps/start/src/components/realtime/map/map-utils.ts+++ b/apps/start/src/components/realtime/map/map-utils.ts@@ -1,11 +1,15 @@-import type { Coordinate, CoordinateCluster } from './coordinates';-import { getClusterDetailLevel } from './coordinates';-import type { DisplayMarker } from './map-types';--export const PILL_W = 220;-export const PILL_H = 32;-export const ANCHOR_R = 3;-export const PILL_GAP = 6;+import {+ DETAIL_CARD_ANCHOR_OFFSET,+ DETAIL_CARD_GAP,+ DETAIL_CARD_INSET,+ DETAIL_CARD_MIN_HEIGHT,+ DETAIL_CARD_WIDTH,+ MARKER_MAX_RADIUS,+ MARKER_MIN_RADIUS,+ MARKER_RADIUS_PER_SQRT_VISITOR,+ PLACE_MAX_LOCATIONS,+} from './map-constants';+import type { DisplayMarker, MapLocation, RealtimeMapPoint } from './map-types';const COUNTRY_CODE_PATTERN = /^[A-Z]{2}$/;@@ -14,57 +18,70 @@ const regionDisplayNames =? new Intl.DisplayNames(['en'], { type: 'region' }): null;-export function normalizeLocationValue(value?: string) {+function normalizeLocationValue(value?: string) {const trimmed = value?.trim();return trimmed ? trimmed : undefined;}-export function isValidCoordinate(coordinate: Coordinate) {- return Number.isFinite(coordinate.lat) && Number.isFinite(coordinate.long);+function isValidPoint(point: RealtimeMapPoint) {+ return Number.isFinite(point.lat) && Number.isFinite(point.long);}-export function getCoordinateIdentity(coordinate: Coordinate) {- return [- normalizeLocationValue(coordinate.country) ?? '',- normalizeLocationValue(coordinate.city) ?? '',- isValidCoordinate(coordinate) ? coordinate.long.toFixed(4) : 'invalid-long',- isValidCoordinate(coordinate) ? coordinate.lat.toFixed(4) : 'invalid-lat',- ].join(':');+export interface MapPlace {+ id: string;+ label: string;+ count: number;+ lat: number;+ long: number;+ locations: MapLocation[];}-export function getDisplayMarkerId(members: Coordinate[]) {- const validMembers = members.filter(isValidCoordinate);-- if (validMembers.length === 0) {- return 'invalid-cluster';+/** A city is one dot: GeoIP gives one city several nearby coordinates, which would stack. */+function getPlaceId(point: RealtimeMapPoint) {+ const country = normalizeLocationValue(point.country) ?? '';+ const city = normalizeLocationValue(point.city);+ if (city) {+ return `${country}:${city}`;}-- return validMembers.map(getCoordinateIdentity).sort().join('|');+ return `${country}:${point.long.toFixed(2)}:${point.lat.toFixed(2)}`;}-export function getWeightedScreenPoint(- markers: Array<{- count: number;- screenPoint: {- x: number;- y: number;- };- }>-) {- let weightedX = 0;- let weightedY = 0;- let totalWeight = 0;+export function groupPointsByPlace(points: RealtimeMapPoint[]): MapPlace[] {+ const places = new Map<string, MapPlace>();- for (const marker of markers) {- weightedX += marker.screenPoint.x * marker.count;- weightedY += marker.screenPoint.y * marker.count;- totalWeight += marker.count;+ for (const point of points) {+ if (!isValidPoint(point)) {+ continue;+ }+ const id = getPlaceId(point);+ const location: MapLocation = {+ city: point.city,+ country: point.country,+ lat: point.lat,+ long: point.long,+ };+ const place = places.get(id);+ if (!place) {+ places.set(id, {+ id,+ label: getPointLabel(point),+ count: point.count,+ lat: point.lat,+ long: point.long,+ locations: [location],+ });+ continue;+ }+ const total = place.count + point.count;+ place.lat = (place.lat * place.count + point.lat * point.count) / total;+ place.long = (place.long * place.count + point.long * point.count) / total;+ place.count = total;+ if (place.locations.length < PLACE_MAX_LOCATIONS) {+ place.locations.push(location);+ }}- return {- x: weightedX / totalWeight,- y: weightedY / totalWeight,- };+ return [...places.values()];}export function formatCountryLabel(country?: string) {@@ -81,149 +98,41 @@ export function formatCountryLabel(country?: string) {return regionDisplayNames?.of(normalized) ?? normalized;}-export function summarizeLocation(members: Coordinate[]) {- const cities = new Set<string>();- const countries = new Set<string>();-- for (const member of members) {- const city = normalizeLocationValue(member.city);- const country = normalizeLocationValue(member.country);-- if (city) {- cities.add(city);- }-- if (country) {- countries.add(country);- }- }-- return {- cityCount: cities.size,- countryCount: countries.size,- firstCity: [...cities][0],- firstCountry: [...countries][0],- };+function getPointLabel(point: RealtimeMapPoint) {+ const city = normalizeLocationValue(point.city);+ const country = formatCountryLabel(point.country);+ return [city, country].filter(Boolean).join(', ') || 'Unknown location';}-export function createDisplayLabel(- marker: CoordinateCluster,- zoom: number-): string {- const detailLevel = getClusterDetailLevel(zoom);-- if (detailLevel === 'country') {- return (- formatCountryLabel(marker.location.country) ?? marker.location.city ?? '?'- );- }-- if (detailLevel === 'city') {- return (- marker.location.city ?? formatCountryLabel(marker.location.country) ?? '?'- );- }-- const cityMember = marker.members.find((member) => member.city?.trim());- return (- cityMember?.city?.trim() ??- formatCountryLabel(marker.location.country) ??- '?'- );-}--export function getDetailQueryScope(- marker: CoordinateCluster,- zoom: number-): DisplayMarker['detailScope'] {- const detailLevel = getClusterDetailLevel(zoom);-- if (detailLevel === 'country') {- return 'country';- }-- if (detailLevel === 'city') {- return marker.location.city ? 'city' : 'country';- }-- return 'coordinate';-}--export function getMergedDetailQueryScope(- zoom: number-): DisplayMarker['detailScope'] {- const detailLevel = getClusterDetailLevel(zoom);-- return detailLevel === 'country' ? 'country' : 'city';-}--export function createMergedDisplayLabel(- marker: CoordinateCluster,- zoom: number-): string {- const detailLevel = getClusterDetailLevel(zoom);- const summary = summarizeLocation(marker.members);-- if (detailLevel === 'country') {- if (summary.countryCount <= 1) {- return (- formatCountryLabel(summary.firstCountry) ?? summary.firstCity ?? '?'- );- }-- return `${summary.countryCount} countries`;- }-- if (detailLevel === 'city') {- if (summary.cityCount === 1 && summary.firstCity) {- return summary.firstCity;- }-- if (summary.countryCount === 1) {- const country = formatCountryLabel(summary.firstCountry);-- if (country && summary.cityCount > 1) {- return `${country}, ${summary.cityCount} cities`;- }-- return country ?? `${summary.cityCount} places`;- }-- if (summary.countryCount > 1) {- return `${summary.countryCount} countries`;- }- }-- if (summary.cityCount === 1 && summary.firstCity) {- return summary.firstCity;- }-- if (summary.countryCount === 1) {- const country = formatCountryLabel(summary.firstCountry);-- if (country && summary.cityCount > 1) {- return `${country}, ${summary.cityCount} places`;- }-- return country ?? `${marker.members.length} places`;- }-- return `${Math.max(summary.countryCount, summary.cityCount, 2)} places`;+export function getMarkerRadius(count: number) {+ const radius =+ MARKER_MIN_RADIUS + Math.sqrt(count) * MARKER_RADIUS_PER_SQRT_VISITOR;+ return Math.min(MARKER_MAX_RADIUS, radius);}+/** Sits beside the dot, never on it, so the place you clicked stays in view. */export function getBadgeOverlayPosition(marker: DisplayMarker,size: { width: number; height: number }) {- const overlayWidth = Math.min(380, size.width - 24);- const preferredLeft = marker.screenPoint.x - overlayWidth / 2;+ const overlayWidth = Math.min(+ DETAIL_CARD_WIDTH,+ size.width - DETAIL_CARD_INSET * 2+ );+ const rightOfDot = marker.screenPoint.x + DETAIL_CARD_GAP;+ const leftOfDot = marker.screenPoint.x - DETAIL_CARD_GAP - overlayWidth;+ const fitsOnRight =+ rightOfDot + overlayWidth <= size.width - DETAIL_CARD_INSET;const left = Math.max(- 12,- Math.min(preferredLeft, size.width - overlayWidth - 12)+ DETAIL_CARD_INSET,+ fitsOnRight ? rightOfDot : leftOfDot);const top = Math.max(- 12,- Math.min(marker.screenPoint.y + 16, size.height - 340)+ DETAIL_CARD_INSET,+ Math.min(+ marker.screenPoint.y - DETAIL_CARD_ANCHOR_OFFSET,+ size.height - DETAIL_CARD_MIN_HEIGHT+ ));return { left, overlayWidth, top };@@ -238,61 +147,3 @@ export function getProfileDisplayName(profile: {const name = [profile.firstName, profile.lastName].filter(Boolean).join(' ');return name || profile.email || profile.id;}--export function getUniqueCoordinateDetailLocations(members: Coordinate[]) {- const locationsByKey: Record<- string,- {- city?: string;- country?: string;- lat: number;- long: number;- }- > = {};-- for (const member of members) {- if (!isValidCoordinate(member)) {- continue;- }-- const key = [- normalizeLocationValue(member.country) ?? '',- normalizeLocationValue(member.city) ?? '',- member.long.toFixed(4),- member.lat.toFixed(4),- ].join(':');-- locationsByKey[key] = {- city: member.city,- country: member.country,- lat: member.lat,- long: member.long,- };- }-- return Object.values(locationsByKey);-}--export function getUniquePlaceDetailLocations(members: Coordinate[]) {- const locationsByKey: Record<- string,- {- city?: string;- country?: string;- }- > = {};-- for (const member of members) {- const key = [- normalizeLocationValue(member.country) ?? '',- normalizeLocationValue(member.city) ?? '',- ].join(':');-- locationsByKey[key] = {- city: member.city,- country: member.country,- };- }-- return Object.values(locationsByKey);-}diff --git a/apps/start/src/components/realtime/map/map.helpers.tsx b/apps/start/src/components/realtime/map/map.helpers.tsxdeleted file mode 100644index da3c6ad45..000000000--- a/apps/start/src/components/realtime/map/map.helpers.tsx+++ /dev/null@@ -1,92 +0,0 @@-import { useCallback, useEffect, useRef, useState } from 'react';-import { useZoomPan } from 'react-simple-maps';-import type { Coordinate } from './coordinates';--export const GEO_MAP_URL =- 'https://unpkg.com/[email protected]/countries-50m.json';--export function useAnimatedState(initialValue: number) {- const [value, setValue] = useState(initialValue);- const [target, setTarget] = useState(initialValue);- const ref = useRef<number>(0);- const animate = useCallback(() => {- ref.current = requestAnimationFrame(() => {- setValue((prevValue) => {- const diff = target - prevValue;- if (Math.abs(diff) < 0.01) {- return target; // Stop animating when close enough- }- // Adjust this factor (e.g., 0.02) to control the speed of the animation- return prevValue + diff * 0.05;- });- animate(); // Loop the animation frame- });- }, [target]);-- useEffect(() => {- animate(); // Start the animation- return () => cancelAnimationFrame(ref.current!); // Cleanup the animation on unmount- }, [animate]);-- useEffect(() => {- setTarget(initialValue);- }, [initialValue]);-- return [value, setTarget] as const;-}--export const getBoundingBox = (coordinates: Coordinate[]) => {- const longitudes = coordinates.map((coord) => coord.long);- const latitudes = coordinates.map((coord) => coord.lat);- const minLat = Math.min(...latitudes);- const maxLat = Math.max(...latitudes);- const minLong = Math.min(...longitudes);- const maxLong = Math.max(...longitudes);-- return { minLat, maxLat, minLong, maxLong };-};--export const determineZoom = (- bbox: ReturnType<typeof getBoundingBox>,- aspectRatio = 1.0-): number => {- const latDiff = bbox.maxLat - bbox.minLat;- const longDiff = bbox.maxLong - bbox.minLong;-- // Normalize longitudinal span based on latitude to correct for increasing distortion- // towards the poles in a Mercator projection.- const avgLat = (bbox.maxLat + bbox.minLat) / 2;- const longDiffAdjusted = longDiff * Math.cos((avgLat * Math.PI) / 180);-- // Adjust calculations depending on the aspect ratio.- const maxDiff =- aspectRatio > 1- ? Math.max(latDiff / aspectRatio, longDiffAdjusted) // Wider than tall- : Math.max(latDiff, longDiffAdjusted * aspectRatio); // Taller than wide-- // Adjust zoom level scaling factor based on application or testing.- const zoom = Math.max(1, Math.min(20, 200 / maxDiff));- return zoom;-};--export function CustomZoomableGroup({- zoom,- center,- children,-}: {- zoom: number;- center: [number, number];- children: React.ReactNode;-}) {- const { mapRef, transformString } = useZoomPan({- center,- zoom,- filterZoomEvent: () => false,- });-- return (- <g ref={mapRef}>- <g transform={transformString}>{children}</g>- </g>- );-}diff --git a/apps/start/src/components/realtime/map/realtime-map-badge-slice.ts b/apps/start/src/components/realtime/map/realtime-map-badge-slice.tsindex 102101e32..3fab3e039 100644--- a/apps/start/src/components/realtime/map/realtime-map-badge-slice.ts+++ b/apps/start/src/components/realtime/map/realtime-map-badge-slice.ts@@ -1,18 +1,6 @@import type { PayloadAction } from '@reduxjs/toolkit';import { createSlice } from '@reduxjs/toolkit';-import type { CoordinateCluster } from './coordinates';--/** Serializable marker payload for the realtime map badge detail panel */-export interface MapBadgeDisplayMarker extends CoordinateCluster {- detailScope: 'city' | 'coordinate' | 'country' | 'merged';- id: string;- label: string;- mergedVisualClusters: number;- screenPoint: {- x: number;- y: number;- };-}+import type { MapBadgeDisplayMarker } from './map-types';interface RealtimeMapBadgeState {open: boolean;diff --git a/apps/start/src/components/realtime/map/realtime-map.tsx b/apps/start/src/components/realtime/map/realtime-map.tsxnew file mode 100644index 000000000..729cbdb62--- /dev/null+++ b/apps/start/src/components/realtime/map/realtime-map.tsx@@ -0,0 +1,875 @@+import { select } from 'd3-selection';+import 'd3-transition';+import type { D3ZoomEvent, ZoomBehavior, ZoomTransform } from 'd3-zoom';+import { zoom, zoomIdentity, zoomTransform } from 'd3-zoom';+import { LocateFixedIcon, MinusIcon, PlusIcon } from 'lucide-react';+import {+ memo,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import {+ LABEL_MAX_COUNT,+ LABEL_MIN_SCREEN_AREA,+ MAP_MAX_ZOOM,+ MAP_MIN_ZOOM,+ MAP_ZOOM_ANIMATION_MS,+ MAP_ZOOM_BUTTON_FACTOR,+ MARKER_HIT_RADIUS,+ MARKER_PULSE_LIMIT,+ NIGHT_MAX_ALPHA_DARK,+ NIGHT_MAX_ALPHA_LIGHT,+ NIGHT_REFRESH_MS,+ RASTER_SETTLE_MS,+ RESIZE_SETTLE_MS,+} from './map-constants';+import type { CountryLabel, MapGeometry, WorldShapes } from './map-geometry';+import {+ createMapGeometry,+ createNightRings,+ loadWorldShapes,+} from './map-geometry';+import type { MarkerStyle } from './map-markers-canvas';+import { drawMarkers } from './map-markers-canvas';+import type { WorldStyle } from './map-raster';+import { WorldRaster } from './map-raster';+import type { RealtimeMapPoint, RealtimeMapProps } from './map-types';+import type { MapPlace } from './map-utils';+import { getMarkerRadius, groupPointsByPlace } from './map-utils';+import {+ closeMapBadgeDetails,+ openMapBadgeDetails,+} from './realtime-map-badge-slice';+import { useTheme } from '@/hooks/use-theme';+import { useDispatch, useSelector } from '@/redux';+import { cn } from '@/utils/cn';++interface PlacedMarker {+ id: string;+ place: MapPlace;+ /** World coordinates at zoom 1. */+ x: number;+ y: number;+ radius: number;+ pulses: boolean;+}++interface ScreenPoint {+ x: number;+ y: number;+}++interface HoveredMarker extends ScreenPoint {+ marker: PlacedMarker;+}++interface MapStyle {+ world: WorldStyle;+ markers: MarkerStyle;+}++/** Safari reports trackpad pinches as its own gesture events, not ctrl+wheel. */+interface SafariGestureEvent extends UIEvent {+ scale: number;+ clientX: number;+ clientY: number;+}++const FALLBACK_MARKER_FILL = '#10b981';+const FALLBACK_MARKER_RING = '#34d399';++let worldShapesPromise: Promise<WorldShapes> | null = null;++function useWorldShapes() {+ const [shapes, setShapes] = useState<WorldShapes | null>(null);++ useEffect(() => {+ let cancelled = false;+ worldShapesPromise ??= loadWorldShapes();+ worldShapesPromise+ .then((loaded) => {+ if (!cancelled) {+ setShapes(loaded);+ }+ })+ .catch(() => {+ // Let the next mount try again instead of caching the failure.+ worldShapesPromise = null;+ });+ return () => {+ cancelled = true;+ };+ }, []);++ return shapes;+}++/** The first size lands at once; later ones wait for the resize to pause. */+function useElementSize(ref: React.RefObject<HTMLElement | null>) {+ const [size, setSize] = useState({ width: 0, height: 0 });++ useEffect(() => {+ const element = ref.current;+ if (!element) {+ return;+ }+ let timer: ReturnType<typeof setTimeout> | null = null;+ let isFirst = true;+ const observer = new ResizeObserver(([entry]) => {+ if (!entry) {+ return;+ }+ const next = {+ width: entry.contentRect.width,+ height: entry.contentRect.height,+ };+ if (isFirst) {+ isFirst = false;+ setSize(next);+ return;+ }+ if (timer) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => setSize(next), RESIZE_SETTLE_MS);+ });+ observer.observe(element);+ return () => {+ observer.disconnect();+ if (timer) {+ clearTimeout(timer);+ }+ };+ }, [ref]);++ return size;+}++function useCurrentMinute() {+ const [now, setNow] = useState(() => new Date());++ useEffect(() => {+ const interval = setInterval(() => setNow(new Date()), NIGHT_REFRESH_MS);+ return () => clearInterval(interval);+ }, []);++ return now;+}++function readMapStyle(element: HTMLElement, isDark: boolean): MapStyle {+ const style = getComputedStyle(element);+ const read = (name: string, fallback = '') =>+ style.getPropertyValue(name).trim() || fallback;++ return {+ world: {+ ocean: read('--def-100'),+ land: read('--def-300'),+ border: read('--def-100'),+ night: isDark ? '#000' : '#0f172a',+ nightAlpha: isDark ? NIGHT_MAX_ALPHA_DARK : NIGHT_MAX_ALPHA_LIGHT,+ },+ markers: {+ fill: read('--color-emerald-500', FALLBACK_MARKER_FILL),+ stroke: read('--def-100'),+ ring: read('--color-emerald-400', FALLBACK_MARKER_RING),+ },+ };+}++/** Canvas cannot use CSS variables, so the theme's values are read once the theme class is applied. */+function useMapStyle(+ containerRef: React.RefObject<HTMLDivElement | null>,+ isDark: boolean+) {+ const [style, setStyle] = useState<MapStyle | null>(null);++ useEffect(() => {+ const frame = requestAnimationFrame(() => {+ if (containerRef.current) {+ setStyle(readMapStyle(containerRef.current, isDark));+ }+ });+ return () => cancelAnimationFrame(frame);+ }, [containerRef, isDark]);++ return style;+}++function isSameMarker(a: PlacedMarker, b: PlacedMarker) {+ return (+ a.x === b.x &&+ a.y === b.y &&+ a.radius === b.radius &&+ a.pulses === b.pulses &&+ a.place.count === b.place.count &&+ a.place.label === b.place.label+ );+}++/**+ * Projects the places, keeping the previous object for any place that did+ * not change, so hit targets of unchanged places skip re-rendering on the+ * refetch that arrives every second under load.+ */+function placeMarkers(+ points: RealtimeMapPoint[],+ geometry: MapGeometry,+ previous: PlacedMarker[]+): PlacedMarker[] {+ const placed: PlacedMarker[] = [];+ for (const place of groupPointsByPlace(points)) {+ const projected = geometry.projection([place.long, place.lat]);+ if (!projected) {+ continue;+ }+ placed.push({+ id: place.id,+ place,+ x: projected[0],+ y: projected[1],+ radius: getMarkerRadius(place.count),+ pulses: false,+ });+ }++ // Busiest places pulse and draw last, so they sit on top of quieter neighbours.+ placed.sort((a, b) => b.place.count - a.place.count);+ for (const marker of placed.slice(0, MARKER_PULSE_LIMIT)) {+ marker.pulses = true;+ }+ placed.reverse();++ const previousById = new Map(previous.map((marker) => [marker.id, marker]));+ let reused = 0;+ const next = placed.map((marker) => {+ const known = previousById.get(marker.id);+ if (known && isSameMarker(known, marker)) {+ reused++;+ return known;+ }+ return marker;+ });+ const isUnchanged = reused === next.length && next.length === previous.length;+ return isUnchanged ? previous : next;+}++/**+ * The world copy under the viewport's centre and one on each side. Three+ * always cover the viewport, and the set only changes when the centre crosses+ * into the next world, so copies are not mounted and unmounted on every nudge.+ */+function getWorldCopyOffsets(+ geometry: MapGeometry,+ transform: ZoomTransform,+ viewportWidth: number+): number[] {+ const centre = Math.floor(+ (transform.invertX(viewportWidth / 2) - geometry.worldLeft) /+ geometry.worldWidth+ );+ return [centre - 1, centre, centre + 1].map(+ (copy) => copy * geometry.worldWidth+ );+}++function sameOffsets(a: number[], b: number[]) {+ return a.length === b.length && a.every((value, index) => value === b[index]);+}++function pointInContainer(+ event: { clientX: number; clientY: number },+ container: HTMLElement+): ScreenPoint {+ const bounds = container.getBoundingClientRect();+ return { x: event.clientX - bounds.left, y: event.clientY - bounds.top };+}++/**+ * The dot under a screen point, if any. A few hundred distance checks per+ * mouse move cost nothing, where a DOM hit target per dot cost a style+ * recalculation per zoom frame.+ */+function findMarkerAt(+ point: ScreenPoint,+ markers: PlacedMarker[],+ transform: ZoomTransform,+ copyOffsets: number[]+): HoveredMarker | null {+ let best: HoveredMarker | null = null;+ let bestDistance = Number.POSITIVE_INFINITY;+ for (const offset of copyOffsets) {+ for (const marker of markers) {+ const x = transform.applyX(marker.x + offset);+ const y = transform.applyY(marker.y);+ const reach = Math.max(MARKER_HIT_RADIUS, marker.radius);+ const distance = Math.hypot(x - point.x, y - point.y);+ if (distance <= reach && distance < bestDistance) {+ best = { marker, x, y };+ bestDistance = distance;+ }+ }+ }+ return best;+}++function sizeCanvas(canvas: HTMLCanvasElement, width: number, height: number) {+ const pixelRatio = window.devicePixelRatio || 1;+ canvas.width = Math.round(width * pixelRatio);+ canvas.height = Math.round(height * pixelRatio);+}++export function RealtimeMap({ projectId, markers }: RealtimeMapProps) {+ const dispatch = useDispatch();+ const { theme } = useTheme();+ const isDark = theme === 'dark';+ const containerRef = useRef<HTMLDivElement>(null);+ const worldCanvasRef = useRef<HTMLCanvasElement>(null);+ const markerCanvasRef = useRef<HTMLCanvasElement>(null);+ const worldRef = useRef<HTMLDivElement>(null);+ const zoomRef = useRef<ZoomBehavior<HTMLDivElement, unknown> | null>(null);+ const transformRef = useRef<ZoomTransform>(zoomIdentity);+ const rasterRef = useRef<WorldRaster | null>(null);+ const copyOffsetsRef = useRef<number[]>([0]);+ const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const isMovingRef = useRef(false);+ const { width, height } = useElementSize(containerRef);+ const shapes = useWorldShapes();+ const now = useCurrentMinute();+ const style = useMapStyle(containerRef, isDark);+ const [copyOffsets, setCopyOffsets] = useState<number[]>([0]);+ const [settledZoom, setSettledZoom] = useState(1);+ const [hovered, setHovered] = useState<HoveredMarker | null>(null);+ const selectedId = useSelector(+ (state) => state.realtimeMapBadge.marker?.id ?? null+ );+ const activeId = hovered?.marker.id ?? selectedId;++ const hasSize = width > 0 && height > 0;+ const geometry = useMemo(+ () =>+ shapes && hasSize ? createMapGeometry(shapes, { width, height }) : null,+ [shapes, hasSize, width, height]+ );+ const night = useMemo(+ () => (geometry ? createNightRings(geometry.projection, now) : null),+ [geometry, now]+ );+ const previousMarkersRef = useRef<PlacedMarker[]>([]);+ const placedMarkers = useMemo(() => {+ const placed = geometry+ ? placeMarkers(markers, geometry, previousMarkersRef.current)+ : [];+ previousMarkersRef.current = placed;+ return placed;+ }, [geometry, markers]);+ const visibleLabels = useMemo(+ () =>+ (geometry?.labels ?? [])+ .filter(+ (label) =>+ label.area * settledZoom * settledZoom >= LABEL_MIN_SCREEN_AREA+ )+ .slice(0, LABEL_MAX_COUNT),+ [geometry, settledZoom]+ );++ const viewport = useCallback(+ () => ({ width, height, pixelRatio: window.devicePixelRatio || 1 }),+ [width, height]+ );++ const paintWorld = useCallback(() => {+ const context = worldCanvasRef.current?.getContext('2d', { alpha: false });+ const raster = rasterRef.current;+ if (!(context && raster && hasSize)) {+ return;+ }+ raster.draw(context, transformRef.current, viewport());+ }, [hasSize, viewport]);++ const paintMarkers = useCallback(+ (now = performance.now()) => {+ const context = markerCanvasRef.current?.getContext('2d');+ if (!(context && style && hasSize)) {+ return;+ }+ drawMarkers({+ context,+ markers: placedMarkers,+ transform: transformRef.current,+ viewport: viewport(),+ copyOffsets: copyOffsetsRef.current,+ activeId,+ style: style.markers,+ now,+ });+ },+ [style, hasSize, placedMarkers, activeId, viewport]+ );+ // The zoom behaviour calls the painters through refs, so a hover or a data+ // refetch changes what gets painted without rebuilding the behaviour.+ const paintWorldRef = useRef(paintWorld);+ const paintMarkersRef = useRef(paintMarkers);+ useLayoutEffect(() => {+ paintWorldRef.current = paintWorld;+ paintMarkersRef.current = paintMarkers;+ });++ // The pan and zoom go straight to the DOM and canvases every frame; React+ // only hears about them once the gesture settles.+ const applyTransform = useCallback(+ (transform: ZoomTransform) => {+ const previous = transformRef.current;+ transformRef.current = transform;+ const world = worldRef.current;+ if (world) {+ world.style.transform = `translate(${transform.x}px, ${transform.y}px) scale(${transform.k})`;+ if (transform.k !== previous.k) {+ world.style.setProperty('--map-inverse-k', String(1 / transform.k));+ }+ }+ if (geometry) {+ const offsets = getWorldCopyOffsets(geometry, transform, width);+ if (!sameOffsets(copyOffsetsRef.current, offsets)) {+ copyOffsetsRef.current = offsets;+ setCopyOffsets(offsets);+ }+ }+ paintWorldRef.current();+ paintMarkersRef.current();+ if (settleTimerRef.current) {+ clearTimeout(settleTimerRef.current);+ }+ settleTimerRef.current = setTimeout(() => {+ settleTimerRef.current = null;+ setSettledZoom(transform.k);+ }, RASTER_SETTLE_MS);+ },+ [geometry, width]+ );++ useLayoutEffect(() => {+ if (!(worldCanvasRef.current && markerCanvasRef.current && hasSize)) {+ return;+ }+ sizeCanvas(worldCanvasRef.current, width, height);+ sizeCanvas(markerCanvasRef.current, width, height);+ }, [hasSize, width, height]);++ useLayoutEffect(() => {+ if (!(geometry && night && style)) {+ return;+ }+ if (rasterRef.current) {+ rasterRef.current.update(geometry, night, style.world);+ } else {+ rasterRef.current = new WorldRaster(geometry, night, style.world, () =>+ paintWorld()+ );+ }+ paintWorld();+ }, [geometry, night, style, paintWorld]);++ useLayoutEffect(() => {+ paintMarkers();+ }, [paintMarkers]);++ // The pulse rings animate on the canvas, one frame at a time, and pause+ // while the tab is hidden.+ const hasPulses = placedMarkers.some((marker) => marker.pulses);+ useEffect(() => {+ if (!hasPulses) {+ return;+ }+ let frame = 0;+ const tick = (now: number) => {+ paintMarkersRef.current(now);+ frame = requestAnimationFrame(tick);+ };+ const start = () => {+ cancelAnimationFrame(frame);+ if (document.visibilityState === 'visible') {+ frame = requestAnimationFrame(tick);+ }+ };+ start();+ document.addEventListener('visibilitychange', start);+ return () => {+ cancelAnimationFrame(frame);+ document.removeEventListener('visibilitychange', start);+ };+ }, [hasPulses]);++ useEffect(+ () => () => {+ rasterRef.current?.dispose();+ if (settleTimerRef.current) {+ clearTimeout(settleTimerRef.current);+ }+ },+ []+ );++ useEffect(() => {+ const element = containerRef.current;+ if (!(element && geometry)) {+ return;+ }++ let gestureStartScale: number | null = null;+ const behavior = zoom<HTMLDivElement, unknown>()+ .scaleExtent([MAP_MIN_ZOOM, MAP_MAX_ZOOM])+ .extent([+ [0, 0],+ [width, height],+ ])+ .translateExtent(geometry.panBounds)+ .filter((event: MouseEvent | WheelEvent) => {+ const isWheel = event.type === 'wheel';+ if (isWheel && gestureStartScale !== null) {+ return false;+ }+ return (!event.ctrlKey || isWheel) && !event.button;+ })+ .on('start', (event: D3ZoomEvent<HTMLDivElement, unknown>) => {+ isMovingRef.current = true;+ if (event.sourceEvent) {+ setHovered(null);+ dispatch(closeMapBadgeDetails());+ }+ })+ .on('zoom', (event: D3ZoomEvent<HTMLDivElement, unknown>) => {+ applyTransform(event.transform);+ })+ .on('end', () => {+ isMovingRef.current = false;+ });++ const selection = select(element);+ selection.call(behavior);+ applyTransform(zoomTransform(element));+ zoomRef.current = behavior;++ const pointFromGesture = (event: SafariGestureEvent): [number, number] => {+ const rect = element.getBoundingClientRect();+ return [event.clientX - rect.left, event.clientY - rect.top];+ };+ const onGestureStart = (event: Event) => {+ event.preventDefault();+ gestureStartScale = zoomTransform(element).k;+ };+ const onGestureChange = (event: Event) => {+ event.preventDefault();+ if (gestureStartScale === null) {+ return;+ }+ const gesture = event as SafariGestureEvent;+ behavior.scaleTo(+ selection,+ gestureStartScale * gesture.scale,+ pointFromGesture(gesture)+ );+ };+ const onGestureEnd = (event: Event) => {+ event.preventDefault();+ gestureStartScale = null;+ };+ element.addEventListener('gesturestart', onGestureStart);+ element.addEventListener('gesturechange', onGestureChange);+ element.addEventListener('gestureend', onGestureEnd);++ return () => {+ selection.on('.zoom', null);+ element.removeEventListener('gesturestart', onGestureStart);+ element.removeEventListener('gesturechange', onGestureChange);+ element.removeEventListener('gestureend', onGestureEnd);+ };+ }, [geometry, width, height, dispatch, applyTransform]);++ const zoomBy = (factor: number) => {+ const element = containerRef.current;+ if (!(element && zoomRef.current)) {+ return;+ }+ select(element)+ .transition()+ .duration(MAP_ZOOM_ANIMATION_MS)+ .call(zoomRef.current.scaleBy, factor);+ };++ const resetZoom = () => {+ const element = containerRef.current;+ if (!(element && zoomRef.current)) {+ return;+ }+ select(element)+ .transition()+ .duration(MAP_ZOOM_ANIMATION_MS)+ .call(zoomRef.current.transform, zoomIdentity);+ };++ const markerScreenPoint = useCallback((marker: PlacedMarker): ScreenPoint => {+ const transform = transformRef.current;+ const copy = copyOffsetsRef.current[1] ?? 0;+ return {+ x: transform.applyX(marker.x + copy),+ y: transform.applyY(marker.y),+ };+ }, []);++ const hoverAt = useCallback(+ (point: ScreenPoint | null) => {+ const next = point+ ? findMarkerAt(+ point,+ placedMarkers,+ transformRef.current,+ copyOffsetsRef.current+ )+ : null;+ setHovered((previous) =>+ previous?.marker === next?.marker ? previous : next+ );+ },+ [placedMarkers]+ );++ const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {+ const container = containerRef.current;+ if (!container || isMovingRef.current) {+ return;+ }+ hoverAt(pointInContainer(event, container));+ };++ const selectMarker = useCallback(+ (marker: PlacedMarker, screenPoint: ScreenPoint) => {+ dispatch(+ openMapBadgeDetails({+ projectId,+ marker: {+ id: marker.place.id,+ label: marker.place.label,+ count: marker.place.count,+ detailScope: 'coordinate',+ locations: marker.place.locations,+ screenPoint,+ },+ })+ );+ },+ [dispatch, projectId]+ );++ const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {+ const container = containerRef.current;+ if (!container) {+ return;+ }+ const hit = findMarkerAt(+ pointInContainer(event, container),+ placedMarkers,+ transformRef.current,+ copyOffsetsRef.current+ );+ if (hit) {+ selectMarker(hit.marker, hit);+ }+ };++ const focusMarker = useCallback(+ (marker: PlacedMarker | null) => {+ setHovered(marker ? { marker, ...markerScreenPoint(marker) } : null);+ },+ [markerScreenPoint]+ );++ const activateMarker = useCallback(+ (marker: PlacedMarker) => selectMarker(marker, markerScreenPoint(marker)),+ [selectMarker, markerScreenPoint]+ );++ return (+ <div+ className="relative h-full w-full touch-none select-none overflow-hidden bg-def-100"+ ref={containerRef}+ >+ <canvas+ className={cn(+ 'absolute inset-0 h-full w-full transition-opacity duration-500',+ geometry ? 'opacity-100' : 'opacity-0'+ )}+ ref={worldCanvasRef}+ />+ <canvas+ className="pointer-events-none absolute inset-0 h-full w-full"+ ref={markerCanvasRef}+ />++ <div+ aria-hidden="true"+ className="pointer-events-none absolute top-0 left-0 origin-top-left will-change-transform"+ ref={worldRef}+ >+ {copyOffsets.map((offset) => (+ <WorldLabels key={offset} labels={visibleLabels} offset={offset} />+ ))}+ </div>++ <MarkerList+ markers={placedMarkers}+ onActivate={activateMarker}+ onFocus={focusMarker}+ />++ {/* Takes the pointer on its own so a cursor change restyles one element, not the whole map. */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: the pointer is read for hit testing; keyboard users get the button list above */}+ {/* biome-ignore lint/a11y/noNoninteractiveElementInteractions: same as above */}+ {/* biome-ignore lint/a11y/useKeyWithClickEvents: keyboard users activate dots through the button list above */}+ <div+ className={cn(+ 'absolute inset-0 active:cursor-grabbing',+ hovered ? 'cursor-pointer' : 'cursor-grab'+ )}+ onClick={handleClick}+ onPointerLeave={() => hoverAt(null)}+ onPointerMove={handlePointerMove}+ />++ {hovered ? (+ <div+ className="pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-lg border bg-card px-2.5 py-1.5 text-xs shadow-lg"+ style={{+ left: hovered.x,+ top: hovered.y - hovered.marker.radius - 8,+ }}+ >+ <div className="font-medium">{hovered.marker.place.label}</div>+ <div className="text-muted-foreground">+ {hovered.marker.place.count.toLocaleString()} online+ </div>+ </div>+ ) : null}++ <div className="absolute right-4 bottom-4 flex flex-col overflow-hidden rounded-lg border bg-card shadow-sm">+ <MapControlButton+ label="Zoom in"+ onClick={() => zoomBy(MAP_ZOOM_BUTTON_FACTOR)}+ >+ <PlusIcon className="size-4" />+ </MapControlButton>+ <MapControlButton+ label="Zoom out"+ onClick={() => zoomBy(1 / MAP_ZOOM_BUTTON_FACTOR)}+ >+ <MinusIcon className="size-4" />+ </MapControlButton>+ <MapControlButton label="Show the whole world" onClick={resetZoom}>+ <LocateFixedIcon className="size-4" />+ </MapControlButton>+ </div>+ </div>+ );+}++function MapControlButton({+ label,+ onClick,+ children,+}: {+ label: string;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ aria-label={label}+ className="flex size-8 items-center justify-center text-muted-foreground transition-colors hover:bg-def-200 hover:text-foreground [&:not(:last-child)]:border-b"+ onClick={onClick}+ onMouseDown={(event) => event.stopPropagation()}+ title={label}+ type="button"+ >+ {children}+ </button>+ );+}++/** Keeps its screen size at every zoom: the world scales up, this scales back down. */+const COUNTER_SCALE = 'translate(-50%, -50%) scale(var(--map-inverse-k))';+const WorldLabels = memo(function WorldLabels({+ offset,+ labels,+}: {+ offset: number;+ labels: CountryLabel[];+}) {+ return (+ <div+ className="absolute top-0 left-0"+ style={{ transform: `translateX(${offset}px)` }}+ >+ {labels.map((label) => (+ <div+ className="absolute whitespace-nowrap font-medium text-2xs text-muted-foreground/60 uppercase tracking-widest"+ key={label.name}+ style={{ left: label.x, top: label.y, transform: COUNTER_SCALE }}+ >+ {label.name}+ </div>+ ))}+ </div>+ );+});++/** Keyboard access to the dots: a visually hidden button per place that never moves. */+const MarkerList = memo(function MarkerList({+ markers,+ onFocus,+ onActivate,+}: {+ markers: PlacedMarker[];+ onFocus: (marker: PlacedMarker | null) => void;+ onActivate: (marker: PlacedMarker) => void;+}) {+ return (+ <ul aria-label="Visitors online now" className="sr-only">+ {markers.map((marker) => (+ <MarkerListItem+ key={marker.id}+ marker={marker}+ onActivate={onActivate}+ onFocus={onFocus}+ />+ ))}+ </ul>+ );+});++const MarkerListItem = memo(function MarkerListItem({+ marker,+ onFocus,+ onActivate,+}: {+ marker: PlacedMarker;+ onFocus: (marker: PlacedMarker | null) => void;+ onActivate: (marker: PlacedMarker) => void;+}) {+ return (+ <li>+ <button+ onBlur={() => onFocus(null)}+ onClick={() => onActivate(marker)}+ onFocus={() => onFocus(marker)}+ type="button"+ >+ {marker.place.label}, {marker.place.count} online+ </button>+ </li>+ );+});diff --git a/apps/start/src/components/realtime/realtime-active-sessions.tsx b/apps/start/src/components/realtime/realtime-active-sessions.tsxdeleted file mode 100644index acb083e23..000000000--- a/apps/start/src/components/realtime/realtime-active-sessions.tsx+++ /dev/null@@ -1,75 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { AnimatePresence, motion } from 'framer-motion';-import { ProjectLink } from '../links';-import { SerieIcon } from '../report-chart/common/serie-icon';-import { useTRPC } from '@/integrations/trpc/react';-import { cn } from '@/utils/cn';-import { formatTimeAgoOrDateTime } from '@/utils/date';--interface RealtimeActiveSessionsProps {- projectId: string;- limit?: number;- className?: string;-}--export function RealtimeActiveSessions({- projectId,- limit = 10,- className,-}: RealtimeActiveSessionsProps) {- const trpc = useTRPC();- const { data: sessions = [] } = useQuery(- trpc.realtime.activeSessions.queryOptions(- { projectId },- { refetchInterval: 5000 }- )- );-- return (- <div className={cn('col card h-full', className)}>- <div className="hide-scrollbar h-full overflow-y-auto">- <AnimatePresence initial={false} mode="popLayout">- <div className="col divide-y">- {sessions.slice(0, limit).map((session) => (- <motion.div- animate={{ opacity: 1, x: 0, scale: 1 }}- exit={{ opacity: 0, x: 200, scale: 0.8 }}- key={session.id}- layout- transition={{ duration: 0.4, type: 'spring', stiffness: 300 }}- >- <ProjectLink- className="relative block p-4 py-3 pr-14"- params={{ sessionId: session.sessionId }}- to="/sessions/$sessionId"- >- <div className="col flex-1 gap-1">- {session.name === 'screen_view' && (- <span className="text-muted-foreground text-xs">- {session.origin}- </span>- )}- <span className="truncate font-medium text-sm">- {session.name === 'screen_view'- ? session.path- : session.name}- </span>- <span className="text-muted-foreground text-xs">- {formatTimeAgoOrDateTime(session.createdAt)}- </span>- </div>- <div className="row absolute top-1/2 right-4 origin-right -translate-y-1/2 scale-50 gap-2">- <SerieIcon name={session.referrerName} />- <SerieIcon name={session.os} />- <SerieIcon name={session.browser} />- <SerieIcon name={session.device} />- </div>- </ProjectLink>- </motion.div>- ))}- </div>- </AnimatePresence>- </div>- </div>- );-}diff --git a/apps/start/src/components/realtime/realtime-geo.tsx b/apps/start/src/components/realtime/realtime-geo.tsxdeleted file mode 100644index 47ead7bcb..000000000--- a/apps/start/src/components/realtime/realtime-geo.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { prop, uniqBy } from 'ramda';-import { OverviewWidgetTable } from '../overview/overview-widget-table';-import { SerieIcon } from '../report-chart/common/serie-icon';-import { Tooltiper } from '../ui/tooltip';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useTRPC } from '@/integrations/trpc/react';-import { countries } from '@/translations/countries';--interface RealtimeGeoProps {- projectId: string;-}--export function RealtimeGeo({ projectId }: RealtimeGeoProps) {- const trpc = useTRPC();- const query = useQuery(- trpc.realtime.geo.queryOptions({- projectId,- })- );-- const data = query.data ?? [];- const maxCount = Math.max(...data.map((item) => item.count));- const number = useNumber();-- // Get unique countries for header icons- const unique = uniqBy(prop('country'), data)- .filter((i) => !!i.country.trim())- .slice(0, 8);-- return (- <div className="col card h-full">- <div className="row items-center justify-between p-4 pb-0">- <div className="font-medium text-muted-foreground">Geo</div>- <div className="row gap-1">- {unique.map((item) => (- <Tooltiper- content={countries[item.country as keyof typeof countries]}- key={item.country}- >- <SerieIcon key={item.country} name={item.country} />- </Tooltiper>- ))}- </div>- </div>- <OverviewWidgetTable- columns={[- {- name: 'Country / City',- width: 'w-full',- responsive: { priority: 1 },- render(item) {- return (- <Tooltiper- asChild- content={`${item.country} / ${item.city}`}- side="left"- >- <div className="row relative min-w-0 items-center gap-2">- <SerieIcon name={item.country} />- {item.city || '(Not set)'}- </div>- </Tooltiper>- );- },- },- {- name: 'Duration',- width: '75px',- responsive: { priority: 7 },- render(item) {- return number.shortWithUnit(item.avg_duration, 'min');- },- },- {- name: 'Events',- width: '60px',- responsive: { priority: 4 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.count)}- </span>- </div>- );- },- },- {- name: 'Sessions',- width: '82px',- responsive: { priority: 2 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.unique_sessions)}- </span>- </div>- );- },- },- ]}- data={data ?? []}- getColumnPercentage={(item) => item.count / maxCount}- keyExtractor={(item) => item.country + item.city}- />- </div>- );-}diff --git a/apps/start/src/components/realtime/realtime-live-histogram.tsx b/apps/start/src/components/realtime/realtime-live-histogram.tsxdeleted file mode 100644index 0c2136b6f..000000000--- a/apps/start/src/components/realtime/realtime-live-histogram.tsx+++ /dev/null@@ -1,147 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import type React from 'react';-import { AnimatedNumber } from '../animated-number';-import { SerieIcon } from '../report-chart/common/serie-icon';-import { Bar } from '@/components/charts/bar';-import { BarChart } from '@/components/charts/bar-chart';-import { OPChartTooltip } from '@/components/charts/op-tooltip';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useTRPC } from '@/integrations/trpc/react';-import type { RouterOutputs } from '@/trpc/client';-import { getChartColor } from '@/utils/theme';--const BAR_COLOR = getChartColor(0);-const BAR_RADIUS = 1;-const BAR_GAP = 0.25;-const NO_MARGIN = { top: 0, right: 0, bottom: 0, left: 0 };-const TOOLTIP_REFERRERS = 3;--type MinutePoint =- RouterOutputs['overview']['liveData']['minuteCounts'][number] & {- [key: string]: unknown;- };--interface RealtimeLiveHistogramProps {- projectId: string;-}--export function RealtimeLiveHistogram({- projectId,-}: RealtimeLiveHistogramProps) {- const trpc = useTRPC();- const number = useNumber();-- // Use the same liveData endpoint as overview- const { data: liveData, isLoading } = useQuery(- trpc.overview.liveData.queryOptions({ projectId })- );-- const chartData: MinutePoint[] = (liveData?.minuteCounts ?? []).map(- (point) => ({ ...point })- );- // Approximation: totalSessions, not unique visitors across the window.- const totalVisitors = liveData?.totalSessions ?? 0;-- if (isLoading) {- return (- <Wrapper count={0}>- <div className="h-full w-full animate-pulse rounded bg-def-200" />- </Wrapper>- );- }-- if (!liveData) {- return null;- }-- return (- <Wrapper count={totalVisitors}>- <BarChart- animationDuration={0}- aspectRatio="auto"- barGap={BAR_GAP}- className="h-full"- data={chartData}- margin={NO_MARGIN}- xDataKey="time"- >- <Bar- animate={false}- dataKey="visitorCount"- fill={BAR_COLOR}- lineCap={BAR_RADIUS}- />- <OPChartTooltip<MinutePoint>- datePill={false}- extra={renderReferrers}- rows={(point) => [- {- color: BAR_COLOR,- label: 'Active users',- value: point.visitorCount,- format: number.format,- },- ]}- showDots={false}- title={(point) => point.time}- />- </BarChart>- </Wrapper>- );-}--function renderReferrers(point: MinutePoint) {- if (point.referrers.length === 0) {- return null;- }- const hidden = point.referrers.length - TOOLTIP_REFERRERS;- return (- <div className="mt-1 border-border border-t pt-2">- <div className="mb-2 text-muted-foreground text-xs">Referrers:</div>- <div className="space-y-1">- {point.referrers.slice(0, TOOLTIP_REFERRERS).map((ref) => (- <div- className="row items-center justify-between text-xs"- key={ref.referrer}- >- <div className="row items-center gap-1">- <SerieIcon name={ref.referrer} />- <span className="max-w-[120px] truncate" title={ref.referrer}>- {ref.referrer}- </span>- </div>- <span className="tabular-nums">{ref.count}</span>- </div>- ))}- {hidden > 0 && (- <div className="text-muted-foreground text-xs">+{hidden} more</div>- )}- </div>- </div>- );-}--interface WrapperProps {- children: React.ReactNode;- count: number;- icons?: React.ReactNode;-}--function Wrapper({ children, count, icons }: WrapperProps) {- return (- <div className="flex flex-col">- <div className="row justify-between gap-2">- <div className="relative font-medium text-muted-foreground text-sm">- Unique visitors last 30 min- </div>- <div>{icons}</div>- </div>- <div className="col -mt-1 gap-2">- <div className="font-bold text-5xl tabular-nums">- <AnimatedNumber value={count} />- </div>- </div>- <div className="relative -mt-2 aspect-[6/1] w-full">{children}</div>- </div>- );-}diff --git a/apps/start/src/components/realtime/realtime-paths.tsx b/apps/start/src/components/realtime/realtime-paths.tsxdeleted file mode 100644index 3032646fa..000000000--- a/apps/start/src/components/realtime/realtime-paths.tsx+++ /dev/null@@ -1,117 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { ExternalLinkIcon } from 'lucide-react';-import { prop, uniqBy } from 'ramda';-import { OverviewWidgetTable } from '../overview/overview-widget-table';-import { SerieIcon } from '../report-chart/common/serie-icon';-import { Tooltiper } from '../ui/tooltip';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useTRPC } from '@/integrations/trpc/react';--interface RealtimePathsProps {- projectId: string;-}--export function RealtimePaths({ projectId }: RealtimePathsProps) {- const trpc = useTRPC();- const query = useQuery(- trpc.realtime.paths.queryOptions({- projectId,- })- );-- const data = query.data ?? [];- const maxCount = Math.max(...data.map((item) => item.count));- const number = useNumber();-- // Get unique origins for header icons- const unique = uniqBy(prop('origin'), data)- .filter((i) => !!i.origin.trim())- .slice(0, 5);-- return (- <div className="col card h-full">- <div className="row items-center justify-between p-4 pb-0">- <div className="font-medium text-muted-foreground">Paths</div>- <div className="row gap-1">- {unique.map((item) => (- <Tooltiper content={item.origin} key={item.origin}>- <SerieIcon key={item.origin} name={item.origin} />- </Tooltiper>- ))}- </div>- </div>- <OverviewWidgetTable- columns={[- {- name: 'Path',- width: 'w-full',- responsive: { priority: 1 },- render(item) {- return (- <Tooltiper- asChild- content={item.origin + item.path}- disabled={item.origin === ''}- side="left"- >- <div className="row relative min-w-0 items-center gap-2">- <SerieIcon name={item.origin} />- <span className="truncate">{item.path || '(Not set)'}</span>- {item.origin && (- <a- href={item.origin + item.path}- rel="noreferrer"- target="_blank"- >- <ExternalLinkIcon className="size-3 opacity-0 transition-opacity group-hover/row:opacity-100" />- </a>- )}- </div>- </Tooltiper>- );- },- },- {- name: 'Duration',- width: '75px',- responsive: { priority: 7 },- render(item) {- return number.shortWithUnit(item.avg_duration, 'min');- },- },- {- name: 'Events',- width: '60px',- responsive: { priority: 4 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.count)}- </span>- </div>- );- },- },- {- name: 'Sessions',- width: '82px',- responsive: { priority: 2 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.unique_sessions)}- </span>- </div>- );- },- },- ]}- data={data ?? []}- getColumnPercentage={(item) => item.count / maxCount}- keyExtractor={(item) => item.path + item.origin}- />- </div>- );-}diff --git a/apps/start/src/components/realtime/realtime-referrals.tsx b/apps/start/src/components/realtime/realtime-referrals.tsxdeleted file mode 100644index 6871a0b3e..000000000--- a/apps/start/src/components/realtime/realtime-referrals.tsx+++ /dev/null@@ -1,100 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { prop, uniqBy } from 'ramda';-import { OverviewWidgetTable } from '../overview/overview-widget-table';-import { SerieIcon } from '../report-chart/common/serie-icon';-import { Tooltiper } from '../ui/tooltip';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useTRPC } from '@/integrations/trpc/react';--interface RealtimeReferralsProps {- projectId: string;-}--export function RealtimeReferrals({ projectId }: RealtimeReferralsProps) {- const trpc = useTRPC();- const query = useQuery(- trpc.realtime.referrals.queryOptions({- projectId,- })- );-- const data = query.data ?? [];- const maxCount = Math.max(...data.map((item) => item.count));- const number = useNumber();- const unique = uniqBy(prop('referrer_name'), data)- .filter((i) => !!i.referrer_name.trim())- .slice(0, 8);-- return (- <div className="col card h-full">- <div className="row items-center justify-between p-4 pb-0">- <div className="font-medium text-muted-foreground">Referrals</div>- <div className="row gap-1">- {unique.map((item) => (- <Tooltiper content={item.referrer_name} key={item.referrer_name}>- <SerieIcon key={item.referrer_name} name={item.referrer_name} />- </Tooltiper>- ))}- </div>- </div>- <OverviewWidgetTable- columns={[- {- name: 'Referrer',- width: 'w-full',- responsive: { priority: 1 },- render(item) {- return (- <Tooltiper asChild content={item.referrer_name} side="left">- <div className="row relative min-w-0 items-center gap-2">- <SerieIcon name={item.referrer_name} />- {item.referrer_name || '(Not set)'}- </div>- </Tooltiper>- );- },- },- {- name: 'Duration',- width: '75px',- responsive: { priority: 7 },- render(item) {- return number.shortWithUnit(item.avg_duration, 'min');- },- },- {- name: 'Events',- width: '60px',- responsive: { priority: 4 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.count)}- </span>- </div>- );- },- },- {- name: 'Sessions',- width: '82px',- responsive: { priority: 2 },- render(item) {- return (- <div className="row justify-end gap-2">- <span className="font-semibold">- {number.short(item.unique_sessions)}- </span>- </div>- );- },- },- ]}- data={data ?? []}- getColumnPercentage={(item) => item.count / maxCount}- keyExtractor={(item) => item.referrer_name}- />- </div>- );-}diff --git a/apps/start/src/components/realtime/realtime-reloader.tsx b/apps/start/src/components/realtime/realtime-reloader.tsxindex 1abefb8e1..82fb60501 100644--- a/apps/start/src/components/realtime/realtime-reloader.tsx+++ b/apps/start/src/components/realtime/realtime-reloader.tsx@@ -1,33 +1,64 @@import { useQueryClient } from '@tanstack/react-query';+import { useEffect, useRef } from 'react';import useWS from '@/hooks/use-ws';import { useTRPC } from '@/integrations/trpc/react';-type Props = {+interface Props {projectId: string;-};+}++/** The feeds refresh this often while events keep arriving. */+const FEED_REFRESH_MS = 5000;+/** The map dots, histogram and top sources refresh this often regardless. */+const SUMMARY_REFRESH_MS = 20_000;+/**+ * Keeps the realtime page fresh on a fixed cadence. The websocket only says+ * that something arrived; it never triggers a refetch by itself, so a busy+ * project costs the same handful of queries as a quiet one.+ */const RealtimeReloader = ({ projectId }: Props) => {const client = useQueryClient();const trpc = useTRPC();+ const hasNewEvents = useRef(false);- useWS<number>(- `/live/events/${projectId}`,- () => {- if (!document.hidden) {- // pathFilter() covers all realtime.* queries for this project- client.refetchQueries(trpc.realtime.pathFilter());- client.refetchQueries(- trpc.overview.liveData.queryFilter({ projectId })- );+ useWS<number>(`/live/events/${projectId}`, () => {+ hasNewEvents.current = true;+ });++ useEffect(() => {+ const refreshFeeds = () => {+ if (document.hidden || !hasNewEvents.current) {+ return;+ }+ hasNewEvents.current = false;+ client.refetchQueries(+ trpc.realtime.recentSessions.queryFilter({ projectId })+ );+ client.refetchQueries(+ trpc.realtime.activeSessions.queryFilter({ projectId })+ );+ };+ // Summaries refresh even with no new events: sessions leave the window too.+ const refreshSummaries = () => {+ if (document.hidden) {+ return;}- },- {- debounce: {- delay: 1000,- maxWait: 60_000,- },- }- );+ client.refetchQueries(+ trpc.realtime.coordinates.queryFilter({ projectId })+ );+ client.refetchQueries(trpc.realtime.histogram.queryFilter({ projectId }));+ client.refetchQueries(+ trpc.realtime.topSources.queryFilter({ projectId })+ );+ };+ const feeds = setInterval(refreshFeeds, FEED_REFRESH_MS);+ const summaries = setInterval(refreshSummaries, SUMMARY_REFRESH_MS);+ return () => {+ clearInterval(feeds);+ clearInterval(summaries);+ };+ }, [client, trpc, projectId]);return null;};diff --git a/apps/start/src/components/report-chart/report-editor.tsx b/apps/start/src/components/report-chart/report-editor.tsxindex c27e1a613..f82a4ec68 100644--- a/apps/start/src/components/report-chart/report-editor.tsx+++ b/apps/start/src/components/report-chart/report-editor.tsx@@ -1,7 +1,8 @@import type { IServiceReport } from '@openpanel/core';-import { GanttChartSquareIcon, ShareIcon } from 'lucide-react';+import { ShareIcon } from 'lucide-react';import { useEffect } from 'react';import EditReportName from '../report/edit-report-name';+import { ReportSummaryTrigger } from '../report/report-summary-trigger';import { ReportChartType } from '@/components/report/ReportChartType';import { ReportInterval } from '@/components/report/ReportInterval';import { ReportLineType } from '@/components/report/ReportLineType';@@ -25,6 +26,9 @@ import { useAppParams } from '@/hooks/use-app-params';import { pushModal } from '@/modals';import { useDispatch, useSelector } from '@/redux';+const TOOLBAR_TRIGGER_CLASS =+ 'h-8 rounded-md px-2.5 hover:bg-card hover:shadow-xs dark:hover:bg-def-400/60';+interface ReportEditorProps {report: IServiceReport | null;}@@ -52,68 +56,78 @@ export default function ReportEditor({return (<Sheet><div>- <div className="flex items-center justify-between p-4">- <EditReportName />- {initialReport?.id && (- <Button- icon={ShareIcon}- onClick={() =>- pushModal('ShareReportModal', { reportId: initialReport.id })- }- variant="outline"- >- Share- </Button>- )}- </div>- <div className="grid grid-cols-2 gap-2 p-4 pt-0 md:grid-cols-6">- <SheetTrigger asChild>- <Button- className="self-start"- icon={GanttChartSquareIcon}- variant="cta"- >- Pick events- </Button>- </SheetTrigger>- <div className="col-span-4 grid grid-cols-2 gap-2 md:grid-cols-4">- <ReportChartType- className="min-w-0 flex-1"- onChange={(type) => {- dispatch(changeChartType(type));- }}- value={report.chartType}- />- <TimeWindowPicker- className="min-w-0 flex-1"- endDate={report.endDate}- onChange={(value) => {- dispatch(changeDateRanges(value));- }}- onEndDateChange={(date) => dispatch(changeEndDate(date))}- onIntervalChange={(interval) =>- dispatch(changeInterval(interval))- }- onStartDateChange={(date) => dispatch(changeStartDate(date))}- startDate={report.startDate}- value={report.range}- />- <ReportInterval- chartType={report.chartType}- className="min-w-0 flex-1"- endDate={report.endDate}- interval={report.interval}- onChange={(newInterval) => dispatch(changeInterval(newInterval))}- range={report.range}- startDate={report.startDate}- />- <ReportLineType className="min-w-0 flex-1" />+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-center justify-between gap-4">+ <EditReportName />+ <div className="flex shrink-0 items-center gap-2">+ {initialReport?.id && (+ <Button+ icon={ShareIcon}+ onClick={() =>+ pushModal('ShareReportModal', {+ reportId: initialReport.id,+ })+ }+ variant="outline"+ >+ Share+ </Button>+ )}+ <ReportSaveButton />+ </div></div>- <div className="col-start-2 row-start-1 text-right md:col-start-6">- <ReportSaveButton />+ <div className="flex flex-col gap-2 md:flex-row md:items-center">+ <SheetTrigger asChild>+ <ReportSummaryTrigger className="max-w-full self-start md:self-auto" />+ </SheetTrigger>+ <div className="flex shrink-0 flex-wrap items-center gap-0.5 self-start rounded-lg bg-def-200 p-0.5 md:ml-auto md:self-auto dark:bg-def-300">+ <ReportChartType+ className={TOOLBAR_TRIGGER_CLASS}+ onChange={(type) => {+ dispatch(changeChartType(type));+ }}+ size="sm"+ value={report.chartType}+ variant="ghost"+ />+ <TimeWindowPicker+ className={TOOLBAR_TRIGGER_CLASS}+ endDate={report.endDate}+ onChange={(value) => {+ dispatch(changeDateRanges(value));+ }}+ onEndDateChange={(date) => dispatch(changeEndDate(date))}+ onIntervalChange={(interval) =>+ dispatch(changeInterval(interval))+ }+ onStartDateChange={(date) => dispatch(changeStartDate(date))}+ size="sm"+ startDate={report.startDate}+ value={report.range}+ variant="ghost"+ />+ <ReportInterval+ chartType={report.chartType}+ className={TOOLBAR_TRIGGER_CLASS}+ endDate={report.endDate}+ interval={report.interval}+ onChange={(newInterval) =>+ dispatch(changeInterval(newInterval))+ }+ range={report.range}+ size="sm"+ startDate={report.startDate}+ variant="ghost"+ />+ <ReportLineType+ className={TOOLBAR_TRIGGER_CLASS}+ size="sm"+ variant="ghost"+ />+ </div></div></div>- <div className="flex flex-col gap-4 p-4" id="report-editor">+ <div className="flex flex-col gap-4 p-4 pt-0" id="report-editor">{report.ready && (<ReportChart isEditMode report={{ ...report, projectId }} />)}diff --git a/apps/start/src/components/report/ReportChartType.tsx b/apps/start/src/components/report/ReportChartType.tsxindex a9f048438..305f220d7 100644--- a/apps/start/src/components/report/ReportChartType.tsx+++ b/apps/start/src/components/report/ReportChartType.tsx@@ -14,7 +14,7 @@ import {TrendingUpIcon,UsersIcon,} from 'lucide-react';-import { Button } from '../ui/button';+import { Button, type ButtonProps } from '../ui/button';import {DropdownMenu,DropdownMenuContent,@@ -30,11 +30,15 @@ import { objectToZodEnums } from '@/utils/object-to-zod-enums';interface ReportChartTypeProps {className?: string;+ variant?: ButtonProps['variant'];+ size?: ButtonProps['size'];value: IChartType;onChange: (type: IChartType) => void;}export function ReportChartType({className,+ variant = 'outline',+ size,value,onChange,}: ReportChartTypeProps) {@@ -65,7 +69,8 @@ export function ReportChartType({<ButtonclassName={cn('justify-start', className)}icon={Icons[value]}- variant="outline"+ size={size}+ variant={variant}>{items.find((item) => item.value === value)?.label}</Button>diff --git a/apps/start/src/components/report/ReportInterval.tsx b/apps/start/src/components/report/ReportInterval.tsxindex 1d153d6a4..8c28d65d6 100644--- a/apps/start/src/components/report/ReportInterval.tsx+++ b/apps/start/src/components/report/ReportInterval.tsx@@ -9,7 +9,7 @@ import {} from '@openpanel/core/modules/report/report.constants';import { differenceInDays } from 'date-fns';import { ClockIcon } from 'lucide-react';-import { Button } from '../ui/button';+import { Button, type ButtonProps } from '../ui/button';import { CommandShortcut } from '../ui/command';import {DropdownMenu,@@ -25,6 +25,8 @@ import { cn } from '@/utils/cn';interface ReportIntervalProps {className?: string;+ variant?: ButtonProps['variant'];+ size?: ButtonProps['size'];interval: IInterval;onChange: (range: IInterval) => void;chartType: IChartType;@@ -34,6 +36,8 @@ interface ReportIntervalProps {}export function ReportInterval({className,+ variant = 'outline',+ size,interval,onChange,chartType,@@ -101,7 +105,8 @@ export function ReportInterval({<ButtonclassName={cn('justify-start', className)}icon={ClockIcon}- variant="outline"+ size={size}+ variant={variant}>{items.find((item) => item.value === interval)?.label || 'Interval'}</Button>diff --git a/apps/start/src/components/report/ReportLineType.tsx b/apps/start/src/components/report/ReportLineType.tsxindex c9451d013..4557656c9 100644--- a/apps/start/src/components/report/ReportLineType.tsx+++ b/apps/start/src/components/report/ReportLineType.tsx@@ -1,14 +1,32 @@+import type { IChartLineType } from '@openpanel/core/modules/report/report.constants';import { lineTypes } from '@openpanel/core/modules/report/report.constants';-import { Tv2Icon } from 'lucide-react';-import { Combobox } from '../ui/combobox';+import { CheckIcon, Tv2Icon } from 'lucide-react';+import { Button, type ButtonProps } from '../ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuTrigger,+} from '../ui/dropdown-menu';import { changeLineType } from './reportSlice';import { useDispatch, useSelector } from '@/redux';+import { cn } from '@/utils/cn';import { objectToZodEnums } from '@/utils/object-to-zod-enums';interface ReportLineTypeProps {className?: string;+ variant?: ButtonProps['variant'];+ size?: ButtonProps['size'];}-export function ReportLineType({ className }: ReportLineTypeProps) {+export function ReportLineType({+ className,+ variant = 'outline',+ size,+}: ReportLineTypeProps) {const dispatch = useDispatch();const chartType = useSelector((state) => state.report.chartType);const type = useSelector((state) => state.report.lineType);@@ -22,18 +40,36 @@ export function ReportLineType({ className }: ReportLineTypeProps) {}return (- <Combobox- className={className}- icon={Tv2Icon}- items={objectToZodEnums(lineTypes).map((key) => ({- label: lineTypes[key],- value: key,- }))}- onChange={(value) => {- dispatch(changeLineType(value));- }}- placeholder="Line type"- value={type}- />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ className={cn('justify-start', className)}+ icon={Tv2Icon}+ size={size}+ variant={variant}+ >+ {lineTypes[type] ?? 'Line type'}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="max-h-(--radix-dropdown-menu-content-available-height) w-56 overflow-y-auto">+ <DropdownMenuLabel>Line type</DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ {objectToZodEnums(lineTypes).map((key) => (+ <DropdownMenuItem+ key={key}+ onClick={() => dispatch(changeLineType(key as IChartLineType))}+ >+ {lineTypes[key]}+ {key === type && (+ <DropdownMenuShortcut>+ <CheckIcon className="size-4" />+ </DropdownMenuShortcut>+ )}+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>);}diff --git a/apps/start/src/components/report/ReportSegment.tsx b/apps/start/src/components/report/ReportSegment.tsxindex bc57add83..60a90ec07 100644--- a/apps/start/src/components/report/ReportSegment.tsx+++ b/apps/start/src/components/report/ReportSegment.tsx@@ -13,7 +13,7 @@ import {UserCheckIcon,UsersIcon,} from 'lucide-react';-import { Button } from '../ui/button';+import { Button, type ButtonProps } from '../ui/button';import {DropdownMenu,DropdownMenuContent,@@ -29,11 +29,15 @@ import { mapKeys } from '@/utils/object-to-zod-enums';interface ReportChartTypeProps {className?: string;+ variant?: ButtonProps['variant'];+ size?: ButtonProps['size'];value: IChartEventSegment;onChange: (segment: IChartEventSegment) => void;}export function ReportSegment({className,+ variant = 'outline',+ size,value,onChange,}: ReportChartTypeProps) {@@ -61,7 +65,8 @@ export function ReportSegment({<ButtonclassName={cn('justify-start text-sm', className)}icon={Icons[value]}- variant="outline"+ size={size}+ variant={variant}>{items.find((item) => item.value === value)?.label}</Button>diff --git a/apps/start/src/components/report/edit-report-name.tsx b/apps/start/src/components/report/edit-report-name.tsxindex 7263963e0..0250039a1 100644--- a/apps/start/src/components/report/edit-report-name.tsx+++ b/apps/start/src/components/report/edit-report-name.tsx@@ -52,6 +52,7 @@ const EditReportName = ({ name }: Props) => {}}}ref={inputRef}+ size="sm"type="text"value={newName}/>diff --git a/apps/start/src/components/report/report-summary-trigger.tsx b/apps/start/src/components/report/report-summary-trigger.tsxnew file mode 100644index 000000000..f31f26295--- /dev/null+++ b/apps/start/src/components/report/report-summary-trigger.tsx@@ -0,0 +1,148 @@+import type { IChartEventItem } from '@openpanel/core/modules/report/report.constants';+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';+import { GanttChartSquareIcon, PencilIcon } from 'lucide-react';+import { forwardRef } from 'react';+import { ColorSquare } from '@/components/color-square';+import { Button } from '@/components/ui/button';+import { useSelector } from '@/redux';+import { cn } from '@/utils/cn';+import { getChartColor } from '@/utils/theme';++type Props = React.ButtonHTMLAttributes<HTMLButtonElement>;++/** Series beyond these collapse into a "+N" chip so the control row stays on one line; narrow windows show fewer. */+const VISIBLE_SERIES_WIDE = 2;+const VISIBLE_SERIES_NARROW = 1;++function MoreSeriesChip({+ hidden,+ className,+}: {+ hidden: IChartEventItem[];+ className: string;+}) {+ if (hidden.length === 0) {+ return null;+ }+ return (+ <span+ className={cn(+ 'h-7 shrink-0 items-center rounded-md bg-card px-2 font-medium text-muted-foreground shadow-xs',+ className+ )}+ title={hidden.map(seriesLabel).join(', ')}+ >+ +{hidden.length}+ </span>+ );+}++function seriesLabel(serie: IChartEventItem): string {+ if (serie.type === 'formula') {+ return serie.displayName || serie.formula || 'Formula';+ }+ if (serie.displayName) {+ return serie.displayName;+ }+ if (serie.name === '*') {+ return 'Any event';+ }+ return serie.name || 'Select event';+}++function countFilters(series: IChartEventItem[]): number {+ let count = 0;+ for (const serie of series) {+ if (serie.type !== 'event') {+ continue;+ }+ // The synthetic `name` filter is how multi-event series pick their events.+ count += serie.filters.filter((filter) => filter.name !== 'name').length;+ }+ return count;+}++/** Summarises the report's series, filters and breakdowns; opens the builder. */+export const ReportSummaryTrigger = forwardRef<HTMLButtonElement, Props>(+ ({ className, ...props }, ref) => {+ const series = useSelector((state) => state.report.series);+ const globalFilters = useSelector((state) => state.report.globalFilters);+ const breakdowns = useSelector((state) => state.report.breakdowns);++ if (series.length === 0) {+ return (+ <Button+ className={className}+ icon={GanttChartSquareIcon}+ ref={ref}+ variant="cta"+ {...props}+ >+ Pick events+ </Button>+ );+ }++ const filterCount = countFilters(series) + globalFilters.length;+ const details: string[] = [];+ if (filterCount > 0) {+ details.push(+ `${filterCount} ${filterCount === 1 ? 'filter' : 'filters'}`+ );+ }+ if (breakdowns.length > 0) {+ details.push(`by ${breakdowns.map((item) => item.name).join(', ')}`);+ }++ return (+ <button+ className={cn(+ 'group flex h-9 min-w-0 items-center gap-1.5 overflow-hidden rounded-lg bg-def-200 py-1 pr-2.5 pl-1 text-left text-sm transition-colors hover:bg-def-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:bg-def-300 dark:hover:bg-def-400/60',+ className+ )}+ ref={ref}+ type="button"+ {...props}+ >+ {series.slice(0, VISIBLE_SERIES_WIDE).map((serie, index) => {+ const isWideOnly = index >= VISIBLE_SERIES_NARROW;+ return (+ <span+ className={cn(+ 'h-7 min-w-0 max-w-48 items-center gap-1.5 rounded-md bg-card pr-2 pl-1.5 font-medium shadow-xs',+ isWideOnly ? 'hidden xl:inline-flex' : 'inline-flex'+ )}+ key={serie.id}+ >+ <ColorSquare+ className="h-4 w-4 text-2xs"+ color={getChartColor(index)}+ >+ {alphabetIds[index]}+ </ColorSquare>+ <span className="truncate">{seriesLabel(serie)}</span>+ </span>+ );+ })}+ <MoreSeriesChip+ className="inline-flex xl:hidden"+ hidden={series.slice(VISIBLE_SERIES_NARROW)}+ />+ <MoreSeriesChip+ className="hidden xl:inline-flex"+ hidden={series.slice(VISIBLE_SERIES_WIDE)}+ />+ {details.length > 0 && (+ <span className="hidden min-w-0 truncate whitespace-nowrap px-1 text-muted-foreground xl:inline">+ {details.join(' · ')}+ </span>+ )}+ <PencilIcon+ className="ml-1 shrink-0 text-muted-foreground opacity-60 transition-opacity group-hover:opacity-100"+ size={14}+ />+ </button>+ );+ }+);+ReportSummaryTrigger.displayName = 'ReportSummaryTrigger';diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsxindex 00e573ba5..b07acccfe 100644--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx@@ -113,6 +113,7 @@ function SearchHeader({autoFocusonChange={(e) => onSearch(e.target.value)}placeholder="Search"+ size="sm"value={value}/></div>diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsxindex d15145d38..72caad952 100644--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx@@ -1,9 +1,14 @@import type { IChartBreakdown } from '@openpanel/core/modules/report/report.constants';-import { ChevronsUpDownIcon, SplitIcon } from 'lucide-react';+import { ChevronsUpDownIcon, PlusIcon, SplitIcon } from 'lucide-react';import { addBreakdown, changeBreakdown, removeBreakdown } from '../reportSlice';import { PropertiesCombobox } from './PropertiesCombobox';import { ReportBreakdownMore } from './ReportBreakdownMore';import type { ReportEventMoreProps } from './ReportEventMore';+import {+ BuilderAddButton,+ BuilderList,+ SidebarSection,+} from './sidebar-section';import { ColorSquare } from '@/components/color-square';import { Button } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';@@ -34,98 +39,101 @@ export function ReportBreakdowns() {return callback;};+ const addBreakdownAction = (+ <PropertiesCombobox+ categories={['event', 'profile', 'group', 'cohort']}+ onSelect={(action) => {+ dispatch(+ addBreakdown({+ name: action.value,+ })+ );+ }}+ >+ {(setOpen) => (+ <BuilderAddButton+ icon={PlusIcon}+ onClick={() => setOpen((prev) => !prev)}+ >+ Add breakdown+ </BuilderAddButton>+ )}+ </PropertiesCombobox>+ );+return (- <div>- <h3 className="mb-2 font-medium">Breakdown</h3>- <div className="flex flex-col gap-4">- {selectedBreakdowns.map((item, index) => {- return (- <div className="rounded-lg border bg-def-100" key={item.name}>- <div className="flex items-center gap-2 p-2 px-4">- <ColorSquare>{index}</ColorSquare>- <PropertiesCombobox- categories={['event', 'profile', 'group', 'cohort']}- onSelect={(action) => {- dispatch(- changeBreakdown({- ...item,- name: action.value,- })- );- }}- >- {(setOpen) => (- <Button- autoHeight- className="flex-1"- onClick={() => setOpen((prev) => !prev)}- size={'sm'}- variant={'outline'}- >- <div className="row w-full items-center gap-2">- <SplitIcon className="size-4" />- {item.name === 'cohort' ? 'Cohorts' : item.name}- </div>- <ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>- )}- </PropertiesCombobox>- <ReportBreakdownMore onClick={handleMore(item)} />- </div>- {showStep && !item.name.startsWith('group.') && (- <div className="flex items-center justify-between gap-2 border-t p-2 px-4">- <span className="text-muted-foreground text-sm">- From step- </span>- <Combobox- align="end"- items={stepItems}- onChange={(value) =>+ <SidebarSection title="Breakdown">+ {selectedBreakdowns.length > 0 && (+ <BuilderList>+ {selectedBreakdowns.map((item, index) => {+ return (+ <div key={item.name}>+ <div className="flex items-center gap-2 px-3 py-2.5">+ <ColorSquare>{index}</ColorSquare>+ <PropertiesCombobox+ categories={['event', 'profile', 'group', 'cohort']}+ onSelect={(action) => {dispatch(changeBreakdown({...item,- step: value === '1' ? undefined : Number(value),+ name: action.value,})- )- }- placeholder="Select step"- value={String(- item.step && item.step <= stepItems.length ? item.step : 1+ );+ }}+ >+ {(setOpen) => (+ <Button+ autoHeight+ className="min-w-0 flex-1"+ onClick={() => setOpen((prev) => !prev)}+ size="default"+ variant="input"+ >+ <div className="row w-full min-w-0 items-center gap-2">+ <SplitIcon className="size-4 shrink-0" />+ <span className="truncate">+ {item.name === 'cohort' ? 'Cohorts' : item.name}+ </span>+ </div>+ <ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ </Button>)}- />+ </PropertiesCombobox>+ <ReportBreakdownMore onClick={handleMore(item)} /></div>- )}- </div>- );- })}-- <PropertiesCombobox- categories={['event', 'profile', 'group', 'cohort']}- onSelect={(action) => {- dispatch(- addBreakdown({- name: action.value,- })- );- }}- >- {(setOpen) => (- <Button- autoHeight- className="flex-1"- onClick={() => setOpen((prev) => !prev)}- size={'sm'}- variant={'outline'}- >- <div className="row w-full items-center gap-2">- <SplitIcon className="size-4" />- Select breakdown+ {showStep && !item.name.startsWith('group.') && (+ <div className="flex items-center justify-between gap-2 border-t px-3 py-2 pl-10">+ <span className="text-muted-foreground text-sm">+ From step+ </span>+ <Combobox+ align="end"+ items={stepItems}+ onChange={(value) =>+ dispatch(+ changeBreakdown({+ ...item,+ step: value === '1' ? undefined : Number(value),+ })+ )+ }+ placeholder="Select step"+ size="sm"+ value={String(+ item.step && item.step <= stepItems.length+ ? item.step+ : 1+ )}+ variant="input"+ />+ </div>+ )}</div>- <ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />- </Button>- )}- </PropertiesCombobox>- </div>- </div>+ );+ })}+ </BuilderList>+ )}+ {addBreakdownAction}+ </SidebarSection>);}diff --git a/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx b/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsxindex a9d76a0d0..3bb16ec89 100644--- a/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx+++ b/apps/start/src/components/report/sidebar/ReportGlobalFilters.tsx@@ -1,95 +1,66 @@import { shortId } from '@openpanel/shared';-import { FilterIcon, type LucideIcon } from 'lucide-react';+import { FilterIcon } from 'lucide-react';import { addGlobalFilter } from '../reportSlice';import { GlobalFilterItem } from './filters/GlobalFilterItem';import { PropertiesCombobox } from './PropertiesCombobox';+import { BuilderAddButton, SidebarSection } from './sidebar-section';import { useDispatch, useSelector } from '@/redux';export function ReportGlobalFilters() {const globalFilters = useSelector((state) => state.report.globalFilters);const dispatch = useDispatch();- return (- <div>- <h3 className="mb-2 font-medium">Global filters</h3>- <p className="mb-2 text-muted-foreground text-sm">- Applied to every series in this report.- </p>- <div className="rounded-lg border bg-def-100">- <div className="flex gap-2 p-2">- <PropertiesCombobox- categories={['event', 'profile', 'group', 'cohort', 'session']}- onSelect={(action) => {- const isCohortAction = action.value === 'cohort';- if (- isCohortAction &&- globalFilters.some(- (f) =>- f.operator === 'inCohort' || f.operator === 'notInCohort'- )- ) {- return;- }- dispatch(- addGlobalFilter(- isCohortAction- ? {- id: shortId(),- name: 'cohort',- operator: 'inCohort',- value: [],- cohortIds: [],- }- : {- id: shortId(),- name: action.value,- operator: 'is',- value: [],- type: 'string',- }- )- );- }}- >- {(setOpen) => (- <SmallButton icon={FilterIcon} onClick={() => setOpen((p) => !p)}>- Add filter- </SmallButton>- )}- </PropertiesCombobox>- </div>-- {globalFilters.length > 0 && (- <div className="flex flex-col divide-y overflow-hidden rounded-b-lg">- {globalFilters.map((filter) => (- <GlobalFilterItem- filter={filter}- key={filter.id ?? filter.name}- />- ))}- </div>- )}- </div>- </div>+ const addFilter = (+ <PropertiesCombobox+ categories={['event', 'profile', 'group', 'cohort', 'session']}+ onSelect={(action) => {+ const isCohortAction = action.value === 'cohort';+ if (+ isCohortAction &&+ globalFilters.some(+ (f) => f.operator === 'inCohort' || f.operator === 'notInCohort'+ )+ ) {+ return;+ }+ dispatch(+ addGlobalFilter(+ isCohortAction+ ? {+ id: shortId(),+ name: 'cohort',+ operator: 'inCohort',+ value: [],+ cohortIds: [],+ }+ : {+ id: shortId(),+ name: action.value,+ operator: 'is',+ value: [],+ type: 'string',+ }+ )+ );+ }}+ >+ {(setOpen) => (+ <BuilderAddButton icon={FilterIcon} onClick={() => setOpen((p) => !p)}>+ Add filter+ </BuilderAddButton>+ )}+ </PropertiesCombobox>);-}-function SmallButton({- children,- icon: Icon,- ...props-}: {- children: React.ReactNode;- icon: LucideIcon;-} & React.ButtonHTMLAttributes<HTMLButtonElement>) {return (- <button- className="flex min-w-0 items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-left font-medium text-sm leading-none"- type="button"- {...props}+ <SidebarSection+ description="Applied to every series in this report."+ title="Global filters">- <Icon className="shrink-0" size={12} />- <span className="truncate">{children}</span>- </button>+ {globalFilters.map((filter) => (+ <GlobalFilterItem filter={filter} key={filter.id ?? filter.name} />+ ))}+ {addFilter}+ </SidebarSection>);}diff --git a/apps/start/src/components/report/sidebar/ReportSeries.tsx b/apps/start/src/components/report/sidebar/ReportSeries.tsxindex 601144ccf..2977c4aaf 100644--- a/apps/start/src/components/report/sidebar/ReportSeries.tsx+++ b/apps/start/src/components/report/sidebar/ReportSeries.tsx@@ -34,6 +34,7 @@ import {ReportSeriesItem,type ReportSeriesItemProps,} from './ReportSeriesItem';+import { BuilderList, SidebarSection } from './sidebar-section';import { ColorSquare } from '@/components/color-square';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';@@ -203,8 +204,7 @@ export function ReportSeries() {chartType !== 'sankey';return (- <div>- <h3 className="mb-2 font-medium">Metrics</h3>+ <SidebarSection title="Metrics"><DndContextcollisionDetection={closestCenter}onDragEnd={handleDragEnd}@@ -216,13 +216,12 @@ export function ReportSeries() {}))}strategy={verticalListSortingStrategy}>- <div className="flex flex-col gap-4">+ <BuilderList>{selectedSeries.map((event, index) => {const isFormula = event.type === 'formula';return (<SortableReportSeriesItem- className="rounded-lg border bg-def-100"event={event}index={index}isSelectManyEvents={isSelectManyEvents}@@ -307,7 +306,7 @@ export function ReportSeries() {) : (<><ComboboxEvents- className="flex-1"+ className="min-w-0 flex-1"customEvents={customEvents}items={eventNames}multiple={isSelectManyEvents as false}@@ -368,9 +367,11 @@ export function ReportSeries() {}).name) as any}+ variant="input"/>{showDisplayNameInput && (<Input+ className="w-36 shrink-0"defaultValue={(event as IChartEventItem & { type: 'event' }).displayName@@ -397,11 +398,12 @@ export function ReportSeries() {);})}- <div className="flex gap-2">+ <div className="flex flex-wrap items-center gap-1 p-2"><ComboboxEvents- className="flex-1"+ className="text-muted-foreground hover:text-foreground"customEvents={customEvents}disabled={isAddEventDisabled || isSankeyEventLimitReached}+ icon={PlusIcon}items={eventNames}onChange={(value) => {if (isSelectManyEvents) {@@ -443,11 +445,13 @@ export function ReportSeries() {}}placeholder="Select event"searchable+ size="sm"value={''}+ variant="ghost"/>{showFormula && (<Button- className="flex-1 justify-start px-4 text-left"+ className="text-muted-foreground hover:text-foreground"icon={PiIcon}onClick={() => {dispatch(@@ -458,17 +462,17 @@ export function ReportSeries() {}));}}+ size="sm"type="button"- variant="outline"+ variant="ghost">Add Formula- <PlusIcon className="ml-auto size-4 text-muted-foreground" /></Button>)}</div>- </div>+ </BuilderList></SortableContext></DndContext>- </div>+ </SidebarSection>);}diff --git a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsxindex 8ccb62e62..4379ce2cd 100644--- a/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx+++ b/apps/start/src/components/report/sidebar/ReportSeriesItem.tsx@@ -4,11 +4,12 @@ import type {} from '@openpanel/core/modules/report/report.constants';import { alphabetIds } from '@openpanel/core/modules/report/report.constants';import { shortId } from '@openpanel/shared';-import { DatabaseIcon, FilterIcon, type LucideIcon } from 'lucide-react';+import { DatabaseIcon, FilterIcon } from 'lucide-react';import { ReportSegment } from '../ReportSegment';import { changeEvent } from '../reportSlice';import { FiltersList } from './filters/FiltersList';import { PropertiesCombobox } from './PropertiesCombobox';+import { BuilderChip } from './sidebar-section';import { ColorSquare } from '@/components/color-square';import { useDispatch } from '@/redux';@@ -44,7 +45,7 @@ export function ReportSeriesItem({return (<div {...props}>- <div className="group flex items-center gap-2 p-2">+ <div className="group flex items-center gap-2 px-3 py-2.5">{renderDragHandle ? (renderDragHandle(index)) : (@@ -57,9 +58,10 @@ export function ReportSeriesItem({{/* Segment and Filter buttons - only for events */}{chartEvent && (showSegment || showAddFilter) && (- <div className="flex gap-2 p-2 pt-0">+ <div className="flex flex-wrap gap-1 px-3 pb-2.5 pl-10">{showSegment && (<ReportSegment+ className="h-7 px-2 text-muted-foreground text-xs hover:text-foreground"onChange={(segment) => {dispatch(changeEvent({@@ -68,7 +70,9 @@ export function ReportSeriesItem({}));}}+ size="sm"value={chartEvent.segment}+ variant="ghost"/>)}{showAddFilter && (@@ -112,12 +116,12 @@ export function ReportSeriesItem({}}>{(setOpen) => (- <SmallButton+ <BuilderChipicon={FilterIcon}onClick={() => setOpen((p) => !p)}>Add filter- </SmallButton>+ </BuilderChip>)}</PropertiesCombobox>)}@@ -137,14 +141,14 @@ export function ReportSeriesItem({}}>{(setOpen) => (- <SmallButton+ <BuilderChipicon={DatabaseIcon}onClick={() => setOpen((p) => !p)}>{chartEvent.property? `Property: ${chartEvent.property}`: 'Select property'}- </SmallButton>+ </BuilderChip>)}</PropertiesCombobox>)}@@ -159,23 +163,3 @@ export function ReportSeriesItem({</div>);}--function SmallButton({- children,- icon: Icon,- ...props-}: {- children: React.ReactNode;- icon: LucideIcon;-} & React.ButtonHTMLAttributes<HTMLButtonElement>) {- return (- <button- className="flex min-w-0 items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-left font-medium text-sm leading-none"- type="button"- {...props}- >- <Icon className="shrink-0" size={12} />- <span className="truncate">{children}</span>- </button>- );-}diff --git a/apps/start/src/components/report/sidebar/ReportSettings.tsx b/apps/start/src/components/report/sidebar/ReportSettings.tsxindex 2a3e1a3a6..9ca289284 100644--- a/apps/start/src/components/report/sidebar/ReportSettings.tsx+++ b/apps/start/src/components/report/sidebar/ReportSettings.tsx@@ -18,6 +18,7 @@ import {changeStacked,changeUnit,} from '../reportSlice';+import { SidebarSection } from './sidebar-section';import { Combobox } from '@/components/ui/combobox';import { ComboboxEvents } from '@/components/ui/combobox-events';import { InputEnter } from '@/components/ui/input-enter';@@ -98,9 +99,8 @@ export function ReportSettings() {}return (- <div>- <h3 className="mb-2 font-medium">Settings</h3>- <div className="col gap-4 rounded-lg border bg-card p-4">+ <SidebarSection title="Settings">+ <div className="flex flex-col gap-3">{fields.includes('previous') && (<Label className="mb-0 flex items-center justify-between"><span className="whitespace-nowrap">@@ -131,7 +131,9 @@ export function ReportSettings() {]}onChange={(val) => dispatch(changeCriteria(val))}placeholder="Select criteria"+ size="sm"value={criteria}+ variant="input"/></div>)}@@ -154,7 +156,9 @@ export function ReportSettings() {dispatch(changeUnit(val === 'count' ? undefined : val));}}placeholder="Unit"+ size="sm"value={unit || 'count'}+ variant="input"/></div>)}@@ -174,8 +178,10 @@ export function ReportSettings() {]}onChange={(val) => dispatch(changeMetric(val as IChartMetric))}placeholder="Aggregation"- // Same labels the report table uses for these columns.+ size="sm"value={metric}+ // Same labels the report table uses for these columns.+ variant="input"/></div>)}@@ -202,7 +208,9 @@ export function ReportSettings() {);}}placeholder="Default: Session"+ size="sm"value={funnelGroup || 'session_id'}+ variant="input"/></div>)}@@ -212,6 +220,7 @@ export function ReportSettings() {Funnel Window</Label><InputEnter+ className="w-36"onChangeValue={(value) => {const parsed = Number.parseFloat(value);if (Number.isNaN(parsed)) {@@ -221,6 +230,7 @@ export function ReportSettings() {}}}placeholder="Default: 24h"+ size="sm"type="number"value={funnelWindow ? String(funnelWindow) : ''}/>@@ -243,7 +253,9 @@ export function ReportSettings() {);}}placeholder="Default: Fixed"+ size="sm"value={conversionYAxisScale}+ variant="input"/></div>)}@@ -272,7 +284,9 @@ export function ReportSettings() {);}}placeholder="Select mode"+ size="sm"value={options?.mode || 'after'}+ variant="input"/></div>)}@@ -280,6 +294,7 @@ export function ReportSettings() {<div className="flex items-center justify-between gap-4"><Label className="mb-0 whitespace-nowrap font-medium">Steps</Label><InputEnter+ className="w-36"onChangeValue={(value) => {const parsed = Number.parseInt(value, 10);if (Number.isNaN(parsed) || parsed < 2 || parsed > 10) {@@ -289,6 +304,7 @@ export function ReportSettings() {}}}placeholder="Default: 5"+ size="sm"type="number"value={options?.steps ? String(options.steps) : '5'}/>@@ -308,6 +324,7 @@ export function ReportSettings() {placeholder="Select events to exclude"searchablevalue={options?.exclude || []}+ variant="input"/></div>)}@@ -327,6 +344,7 @@ export function ReportSettings() {placeholder="Leave empty to include all"searchablevalue={options?.include || []}+ variant="input"/></div>)}@@ -340,6 +358,6 @@ export function ReportSettings() {</Label>)}</div>- </div>+ </SidebarSection>);}diff --git a/apps/start/src/components/report/sidebar/ReportSidebar.tsx b/apps/start/src/components/report/sidebar/ReportSidebar.tsxindex 7023136e1..1bd4399bb 100644--- a/apps/start/src/components/report/sidebar/ReportSidebar.tsx+++ b/apps/start/src/components/report/sidebar/ReportSidebar.tsx@@ -4,7 +4,13 @@ import { ReportSeries } from './ReportSeries';import { ReportSettings } from './ReportSettings';import { ReportFixedEvents } from './report-fixed-events';import { Button } from '@/components/ui/button';-import { SheetClose, SheetFooter } from '@/components/ui/sheet';+import {+ SheetClose,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from '@/components/ui/sheet';import { useSelector } from '@/redux';export function ReportSidebar() {@@ -13,7 +19,15 @@ export function ReportSidebar() {const showFixedEvents = chartType === 'sankey';return (<>- <div className="flex flex-col gap-8">+ <SheetHeader>+ <div className="flex flex-col gap-1">+ <SheetTitle>Report builder</SheetTitle>+ <SheetDescription>+ What to measure, how to filter it and how to split it.+ </SheetDescription>+ </div>+ </SheetHeader>+ <div className="flex flex-col gap-7 py-2">{showFixedEvents ? (<ReportFixedEventsnumberOfEvents={diff --git a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsxindex 4a678c172..3482ad79e 100644--- a/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx+++ b/apps/start/src/components/report/sidebar/filters/CohortFilterItem.tsx@@ -4,9 +4,9 @@ import {type IChartEventFilter,type IChartEventFilterOperator,} from '@openpanel/core/modules/report/report.constants';-import { SlidersHorizontal, Trash } from 'lucide-react';+import { FilterIcon, XIcon } from 'lucide-react';import { changeEvent } from '../../reportSlice';-import { ColorSquare } from '@/components/color-square';+import { FILTER_CARD_CLASS } from '@/components/report/sidebar/sidebar-section';import { Button } from '@/components/ui/button';import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';@@ -14,6 +14,7 @@ import { RenderDots } from '@/components/ui/RenderDots';import { useAppParams } from '@/hooks/use-app-params';import { useCohorts } from '@/hooks/use-cohorts';import { useDispatch } from '@/redux';+import { cn } from '@/utils/cn';interface CohortFilterItemProps {event: IChartEvent;@@ -83,7 +84,7 @@ export function CohortFilterItem({ filter, event }: CohortFilterItemProps) {return (<PureCohortFilterItem- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"+ className={FILTER_CARD_CLASS}filter={filter}onChangeCohort={onChangeCohort}onChangeOperator={onChangeOperator}@@ -137,19 +138,23 @@ export function PureCohortFilterItem({};return (- <div className={className}>- <div className="mb-2 flex items-center gap-2">- <ColorSquare className="bg-emerald-500">- <SlidersHorizontal size={10} />- </ColorSquare>- <div className="flex flex-1">- <RenderDots truncate>{cohortLabel}</RenderDots>- </div>- <Button onClick={removeFilter} size="sm" variant="ghost">- <Trash size={16} />+ <div className={cn('flex flex-col gap-1.5', className)}>+ <div className="flex min-h-6 items-center gap-1.5 text-muted-foreground text-xs">+ <FilterIcon className="shrink-0" size={12} />+ <RenderDots className="min-w-0 font-medium" truncate>+ {cohortLabel}+ </RenderDots>+ <Button+ aria-label="Delete filter"+ className="ml-auto size-6 text-muted-foreground hover:text-foreground"+ onClick={removeFilter}+ size="icon"+ variant="ghost"+ >+ <XIcon size={14} /></Button></div>- <div className="flex gap-1">+ <div className="flex flex-wrap gap-1.5"><DropdownMenuComposeditems={[{ value: 'inCohort', label: 'In cohort' },@@ -158,16 +163,18 @@ export function PureCohortFilterItem({label="Operator"onChange={changeFilterOperator}>- <Button className="whitespace-nowrap" variant="outline">+ <Button className="whitespace-nowrap" size="sm" variant="input">{filter.operator === 'inCohort' ? 'In cohort' : 'Not in cohort'}</Button></DropdownMenuComposed><ComboboxAdvanced- className="flex-1"+ className="min-w-40 flex-1"items={cohortsCombobox}onChange={changeCohort}placeholder="Select cohorts..."+ size="sm"value={selectedIds}+ variant="input"/></div></div>diff --git a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx b/apps/start/src/components/report/sidebar/filters/FilterItem.tsxindex 7773bdd37..f41e927da 100644--- a/apps/start/src/components/report/sidebar/filters/FilterItem.tsx+++ b/apps/start/src/components/report/sidebar/filters/FilterItem.tsx@@ -6,11 +6,11 @@ import type {IChartFilterValueType,} from '@openpanel/core/modules/report/report.constants';import { getOperatorsForType } from '@openpanel/core/modules/report/report.constants';-import { SlidersHorizontal, Trash } from 'lucide-react';+import { FilterIcon, XIcon } from 'lucide-react';import { changeEvent } from '../../reportSlice';-import { ColorSquare } from '@/components/color-square';import { FilterOperatorSelect } from '@/components/report/sidebar/filters/FilterOperatorSelect';import { FilterTypeSelect } from '@/components/report/sidebar/filters/FilterTypeSelect';+import { FILTER_CARD_CLASS } from '@/components/report/sidebar/sidebar-section';import { Button } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';@@ -21,6 +21,7 @@ import { useAppParams } from '@/hooks/use-app-params';import { useEventNames } from '@/hooks/use-event-names';import { usePropertyValues } from '@/hooks/use-property-values';import { useDispatch } from '@/redux';+import { cn } from '@/utils/cn';// Client-side sanity check: can this raw value possibly match the chosen cast// type? Mirrors the SQL casts in@@ -173,7 +174,7 @@ export function FilterItem({ filter, event }: FilterProps) {const dispatch = useDispatch();return (<PureFilterItem- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"+ className={FILTER_CARD_CLASS}eventName={event.name}filter={filter}onChangeOperator={onChangeOperator}@@ -261,11 +262,13 @@ export function PureFilterItem({if (isBooleanSessionFilter) {return (<Combobox- className="flex-1"+ className="w-full"items={BOOLEAN_VALUE_ITEMS}onChange={(v) => changeFilterValue([v])}placeholder="Yes / No"+ size="sm"value={filter.value[0] === undefined ? null : String(filter.value[0])}+ variant="input"/>);}@@ -273,12 +276,14 @@ export function PureFilterItem({if (isPerformedEventFilter) {return (<ComboboxEvents- className="flex-1"+ className="w-full"items={eventNames}onChange={(v: string) => changeFilterValue([v])}placeholder="Select event"searchable+ size="sm"value={filter.value[0] ? String(filter.value[0]) : null}+ variant="input"/>);}@@ -286,11 +291,13 @@ export function PureFilterItem({if (filter.operator === 'is' || filter.operator === 'isNot') {return (<ComboboxAdvanced- className="flex-1"+ className="w-full"items={valuesCombobox}onChange={changeFilterValue}placeholder="Select..."+ size="sm"value={filter.value}+ variant="input"/>);}@@ -300,25 +307,30 @@ export function PureFilterItem({error={valueError}immediate={immediateInput}onChangeValue={(value) => changeFilterValue([value])}+ size="sm"value={filter.value[0] ? String(filter.value[0]) : ''}/>);};return (- <div className={className}>- <div className="mb-2 flex items-center gap-2">- <ColorSquare className="bg-emerald-500">- <SlidersHorizontal size={10} />- </ColorSquare>- <div className="flex flex-1">- <RenderDots truncate>{filter.name}</RenderDots>- </div>- <Button onClick={removeFilter} size="sm" variant="ghost">- <Trash size={16} />+ <div className={cn('flex flex-col gap-1.5', className)}>+ <div className="flex min-h-6 items-center gap-1.5 text-muted-foreground text-xs">+ <FilterIcon className="shrink-0" size={12} />+ <RenderDots className="min-w-0 font-medium" truncate>+ {filter.name}+ </RenderDots>+ <Button+ aria-label="Delete filter"+ className="ml-auto size-6 text-muted-foreground hover:text-foreground"+ onClick={removeFilter}+ size="icon"+ variant="ghost"+ >+ <XIcon size={14} /></Button></div>- <div className="flex gap-1">+ <div className="flex flex-wrap gap-1.5">{showTypeSelect && (<FilterTypeSelect onChange={changeFilterType} value={filter.type} />)}@@ -327,11 +339,9 @@ export function PureFilterItem({type={filter.type}value={filter.operator}/>- {renderValueControl()}+ <div className="min-w-40 flex-1">{renderValueControl()}</div></div>- {valueError && (- <p className="mt-1 text-destructive text-xs">{valueError}</p>- )}+ {valueError && <p className="text-destructive text-xs">{valueError}</p>}</div>);}diff --git a/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx b/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsxindex a2b94f4c8..0ecf868fb 100644--- a/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx+++ b/apps/start/src/components/report/sidebar/filters/FilterOperatorSelect.tsx@@ -26,7 +26,7 @@ export function FilterOperatorSelect({children,}: FilterOperatorSelectProps) {const trigger = children ?? (- <Button className="whitespace-nowrap" variant="outline">+ <Button className="whitespace-nowrap" size="sm" variant="input">{operatorsShort[value]}</Button>);diff --git a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsxindex 895e0f4fd..e667b3222 100644--- a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx+++ b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx@@ -19,7 +19,7 @@ export function FilterTypeSelect({children,}: FilterTypeSelectProps) {const trigger = children ?? (- <Button className="whitespace-nowrap" variant="outline">+ <Button className="whitespace-nowrap" size="sm" variant="input">{filterValueTypes[value ?? 'string']}</Button>);diff --git a/apps/start/src/components/report/sidebar/filters/FiltersList.tsx b/apps/start/src/components/report/sidebar/filters/FiltersList.tsxindex 88c5c634e..974f3c70c 100644--- a/apps/start/src/components/report/sidebar/filters/FiltersList.tsx+++ b/apps/start/src/components/report/sidebar/filters/FiltersList.tsx@@ -25,8 +25,8 @@ export function FiltersList({}return (- <div>- <div className="flex flex-col divide-y overflow-hidden rounded-b-md bg-def-100">+ <div className="px-3 pb-3 pl-10">+ <div className="flex flex-col gap-2">{filters.map((filter) => {const isCohortFilter =filter.operator === 'inCohort' || filter.operator === 'notInCohort';diff --git a/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx b/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsxindex 8aa04ecf2..0b4c4506f 100644--- a/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx+++ b/apps/start/src/components/report/sidebar/filters/GlobalFilterItem.tsx@@ -8,6 +8,7 @@ import { getOperatorsForType } from '@openpanel/core/modules/report/report.constimport { changeGlobalFilter, removeGlobalFilter } from '../../reportSlice';import { PureCohortFilterItem } from './CohortFilterItem';import { PureFilterItem } from './FilterItem';+import { FILTER_CARD_CLASS } from '@/components/report/sidebar/sidebar-section';import { useDispatch } from '@/redux';interface GlobalFilterItemProps {@@ -89,7 +90,7 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {if (isCohortFilter) {return (<PureCohortFilterItem- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"+ className={FILTER_CARD_CLASS}filter={filter}onChangeCohort={onChangeCohort}onChangeOperator={onChangeOperator}@@ -100,7 +101,7 @@ export function GlobalFilterItem({ filter }: GlobalFilterItemProps) {return (<PureFilterItem- className="px-4 py-2 shadow-[inset_6px_0_0] shadow-def-300 first:border-t"+ className={FILTER_CARD_CLASS}eventName="*"filter={filter}onChangeOperator={onChangeOperator}diff --git a/apps/start/src/components/report/sidebar/report-fixed-events.tsx b/apps/start/src/components/report/sidebar/report-fixed-events.tsxindex 76180cc8d..909ce3a5a 100644--- a/apps/start/src/components/report/sidebar/report-fixed-events.tsx+++ b/apps/start/src/components/report/sidebar/report-fixed-events.tsx@@ -13,6 +13,7 @@ import {import type { ReportEventMoreProps } from './ReportEventMore';import { ReportEventMore } from './ReportEventMore';import { ReportSeriesItem } from './ReportSeriesItem';+import { BuilderList, SidebarSection } from './sidebar-section';import { ColorSquare } from '@/components/color-square';import { ComboboxEvents } from '@/components/ui/combobox-events';import { Input } from '@/components/ui/input';@@ -74,9 +75,8 @@ export function ReportFixedEvents({chartType !== 'sankey';return (- <div>- <h3 className="mb-2 font-medium">Metrics</h3>- <div className="flex flex-col gap-4">+ <SidebarSection title="Metrics">+ <BuilderList>{Array.from({ length: numberOfEvents }, (_, index) => ({slotId: `fixed-event-slot-${index}`,index,@@ -86,8 +86,8 @@ export function ReportFixedEvents({// If no event exists at this index, render an empty slotif (!event) {return (- <div className="rounded-lg border bg-def-100" key={slotId}>- <div className="flex items-center gap-2 p-2">+ <div key={slotId}>+ <div className="flex items-center gap-2 px-3 py-2.5"><ColorSquare><span className="block">{alphabetIds[index]}</span></ColorSquare>@@ -125,6 +125,7 @@ export function ReportFixedEvents({placeholder="Select event"searchablevalue={''}+ variant="input"/></div></div>@@ -138,7 +139,6 @@ export function ReportFixedEvents({return (<ReportSeriesItem- className="rounded-lg border bg-def-100"event={event}index={index}isSelectManyEvents={isSelectManyEvents}@@ -191,9 +191,11 @@ export function ReportFixedEvents({}).name) as any}+ variant="input"/>{showDisplayNameInput && (<Input+ className="w-36 shrink-0"defaultValue={(event as IChartEventItem & { type: 'event' }).displayName}@@ -216,7 +218,7 @@ export function ReportFixedEvents({</ReportSeriesItem>);})}- </div>- </div>+ </BuilderList>+ </SidebarSection>);}diff --git a/apps/start/src/components/report/sidebar/sidebar-section.tsx b/apps/start/src/components/report/sidebar/sidebar-section.tsxnew file mode 100644index 000000000..aa3559806--- /dev/null+++ b/apps/start/src/components/report/sidebar/sidebar-section.tsx@@ -0,0 +1,90 @@+import type { LucideIcon } from 'lucide-react';+import { forwardRef } from 'react';+import { cn } from '@/utils/cn';++interface SidebarSectionProps {+ title: string;+ description?: string;+ action?: React.ReactNode;+ children?: React.ReactNode;+}++export function SidebarSection({+ title,+ description,+ action,+ children,+}: SidebarSectionProps) {+ return (+ <section className="flex flex-col gap-2.5">+ <div className="flex items-center justify-between gap-2">+ <div className="flex flex-col gap-0.5">+ <h3 className="font-medium text-3xs text-muted-foreground uppercase tracking-wider">+ {title}+ </h3>+ {description && (+ <p className="text-muted-foreground text-xs">{description}</p>+ )}+ </div>+ {action}+ </div>+ {children}+ </section>+ );+}++/** Quiet text-and-icon action used inside the builder: add filter, add breakdown, segment. */+export const BuilderChip = forwardRef<+ HTMLButtonElement,+ { icon: LucideIcon } & React.ButtonHTMLAttributes<HTMLButtonElement>+>(({ icon: Icon, children, className, ...props }, ref) => (+ <button+ className={cn(+ 'inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-2 font-medium text-muted-foreground text-xs transition-colors hover:bg-def-200 hover:text-foreground dark:hover:bg-def-300',+ className+ )}+ ref={ref}+ type="button"+ {...props}+ >+ <Icon className="shrink-0" size={13} />+ <span className="truncate">{children}</span>+ </button>+));+BuilderChip.displayName = 'BuilderChip';++/** One filter as a self-contained card: label, controls and delete button together. */+export const FILTER_CARD_CLASS = 'rounded-lg border bg-card p-2.5';++/** Full-width dashed action that invites the first item of a section and adds more after it. */+export const BuilderAddButton = forwardRef<+ HTMLButtonElement,+ { icon: LucideIcon } & React.ButtonHTMLAttributes<HTMLButtonElement>+>(({ icon: Icon, children, className, ...props }, ref) => (+ <button+ className={cn(+ 'flex h-10 w-full items-center gap-2 rounded-xl border border-def-400/70 border-dashed px-3 font-medium text-muted-foreground text-sm transition-colors hover:border-solid hover:bg-def-100 hover:text-foreground dark:border-def-400 dark:hover:bg-def-200',+ className+ )}+ ref={ref}+ type="button"+ {...props}+ >+ <Icon className="shrink-0" size={15} />+ <span className="truncate">{children}</span>+ </button>+));+BuilderAddButton.displayName = 'BuilderAddButton';++/** Bordered list that holds the series, breakdown and global filter rows. */+export function BuilderList({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) {+ return (+ <div+ className={cn('flex flex-col divide-y rounded-xl border', className)}+ {...props}+ />+ );+}diff --git a/apps/start/src/components/time-window-picker.tsx b/apps/start/src/components/time-window-picker.tsxindex 9f19405de..306fda859 100644--- a/apps/start/src/components/time-window-picker.tsx+++ b/apps/start/src/components/time-window-picker.tsx@@ -10,7 +10,7 @@ import { bind } from 'bind-event-listener';import { addDays, endOfDay, format, startOfDay, subDays } from 'date-fns';import { CalendarIcon } from 'lucide-react';import { useCallback, useEffect, useRef, useState } from 'react';-import { Button } from '@/components/ui/button';+import { Button, type ButtonProps } from '@/components/ui/button';import {DropdownMenu,DropdownMenuContent,@@ -35,6 +35,8 @@ interface Props {endDate: string | null;startDate: string | null;className?: string;+ variant?: ButtonProps['variant'];+ size?: ButtonProps['size'];}export function TimeWindowPicker({value,@@ -45,6 +47,8 @@ export function TimeWindowPicker({onEndDateChange,onIntervalChange,className,+ variant = 'outline',+ size,}: Props) {const isDateRangerPickerOpen = useRef(false);useOnPushModal('DateRangerPicker', (open) => {@@ -122,7 +126,8 @@ export function TimeWindowPicker({<ButtonclassName={cn('justify-start', className)}icon={CalendarIcon}- variant="outline"+ size={size}+ variant={variant}>{timeWindow?.label}</Button>diff --git a/apps/start/src/components/ui/button.tsx b/apps/start/src/components/ui/button.tsxindex 2e8502fd5..5e68fe3e9 100644--- a/apps/start/src/components/ui/button.tsx+++ b/apps/start/src/components/ui/button.tsx@@ -19,19 +19,21 @@ const buttonVariants = cva(outline:'border border-input bg-card hover:bg-accent hover:text-accent-foreground',secondary: 'bg-def-100 text-secondary-foreground hover:bg-def-100/80',+ input:+ 'rounded-lg bg-def-200 font-normal text-foreground hover:translate-y-0 hover:bg-def-300 dark:bg-def-300 dark:hover:bg-def-400/60',ghost: 'hover:bg-accent hover:text-accent-foreground',link: 'text-primary underline-offset-4 hover:underline',},size: {- default: 'h-10 px-4 py-2',- sm: 'h-8 rounded-md px-2',- lg: 'h-11 rounded-md px-8',+ default: 'h-9 px-3.5',+ sm: 'h-8 rounded-md px-2.5',+ lg: 'h-10 rounded-md px-6',icon: 'h-8 w-8',},},defaultVariants: {variant: 'default',- size: 'sm',+ size: 'default',},});@@ -59,13 +61,13 @@ function fixHeight({if (autoHeight) {switch (size) {case 'lg':- return 'h-auto min-h-11 py-2';+ return 'h-auto min-h-10 py-2';case 'icon':return 'h-auto min-h-8 py-1';- case 'default':- return 'h-auto min-h-10 py-2';- default:+ case 'sm':return 'h-auto min-h-8 py-1';+ default:+ return 'h-auto min-h-9 py-1.5';}}return '';diff --git a/apps/start/src/components/ui/combobox-advanced.tsx b/apps/start/src/components/ui/combobox-advanced.tsxindex e20e945d4..61eda0a11 100644--- a/apps/start/src/components/ui/combobox-advanced.tsx+++ b/apps/start/src/components/ui/combobox-advanced.tsx@@ -11,6 +11,7 @@ import {} from './popover';import { Badge } from '@/components/ui/badge';import { Command, CommandInput, CommandItem } from '@/components/ui/command';+import { cn } from '@/utils/cn';type IValue = any;type IItem = Record<'value' | 'label', IValue>;@@ -30,6 +31,7 @@ interface ComboboxAdvancedProps {placeholder?: string;className?: string;size?: ButtonProps['size'];+ variant?: ButtonProps['variant'];children?: React.ReactNode;}@@ -40,6 +42,7 @@ export function ComboboxAdvanced({placeholder,className,size,+ variant = 'outline',children,}: ComboboxAdvancedProps) {const [open, setOpen] = React.useState(false);@@ -104,7 +107,7 @@ export function ComboboxAdvanced({}, [inputValue, selectables, items, value]);const trigger = children ?? (- <Button autoHeight className={className} size={size} variant={'outline'}>+ <Button autoHeight className={className} size={size} variant={variant}><div className="flex w-full flex-wrap gap-1">{value.length === 0 && placeholder}{value.map((val) => {@@ -112,7 +115,18 @@ export function ComboboxAdvanced({value: val,label: val,};- return <Badge key={String(item.value)}>{item.label}</Badge>;+ return (+ <Badge+ className={cn(+ variant === 'input' &&+ 'border-transparent bg-card font-normal shadow-xs dark:bg-def-200'+ )}+ key={String(item.value)}+ variant={variant === 'input' ? 'outline' : 'default'}+ >+ {item.label}+ </Badge>+ );})}</div><ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />diff --git a/apps/start/src/components/ui/combobox-events.tsx b/apps/start/src/components/ui/combobox-events.tsxindex 3feb36475..42b3b070e 100644--- a/apps/start/src/components/ui/combobox-events.tsx+++ b/apps/start/src/components/ui/combobox-events.tsx@@ -4,6 +4,7 @@ import {ChevronsUpDown,GanttChartIcon,LayersIcon,+ type LucideIcon,} from 'lucide-react';import VirtualList from 'rc-virtual-list';import * as React from 'react';@@ -55,6 +56,9 @@ export interface ComboboxProps<T, TMultiple extends boolean = false> {className?: string;searchable?: boolean;size?: ButtonProps['size'];+ variant?: ButtonProps['variant'];+ /** Icon shown while nothing is selected. */+ icon?: LucideIcon;label?: string;align?: 'start' | 'end' | 'center';portal?: boolean;@@ -89,6 +93,8 @@ export function ComboboxEvents<className,searchable,size,+ variant = 'outline',+ icon: PlaceholderIcon = GanttChartIcon,align = 'start',portal,error,@@ -167,7 +173,7 @@ export function ComboboxEvents</>);}- return <GanttChartIcon className="mr-2 shrink-0" size={16} />;+ return <PlaceholderIcon className="mr-2 shrink-0" size={16} />;};const renderTriggerContent = () => {@@ -202,7 +208,7 @@ export function ComboboxEvents<disabled={disabled}role="combobox"size={size}- variant="outline"+ variant={variant}><div className="flex min-w-0 items-center">{renderTriggerIcon()}diff --git a/apps/start/src/components/ui/combobox.tsx b/apps/start/src/components/ui/combobox.tsxindex 62c218b0e..12519043c 100644--- a/apps/start/src/components/ui/combobox.tsx+++ b/apps/start/src/components/ui/combobox.tsx@@ -33,11 +33,19 @@ export interface ComboboxProps<T> {searchable?: boolean;icon?: LucideIcon;size?: ButtonProps['size'];+ /** `input` makes the trigger look like a form field; use it inside forms. */+ variant?: ButtonProps['variant'];label?: string;align?: 'start' | 'end' | 'center';portal?: boolean;error?: string;disabled?: boolean;+ /**+ * Let a label and a hint point at the built-in trigger. A custom trigger+ * passed as `children` carries its own id and description.+ */+ id?: string;+ 'aria-describedby'?: string;}export type ExtendedComboboxProps<T> = Omit<@@ -58,10 +66,13 @@ export function Combobox<T extends string>({searchable,icon: Icon,size,+ variant = 'outline',align = 'start',portal,error,disabled,+ id,+ 'aria-describedby': describedBy,}: ComboboxProps<T>) {const [open, setOpen] = React.useState(false);const [search, setSearch] = React.useState('');@@ -76,16 +87,20 @@ export function Combobox<T extends string>({<PopoverTrigger asChild>{children ?? (<Button+ aria-describedby={describedBy}aria-expanded={open}+ aria-invalid={error ? true : undefined}className={cn('justify-between',- !!error && 'border-destructive',+ !!error &&+ 'border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive',className)}disabled={disabled}+ id={id}role="combobox"size={size}- variant="outline"+ variant={variant}><div className="flex min-w-0 items-center">{Icon ? <Icon className="mr-2 shrink-0" size={16} /> : null}diff --git a/apps/start/src/components/ui/command.tsx b/apps/start/src/components/ui/command.tsxindex 45c06ac3f..85a5fa364 100644--- a/apps/start/src/components/ui/command.tsx+++ b/apps/start/src/components/ui/command.tsx@@ -46,7 +46,8 @@ function CommandDialog({<DialogDescription>{description}</DialogDescription></DialogHeader><DialogContent- className={cn('overflow-hidden p-0', className)}+ bodyClassName="overflow-hidden p-0"+ className={className}showCloseButton={showCloseButton}><Command className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">diff --git a/apps/start/src/components/ui/data-table/data-table-slider-filter.tsx b/apps/start/src/components/ui/data-table/data-table-slider-filter.tsxindex 7c401f063..932c78ce6 100644--- a/apps/start/src/components/ui/data-table/data-table-slider-filter.tsx+++ b/apps/start/src/components/ui/data-table/data-table-slider-filter.tsx@@ -177,6 +177,7 @@ export function DataTableSliderFilter<TData>({onChange={onFromInputChange}pattern="[0-9]*"placeholder={min.toString()}+ size="sm"type="number"value={range[0]?.toString()}/>@@ -201,6 +202,7 @@ export function DataTableSliderFilter<TData>({onChange={onToInputChange}pattern="[0-9]*"placeholder={max.toString()}+ size="sm"type="number"value={range[1]?.toString()}/>diff --git a/apps/start/src/components/ui/data-table/data-table-toolbar.tsx b/apps/start/src/components/ui/data-table/data-table-toolbar.tsxindex f3d705f03..b287430f6 100644--- a/apps/start/src/components/ui/data-table/data-table-toolbar.tsx+++ b/apps/start/src/components/ui/data-table/data-table-toolbar.tsx@@ -125,6 +125,7 @@ function DataTableToolbarFilter<TData>({inputMode="numeric"onChange={(event) => column.setFilterValue(event.target.value)}placeholder={getTitle()}+ size="sm"type="number"value={(column.getFilterValue() as string) ?? ''}/>diff --git a/apps/start/src/components/ui/dialog.tsx b/apps/start/src/components/ui/dialog.tsxindex 079547f03..92a580669 100644--- a/apps/start/src/components/ui/dialog.tsx+++ b/apps/start/src/components/ui/dialog.tsx@@ -43,12 +43,20 @@ function DialogOverlay({);}+/**+ * Two layers: a tinted shell that carries the footer, and an inset card for+ * the content. The footer stays in the markup where each modal renders it+ * (often inside a form so submit buttons keep working) and is pinned to the+ * bottom of the shell, which reserves the footer's height while one exists.+ */function DialogContent({className,+ bodyClassName,children,showCloseButton = false,...props}: React.ComponentProps<typeof DialogPrimitive.Content> & {+ bodyClassName?: string;showCloseButton?: boolean;}) {// Not using DialogPortal because it's breaking useRef's for some reason@@ -57,20 +65,29 @@ function DialogContent({<DialogOverlay /><DialogPrimitive.ContentclassName={cn(- 'max-h-screen overflow-y-auto overflow-x-hidden', // Ensure the dialog is scrollable if it exceeds the screen height- 'mt-auto', // Add margin-top: auto for all screen sizes+ 'fixed top-[50%] left-[50%] z-50 flex w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] flex-col sm:max-w-lg',+ 'max-h-[calc(100vh-2rem)] md:max-h-[90vh]','transition-none focus:outline-none focus:ring-0',- 'border bg-card shadow-2xl sm:rounded-xl md:max-h-[90vh]',- 'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border bg-card p-6 shadow-2xl duration-200 data-[state=closed]:animate-out data-[state=open]:animate-in sm:max-w-lg [&>*]:min-w-0',+ 'rounded-2xl border bg-def-100 p-1.5 shadow-2xl [--dialog-footer-height:3.5rem]',+ 'has-[[data-slot=dialog-footer]]:pb-[calc(var(--dialog-footer-height)_+_--spacing(1.5))]',+ 'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 duration-200 data-[state=closed]:animate-out data-[state=open]:animate-in',className)}data-slot="dialog-content"{...props}>- {children}+ <div+ className={cn(+ 'grid min-h-0 flex-1 gap-4 overflow-y-auto overflow-x-hidden rounded-[10px] border bg-card p-6 [&>*]:min-w-0',+ bodyClassName+ )}+ data-slot="dialog-body"+ >+ {children}+ </div>{showCloseButton && (<DialogPrimitive.Close- className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"+ className="absolute top-5 right-5 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"data-slot="dialog-close"><XIcon />@@ -96,7 +113,7 @@ function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {return (<divclassName={cn(- '-mx-6 mt-2 -mb-6 flex flex-col-reverse gap-2 rounded-b-xl border-border border-t bg-def-100 px-6 py-4 sm:flex-row sm:justify-end',+ 'absolute inset-x-0 bottom-0 flex h-(--dialog-footer-height) items-center justify-end gap-2 px-3',className)}data-slot="dialog-footer"diff --git a/apps/start/src/components/ui/input.tsx b/apps/start/src/components/ui/input.tsxindex 98578fced..e834a9e82 100644--- a/apps/start/src/components/ui/input.tsx+++ b/apps/start/src/components/ui/input.tsx@@ -3,18 +3,25 @@ import { cva } from 'class-variance-authority';import * as React from 'react';import { cn } from '@/utils/cn';+/** The filled, borderless surface every form field shares: inputs, textareas, select and combobox triggers, tag inputs. */+export const fieldSurface =+ 'rounded-lg bg-def-200 text-foreground transition-[background-color,box-shadow] placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring aria-invalid:ring-1 aria-invalid:ring-destructive disabled:cursor-not-allowed disabled:opacity-50 dark:bg-def-300';+const inputVariant = cva(- 'flex w-full rounded-md border border-input bg-card text-sm ring-offset-background file:border-0 file:bg-transparent file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50',+ cn(+ fieldSurface,+ 'flex w-full text-sm file:border-0 file:bg-transparent file:font-medium'+ ),{variants: {size: {- sm: 'h-8 px-3 py-2',- default: 'h-10 px-3 py-2',- large: 'h-12 px-4 py-3 text-lg',+ sm: 'h-8 rounded-md px-2.5',+ default: 'h-9 px-3',+ large: 'h-10 px-3.5',},},defaultVariants: {- size: 'sm',+ size: 'default',},});@@ -28,12 +35,10 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, error, type, size, ...props }, ref) => {return (<input+ aria-invalid={error ? true : undefined}autoComplete="off"autoCorrect="off"- className={cn(- inputVariant({ size, className }),- !!error && 'border-destructive'- )}+ className={cn(inputVariant({ size, className }))}ref={ref}type={type}{...props}diff --git a/apps/start/src/components/ui/label.tsx b/apps/start/src/components/ui/label.tsxindex f820d93e9..edca92d6f 100644--- a/apps/start/src/components/ui/label.tsx+++ b/apps/start/src/components/ui/label.tsx@@ -5,7 +5,7 @@ import * as React from 'react';import { cn } from '@/utils/cn';const labelVariants = cva(- 'mb-2 block font-medium text-foreground/70 text-sm peer-disabled:cursor-not-allowed peer-disabled:opacity-70'+ 'mb-2 block font-medium text-foreground text-sm peer-disabled:cursor-not-allowed peer-disabled:opacity-70');const Label = React.forwardRef<diff --git a/apps/start/src/components/ui/select.tsx b/apps/start/src/components/ui/select.tsxindex b3abc32a6..eaf5d2e91 100644--- a/apps/start/src/components/ui/select.tsx+++ b/apps/start/src/components/ui/select.tsx@@ -1,6 +1,7 @@import * as SelectPrimitive from '@radix-ui/react-select';import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';import type * as React from 'react';+import { fieldSurface } from './input';import { cn } from '@/lib/utils';function Select({@@ -32,7 +33,8 @@ function SelectTrigger({return (<SelectPrimitive.TriggerclassName={cn(- "flex w-fit items-center justify-between gap-2 whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 font-medium text-sm shadow-xs outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[size=default]:h-8 data-[size=sm]:h-8 data-[placeholder]:text-muted-foreground *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:hover:bg-input/50 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0",+ fieldSurface,+ "flex w-fit items-center justify-between gap-2 whitespace-nowrap px-3 py-2 text-sm data-[size=default]:h-9 data-[size=sm]:h-8 data-[size=sm]:rounded-md data-[placeholder]:text-muted-foreground *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0",className)}data-size={size}diff --git a/apps/start/src/components/ui/sheet.tsx b/apps/start/src/components/ui/sheet.tsxindex f1ef5e94d..01a3cb8ec 100644--- a/apps/start/src/components/ui/sheet.tsx+++ b/apps/start/src/components/ui/sheet.tsx@@ -85,7 +85,7 @@ const SheetHeader = ({}: React.HTMLAttributes<HTMLDivElement>) => (<divclassName={cn(- 'relative -mx-6 -mt-6 mb-0 flex justify-between border-border border-b p-6 pb-5',+ 'sticky -top-6 z-10 -mx-6 -mt-6 mb-0 flex justify-between rounded-t-xl border-border border-b bg-card p-6 pb-5',className)}{...props}@@ -103,7 +103,7 @@ const SheetFooter = ({}: React.HTMLAttributes<HTMLDivElement>) => (<divclassName={cn(- '-mx-6 mt-auto -mb-6 flex flex-col-reverse gap-2 rounded-b-xl border-border border-t bg-def-100 px-6 py-4 sm:flex-row sm:justify-end',+ 'sticky -bottom-6 z-10 -mx-6 mt-auto -mb-6 flex flex-col-reverse gap-2 rounded-b-xl border-border border-t bg-def-100 px-6 py-4 sm:flex-row sm:justify-end',className)}{...props}diff --git a/apps/start/src/components/ui/textarea.tsx b/apps/start/src/components/ui/textarea.tsxindex bde7c006d..e4daddb0d 100644--- a/apps/start/src/components/ui/textarea.tsx+++ b/apps/start/src/components/ui/textarea.tsx@@ -1,4 +1,5 @@import * as React from 'react';+import { fieldSurface } from './input';import { cn } from '@/utils/cn';export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;@@ -8,7 +9,8 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(return (<textareaclassName={cn(- 'flex min-h-[80px] w-full rounded-md border border-input bg-card px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',+ fieldSurface,+ 'flex min-h-20 w-full px-3 py-2.5 text-sm',className)}ref={ref}diff --git a/apps/start/src/modals/Modal/Container.tsx b/apps/start/src/modals/Modal/Container.tsxindex eb32d87c8..d905b8122 100644--- a/apps/start/src/modals/Modal/Container.tsx+++ b/apps/start/src/modals/Modal/Container.tsx@@ -8,6 +8,7 @@ import { cn } from '@/utils/cn';interface ModalContentProps extends DialogContentProps {children: React.ReactNode;+ bodyClassName?: string;}export function ModalContent({ children, ...props }: ModalContentProps) {diff --git a/apps/start/src/modals/Modal/scrollable-modal.tsx b/apps/start/src/modals/Modal/scrollable-modal.tsxindex 02fd05387..7ab760e31 100644--- a/apps/start/src/modals/Modal/scrollable-modal.tsx+++ b/apps/start/src/modals/Modal/scrollable-modal.tsx@@ -25,7 +25,7 @@ export function ScrollableModal({const scrollAreaRef = useRef<HTMLDivElement>(null);return (<ScrollableModalContext.Provider value={{ scrollAreaRef }}>- <ModalContent className="!max-h-[90vh] flex flex-col gap-0 p-0">+ <ModalContent bodyClassName="flex flex-col gap-0 p-0"><div className="flex-shrink-0 p-6">{header}</div><VirtualScrollAreaclassName={cn(diff --git a/apps/start/src/modals/add-client.tsx b/apps/start/src/modals/add-client.tsxindex acec2be5c..88cbb7dab 100644--- a/apps/start/src/modals/add-client.tsx+++ b/apps/start/src/modals/add-client.tsx@@ -1,6 +1,7 @@import { zodResolver } from '@hookform/resolvers/zod';import { useMutation, useQueryClient } from '@tanstack/react-query';import { SaveIcon } from 'lucide-react';+import { useId } from 'react';import type { SubmitHandler } from 'react-hook-form';import { Controller, useForm } from 'react-hook-form';import { toast } from 'sonner';@@ -8,15 +9,32 @@ import { z } from 'zod';import { popModal } from '.';import { ModalContent, ModalHeader } from './Modal/Container';import { CreateClientSuccess } from '@/components/clients/create-client-success';+import {+ fieldMessageId,+ InputWithLabel,+ WithLabel,+} from '@/components/forms/input-with-label';import { Button, buttonVariants } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';import { DialogFooter } from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';import { useAppParams } from '@/hooks/use-app-params';import { handleError, useTRPC } from '@/integrations/trpc/react';import { cn } from '@/utils/cn';+type ClientType = 'write' | 'read' | 'root';++const CLIENT_TYPE_ITEMS: { value: ClientType; label: string }[] = [+ { value: 'write', label: 'Write (for ingestion)' },+ { value: 'read', label: 'Read (access export API)' },+ { value: 'root', label: 'Root (access export API)' },+];++const CLIENT_TYPE_HINTS: Record<ClientType, string> = {+ write: 'The default client type, used for ingesting data',+ read: "Can read this project's data from the export API",+ root: "Can read any project's data from the export API",+};+const validation = z.object({name: z.string().min(1),type: z.enum(['read', 'write', 'root']),@@ -30,6 +48,7 @@ export interface AddClientProps {}export default function AddClient({ name, type }: AddClientProps = {}) {+ const clientTypeId = useId();const { organizationId, projectId } = useAppParams();const form = useForm<IForm>({resolver: zodResolver(validation),@@ -91,58 +110,35 @@ export default function AddClient({ name, type }: AddClientProps = {}) {className="flex flex-col gap-4"onSubmit={form.handleSubmit(onSubmit)}>- <div>- <Label>Client name</Label>- <Input- error={form.formState.errors.name?.message}- placeholder="Eg. My App Client"- {...form.register('name')}- />- </div>+ <InputWithLabel+ error={form.formState.errors.name?.message}+ label="Client name"+ placeholder="Eg. My App Client"+ {...form.register('name')}+ />- <div>- <Controller- control={form.control}- name="type"- render={({ field }) => {- return (- <div>- <Label>Type of client</Label>- <Combobox- {...field}- className="w-full"- items={[- {- value: 'write',- label: 'Write (for ingestion)',- },- {- value: 'read',- label: 'Read (access export API)',- },- {- value: 'root',- label: 'Root (access export API)',- },- ]}- onChange={(value) => {- field.onChange(value);- }}- placeholder="Select a project"- />- <p className="mt-2 text-muted-foreground text-sm">- {field.value === 'write' &&- 'Write: Is the default client type and is used for ingestion of data'}- {field.value === 'read' &&- 'Read: You can access the current projects data from the export API'}- {field.value === 'root' &&- 'Root: You can access any projects data from the export API'}- </p>- </div>- );- }}- />- </div>+ <Controller+ control={form.control}+ name="type"+ render={({ field }) => (+ <WithLabel+ hint={CLIENT_TYPE_HINTS[field.value]}+ id={clientTypeId}+ label="Type of client"+ >+ <Combobox+ {...field}+ aria-describedby={fieldMessageId(clientTypeId)}+ className="w-full"+ id={clientTypeId}+ items={CLIENT_TYPE_ITEMS}+ onChange={field.onChange}+ placeholder="Select a client type"+ variant="input"+ />+ </WithLabel>+ )}+ /><DialogFooter><ButtononClick={() => popModal()}diff --git a/apps/start/src/modals/add-notification-rule.tsx b/apps/start/src/modals/add-notification-rule.tsxindex acca30cce..3d2a60547 100644--- a/apps/start/src/modals/add-notification-rule.tsx+++ b/apps/start/src/modals/add-notification-rule.tsx@@ -4,6 +4,7 @@ import { zCreateNotificationRule } from '@openpanel/core/modules/notification/noimport { shortId } from '@openpanel/shared';import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { FilterIcon, PlusIcon, SaveIcon, TrashIcon } from 'lucide-react';+import { useId } from 'react';import {Controller,type SubmitHandler,@@ -17,7 +18,11 @@ import type { z } from 'zod';import { popModal } from '.';import { ModalHeader } from './Modal/Container';import { ColorSquare } from '@/components/color-square';-import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';+import {+ fieldMessageId,+ InputWithLabel,+ WithLabel,+} from '@/components/forms/input-with-label';import { PureFilterItem } from '@/components/report/sidebar/filters/FilterItem';import { Button } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';@@ -38,6 +43,7 @@ interface Props {type IForm = z.infer<typeof zCreateNotificationRule>;export default function AddNotificationRule({ rule }: Props) {+ const typeId = useId();const client = useQueryClient();const { projectId } = useAppParams();const form = useForm<IForm>({@@ -63,6 +69,11 @@ export default function AddNotificationRule({ rule }: Props) {},},});+ // The config union hides `type` from the inferred error shape.+ const configErrors = form.formState.errors.config as+ | { type?: { message?: string } }+ | undefined;+ const typeError = configErrors?.type?.message;const trpc = useTRPC();const mutation = useMutation(trpc.notification.createOrUpdateRule.mutationOptions({@@ -115,20 +126,20 @@ export default function AddNotificationRule({ rule }: Props) {{...form.register('name')}/>- <WithLabel- // @ts-expect-error- error={form.formState.errors.config?.type.message}- label="Type"- >+ <WithLabel error={typeError} id={typeId} label="Type"><Controllercontrol={form.control}name="config.type"render={({ field }) => (<Combobox+ variant="input"{...field}+ aria-describedby={+ typeError ? fieldMessageId(typeId) : undefined+ }className="w-full"- // @ts-expect-error- error={form.formState.errors.config?.type.message}+ error={typeError}+ id={typeId}items={[{label: 'Events',diff --git a/apps/start/src/modals/date-ranger-picker.tsx b/apps/start/src/modals/date-ranger-picker.tsxindex 2b340a9d6..3ee0bf2fc 100644--- a/apps/start/src/modals/date-ranger-picker.tsx+++ b/apps/start/src/modals/date-ranger-picker.tsx@@ -1,12 +1,13 @@import type { IInterval } from '@openpanel/core/modules/report/report.constants';import { getDefaultIntervalByDates } from '@openpanel/core/modules/report/report.constants';import { endOfDay, startOfDay, subMonths } from 'date-fns';-import { CheckIcon, XIcon } from 'lucide-react';+import { CheckIcon } from 'lucide-react';import { useState } from 'react';import { popModal } from '.';import { ModalContent } from './Modal/Container';import { Button } from '@/components/ui/button';import { Calendar } from '@/components/ui/calendar';+import { DialogFooter } from '@/components/ui/dialog';import { useBreakpoint } from '@/hooks/use-breakpoint';import { formatDate } from '@/utils/date';@@ -30,7 +31,7 @@ export default function DateRangerPicker({const [endDate, setEndDate] = useState(initialEndDate);return (- <ModalContent className="min-w-fit p-4 md:p-8">+ <ModalContent bodyClassName="p-4 md:p-8" className="min-w-fit"><CalendarcaptionLayout="dropdown"className="mx-auto min-h-[310px] p-0 [&_table]:mx-auto [&_table]:w-auto"@@ -57,43 +58,32 @@ export default function DateRangerPicker({to: endDate,}}/>- <div className="col md:row flex-col-reverse gap-2">- <Button- icon={XIcon}- onClick={() => popModal()}- type="button"- variant="outline"- >+ <DialogFooter>+ <Button onClick={() => popModal()} type="button" variant="outline">Cancel</Button>-{startDate && endDate && (<Button- className="md:ml-auto"- icon={startDate && endDate ? CheckIcon : XIcon}+ icon={CheckIcon}onClick={() => {popModal();- if (startDate && endDate) {- const rangeStart = startOfDay(startDate);- const rangeEnd = endOfDay(endDate);- onChange({- startDate: rangeStart,- endDate: rangeEnd,- interval: getDefaultIntervalByDates(- rangeStart.toISOString(),- rangeEnd.toISOString()- )!,- });- }+ const rangeStart = startOfDay(startDate);+ const rangeEnd = endOfDay(endDate);+ onChange({+ startDate: rangeStart,+ endDate: rangeEnd,+ interval: getDefaultIntervalByDates(+ rangeStart.toISOString(),+ rangeEnd.toISOString()+ )!,+ });}}type="button">- {startDate && endDate- ? `Select ${formatDate(startDate)} - ${formatDate(endDate)}`- : 'Cancel'}+ Select {formatDate(startDate)} - {formatDate(endDate)}</Button>)}- </div>+ </DialogFooter></ModalContent>);}diff --git a/apps/start/src/modals/date-time-picker.tsx b/apps/start/src/modals/date-time-picker.tsxindex 54e1848f2..a3365a66f 100644--- a/apps/start/src/modals/date-time-picker.tsx+++ b/apps/start/src/modals/date-time-picker.tsx@@ -5,6 +5,7 @@ import { popModal } from '.';import { ModalContent, ModalHeader } from './Modal/Container';import { Button } from '@/components/ui/button';import { Calendar } from '@/components/ui/calendar';+import { DialogFooter } from '@/components/ui/dialog';import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';import { cn } from '@/lib/utils';@@ -164,26 +165,20 @@ export default function DateTimePicker({<ScrollBar orientation="vertical" /></ScrollArea></div>-- <div className="flex gap-3 pt-2">- <Button- className="flex-1"- onClick={() => popModal()}- variant="outline"- >- Cancel- </Button>- <Button- className="flex-1"- onClick={() => {- popModal();- onChange(selectedDate);- }}- >- Confirm Selection- </Button>- </div></div>+ <DialogFooter>+ <Button onClick={() => popModal()} variant="outline">+ Cancel+ </Button>+ <Button+ onClick={() => {+ popModal();+ onChange(selectedDate);+ }}+ >+ Confirm selection+ </Button>+ </DialogFooter></ModalContent>);}diff --git a/apps/start/src/modals/select-billing-plan.tsx b/apps/start/src/modals/select-billing-plan.tsxindex f18469970..e0f0715ac 100644--- a/apps/start/src/modals/select-billing-plan.tsx+++ b/apps/start/src/modals/select-billing-plan.tsx@@ -22,7 +22,7 @@ export default function SelectBillingPlan({const [view, setView] = useState<'plans' | 'cancel'>('plans');return (- <ModalContent className="!flex !flex-col !overflow-hidden">+ <ModalContent bodyClassName="flex flex-col overflow-hidden">{view === 'plans' ? (<><ModalHeader title="Select a billing plan" />diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.realtime.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.realtime.tsxindex 2d5df9d7c..adae59bfc 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.realtime.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.realtime.tsx@@ -1,12 +1,8 @@import { keepPreviousData, useQuery } from '@tanstack/react-query';import { createFileRoute } from '@tanstack/react-router';import { Fullscreen, FullscreenClose } from '@/components/fullscreen-toggle';+import { RealtimeLiveOverlays } from '@/components/realtime/live/realtime-live-overlays';import RealtimeMap from '@/components/realtime/map';-import { RealtimeActiveSessions } from '@/components/realtime/realtime-active-sessions';-import { RealtimeGeo } from '@/components/realtime/realtime-geo';-import { RealtimeLiveHistogram } from '@/components/realtime/realtime-live-histogram';-import { RealtimePaths } from '@/components/realtime/realtime-paths';-import { RealtimeReferrals } from '@/components/realtime/realtime-referrals';import RealtimeReloader from '@/components/realtime/realtime-reloader';import { useTRPC } from '@/integrations/trpc/react';import { createProjectTitle, PAGE_TITLES } from '@/utils/title';@@ -45,71 +41,12 @@ function Component() {<FullscreenClose /><RealtimeReloader projectId={projectId} />- <div className="flex flex-col gap-4 p-4 md:hidden">- <div className="card bg-background/90 p-4">- <RealtimeLiveHistogram projectId={projectId} />- </div>-- <div className="-mx-4 aspect-square">- <RealtimeMap- markers={coordinatesQuery.data ?? []}- projectId={projectId}- />- </div>-- <div className="min-h-[320px]">- <RealtimeActiveSessions projectId={projectId} />- </div>-- <div>- <RealtimeGeo projectId={projectId} />- </div>-- <div>- <RealtimeReferrals projectId={projectId} />- </div>-- <div>- <RealtimePaths projectId={projectId} />- </div>- </div>-- <div className="hidden md:block">- <div className="row relative">- <div className="aspect-[4/2] w-full">- <RealtimeMap- markers={coordinatesQuery.data ?? []}- projectId={projectId}- sidebarConfig={{- width: 280, // w-96 = 384px- position: 'left',- }}- />- </div>- <div className="col absolute top-8 bottom-4 left-8 gap-4">- <div className="card w-72 bg-background/90 p-4">- <RealtimeLiveHistogram projectId={projectId} />- </div>- <div className="relative min-h-0 w-72 flex-1">- <RealtimeActiveSessions- className="max-md:hidden"- projectId={projectId}- />- </div>- </div>- </div>-- <div className="grid grid-cols-1 gap-4 p-4 pt-4 md:grid-cols-2 md:p-8 md:pt-0 xl:grid-cols-3">- <div>- <RealtimeGeo projectId={projectId} />- </div>- <div>- <RealtimeReferrals projectId={projectId} />- </div>- <div>- <RealtimePaths projectId={projectId} />- </div>- </div>+ <div className="relative h-svh w-full overflow-hidden">+ <RealtimeMap+ markers={coordinatesQuery.data ?? []}+ projectId={projectId}+ />+ <RealtimeLiveOverlays key={projectId} projectId={projectId} /></div></Fullscreen>);diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsxindex 3554601a0..3bccb8f3d 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx@@ -646,6 +646,7 @@ function GscTable({className="rounded-none border-0 border-t bg-transparent pl-9 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground focus-visible:ring-offset-0"onChange={(e) => onSearchChange(e.target.value)}placeholder={searchPlaceholder ?? 'Search'}+ size="sm"type="search"value={searchValue ?? ''}/>diff --git a/apps/start/src/routes/_app.$organizationId.settings.tsx b/apps/start/src/routes/_app.$organizationId.settings.tsxindex 9b9b895cc..6f15373bf 100644--- a/apps/start/src/routes/_app.$organizationId.settings.tsx+++ b/apps/start/src/routes/_app.$organizationId.settings.tsx@@ -117,6 +117,7 @@ function Component() {onChange={field.onChange}placeholder="Select timezone"value={field.value}+ variant="input"/></WithLabel>)}diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsxindex bc0c5360f..51975844e 100644--- a/apps/start/src/routes/_steps.onboarding.project.tsx+++ b/apps/start/src/routes/_steps.onboarding.project.tsx@@ -8,7 +8,7 @@ import {ServerIcon,SmartphoneIcon,} from 'lucide-react';-import { useEffect, useState } from 'react';+import { useEffect, useId, useState } from 'react';import {Controller,type SubmitHandler,@@ -18,7 +18,11 @@ import {import { z } from 'zod';import AnimateHeight from '@/components/animate-height';import { ButtonContainer } from '@/components/button-container';-import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';+import {+ fieldMessageId,+ InputWithLabel,+ WithLabel,+} from '@/components/forms/input-with-label';import TagInput from '@/components/forms/tag-input';import FullPageLoadingState from '@/components/full-page-loading-state';import { Button } from '@/components/ui/button';@@ -65,6 +69,7 @@ export const Route = createFileRoute('/_steps/onboarding/project')({type IForm = z.infer<typeof zOnboardingProject>;function Component() {+ const workspaceId = useId();const trpc = useTRPC();const queryClient = useQueryClient();const { data: organizations } = useQuery(@@ -207,6 +212,7 @@ function Component() {placeholder="Select timezone"searchablevalue={field.value}+ variant="input"/></WithLabel>)}@@ -219,11 +225,21 @@ function Component() {name="organizationId"render={({ field, formState }) => {return (- <WithLabel label="Workspace">+ <WithLabel+ error={formState.errors.organizationId?.message}+ id={workspaceId}+ label="Workspace"+ ><Combobox+ aria-describedby={+ formState.errors.organizationId+ ? fieldMessageId(workspaceId)+ : undefined+ }className="w-full"error={formState.errors.organizationId?.message}icon={BuildingIcon}+ id={workspaceId}items={organizations.filter((item) => item.id)@@ -235,6 +251,7 @@ function Component() {onChange={field.onChange}placeholder="Select workspace"value={field.value}+ variant="input"/></WithLabel>);diff --git a/apps/start/src/styles.css b/apps/start/src/styles.cssindex 8651a1d74..149a8f0c4 100644--- a/apps/start/src/styles.css+++ b/apps/start/src/styles.css@@ -248,6 +248,8 @@ body {@layer base {* {@apply border-border outline-ring/50;+ scrollbar-width: thin;+ scrollbar-color: oklch(from var(--foreground) l c h / 0.18) transparent;}body {@apply bg-background text-foreground;@@ -450,6 +452,24 @@ button {animation: ping-slow 2s cubic-bezier(0, 0, 0.2, 1) infinite;}+/* Realtime feeds: a new row pushes the list down as it grows in, no measuring needed */+@keyframes live-feed-in {+ from {+ margin-top: calc(-1 * (1.75rem + 0.25rem));+ opacity: 0;+ transform: translateY(-4px);+ }+ to {+ margin-top: 0;+ opacity: 1;+ transform: translateY(0);+ }+}++.animate-live-feed-in {+ animation: live-feed-in 320ms cubic-bezier(0.2, 0.8, 0.2, 1);+}+.scrollarea {position: relative;width: 100%;diff --git a/apps/start/src/types/react-simple-map.d.ts b/apps/start/src/types/react-simple-map.d.tsdeleted file mode 100644index 262f99736..000000000--- a/apps/start/src/types/react-simple-map.d.ts+++ /dev/null@@ -1,296 +0,0 @@-import type { GeoPath, GeoProjection } from 'd3-geo';-import type { D3ZoomEvent } from 'd3-zoom';-import type { Feature } from 'geojson';-import type * as React from 'react';--declare module 'react-simple-maps' {- export type Point = [number, number];-- export interface ProjectionConfig {- scale?: number | undefined;- center?: [number, number] | undefined;- parallels?: [number, number] | undefined;- rotate?: [number, number, number] | undefined;- }- export type ProjectionFunction = (- width: number,- height: number,- config: ProjectionConfig- ) => GeoProjection;-- export interface ComposableMapProps- extends React.SVGAttributes<SVGSVGElement> {- children?: React.ReactNode;- /**- * @default 800- */- width?: number | undefined;- /**- * @default 600- */- height?: number | undefined;- /**- * @default "geoEqualEarth"- */- projection?: string | ProjectionFunction | undefined;- /**- * @default {}- */- projectionConfig?: ProjectionConfig | undefined;- }-- export interface Position {- x: number;- y: number;- last: Point;- zoom: number;- dragging: boolean;- zooming: boolean;- }-- export interface ZoomableGroupProps extends React.SVGAttributes<SVGGElement> {- children?: React.ReactNode;- /**- * @default [0, 0]- */- center?: Point | undefined;- /**- * @default 1- */- zoom?: number | undefined;- /**- * @default 1- */- minZoom?: number | undefined;- /**- * @default 5- */- maxZoom?: number | undefined;- /**- * @default 0.025- */- zoomSensitivity?: number | undefined;- /**- * @default false- */- disablePanning?: boolean | undefined;- /**- * @default false- */- disableZooming?: boolean | undefined;- onMoveStart?:- | ((- position: { coordinates: [number, number]; zoom: number },- event: D3ZoomEvent<SVGElement, any>- ) => void)- | undefined;- onMove?:- | ((- position: {- x: number;- y: number;- zoom: number;- dragging: WheelEvent;- },- event: D3ZoomEvent<SVGElement, any>- ) => void)- | undefined;- onMoveEnd?:- | ((- position: { coordinates: [number, number]; zoom: number },- event: D3ZoomEvent<SVGElement, any>- ) => void)- | undefined;- filterZoomEvent?: ((element: SVGElement) => boolean) | undefined;- translateExtent?: [[number, number], [number, number]] | undefined;- }-- interface GeographiesChildrenArgument {- geographies: any[];- path: GeoPath;- projection: GeoProjection;- }-- export interface GeographiesProps- extends Omit<React.SVGAttributes<SVGGElement>, 'children'> {- parseGeographies?:- | ((features: Feature<any, any>[]) => Feature<any, any>[])- | undefined;- geography?: string | Record<string, any> | string[] | undefined;- children?: ((data: GeographiesChildrenArgument) => void) | undefined;- }-- export interface GeographyProps- extends Pick<- React.SVGProps<SVGPathElement>,- Exclude<keyof React.SVGProps<SVGPathElement>, 'style'>- > {- geography?: any;- style?:- | {- default?: React.CSSProperties | undefined;- hover?: React.CSSProperties | undefined;- pressed?: React.CSSProperties | undefined;- }- | undefined;- onMouseEnter?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseLeave?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseDown?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseUp?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onFocus?: ((event: React.FocusEvent<SVGPathElement>) => void) | undefined;- onBlur?: ((event: React.FocusEvent<SVGPathElement>) => void) | undefined;- }-- export interface MarkerProps- extends Pick<- React.SVGProps<SVGPathElement>,- Exclude<keyof React.SVGProps<SVGPathElement>, 'style'>- > {- children?: React.ReactNode;- coordinates?: Point | undefined;- style?:- | {- default?: React.CSSProperties | undefined;- hover?: React.CSSProperties | undefined;- pressed?: React.CSSProperties | undefined;- }- | undefined;- onMouseEnter?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseLeave?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseDown?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onMouseUp?:- | ((event: React.MouseEvent<SVGPathElement, MouseEvent>) => void)- | undefined;- onFocus?: ((event: React.FocusEvent<SVGPathElement>) => void) | undefined;- onBlur?: ((event: React.FocusEvent<SVGPathElement>) => void) | undefined;- }-- export interface AnnotationProps extends React.SVGProps<SVGGElement> {- children?: React.ReactNode;- subject?: Point | undefined;- connectorProps: React.SVGProps<SVGPathElement>;- /**- * @default 30- */- dx?: number | string | undefined;- /**- * @default 30- */- dy?: number | string | undefined;- /**- * @default 0- */- curve?: number | undefined;- }-- export interface GraticuleProps extends React.SVGProps<SVGPathElement> {- /**- * @default [10, 10]- */- step?: Point | undefined;- /**- * @default "currentcolor"- */- stroke?: string | undefined;- /**- * @default "transparent"- */- fill?: string | undefined;- }-- export interface LineProps- extends Pick<- React.SVGProps<SVGPathElement>,- Exclude<keyof React.SVGProps<SVGPathElement>, 'from' | 'to'>- > {- /**- * @default [0, 0]- */- from?: Point | undefined;- /**- * @default [0, 0]- */- to?: Point | undefined;- /**- * @default [[0, 0], [0, 0]]- */- coordinates?: Point[] | undefined;- /**- * @default "currentcolor"- */- stroke?: string | undefined;- /**- * @default 3- */- strokeWidth?: number | string | undefined;- /**- * @default "transparent"- */- fill?: string | undefined;- }-- interface SphereProps extends React.SVGProps<SVGPathElement> {- /**- * @default "rsm-sphere"- */- id: string;- /**- * @default "transparent"- */- fill: string;- /**- * @default "currentcolor"- */- stroke: string;- /**- * @default 0.5- */- strokeWidth: number;- }-- declare const ComposableMap: React.FunctionComponent<ComposableMapProps>;- declare const ZoomableGroup: React.FunctionComponent<ZoomableGroupProps>;- declare const Geographies: React.FunctionComponent<GeographiesProps>;- declare const Geography: React.FunctionComponent<GeographyProps>;- declare const Marker: React.FunctionComponent<MarkerProps>;- declare const Annotation: React.FunctionComponent<AnnotationProps>;- declare const Graticule: React.FunctionComponent<GraticuleProps>;- declare const Line: React.FunctionComponent<LineProps>;- declare const Sphere: React.FunctionComponent<SphereProps>;-- declare const useZoomPan: (options: {- center: Point;- zoom: number;- filterZoomEvent?: () => boolean;- }) => {- mapRef: React.MutableRefObject<SVGGElement | null>;- transformString: string;- };-- export {- useZoomPan,- Annotation,- ComposableMap,- Geographies,- Geography,- Graticule,- Line,- Marker,- Sphere,- ZoomableGroup,- };-}diff --git a/bun.lock b/bun.lockindex 2a43b3ea1..b27efa7f0 100644--- a/bun.lock+++ b/bun.lock@@ -184,7 +184,10 @@"d3-array": "3.2.4","d3-geo": "3.1.1","d3-sankey": "0.12.3",+ "d3-selection": "3.0.0","d3-shape": "3.2.0",+ "d3-transition": "3.0.1",+ "d3-zoom": "3.0.0","date-fns": "3.3.1","debounce": "2.2.0","embla-carousel-autoplay": "8.6.0",@@ -219,7 +222,6 @@"react-markdown": "10.1.0","react-redux": "8.1.3","react-responsive": "9.0.2",- "react-simple-maps": "3.0.0","react-svg-worldmap": "2.0.0-alpha.16","react-syntax-highlighter": "15.5.0","react-use-websocket": "4.7.0",@@ -237,10 +239,12 @@"tailwind-merge": "3.3.1","tailwindcss": "4.1.12","tailwindcss-animate": "1.0.7",+ "topojson-client": "3.1.0","tw-animate-css": "1.3.7","use-stick-to-bottom": "1.1.3","usehooks-ts": "2.14.0","vite-tsconfig-paths": "5.1.4",+ "world-atlas": "2.0.2","zod": "catalog:",},"devDependencies": {@@ -255,7 +259,10 @@"@types/d3-array": "3.2.2","@types/d3-geo": "3.1.1","@types/d3-sankey": "0.12.5",+ "@types/d3-selection": "3.0.11","@types/d3-shape": "3.2.0",+ "@types/d3-transition": "3.0.9",+ "@types/d3-zoom": "3.0.8","@types/geojson": "7946.0.16","@types/lodash.debounce": "4.0.9","@types/lodash.isequal": "4.5.8",@@ -263,8 +270,9 @@"@types/ramda": "0.31.0","@types/react": "catalog:","@types/react-dom": "catalog:",- "@types/react-simple-maps": "3.0.4","@types/react-syntax-highlighter": "15.5.11",+ "@types/topojson-client": "3.1.5",+ "@types/topojson-specification": "1.0.5","@vitejs/plugin-react": "5.2.0","jsdom": "26.1.0","typescript": "catalog:",@@ -2819,8 +2827,6 @@"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],- "@types/react-simple-maps": ["@types/[email protected]", "", { "dependencies": { "@types/d3-geo": "^2", "@types/d3-zoom": "^2", "@types/geojson": "*", "@types/react": "*" } }, "sha512-U9qnX0wVhxldrTpsase44fIoLpyO1OT/hgNMRoJTixj1qjpMRdSRIfih93mR3D/Tss/8CmM7dPwKMjtaGkDpmw=="],-"@types/react-syntax-highlighter": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-ZqIJl+Pg8kD+47kxUjvrlElrraSUrYa4h0dauY/U/FTUuprSCqvUj+9PNQNQzVc6AJgIWUUxn87/gqsMHNbRjw=="],"@types/request": ["@types/[email protected]", "", { "dependencies": { "@types/caseless": "*", "@types/node": "*", "@types/tough-cookie": "*", "form-data": "^2.5.5" } }, "sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg=="],@@ -2851,6 +2857,10 @@"@types/through": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-HsJ+z3QuETzP3cswwtzt2vEIiHBk/dCcHGhbmG5X3ecnwFD/lPrMpliGXxSCg03L9AhrdwA4Oz/qfspkDW+xGQ=="],+ "@types/topojson-client": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*", "@types/topojson-specification": "*" } }, "sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw=="],++ "@types/topojson-specification": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*" } }, "sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ=="],+"@types/tough-cookie": ["@types/[email protected]", "", {}, "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA=="],"@types/triple-beam": ["@types/[email protected]", "", {}, "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw=="],@@ -5157,8 +5167,6 @@"react-shallow-renderer": ["[email protected]", "", { "dependencies": { "object-assign": "^4.1.1", "react-is": "^16.12.0 || ^17.0.0 || ^18.0.0" }, "peerDependencies": { "react": "^16.0.0 || ^17.0.0 || ^18.0.0" } }, "sha512-oScf2FqQ9LFVQgA73vr86xl2NaOIX73rh+YFqcOp68CWj56tSfgtGKrEbyhCj0rSijyG9M1CYprTh39fBi5hzA=="],- "react-simple-maps": ["[email protected]", "", { "dependencies": { "d3-geo": "^2.0.2", "d3-selection": "^2.0.0", "d3-zoom": "^2.0.0", "topojson-client": "^3.1.0" }, "peerDependencies": { "prop-types": "^15.7.2", "react": "^16.8.0 || 17.x || 18.x", "react-dom": "^16.8.0 || 17.x || 18.x" } }, "sha512-vKNFrvpPG8Vyfdjnz5Ne1N56rZlDfHXv5THNXOVZMqbX1rWZA48zQuYT03mx6PAKanqarJu/PDLgshIZAfHHqw=="],-"react-smooth": ["[email protected]", "", { "dependencies": { "fast-equals": "^5.0.1", "prop-types": "^15.8.1", "react-transition-group": "^4.4.5" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q=="],"react-style-singleton": ["[email protected]", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],@@ -5933,6 +5941,8 @@"workerd": ["[email protected]", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260424.1", "@cloudflare/workerd-darwin-arm64": "1.20260424.1", "@cloudflare/workerd-linux-64": "1.20260424.1", "@cloudflare/workerd-linux-arm64": "1.20260424.1", "@cloudflare/workerd-windows-64": "1.20260424.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oKsB0Xo/mfkYMdSACoS06XZg09VUK4rXwHfF/1t3P++sMbwzf4UHQvMO57+zxpEB2nVrY/ZkW0bYFGq4GdAFSQ=="],+ "world-atlas": ["[email protected]", "", {}, "sha512-IXfV0qwlKXpckz1FhwXVwKRjiIhOnWttOskm5CtxMsjgE/MXAYRHWJqgXOpM8IkcPBoXnyTU5lFHcYa5ChG0LQ=="],+"wrangler": ["[email protected]", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260424.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260424.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260424.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-93cwt2RPb1qdcmEgPzH7ybiLN4BIKoWpscIX6SywjHrQOeIZrQk2haoc3XMLKtQTmzapxza9OuDD+kMHpsuuhg=="],"wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],@@ -6653,10 +6663,6 @@"@types/pg/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.12.0" } }, "sha512-FYxk1I7wPv3K2XBaoyH2cTnocQEu8AOZ60hPbsyukMPLv5/5qr7V1i8PLHdl6Zf87I+xZXFvPCXYjiTFq+YSDQ=="],- "@types/react-simple-maps/@types/d3-geo": ["@types/[email protected]", "", { "dependencies": { "@types/geojson": "*" } }, "sha512-RIXlxPdxvX+LAZFv+t78CuYpxYag4zuw9mZc+AwfB8tZpKU90rMEn2il2ADncmeZlb7nER9dDsJpRisA3lRvjA=="],-- "@types/react-simple-maps/@types/d3-zoom": ["@types/[email protected]", "", { "dependencies": { "@types/d3-interpolate": "^2", "@types/d3-selection": "^2" } }, "sha512-JWke4E8ZyrKUQ68ESTWSK16fVb0OYnaiJ+WXJRYxKLn4aXU0o4CLYxMWBEiouUfO3TTCoyroOrGPcBG6u1aAxA=="],-"@types/tedious/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.12.0" } }, "sha512-FYxk1I7wPv3K2XBaoyH2cTnocQEu8AOZ60hPbsyukMPLv5/5qr7V1i8PLHdl6Zf87I+xZXFvPCXYjiTFq+YSDQ=="],"@types/uglify-js/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],@@ -7355,12 +7361,6 @@"react-redux/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],- "react-simple-maps/d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "^2.5.0" } }, "sha512-8pM1WGMLGFuhq9S+FpPURxic+gKzjluCD/CHTuUF3mXMeiCo0i6R0tO1s4+GArRFde96SLcW/kOFRjoAosPsFA=="],-- "react-simple-maps/d3-selection": ["[email protected]", "", {}, "sha512-XoGGqhLUN/W14NmaqcO/bb1nqjDAw5WtSYb2X8wiuQWvSZUsUVYsOSkOybUrNvcBjaywBdYPy03eXHMXjk9nZA=="],-- "react-simple-maps/d3-zoom": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 2", "d3-drag": "2", "d3-interpolate": "1 - 2", "d3-selection": "2", "d3-transition": "2" } }, "sha512-fFg7aoaEm9/jf+qfstak0IYpnesZLiMX6GZvXtUSdv8RH2o4E2qeelgdU09eKS6wGuiGMfcnMI0nTIqWzRHGpw=="],-"react-smooth/fast-equals": ["[email protected]", "", {}, "sha512-Ywe6jodPTWOTL9/k0bV7gdfP8twKL5Y8I8CZ933fAY5gBekICZSUQTbyH6ut2NZCNyB05mSUwAuEqdEIaOOlDQ=="],"react-svg-worldmap/d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "^2.5.0" } }, "sha512-8pM1WGMLGFuhq9S+FpPURxic+gKzjluCD/CHTuUF3mXMeiCo0i6R0tO1s4+GArRFde96SLcW/kOFRjoAosPsFA=="],@@ -8129,10 +8129,6 @@"@types/pg/@types/node/undici-types": ["[email protected]", "", {}, "sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ=="],- "@types/react-simple-maps/@types/d3-zoom/@types/d3-interpolate": ["@types/[email protected]", "", { "dependencies": { "@types/d3-color": "^2" } }, "sha512-UINE41RDaUMbulp+bxQMDnhOi51rh5lA2dG+dWZU0UY/IwQiG/u2x8TfnWYU9+xwGdXsJoAvrBYUEQl0r91atg=="],-- "@types/react-simple-maps/@types/d3-zoom/@types/d3-selection": ["@types/[email protected]", "", {}, "sha512-71BorcY0yXl12S7lvb01JdaN9TpeUHBDb4RRhSq8U8BEkX/nIk5p7Byho+ZRTsx5nYLMpAbY3qt5EhqFzfGJlw=="],-"@types/tedious/@types/node/undici-types": ["[email protected]", "", {}, "sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ=="],"@visx/vendor/@types/d3-interpolate/@types/d3-color": ["@types/[email protected]", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],@@ -8853,16 +8849,6 @@"react-native/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],- "react-simple-maps/d3-geo/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="],-- "react-simple-maps/d3-zoom/d3-dispatch": ["[email protected]", "", {}, "sha512-S/m2VsXI7gAti2pBoLClFFTMOO1HTtT0j99AuXLoGFKO6deHDdnv6ZGTxSTTUTgO1zVcv82fCOtDjYK4EECmWA=="],-- "react-simple-maps/d3-zoom/d3-drag": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 2", "d3-selection": "2" } }, "sha512-g9y9WbMnF5uqB9qKqwIIa/921RYWzlUDv9Jl1/yONQwxbOfszAWTCm8u7HOTgJgRDXiRZN56cHT9pd24dmXs8w=="],-- "react-simple-maps/d3-zoom/d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 2" } }, "sha512-c5UhwwTs/yybcmTpAVqwSFl6vrQ8JZJoT5F7xNFK9pymv5C0Ymcc9/LIJHtYIggg/yS9YHw8i8O8tgb9pupjeQ=="],-- "react-simple-maps/d3-zoom/d3-transition": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 2", "d3-dispatch": "1 - 2", "d3-ease": "1 - 2", "d3-interpolate": "1 - 2", "d3-timer": "1 - 2" }, "peerDependencies": { "d3-selection": "2" } }, "sha512-42ltAGgJesfQE3u9LuuBHNbGrI/AJjNL2OAUdclE70UE6Vy239GCBEYD38uBPoLeNsOhFStGpPI0BAOV+HMxog=="],-"react-svg-worldmap/d3-geo/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="],"rimraf/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],@@ -9395,8 +9381,6 @@"@tanstack/router-plugin/@tanstack/router-utils/tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],- "@types/react-simple-maps/@types/d3-zoom/@types/d3-interpolate/@types/d3-color": ["@types/[email protected]", "", {}, "sha512-tbaFGDmJWHqnenvk3QGSvD3RVwr631BjKRD7Sc7VLRgrdX5mk5hTyoeBL6rXZaeoXzmZwIl1D2HPogEdt1rHBg=="],-"@vitest/mocker/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw=="],"@vitest/mocker/vite/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-dQAxF1dW1C3zpeCDc5KqIYuZ1tgAdRXNoZP7vkBIRtKZPYe2xVr/d3SkirklCHudW1B45tGiUlz2pUWDfbDD4w=="],@@ -9569,16 +9553,6 @@"react-native/yargs/cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],- "react-simple-maps/d3-geo/d3-array/internmap": ["[email protected]", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],-- "react-simple-maps/d3-zoom/d3-interpolate/d3-color": ["[email protected]", "", {}, "sha512-SPXi0TSKPD4g9tw0NMZFnR95XVgUZiBH+uUTqQuDu1OsE2zomHU7ho0FISciaPvosimixwHFl3WHLGabv6dDgQ=="],-- "react-simple-maps/d3-zoom/d3-transition/d3-color": ["[email protected]", "", {}, "sha512-SPXi0TSKPD4g9tw0NMZFnR95XVgUZiBH+uUTqQuDu1OsE2zomHU7ho0FISciaPvosimixwHFl3WHLGabv6dDgQ=="],-- "react-simple-maps/d3-zoom/d3-transition/d3-ease": ["[email protected]", "", {}, "sha512-68/n9JWarxXkOWMshcT5IcjbB+agblQUaIsbnXmrzejn2O82n3p2A9R2zEB9HIEFWKFwPAEDDN8gR0VdSAyyAQ=="],-- "react-simple-maps/d3-zoom/d3-transition/d3-timer": ["[email protected]", "", {}, "sha512-TO4VLh0/420Y/9dO3+f9abDEFYeCUr2WZRlxJvbp4HPTQcSylXNiL6yZa9FIUvV1yRiFufl1bszTCLDqv9PWNA=="],-"react-svg-worldmap/d3-geo/d3-array/internmap": ["[email protected]", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],"rimraf/glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],diff --git a/packages/core/src/modules/realtime/realtime.rpc.test.ts b/packages/core/src/modules/realtime/realtime.rpc.test.tsindex 0ce427c1c..c1cb28b18 100644--- a/packages/core/src/modules/realtime/realtime.rpc.test.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.test.ts@@ -50,23 +50,23 @@ test('activeSessions rejects an unauthenticated caller before querying ClickHous).rejects.toMatchObject({ code: 'UNAUTHORIZED' });});-test('paths rejects an unauthenticated caller before querying ClickHouse', async () => {+test('recentSessions rejects an unauthenticated caller before querying ClickHouse', async () => {const caller = await anonCaller();- await expect(caller.paths({ projectId: 'proj_1' })).rejects.toMatchObject({- code: 'UNAUTHORIZED',- });+ await expect(+ caller.recentSessions({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });});-test('referrals rejects an unauthenticated caller before querying ClickHouse', async () => {+test('topSources rejects an unauthenticated caller before querying ClickHouse', async () => {const caller = await anonCaller();- await expect(caller.referrals({ projectId: 'proj_1' })).rejects.toMatchObject(- { code: 'UNAUTHORIZED' }- );+ await expect(+ caller.topSources({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });});-test('geo rejects an unauthenticated caller before querying ClickHouse', async () => {+test('histogram rejects an unauthenticated caller before querying ClickHouse', async () => {const caller = await anonCaller();- await expect(caller.geo({ projectId: 'proj_1' })).rejects.toMatchObject({- code: 'UNAUTHORIZED',- });+ await expect(caller.histogram({ projectId: 'proj_1' })).rejects.toMatchObject(+ { code: 'UNAUTHORIZED' }+ );});diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.tsindex c420481ee..1ab5a5649 100644--- a/packages/core/src/modules/realtime/realtime.rpc.ts+++ b/packages/core/src/modules/realtime/realtime.rpc.ts@@ -12,10 +12,10 @@ import { createTRPCRouter, protectedProcedure } from '../../rpc/base';import {getRealtimeActiveSessions,getRealtimeCoordinates,- getRealtimeGeo,+ getRealtimeHistogram,getRealtimeMapBadgeDetails,- getRealtimePaths,- getRealtimeReferrals,+ getRealtimeRecentSessions,+ getRealtimeTopSources,} from './realtime.service';const MAP_BADGE_LOCATIONS_MIN = 1;@@ -78,7 +78,7 @@ export const realtimeRouter = createTRPCRouter({return getRealtimeActiveSessions(ctx, input.projectId);}),- paths: protectedProcedure+ recentSessions: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {await ctx.services.auth.requireProjectAccess({@@ -87,9 +87,9 @@ export const realtimeRouter = createTRPCRouter({level: 'read',});- return getRealtimePaths(ctx, input.projectId);+ return getRealtimeRecentSessions(ctx, input.projectId);}),- referrals: protectedProcedure+ topSources: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {await ctx.services.auth.requireProjectAccess({@@ -98,9 +98,9 @@ export const realtimeRouter = createTRPCRouter({level: 'read',});- return getRealtimeReferrals(ctx, input.projectId);+ return getRealtimeTopSources(ctx, input.projectId);}),- geo: protectedProcedure+ histogram: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {await ctx.services.auth.requireProjectAccess({@@ -109,6 +109,6 @@ export const realtimeRouter = createTRPCRouter({level: 'read',});- return getRealtimeGeo(ctx, input.projectId);+ return getRealtimeHistogram(ctx, input.projectId);}),});diff --git a/packages/core/src/modules/realtime/realtime.service.test.ts b/packages/core/src/modules/realtime/realtime.service.test.tsindex 793803a34..c0adf5ec3 100644--- a/packages/core/src/modules/realtime/realtime.service.test.ts+++ b/packages/core/src/modules/realtime/realtime.service.test.ts@@ -62,6 +62,7 @@ const MS_PER_MINUTE = 60_000;const REALTIME_WINDOW_MS = MINUTES_PER_REALTIME_WINDOW * MS_PER_MINUTE;const CLOCK_TOLERANCE_MS = 5000;const ACTIVE_SESSIONS_LIMIT = 50;+const RECENT_SESSIONS_LIMIT = 30;const noop = () => undefined;const deps = {@@ -204,3 +205,111 @@ test('getRealtimeActiveSessions scopes the query to the project and the 30-minutexpect(result).toHaveLength(1);expect(result[0]?.sessionId).toBe('sess_1');});++test('getRealtimeRecentSessions only reads session starts in the project and window', async () => {+ nextRows = [+ {+ name: 'session_start',+ session_id: 'sess_2',+ profile_id: 'prof_2',+ created_at: '2026-09-04 00:00:00',+ path: '/pricing',+ origin: 'https://example.com',+ referrer: '',+ referrer_name: 'Google',+ country: 'SE',+ city: 'Stockholm',+ region: '',+ os: 'macOS',+ os_version: '',+ browser: 'Chrome',+ browser_version: '',+ device: 'desktop',+ },+ ];++ const result = await subject.getRealtimeRecentSessions(deps, 'proj_1');++ expect(chQuery).toHaveBeenCalledTimes(1);+ const { query, query_params } = chQuery.mock.calls[0]![0];+ expect(query).toContain('project_id = {p1:String}');+ expect(query).toContain('name = {p2:String}');+ expect(query).toContain('created_at >= {p3:String}');+ expect(query).toContain('LIMIT {p4:UInt64}');+ expect(query_params.p1).toBe('proj_1');+ expect(query_params.p2).toBe('session_start');+ expect(query_params.p4).toBe(RECENT_SESSIONS_LIMIT);+ expect(result).toHaveLength(1);+ expect(result[0]?.sessionId).toBe('sess_2');+ expect(result[0]?.referrerName).toBe('Google');+});++test('getRealtimeTopSources splits one grouping-sets scan into referrers and countries', async () => {+ nextRows = [+ {+ referrer_name: 'Google',+ country: '',+ sessions: 12,+ is_referrer_row: 1,+ is_country_row: 0,+ },+ {+ referrer_name: '',+ country: 'SE',+ sessions: 9,+ is_referrer_row: 0,+ is_country_row: 1,+ },+ {+ referrer_name: 'Reddit',+ country: '',+ sessions: 3,+ is_referrer_row: 1,+ is_country_row: 0,+ },+ ];++ const result = await subject.getRealtimeTopSources(deps, 'proj_1');++ expect(chQuery).toHaveBeenCalledTimes(1);+ const { query, query_params } = chQuery.mock.calls[0]![0];+ expect(query).toContain('GROUPING SETS ((referrer_name), (country))');+ expect(query).toContain('project_id = {p1:String}');+ expect(query_params.p1).toBe('proj_1');+ expect(result).toEqual({+ referrers: [+ { name: 'Google', sessions: 12 },+ { name: 'Reddit', sessions: 3 },+ ],+ countries: [{ country: 'SE', sessions: 9 }],+ });+});++test('getRealtimeHistogram fills every minute of the window and takes the total from the same scan', async () => {+ const minuteAgo = new Date(Math.floor(Date.now() / 60_000) * 60_000 - 60_000);+ const minuteKey = minuteAgo.toISOString().slice(0, 19).replace('T', ' ');+ nextRows = [+ { minute: '1970-01-01 00:00:00', sessions: 40, visitors: 15, is_total: 1 },+ { minute: minuteKey, sessions: 4, visitors: 2, is_total: 0 },+ ];++ const result = await subject.getRealtimeHistogram(deps, 'proj_1');++ expect(chQuery).toHaveBeenCalledTimes(1);+ expect(chQuery.mock.calls[0]![0].query).toContain(+ 'GROUPING SETS ((minute), ())'+ );+ expect(result.totalSessions).toBe(40);+ expect(result.minutes).toHaveLength(MINUTES_PER_REALTIME_WINDOW + 1);+ const filled = result.minutes.find(+ (entry) => entry.minute === minuteAgo.toISOString()+ );+ expect(filled).toEqual({+ minute: minuteAgo.toISOString(),+ sessions: 4,+ visitors: 2,+ });+ expect(result.minutes.filter((entry) => entry.sessions === 0)).toHaveLength(+ MINUTES_PER_REALTIME_WINDOW+ );+});diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex 45567df77..39d94ad82 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -19,9 +19,10 @@ import { getProfiles } from '../profile/profile.service';const REALTIME_WINDOW_MINUTES = 30;const ACTIVE_SESSIONS_LIMIT = 50;-const PATHS_LIMIT = 50;-const REFERRALS_LIMIT = 50;-const GEO_LIMIT = 50;+const RECENT_SESSIONS_LIMIT = 30;+const SESSION_START_EVENT = 'session_start';+const TOP_SOURCES_LIMIT = 8;+const MS_PER_MINUTE = 60_000;const COORDINATES_QUERY_LIMIT = 5000;const COORDINATES_CLUSTER_TARGET = 500;const MAP_BADGE_TOP_LIMIT = 3;@@ -373,7 +374,7 @@ export async function getRealtimeActiveSessions(const rows = await chQuery<IClickhouseEvent>(deps,sql`SELECT- name, session_id, created_at, path, origin, referrer, referrer_name,+ id, name, session_id, created_at, path, origin, referrer, referrer_name,country, city, region, os, os_version, browser, browser_version,deviceFROM ${sql.id(TABLE_NAMES.events)}@@ -385,46 +386,132 @@ export async function getRealtimeActiveSessions(return rows.map(transformEvent);}-export function getRealtimePaths(deps: ServiceDeps, projectId: string) {- return chQuery<{- origin: string;- path: string;- count: number;- avg_duration: number;- unique_sessions: number;- }>(+/** The latest sessions to start, newest first: one `session_start` row each. */+export async function getRealtimeRecentSessions(+ deps: ServiceDeps,+ projectId: string+) {+ const rows = await chQuery<IClickhouseEvent>(deps,- sql`SELECT origin, path, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM ${sql.id(TABLE_NAMES.events)} WHERE project_id = ${sql.string(projectId)} AND path != ${sql.string('')} AND created_at >= ${sql.string(formatClickhouseDate(since()))} GROUP BY path, origin ORDER BY count DESC LIMIT ${sql.uint64(PATHS_LIMIT)}`,- CLIX_SESSION_TIMEZONE+ sql`SELECT+ id, name, session_id, profile_id, created_at, path, origin, referrer,+ referrer_name, country, city, region, os, os_version, browser,+ browser_version, device+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE project_id = ${sql.string(projectId)}+ AND name = ${sql.string(SESSION_START_EVENT)}+ AND created_at >= ${sql.string(formatClickhouseDate(since()))}+ ORDER BY created_at DESC+ LIMIT ${sql.uint64(RECENT_SESSIONS_LIMIT)}`);+ return rows.map(transformEvent);+}++export interface RealtimeTopSources {+ referrers: Array<{ name: string; sessions: number }>;+ countries: Array<{ country: string; sessions: number }>;}-export function getRealtimeReferrals(deps: ServiceDeps, projectId: string) {- return chQuery<{+/** Top referrers and top countries from one scan of the window. */+export async function getRealtimeTopSources(+ deps: ServiceDeps,+ projectId: string+): Promise<RealtimeTopSources> {+ const rows = await chQuery<{referrer_name: string;- count: number;- avg_duration: number;- unique_sessions: number;+ country: string;+ sessions: number;+ is_referrer_row: number;+ is_country_row: number;}>(deps,- sql`SELECT referrer_name, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM ${sql.id(TABLE_NAMES.events)} WHERE project_id = ${sql.string(projectId)} AND referrer_name IS NOT NULL AND created_at >= ${sql.string(formatClickhouseDate(since()))} GROUP BY referrer_name ORDER BY count DESC LIMIT ${sql.uint64(REFERRALS_LIMIT)}`,- CLIX_SESSION_TIMEZONE+ sql`SELECT+ referrer_name,+ country,+ uniq(session_id) AS sessions,+ grouping(country) AS is_referrer_row,+ grouping(referrer_name) AS is_country_row+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE project_id = ${sql.string(projectId)}+ AND created_at >= ${sql.string(formatClickhouseDate(since()))}+ GROUP BY GROUPING SETS ((referrer_name), (country))+ HAVING (is_referrer_row = 1 AND referrer_name != ${sql.string('')})+ OR (is_country_row = 1 AND country != ${sql.string('')})+ ORDER BY sessions DESC+ LIMIT ${sql.uint64(TOP_SOURCES_LIMIT)} BY is_referrer_row, is_country_row`);++ return {+ referrers: rows+ .filter((row) => row.is_referrer_row === 1)+ .map((row) => ({ name: row.referrer_name, sessions: row.sessions })),+ countries: rows+ .filter((row) => row.is_country_row === 1)+ .map((row) => ({ country: row.country, sessions: row.sessions })),+ };}-export function getRealtimeGeo(deps: ServiceDeps, projectId: string) {- return chQuery<{- country: string;- city: string;- count: number;- avg_duration: number;- unique_sessions: number;+export interface RealtimeHistogram {+ /** Distinct sessions across the whole window. */+ totalSessions: number;+ /** One entry per minute of the window, oldest first, empty minutes included. */+ minutes: Array<{ minute: string; sessions: number; visitors: number }>;+}++/** Per-minute activity for the window, with the window total from the same scan. */+export async function getRealtimeHistogram(+ deps: ServiceDeps,+ projectId: string+): Promise<RealtimeHistogram> {+ const windowStart = since();+ const rows = await chQuery<{+ minute: string;+ sessions: number;+ visitors: number;+ is_total: number;}>(deps,- sql`SELECT country, city, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM ${sql.id(TABLE_NAMES.events)} WHERE project_id = ${sql.string(projectId)} AND created_at >= ${sql.string(formatClickhouseDate(since()))} GROUP BY country, city ORDER BY count DESC LIMIT ${sql.uint64(GEO_LIMIT)}`,+ sql`SELECT+ toStartOfMinute(created_at) AS minute,+ uniq(session_id) AS sessions,+ uniq(profile_id) AS visitors,+ grouping(minute) AS is_total+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE project_id = ${sql.string(projectId)}+ AND created_at >= ${sql.string(formatClickhouseDate(windowStart))}+ GROUP BY GROUPING SETS ((minute), ())`,CLIX_SESSION_TIMEZONE);++ const byMinute = new Map<number, { sessions: number; visitors: number }>();+ let totalSessions = 0;+ for (const row of rows) {+ if (row.is_total === 1) {+ totalSessions = row.sessions;+ continue;+ }+ byMinute.set(Date.parse(`${row.minute.replace(' ', 'T')}Z`), {+ sessions: row.sessions,+ visitors: row.visitors,+ });+ }++ const minutes: RealtimeHistogram['minutes'] = [];+ const firstMinute =+ Math.floor(windowStart.getTime() / MS_PER_MINUTE) * MS_PER_MINUTE;+ const lastMinute = Math.floor(Date.now() / MS_PER_MINUTE) * MS_PER_MINUTE;+ for (let at = firstMinute; at <= lastMinute; at += MS_PER_MINUTE) {+ const counts = byMinute.get(at);+ minutes.push({+ minute: new Date(at).toISOString(),+ sessions: counts?.sessions ?? 0,+ visitors: counts?.visitors ?? 0,+ });+ }++ return { totalSessions, minutes };}+// Each resolves to an unsubscribe function; nothing here is HTTP- or ws-library-specific.export function getActiveVisitorCount(@@ -514,14 +601,14 @@ export function createRealtimeService(projectId: string): ReturnType<typeof getRealtimeActiveSessions> =>getRealtimeActiveSessions(deps, projectId),- getPaths: (projectId: string): ReturnType<typeof getRealtimePaths> =>- getRealtimePaths(deps, projectId),- getReferrals: (+ getRecentSessions: (projectId: string- ): ReturnType<typeof getRealtimeReferrals> =>- getRealtimeReferrals(deps, projectId),- getGeo: (projectId: string): ReturnType<typeof getRealtimeGeo> =>- getRealtimeGeo(deps, projectId),+ ): ReturnType<typeof getRealtimeRecentSessions> =>+ getRealtimeRecentSessions(deps, projectId),+ getTopSources: (projectId: string): Promise<RealtimeTopSources> =>+ getRealtimeTopSources(deps, projectId),+ getHistogram: (projectId: string): Promise<RealtimeHistogram> =>+ getRealtimeHistogram(deps, projectId),getActiveVisitorCount: (projectId: string): Promise<number> =>getActiveVisitorCount(deps, projectId),};