Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
improve(web): redesign analytics header and overview card
Richie McIlroy5e9dab0ea1c4
diff --git a/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsxindex e702bb341..219225ef8 100644--- a/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/AnalyticsDashboard.tsx@@ -20,15 +20,16 @@ import { useEffectQuery } from "@/lib/EffectRuntime";import { Fit, Layout, useRive } from "@/lib/rive";import { useDashboardContext } from "../../Contexts";import type { AnalyticsRange, OrgAnalyticsResponse } from "../types";+import { DoodleFilters } from "./Doodles";import Header from "./Header";import OtherStats from "./OtherStats";import StatsChart from "./StatsChart";const RANGE_OPTIONS: { value: AnalyticsRange; label: string }[] = [- { value: "24h", label: "Last 24 hours" },- { value: "7d", label: "Last 7 days" },- { value: "30d", label: "Last 30 days" },- { value: "lifetime", label: "Lifetime" },+ { value: "24h", label: "24 hours" },+ { value: "7d", label: "7 days" },+ { value: "30d", label: "30 days" },+ { value: "lifetime", label: "All time" },];const ProRiveArt = memo(() => {@@ -139,6 +140,15 @@ export function AnalyticsDashboard() {}),enabled: Boolean(orgId),staleTime: 60 * 1000,+ placeholderData: (previous, previousQuery) => {+ const key = previousQuery?.queryKey;+ return key &&+ key[1] === orgId &&+ key[2] === selectedSpaceId &&+ key[4] === capId+ ? previous+ : undefined;+ },});const analytics = (query.data as { data: OrgAnalyticsResponse } | undefined)@@ -177,12 +187,15 @@ export function AnalyticsDashboard() {showOverlay && "overflow-hidden max-h-screen",)}>- <div className="space-y-8">+ <DoodleFilters />+ <div className="flex flex-col gap-5 mx-auto w-full max-w-[1280px]"><Headeroptions={RANGE_OPTIONS}value={range}onChange={setRange}- isLoading={query.isFetching}+ isLoading={query.isLoading}+ isFetching={query.isFetching}+ onRefresh={() => query.refetch()}organizations={organizationData}activeOrganization={activeOrganization}spacesData={spacesData}@@ -204,6 +217,20 @@ export function AnalyticsDashboard() {data={analytics?.chart ?? []}isLoading={query.isLoading}capId={capId}+ granularity={range === "24h" ? "hour" : "day"}+ animationKey={`${orgId}-${selectedSpaceId ?? ""}-${capId ?? ""}`}+ emptyAction={+ capId ? (+ <a+ href={`/s/${capId}`}+ target="_blank"+ rel="noreferrer"+ className="inline-flex gap-2 items-center px-5 h-10 text-sm font-medium rounded-full transition-colors bg-gray-12 text-gray-1 hover:bg-gray-11"+ >+ Open Cap+ </a>+ ) : undefined+ }/><OtherStats data={otherStats} isLoading={query.isLoading} /></div>diff --git a/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsx b/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsxdeleted file mode 100644index c2f9f95a6..000000000--- a/apps/web/app/(org)/dashboard/analytics/components/ChartArea.tsx+++ /dev/null@@ -1,255 +0,0 @@-"use client";--import { useId, useMemo } from "react";-import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";-import {- type ChartConfig,- ChartContainer,- ChartTooltip,- ChartTooltipContent,-} from "@/components/ui/chart";--export const description = "An area chart with gradient fill";--const chartConfig = {- views: {- label: "Views",- color: "#3b82f6",- },- comments: {- label: "Comments",- color: "#ec4899",- },- reactions: {- label: "Reactions",- color: "#f97316",- },- caps: {- label: "Caps",- color: "var(--gray-12)",- },-} satisfies ChartConfig;--interface ChartAreaProps {- selectedMetrics: Array<"caps" | "views" | "comments" | "reactions">;- data: Array<{- bucket: string;- caps: number;- views: number;- comments: number;- reactions: number;- }>;- isLoading?: boolean;-}--function ChartArea({ selectedMetrics, data, isLoading }: ChartAreaProps) {- const viewsGradientId = useId();- const commentsGradientId = useId();- const reactionsGradientId = useId();- const capsGradientId = useId();- const glowFilterId = useId();-- const chartData = useMemo(() => {- if (!data || data.length === 0) return [];- const bucketDuration =- data.length > 1 && data[1]?.bucket && data[0]?.bucket- ? new Date(data[1].bucket).getTime() -- new Date(data[0].bucket).getTime()- : 0;- const hourly = bucketDuration > 0 && bucketDuration <= 60 * 60 * 1000;- return data.map((point) => ({- ...point,- label: formatBucketLabel(point.bucket, hourly),- }));- }, [data]);-- const { maxValue, yAxisTicks } = useMemo(() => {- if (!chartData.length || selectedMetrics.length === 0) {- return { maxValue: 100, yAxisTicks: [0, 20, 40, 60, 80, 100] };- }-- let max = 0;- for (const point of chartData) {- for (const metric of selectedMetrics) {- const value = point[metric] ?? 0;- if (value > max) {- max = value;- }- }- }-- if (max === 0) {- return { maxValue: 100, yAxisTicks: [0, 20, 40, 60, 80, 100] };- }-- const roundedMax = Math.ceil(max * 1.1);- const magnitude = 10 ** Math.floor(Math.log10(roundedMax));- const normalized = roundedMax / magnitude;- let niceMax: number;-- if (normalized <= 1) {- niceMax = magnitude;- } else if (normalized <= 2) {- niceMax = 2 * magnitude;- } else if (normalized <= 5) {- niceMax = 5 * magnitude;- } else {- niceMax = 10 * magnitude;- }-- const step = niceMax / 5;- const ticks: number[] = [];- for (let i = 0; i <= 5; i++) {- ticks.push(Math.round(i * step));- }-- return { maxValue: niceMax, yAxisTicks: ticks };- }, [chartData, selectedMetrics]);-- if (isLoading && chartData.length === 0) {- return (- <div className="h-[500px] w-full animate-pulse rounded-xl border bg-gray-2 border-gray-3" />- );- }-- if (chartData.length === 0) {- return (- <div className="flex h-[300px] w-full flex-col items-center justify-center rounded-xl border border-dashed border-gray-5 text-sm text-gray-9">- No analytics data yet.- </div>- );- }-- if (selectedMetrics.length === 0) {- return (- <div className="flex h-[300px] w-full flex-col items-center justify-center rounded-xl border border-dashed border-gray-5 text-sm text-gray-9">- Select at least one metric to view.- </div>- );- }-- return (- <ChartContainer className="h-[500px] bg-gray-2" config={chartConfig}>- <AreaChart- accessibilityLayer- data={chartData}- margin={{- left: 20,- right: 20,- top: 20,- bottom: 10,- }}- >- <CartesianGrid- vertical={false}- strokeDasharray="3 3"- stroke="var(--gray-8)"- opacity={0.3}- />- <XAxis- dataKey="label"- axisLine={false}- tickMargin={10}- interval={0}- height={40}- tick={{ fontSize: 11 }}- />- <YAxis- axisLine={false}- tickMargin={8}- ticks={yAxisTicks}- domain={[0, maxValue]}- width={16}- allowDataOverflow={false}- />- <ChartTooltip content={<ChartTooltipContent />} />- <defs>- <filter id={glowFilterId}>- <feGaussianBlur stdDeviation="2" result="coloredBlur" />- <feMerge>- <feMergeNode in="coloredBlur" />- <feMergeNode in="SourceGraphic" />- </feMerge>- </filter>- <linearGradient id={viewsGradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.5} />- <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />- </linearGradient>- <linearGradient id={commentsGradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#ec4899" stopOpacity={0.5} />- <stop offset="95%" stopColor="#ec4899" stopOpacity={0} />- </linearGradient>- <linearGradient id={reactionsGradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#f97316" stopOpacity={0.5} />- <stop offset="95%" stopColor="#f97316" stopOpacity={0} />- </linearGradient>- <linearGradient id={capsGradientId} x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="var(--gray-12)" stopOpacity={0.5} />- <stop offset="95%" stopColor="var(--gray-12)" stopOpacity={0} />- </linearGradient>- </defs>- {selectedMetrics.includes("views") && (- <Area- dataKey="views"- type="monotone"- fill={`url(#${viewsGradientId})`}- fillOpacity={0.4}- stroke="#3b82f6"- strokeWidth={1}- filter={`url(#${glowFilterId})`}- />- )}- {selectedMetrics.includes("comments") && (- <Area- dataKey="comments"- type="monotone"- fill={`url(#${commentsGradientId})`}- fillOpacity={0.4}- stroke="#ec4899"- strokeWidth={1}- filter={`url(#${glowFilterId})`}- />- )}- {selectedMetrics.includes("reactions") && (- <Area- dataKey="reactions"- type="monotone"- fill={`url(#${reactionsGradientId})`}- fillOpacity={0.4}- stroke="#f97316"- strokeWidth={1}- filter={`url(#${glowFilterId})`}- />- )}- {selectedMetrics.includes("caps") && (- <Area- dataKey="caps"- type="monotone"- fill={`url(#${capsGradientId})`}- fillOpacity={0.4}- stroke="var(--gray-12)"- strokeWidth={1}- filter={`url(#${glowFilterId})`}- />- )}- </AreaChart>- </ChartContainer>- );-}--export default ChartArea;--const formatBucketLabel = (bucket: string, hourly: boolean) => {- const date = new Date(bucket);- if (Number.isNaN(date.getTime())) return bucket;- if (hourly)- return date.toLocaleTimeString([], {- hour: "numeric",- minute: undefined,- });- return date.toLocaleDateString([], {- month: "short",- day: "numeric",- timeZone: "UTC",- });-};diff --git a/apps/web/app/(org)/dashboard/analytics/components/Header.tsx b/apps/web/app/(org)/dashboard/analytics/components/Header.tsxindex a0dd840c3..fc24bc210 100644--- a/apps/web/app/(org)/dashboard/analytics/components/Header.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/Header.tsx@@ -3,14 +3,16 @@import type { Organisation } from "@cap/web-domain";import * as SelectPrimitive from "@radix-ui/react-select";import clsx from "clsx";+import { motion } from "framer-motion";import {ArrowLeft,+ ArrowUpRight,+ Check,ChevronDown,- ChevronLeft,- ChevronRight,+ RotateCw,} from "lucide-react";-import { useRouter } from "next/navigation";-import { useEffect, useState } from "react";+import Link from "next/link";+import { useEffect } from "react";import { useCurrentUser } from "@/app/Layout/AuthContext";import { SignedImageUrl } from "@/components/SignedImageUrl";import type { Organization, Spaces } from "../../dashboard-data";@@ -21,6 +23,8 @@ interface HeaderProps {value: AnalyticsRange;onChange: (value: AnalyticsRange) => void;isLoading?: boolean;+ isFetching?: boolean;+ onRefresh?: () => void;organizations?: Organization[] | null;activeOrganization?: Organization | null;spacesData?: Spaces[] | null;@@ -33,72 +37,16 @@ interface HeaderProps {capName?: string | null;}-const DATE_RANGE_OPTIONS = [- { value: "today", label: "Today" },- { value: "yesterday", label: "Yesterday" },- { value: "24h", label: "Last 24 hours" },- { value: "7d", label: "Last 7 days" },- { value: "30d", label: "Last 30 days" },- { value: "wtd", label: "Week to date" },- { value: "mtd", label: "Month to date" },- { value: "lifetime", label: "Lifetime" },-] as const;--const mapToBackendRange = (value: string): AnalyticsRange => {- if (- value === "24h" ||- value === "7d" ||- value === "30d" ||- value === "lifetime"- ) {- return value as AnalyticsRange;- }- if (value === "today" || value === "yesterday") {- return "24h";- }- if (value === "wtd") {- return "7d";- }- if (value === "mtd") {- return "30d";- }- return "7d";-};--const getDisplayValue = (- backendValue: AnalyticsRange,- lastUISelection?: string,-): string => {- if (- lastUISelection &&- (lastUISelection === "today" || lastUISelection === "yesterday")- ) {- if (backendValue === "24h") {- return lastUISelection;- }- }- if (lastUISelection && lastUISelection === "wtd") {- if (backendValue === "7d") {- return lastUISelection;- }- }- if (lastUISelection && lastUISelection === "mtd") {- if (backendValue === "30d") {- return lastUISelection;- }- }- if (backendValue === "lifetime") return "lifetime";- if (backendValue === "24h") return "24h";- if (backendValue === "7d") return "7d";- if (backendValue === "30d") return "30d";- return "7d";-};+const chip =+ "flex items-center gap-2 h-10 rounded-xl border border-gray-4 bg-gray-1 px-3.5 shadow-[0_1px_2px_rgba(0,0,0,0.04)] outline-none transition-colors hover:bg-gray-2 focus-visible:ring-2 focus-visible:ring-blue-9/40";export default function Header({- options: _options,+ options,value,onChange,isLoading,+ isFetching,+ onRefresh,organizations,activeOrganization,spacesData,@@ -111,26 +59,6 @@ export default function Header({capName,}: HeaderProps) {const user = useCurrentUser();- const router = useRouter();- const [open, setOpen] = useState(false);- const [orgOpen, setOrgOpen] = useState(false);- const [lastUISelection, setLastUISelection] = useState<string | undefined>(- undefined,- );-- useEffect(() => {- if (!lastUISelection) {- if (value === "24h") {- setLastUISelection("24h");- } else if (value === "7d") {- setLastUISelection("7d");- } else if (value === "30d") {- setLastUISelection("30d");- } else if (value === "lifetime") {- setLastUISelection("lifetime");- }- }- }, [value, lastUISelection]);useEffect(() => {const currentOrgId =@@ -150,59 +78,23 @@ export default function Header({onSpaceChange,]);- const selectedOption =- DATE_RANGE_OPTIONS.find(- (opt) => opt.value === getDisplayValue(value, lastUISelection),- ) || DATE_RANGE_OPTIONS[3];-- const handleValueChange = (newValue: string) => {- setLastUISelection(newValue);- const backendRange = mapToBackendRange(newValue);- onChange(backendRange);- setOpen(false);- };-- const handlePrevious = () => {- const currentIndex = DATE_RANGE_OPTIONS.findIndex(- (opt) => opt.value === selectedOption.value,- );- if (currentIndex > 0) {- const prevOption = DATE_RANGE_OPTIONS[currentIndex - 1];- handleValueChange(prevOption?.value ?? "");- }- };-- const handleNext = () => {- const currentIndex = DATE_RANGE_OPTIONS.findIndex(- (opt) => opt.value === selectedOption.value,- );- if (currentIndex < DATE_RANGE_OPTIONS.length - 1) {- const nextOption = DATE_RANGE_OPTIONS[currentIndex + 1];- handleValueChange(nextOption?.value ?? "");- }- };-- const canGoPrevious =- DATE_RANGE_OPTIONS.findIndex((opt) => opt.value === selectedOption.value) >- 0;- const canGoNext =- DATE_RANGE_OPTIONS.findIndex((opt) => opt.value === selectedOption.value) <- DATE_RANGE_OPTIONS.length - 1;+ if (!activeOrganization) {+ return null;+ }const selectedOrgId =- selectedOrganizationId || activeOrganization?.organization.id;+ selectedOrganizationId || activeOrganization.organization.id;const selectedOrg =organizations?.find((org) => org.organization.id === selectedOrgId) ||- activeOrganization ||- organizations?.[0];+ activeOrganization;const filteredSpaces = spacesData?.filter((space) => space.organizationId === selectedOrgId,);- const handleOrgChange = (value: string) => {- if (value.startsWith("space:")) {- const spaceId = value.replace("space:", "");+ const handleOrgChange = (next: string) => {+ if (next.startsWith("space:")) {+ const spaceId = next.replace("space:", "");const space = filteredSpaces?.find((s) => s.id === spaceId);if (space) {onSpaceChange?.(spaceId);@@ -212,143 +104,122 @@ export default function Header({}} else {onSpaceChange?.(null);- onOrganizationChange?.(value as Organisation.OrganisationId);+ onOrganizationChange?.(next as Organisation.OrganisationId);}- setOrgOpen(false);};const selectedSpace = selectedSpaceId? filteredSpaces?.find((s) => s.id === selectedSpaceId): null;- const isMyCapsSelected =- !selectedSpaceId &&- selectedOrg?.organization.id === activeOrganization?.organization.id;-- const displayName = selectedSpace- ? selectedSpace.name- : isMyCapsSelected- ? user?.name- ? `${user.name}'s Caps`- : "My Caps"- : selectedOrg?.organization.name || "Select organization";-+ const myCapsLabel = user?.name ? `${user.name}'s Caps` : "My Caps";+ const displayName = selectedSpace ? selectedSpace.name : myCapsLabel;const displayIcon = selectedSpace? selectedSpace.iconUrl- : isMyCapsSelected- ? user?.imageUrl || selectedOrg?.organization.iconUrl || undefined- : selectedOrg?.organization.iconUrl;-+ : user?.imageUrl || selectedOrg?.organization.iconUrl || undefined;const displayIconName = selectedSpace? selectedSpace.name- : isMyCapsSelected- ? user?.name || selectedOrg?.organization.name || "My Caps"- : selectedOrg?.organization.name || "Select organization";-- if (!activeOrganization) {- return null;- }+ : user?.name || selectedOrg?.organization.name || "My Caps";const selectValue = selectedSpaceId? `space:${selectedSpaceId}`- : selectedOrgId || activeOrganization.organization.id;-- const handleBackClick = () => {- router.push("/dashboard/analytics");- };+ : activeOrganization.organization.id;return (- <div className="flex gap-2 items-center">+ <div className="flex flex-wrap gap-2.5 items-center">{capId && (- <div className="flex items-center rounded-xl border border-gray-4 bg-gray-2 overflow-hidden">- <button- type="button"- onClick={handleBackClick}- className="flex items-center justify-center px-3 py-2.5 border-r border-gray-4 transition-colors text-gray-11 cursor-pointer"+ <>+ <Link+ href="/dashboard/analytics"+ className={clsx(chip, "justify-center w-10 px-0")}+ aria-label="Back to all analytics"+ >+ <ArrowLeft className="size-4 text-gray-11" />+ </Link>+ <a+ href={`/s/${capId}`}+ target="_blank"+ rel="noreferrer"+ className={clsx(chip, "group max-w-[min(420px,100%)]")}>- <ArrowLeft className="size-4" />- </button>- <div className="flex items-center px-4 py-2.5">+ <span className="flex flex-shrink-0 justify-center items-center rounded-md size-5 bg-[#4785ff]">+ <svg viewBox="0 0 12 12" className="size-2" aria-hidden="true">+ <path d="M3 1.8v8.4L10 6z" fill="white" />+ </svg>+ </span>{capName ? (- <span className="text-sm font-semibold text-gray-12">+ <span className="text-sm font-semibold truncate text-gray-12">{capName}</span>) : (- <div className="h-4 w-32 rounded bg-gray-4 animate-pulse" />+ <span className="w-32 h-4 rounded animate-pulse bg-gray-4" />)}- </div>- </div>+ <ArrowUpRight className="flex-shrink-0 transition-transform size-3.5 text-gray-10 group-hover:translate-x-px group-hover:-translate-y-px" />+ </a>+ </>)}+{!hideCapsSelect && (<SelectPrimitive.Rootvalue={selectValue}onValueChange={handleOrgChange}- open={orgOpen}- onOpenChange={setOrgOpen}disabled={isLoading}>- <SelectPrimitive.Trigger className="flex items-center gap-2 rounded-xl border border-gray-4 bg-gray-2 px-4 py-2.5 outline-none transition-colors disabled:opacity-50 disabled:cursor-not-allowed">- {displayIconName && (- <SignedImageUrl- image={displayIcon}- name={displayIconName}- className="size-5 flex-shrink-0"- />+ <SelectPrimitive.Trigger+ className={clsx(+ chip,+ "disabled:opacity-50 disabled:cursor-not-allowed",)}+ >+ <SignedImageUrl+ image={displayIcon}+ name={displayIconName}+ className="flex-shrink-0 size-5"+ /><span className="text-sm font-semibold text-gray-12">{displayName}</span>- <SelectPrimitive.Icon className="ml-1">+ <SelectPrimitive.Icon><ChevronDown className="size-4 text-gray-9" /></SelectPrimitive.Icon></SelectPrimitive.Trigger><SelectPrimitive.Portal><SelectPrimitive.Content- className="z-50 min-w-[200px] rounded-xl border border-gray-4 bg-gray-2 shadow-lg overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2"+ className="z-50 min-w-[220px] rounded-xl border border-gray-4 bg-gray-1 shadow-lg overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2"position="popper"- sideOffset={4}+ sideOffset={6}><SelectPrimitive.Viewport className="p-1">- <SelectPrimitive.Item- key={activeOrganization.organization.id}- value={activeOrganization.organization.id}- className="relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm outline-none transition-colors font-semibold text-gray-12 data-[state=checked]:bg-gray-3 data-[highlighted]:bg-gray-3 data-[highlighted]:text-gray-12"- >+ <SelectItem value={activeOrganization.organization.id}><SignedImageUrlimage={user?.imageUrl || activeOrganization.organization.iconUrl}name={user?.name || activeOrganization.organization.name}- className="size-5 flex-shrink-0"+ className="flex-shrink-0 size-5"/><SelectPrimitive.ItemText>- {user?.name ? `${user.name}'s Caps` : "My Caps"}+ {myCapsLabel}</SelectPrimitive.ItemText>- </SelectPrimitive.Item>+ </SelectItem>{filteredSpaces && filteredSpaces.length > 0 && (<>- <div className="px-3 py-2 text-xs font-semibold text-gray-9 uppercase tracking-wider">+ <div className="px-3 pt-3 pb-1 text-xs font-medium text-gray-10">Spaces</div>- {filteredSpaces.map((space) => {- return (- <SelectPrimitive.Item- key={space.id}- value={`space:${space.id}`}- className="relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm outline-none transition-colors text-gray-12 data-[state=checked]:bg-gray-3 data-[highlighted]:bg-gray-3 data-[highlighted]:text-gray-12"- >- <SignedImageUrl- image={space.iconUrl}- name={space.name}- className="size-5 flex-shrink-0"- />- <SelectPrimitive.ItemText>- {space.name}- </SelectPrimitive.ItemText>- </SelectPrimitive.Item>- );- })}+ {filteredSpaces.map((space) => (+ <SelectItem key={space.id} value={`space:${space.id}`}>+ <SignedImageUrl+ image={space.iconUrl}+ name={space.name}+ className="flex-shrink-0 size-5"+ />+ <SelectPrimitive.ItemText>+ {space.name}+ </SelectPrimitive.ItemText>+ </SelectItem>+ ))}</>)}</SelectPrimitive.Viewport>@@ -357,82 +228,73 @@ export default function Header({</SelectPrimitive.Root>)}- <SelectPrimitive.Root- value={selectedOption.value}- onValueChange={handleValueChange}- open={open}- onOpenChange={setOpen}- disabled={isLoading}- >- <div className="flex items-center rounded-xl border border-gray-4 bg-gray-2 overflow-hidden">- <button- type="button"- onClick={handlePrevious}- disabled={!canGoPrevious || isLoading}- className={clsx(- "flex items-center justify-center px-3 py-2.5 border-r border-gray-4 transition-colors",- canGoPrevious && !isLoading- ? "text-gray-11 cursor-pointer"- : "text-gray-6 cursor-not-allowed",- )}- >- <ChevronLeft className="size-4" />- </button>-- <SelectPrimitive.Trigger className="flex-1 flex items-center justify-between px-4 py-2.5 border-r border-gray-4 outline-none hover:bg-gray-3 transition-colors disabled:opacity-50 disabled:cursor-not-allowed space-x-1">- <span className="text-sm font-semibold text-gray-12">- {selectedOption.label}- </span>- <SelectPrimitive.Icon>- <ChevronDown className="size-4 text-gray-9" />- </SelectPrimitive.Icon>- </SelectPrimitive.Trigger>+ <fieldset className="flex items-center gap-0.5 p-1 h-10 rounded-xl border shadow-[0_1px_2px_rgba(0,0,0,0.04)] border-gray-4 bg-gray-1 m-0 min-w-0">+ <legend className="sr-only">Date range</legend>+ {options.map((option) => {+ const selected = option.value === value;+ return (+ <button+ key={option.value}+ type="button"+ aria-pressed={selected}+ onClick={() => onChange(option.value)}+ className={clsx(+ "relative h-full px-3 text-[13px] font-medium rounded-lg transition-colors outline-none focus-visible:ring-2 focus-visible:ring-blue-9/40",+ selected ? "text-gray-1" : "text-gray-10 hover:text-gray-12",+ )}+ >+ {selected && (+ <motion.span+ layoutId="analytics-range-pill"+ className="absolute inset-0 rounded-lg bg-gray-12"+ transition={{ type: "spring", stiffness: 500, damping: 38 }}+ />+ )}+ <span className="relative whitespace-nowrap">{option.label}</span>+ </button>+ );+ })}+ </fieldset>- <button- type="button"- onClick={handleNext}- disabled={!canGoNext || isLoading}+ {onRefresh && (+ <button+ type="button"+ onClick={onRefresh}+ disabled={isFetching}+ className={clsx(+ chip,+ "justify-center w-10 px-0 disabled:cursor-default",+ )}+ aria-label="Refresh analytics"+ >+ <RotateCwclassName={clsx(- "flex items-center justify-center px-3 py-2.5 transition-colors",- canGoNext && !isLoading- ? "text-gray-6 cursor-pointer"- : "text-gray-4 cursor-not-allowed",+ "size-4 text-gray-11",+ isFetching && "animate-spin [animation-duration:0.8s]",)}- >- <ChevronRight className="size-4" />- </button>- </div>-- <SelectPrimitive.Portal>- <SelectPrimitive.Content- className="z-50 min-w-[200px] rounded-xl border border-gray-4 bg-gray-2 shadow-lg overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2"- position="popper"- sideOffset={4}- >- <SelectPrimitive.Viewport className="p-1">- {DATE_RANGE_OPTIONS.map((option) => {- const isSelected = selectedOption.value === option.value;- return (- <SelectPrimitive.Item- key={option.value}- value={option.value}- className={clsx(- "relative flex w-full cursor-pointer items-center rounded-lg px-3 py-2 text-sm outline-none transition-colors font-semibold",- isSelected- ? "bg-gray-3 text-gray-12 data-[highlighted]:bg-gray-3 data-[highlighted]:text-gray-12"- : "text-gray-12 data-[highlighted]:bg-gray-3 data-[highlighted]:text-gray-12",- )}- >- <SelectPrimitive.ItemText>- {option.label}- </SelectPrimitive.ItemText>- </SelectPrimitive.Item>- );- })}- </SelectPrimitive.Viewport>- </SelectPrimitive.Content>- </SelectPrimitive.Portal>- </SelectPrimitive.Root>+ />+ </button>+ )}</div>);}++function SelectItem({+ value,+ children,+}: {+ value: string;+ children: React.ReactNode;+}) {+ return (+ <SelectPrimitive.Item+ value={value}+ className="flex relative gap-2 items-center py-2 pr-8 pl-3 w-full text-sm rounded-lg transition-colors cursor-pointer outline-none text-gray-12 data-[highlighted]:bg-gray-3"+ >+ {children}+ <SelectPrimitive.ItemIndicator className="absolute right-2.5">+ <Check className="size-3.5 text-gray-11" />+ </SelectPrimitive.ItemIndicator>+ </SelectPrimitive.Item>+ );+}diff --git a/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx b/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsxindex 0301e9ec2..e6c6821de 100644--- a/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx+++ b/apps/web/app/(org)/dashboard/analytics/components/StatsChart.tsx@@ -1,259 +1,273 @@"use client";-import { Check } from "lucide-react";-import { cloneElement, type SVGProps, useMemo, useRef, useState } from "react";+import NumberFlow from "@number-flow/react";+import clsx from "clsx";+import { type ReactNode, useMemo, useState } from "react";import {- CapIcon,- ChatIcon,- ClapIcon,- ReactionIcon,-} from "@/app/(org)/dashboard/_components/AnimatedIcons";-import { classNames } from "@/utils/helpers";-import type { CapIconHandle } from "../../_components/AnimatedIcons/Cap";-import ChartArea from "./ChartArea";--type boxes = "caps" | "views" | "comments" | "reactions";-type ChartPoint = {- bucket: string;- caps: number;- views: number;- comments: number;- reactions: number;-};--const formatCount = (value: number) => {- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;- if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;- return value.toLocaleString();-};+ BubbleDoodle,+ EyeDoodle,+ PaperPlaneDoodle,+ ReelDoodle,+ SmileDoodle,+ SquiggleLoader,+} from "./Doodles";+import type { Granularity } from "./format";+import TrafficChart, {+ type ChartPoint,+ METRIC_META,+ type Metric,+} from "./TrafficChart";interface StatsChartProps {- counts: Record<boxes, number>;+ counts: Record<Metric, number>;data: ChartPoint[];isLoading?: boolean;capId?: string | null;+ granularity: Granularity;+ animationKey: string;+ emptyAction?: ReactNode;}-export default function StatsBox({+const DOODLES: Record<Metric, () => ReactNode> = {+ views: () => <EyeDoodle />,+ comments: () => <BubbleDoodle />,+ reactions: () => <SmileDoodle />,+ caps: () => <ReelDoodle />,+};++export default function StatsChart({counts,data,isLoading,capId,+ granularity,+ animationKey,+ emptyAction,}: StatsChartProps) {- const [selectedBoxes, setSelectedBoxes] = useState<Set<boxes>>(- new Set(["views", "comments", "reactions"]),+ const available: Metric[] = capId+ ? ["views", "comments", "reactions"]+ : ["views", "comments", "reactions", "caps"];+ const [selected, setSelected] = useState<Set<Metric>>(+ () => new Set<Metric>(["views", "comments", "reactions"]),);- const capsBoxRef = useRef<CapIconHandle | null>(null);- const viewsBoxRef = useRef<CapIconHandle | null>(null);- const chatsBoxRef = useRef<CapIconHandle | null>(null);- const reactionsBoxRef = useRef<CapIconHandle | null>(null);-- const toggleHandler = (box: boxes) => {- setSelectedBoxes((prev) => {+ const toggle = (metric: Metric) => {+ setSelected((prev) => {const next = new Set(prev);- if (next.has(box)) {- next.delete(box);+ if (next.has(metric)) {+ const visibleCount = available.filter((m) => next.has(m)).length;+ if (visibleCount > 1) next.delete(metric);} else {- next.add(box);+ next.add(metric);}return next;});};- const formattedCounts = useMemo(- () => ({- caps: formatCount(counts.caps),- views: formatCount(counts.views),- comments: formatCount(counts.comments),- reactions: formatCount(counts.reactions),- }),- [counts],+ const metrics = available.filter((m) => selected.has(m));+ const display = useMemo(+ () => rollUpLongRanges(data, granularity),+ [data, granularity],+ );+ const completeBuckets = Math.max(1, data.length - 1);+ const perUnit = granularity === "hour" ? "an hour" : "a day";++ const hints = useMemo<Record<Metric, string>>(() => {+ const per100 = (value: number) =>+ counts.views > 0+ ? `${((value / counts.views) * 100).toFixed(1).replace(/\.0$/, "")} per 100 views`+ : "No views yet";+ const avg = (value: number) => {+ const v = value / completeBuckets;+ if (value === 0) return "None yet";+ return `About ${v >= 10 ? Math.round(v).toLocaleString() : v.toFixed(1).replace(/\.0$/, "")} ${perUnit}`;+ };+ return {+ views: avg(counts.views),+ comments: per100(counts.comments),+ reactions: per100(counts.reactions),+ caps: counts.caps === 0 ? "None yet" : avg(counts.caps),+ };+ }, [counts, completeBuckets, perUnit]);++ const hasActivity = data.some(+ (p) => p.views > 0 || p.comments > 0 || p.reactions > 0 || p.caps > 0,);return (- <div className="flex flex-col gap-4 px-8 pt-8 w-full rounded-xl border bg-gray-2 border-gray-3">- <div className="flex flex-wrap gap-4">+ <section className="overflow-hidden w-full rounded-2xl border shadow-[0_1px_2px_rgba(0,0,0,0.04)] bg-gray-1 border-gray-4">+ <div+ className={clsx(+ "grid gap-px border-b bg-gray-3 border-gray-3",+ available.length === 4+ ? "grid-cols-2 lg:grid-cols-4"+ : "grid-cols-1 sm:grid-cols-3",+ )}+ >+ {available.map((metric) => (+ <StatTile+ key={metric}+ metric={metric}+ value={counts[metric]}+ hint={hints[metric]}+ isSelected={selected.has(metric)}+ isLoading={isLoading}+ onClick={() => toggle(metric)}+ />+ ))}+ </div>+ <div className="px-3 pt-4 pb-3 sm:px-5">{isLoading ? (- Array.from({ length: capId ? 3 : 4 }, (_, index) => (- <StatBoxSkeleton key={`skeleton-${capId ? 3 : 4}-${index}`} />- ))+ <div className="flex h-[340px] flex-col items-center justify-center gap-3">+ <SquiggleLoader />+ <p className="text-sm text-gray-10">Counting views…</p>+ </div>+ ) : !hasActivity ? (+ <div className="flex h-[340px] flex-col items-center justify-center text-center">+ <PaperPlaneDoodle />+ <p className="mt-5 text-lg font-medium text-gray-12">+ No views in this period+ </p>+ <p className="mt-1 max-w-sm text-sm text-gray-10 text-pretty">+ {capId+ ? "Send this Cap to someone and every view, comment and reaction will land here."+ : "Share a Cap and every view, comment and reaction will land here."}+ </p>+ {emptyAction && <div className="mt-5">{emptyAction}</div>}+ </div>) : (- <>- <StatBox- onClick={() => toggleHandler("views")}- isSelected={selectedBoxes.has("views")}- title="Views"- value={formattedCounts.views}- metric="views"- onMouseEnter={() => viewsBoxRef.current?.startAnimation()}- onMouseLeave={() => viewsBoxRef.current?.stopAnimation()}- icon={<ClapIcon ref={viewsBoxRef} size={20} />}- />- <StatBox- onClick={() => toggleHandler("comments")}- isSelected={selectedBoxes.has("comments")}- title="Comments"- value={formattedCounts.comments}- metric="comments"- onMouseEnter={() => chatsBoxRef.current?.startAnimation()}- onMouseLeave={() => chatsBoxRef.current?.stopAnimation()}- icon={<ChatIcon ref={chatsBoxRef} size={20} />}- />- <StatBox- onClick={() => toggleHandler("reactions")}- isSelected={selectedBoxes.has("reactions")}- title="Reactions"- value={formattedCounts.reactions}- metric="reactions"- onMouseEnter={() => reactionsBoxRef.current?.startAnimation()}- onMouseLeave={() => reactionsBoxRef.current?.stopAnimation()}- icon={<ReactionIcon ref={reactionsBoxRef} size={20} />}- />- {!capId && (- <StatBox- onClick={() => toggleHandler("caps")}- isSelected={selectedBoxes.has("caps")}- title="Caps"- value={formattedCounts.caps}- metric="caps"- onMouseEnter={() => capsBoxRef.current?.startAnimation()}- onMouseLeave={() => capsBoxRef.current?.stopAnimation()}- icon={<CapIcon ref={capsBoxRef} size={20} />}- />- )}- </>+ <TrafficChart+ data={display.data}+ metrics={metrics}+ granularity={display.granularity}+ animationKey={`${animationKey}-${display.data.length}-${display.data[0]?.bucket ?? ""}`}+ />)}</div>- <ChartArea- selectedMetrics={Array.from(selectedBoxes).filter(- (metric) => !capId || metric !== "caps",- )}- data={data}- isLoading={isLoading}- />- </div>+ </section>);}-const metricColors = {- views: {- bg: "rgba(59, 130, 246, 0.03)",- bgHover: "rgba(59, 130, 246, 0.05)",- bgSelected: "rgba(59, 130, 246, 0.08)",- border: "rgba(59, 130, 246, 0.15)",- borderSelected: "rgba(59, 130, 246, 0.25)",- },- comments: {- bg: "rgba(236, 72, 153, 0.03)",- bgHover: "rgba(236, 72, 153, 0.05)",- bgSelected: "rgba(236, 72, 153, 0.08)",- border: "rgba(236, 72, 153, 0.15)",- borderSelected: "rgba(236, 72, 153, 0.25)",- },- reactions: {- bg: "rgba(249, 115, 22, 0.03)",- bgHover: "rgba(249, 115, 22, 0.05)",- bgSelected: "rgba(249, 115, 22, 0.08)",- border: "rgba(249, 115, 22, 0.15)",- borderSelected: "rgba(249, 115, 22, 0.25)",- },- caps: {- bg: "rgba(0, 0, 0, 0.02)",- bgHover: "rgba(0, 0, 0, 0.03)",- bgSelected: "rgba(0, 0, 0, 0.05)",- border: "rgba(0, 0, 0, 0.12)",- borderSelected: "rgba(0, 0, 0, 0.2)",- },-} as const;+const WEEKLY_THRESHOLD = 92;-interface StatBoxProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {- title: string;- value: string;- icon: React.ReactElement<SVGProps<SVGSVGElement>>;- isSelected?: boolean;- metric: boxes;-}-function StatBox({- title,- value,- icon,- isSelected = false,+const rollUpLongRanges = (+ data: ChartPoint[],+ granularity: Granularity,+): { data: ChartPoint[]; granularity: Granularity } => {+ if (granularity !== "day" || data.length <= WEEKLY_THRESHOLD) {+ return { data, granularity };+ }+ const weeks: ChartPoint[] = [];+ for (let end = data.length; end > 0; end -= 7) {+ const chunk = data.slice(Math.max(0, end - 7), end);+ const first = chunk[0];+ if (!first) continue;+ weeks.unshift(+ chunk.reduce(+ (acc, point) => ({+ bucket: acc.bucket,+ views: acc.views + point.views,+ comments: acc.comments + point.comments,+ reactions: acc.reactions + point.reactions,+ caps: acc.caps + point.caps,+ }),+ { bucket: first.bucket, views: 0, comments: 0, reactions: 0, caps: 0 },+ ),+ );+ }+ return { data: weeks, granularity: "week" };+};++function StatTile({metric,- ...props-}: StatBoxProps) {- const colors = metricColors[metric];+ value,+ hint,+ isSelected,+ isLoading,+ onClick,+}: {+ metric: Metric;+ value: number;+ hint: string;+ isSelected: boolean;+ isLoading?: boolean;+ onClick: () => void;+}) {+ const [hovered, setHovered] = useState(false);+ const meta = METRIC_META[metric];return (<button- {...props}type="button"- className={classNames(- "flex flex-col flex-1 min-w-[150px] gap-2 px-8 py-6 rounded-xl border transition-all duration-200 cursor-pointer group h-fit border-gray-5 text-left",- isSelected ? "border-gray-8" : "",+ onClick={onClick}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ onFocus={() => setHovered(true)}+ onBlur={() => setHovered(false)}+ aria-pressed={isSelected}+ data-doodle-hover={hovered ? "" : undefined}+ className={clsx(+ "group relative flex flex-col gap-1 px-6 py-5 text-left transition-colors duration-200 outline-none bg-gray-1 focus-visible:bg-gray-2 hover:bg-gray-2",)}- style={{- backgroundColor: isSelected ? colors.bgSelected : colors.bg,- borderColor: isSelected ? colors.borderSelected : colors.border,- }}- onMouseEnter={(e) => {- if (!isSelected) {- e.currentTarget.style.backgroundColor = colors.bgHover;- }- props.onMouseEnter?.(e);- }}- onMouseLeave={(e) => {- if (!isSelected) {- e.currentTarget.style.backgroundColor = colors.bg;- }- props.onMouseLeave?.(e);- }}>- <div className="flex gap-2 items-center h-fit justify-between">- <div className="flex gap-2 items-center h-fit">- {cloneElement(icon, {- className: classNames(- "group-hover:text-gray-12 transition-colors duration-200",+ <div className="flex justify-between items-center">+ <div className="flex gap-2 items-center">+ <span className="-ml-1 flex size-7 items-center justify-center">+ {DOODLES[metric]()}+ </span>+ <span+ className={clsx(+ "text-sm font-medium transition-colors",isSelected ? "text-gray-12" : "text-gray-10",- ),- })}- <p- className={classNames(- "text-base font-medium transition-colors duration-200 group-hover:text-gray-12 text-gray-10",- isSelected && "text-gray-12",)}>- {title}- </p>+ {meta.label}+ </span></div>- <div- className={classNames(- "flex items-center justify-center size-5 rounded border transition-all duration-200",- isSelected- ? "bg-gray-3 border-gray-9 dark:bg-gray-10 dark:border-gray-10"- : "bg-transparent border-gray-8 group-hover:border-gray-10",+ <span+ className={clsx(+ "flex size-4 items-center justify-center rounded-[5px] border-[1.5px] transition-all duration-200",+ !isSelected && "border-gray-7 group-hover:border-gray-9",)}+ style={+ isSelected+ ? { background: meta.color, borderColor: meta.color }+ : undefined+ }+ aria-hidden="true">{isSelected && (- <Check className="size-3.5 text-gray-12 dark:text-gray-1" />+ <svg viewBox="0 0 12 12" className="size-2.5" aria-hidden="true">+ <path+ d="M2.5 6.2 5 8.5 9.5 3.5"+ fill="none"+ stroke="white"+ strokeWidth={1.8}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>)}- </div>+ </span></div>- <p className="text-2xl font-medium transition-colors duration-200 text-gray-12">- {value}- </p>+ {isLoading ? (+ <>+ <div className="mt-1.5 h-8 w-20 rounded-md animate-pulse bg-gray-3" />+ <div className="mt-1 h-3.5 w-28 rounded animate-pulse bg-gray-3" />+ </>+ ) : (+ <>+ <NumberFlow+ value={value}+ format={value >= 10_000 ? { notation: "compact" } : undefined}+ className={clsx(+ "text-[32px] font-semibold leading-tight tracking-tight tabular-nums transition-colors",+ isSelected ? "text-gray-12" : "text-gray-9",+ )}+ />+ <span className="text-[13px] text-gray-10">{hint}</span>+ </>+ )}</button>);}--function StatBoxSkeleton() {- return (- <div className="flex flex-col flex-1 min-w-[150px] gap-2 px-8 py-6 bg-transparent rounded-xl border border-gray-5 h-fit">- <div className="flex gap-2 items-center h-fit">- <div className="size-5 rounded bg-gray-4 animate-pulse" />- <div className="h-4 w-20 rounded bg-gray-4 animate-pulse" />- </div>- <div className="h-8 w-16 rounded bg-gray-4 animate-pulse" />- </div>- );-}