Merge pull request #42 from ciphera-net/staging

Release 0.14.0-alpha
This commit is contained in:
Usman
2026-03-12 13:12:03 +01:00
committed by GitHub
67 changed files with 7327 additions and 1871 deletions

View File

@@ -6,12 +6,69 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.14.0-alpha] - 2026-03-12
### Improved
- **Smarter referrer attribution.** Traffic that arrives without a referrer on a deep page (like a blog post) is now shown as "Shared Link" instead of "Direct." Real direct traffic — visitors who land on your homepage — still shows as "Direct." This gives you a much clearer picture of where your traffic actually comes from, since most unattributed deep-page visits are people clicking links shared in messaging apps or AI chatbots that strip the referrer header.
- **More in-app browsers detected.** Pulse now recognises visits from WhatsApp, Telegram, Snapchat, Pinterest, Reddit, and Threads in-app browsers and attributes them correctly instead of lumping them into "Direct."
- **Dashboard blocks are now consistent in height.** The Goals & Events and Scroll Depth panels now match the height of every other block on the dashboard.
- **Cleaner period picker.** The date range dropdown now has visual separators between the rolling windows (Today, Last 7 days, Last 30 days), the calendar periods (This week, This month), and Custom — so it's easy to tell them apart at a glance.
- **New date range options.** The period selector now includes "This week" (Monday to today) and "This month" (1st to today) alongside the existing rolling windows. Your selection is remembered between sessions.
- **Smarter comparison labels.** The "vs …" label under each stat now matches the period you're viewing — "vs yesterday" for today, "vs last week" for this week, "vs last month" for this month, and "vs previous N days" for rolling windows.
- **Refreshed stat headers.** The Unique Visitors, Total Pageviews, Bounce Rate, and Visit Duration stats at the top of the chart have a new look — uppercase labels, the percentage change shown inline next to the number, and an orange underline on whichever metric you're currently graphing.
- **Consistent green and red colors.** The up/down percentage indicators now use the same green and red as the rest of the app, instead of slightly different shades.
- **Scroll Depth is now a radar chart.** The Scroll Depth panel has been redesigned from a bar chart into a radar chart. The four scroll milestones (25%, 50%, 75%, 100%) are plotted as axes, with the filled shape showing how far visitors are getting through your pages at a glance.
- **Polished Goals & Events panel.** The Goals & Events block on your dashboard got a visual refresh to match the style of the Pages, Referrers, and Locations panels. Counts are shown in a consistent style, and hovering any row reveals what percentage of total events that action accounts for — sliding in smoothly from the right.
- **Smarter bot protection.** The security checks on shared dashboard access and organization settings now use action-specific tokens tied to each page. A token earned on one page can't be reused on another, making it harder for automated tools to bypass the captcha.
- **More resilient under Redis outages.** If the caching layer goes down temporarily, Pulse now continues enforcing rate limits using an in-memory fallback instead of letting all traffic through unchecked. This prevents one infrastructure hiccup from snowballing into a bigger problem.
- **Better handling of traffic bursts.** The system can now absorb 5x larger spikes of incoming events before applying backpressure. When events are dropped during extreme bursts, the system now tracks and logs exactly how many — so we can detect and respond to sustained overload before it affects your data.
- **Faster map and globe loading.** The interactive 3D globe and dotted map in the Locations panel now only load when you scroll down to them, instead of rendering immediately on page load. This makes the initial dashboard load faster and saves battery on mobile devices.
- **Real-time updates work across all servers.** If Pulse runs on multiple servers behind a load balancer, real-time visitor updates now stay in sync no matter which server you're connected to. Previously, you might miss live visitor changes if your connection landed on a different server than the one fetching data.
- **Lighter memory usage in long sessions.** If you manage many sites and keep Pulse open for hours, the app now automatically clears out old cached data for sites you're no longer viewing. This keeps the tab responsive and prevents it from slowly using more and more memory over time.
- **Cleaner login storage.** Temporary data left behind by abandoned sign-in attempts is now cleaned up automatically when the app loads. This prevents clutter from building up in your browser's storage over time.
- **Tidier annotation display.** If you've added a lot of annotations to your chart, only the 20 most recent are shown as lines on the chart to keep it readable. A "+N more" label lets you know there are additional annotations.
- **Even faster dashboard loading.** Your dashboard now fetches all its data — pages, locations, devices, referrers, performance, and goals — in a single request instead of seven separate ones. This means the entire dashboard appears at once rather than sections loading one by one, and puts much less strain on the server when many people are viewing their analytics at the same time.
- **Smoother real-time updates.** The real-time visitors page now streams updates instantly from the server instead of checking for new data every few seconds. Visitors appear and disappear in real-time with no delay, and the page uses far fewer server resources — especially when many people are watching their live traffic at the same time.
- **More reliable under heavy load.** Database queries now have automatic time limits so a single slow query can never lock up the system. If your dashboard or stats take too long to load, the request is gracefully cancelled instead of hanging forever — keeping everything responsive even during traffic spikes.
- **Smarter caching for dashboard data.** Your dashboard stats are now cached for longer and shared more efficiently between requests. When the cache refreshes, only one request does the work while others wait for the result — so your dashboard loads consistently fast even when lots of people are viewing their analytics at the same time.
- **Faster filtered views.** When you filter your dashboard by country, browser, page, or any other dimension, the results are now cached so repeat views load instantly. If multiple people apply the same filter, only one lookup runs and the result is shared — making filtered views much snappier under heavy use.
- **Faster entry and exit page stats.** The queries that figure out which pages visitors land on and leave from have been rewritten to be much more efficient. Instead of sorting through every single event, they now look up just the first and last page per visit — so your Entry Pages and Exit Pages panels load noticeably faster, especially on high-traffic sites.
- **Faster goal stats.** The Goals panel on your dashboard now loads faster, especially for sites with many custom events. Goal names are now looked up in a single step instead of one at a time.
- **Fairer performance under heavy traffic.** One busy site can no longer slow down dashboards for everyone else. Each site now gets its own dedicated share of server resources, so your analytics stay fast and responsive even when other sites on the platform are experiencing traffic spikes.
- **Smoother exports.** Exporting your data to PDF, Excel, or CSV no longer freezes the page. You'll see a clear "Exporting..." indicator while your file is being prepared, and the rest of the dashboard stays fully interactive.
- **Smoother "View All" popups.** Opening the expanded view for Pages, Locations, Technology, Referrers, or Campaigns now scrolls smoothly even with hundreds of items. Only the rows you can see are rendered, so the popup opens instantly on any device.
- **Faster daily stats processing.** Behind the scenes, the system that calculates your daily visitor stats now automatically scales up when there are more sites to process — so your dashboard numbers stay accurate and up to date even as the platform grows.
- **More reliable background processing.** When multiple servers are running, long-running background tasks like daily stats calculations no longer risk being interrupted or duplicated. The system now keeps its coordination lock active for as long as the task is running.
### Added
- **Peak Hours heatmap.** A new panel on your dashboard shows a 7×24 grid of when your visitors are most active — every day of the week against every hour of the day. Cells glow brighter in brand orange the busier that hour is. Hover any cell to see the exact pageview count. No other indie analytics tool surfaces this on the main dashboard.
- **Interactive 3D Globe.** The Locations panel now has a "Globe" tab showing your visitor locations on a beautiful, interactive 3D globe. Drag to rotate, and orange markers highlight where your visitors are — sized by how much traffic each country sends. The globe slowly auto-rotates and adapts to light and dark mode.
- **Dotted world map.** The "Map" tab in Locations now uses a sleek dotted map style instead of the old filled map. Country markers glow in brand orange and show a tooltip with the country name and pageview count when you hover.
- **Hide unknown locations.** New toggle in Site Settings under Data & Privacy to hide "Unknown" entries from your Locations panel. When geographic data can't be determined for a visitor, it normally shows as "Unknown" in countries, cities, and regions. Turn this on to keep your location stats clean and only show resolved locations.
- **Chart annotations.** Mark events on your dashboard timeline — like deploys, campaigns, or incidents — so you always know why traffic changed. Click the + button on the chart to add a note on any date. Annotations appear as colored markers on the chart: blue for deploys, green for campaigns, red for incidents. Hover to see the details. Team owners and admins can add, edit, and delete annotations; everyone else (including public dashboard viewers) can see them.
### Improved
- **Beautiful funnel visualization.** Funnel reports now show a smooth, animated funnel shape instead of a plain bar chart. Each step flows into the next with curved segments, hover effects, and labels showing visitor counts and conversion percentages at a glance.
- **Tidier dashboard layout.** The tab navigation (Dashboard, Uptime, Funnels, Settings) now sits above your site name and controls, keeping the tabs front and center.
- **Instant tab switching.** Clicking between Dashboard, Uptime, Funnels, and Settings now feels instant — the tab bar stays in place while the page content loads below it, instead of the whole screen flashing with a loading skeleton.
- **Smooth tab animations.** Switching tabs now plays a sliding indicator animation on the active tab and a subtle crossfade on the page content, making navigation feel polished and responsive.
- **Cleaner focus styles.** Buttons, tabs, and links no longer show an orange outline when you click them — the focus ring now only appears when navigating with the keyboard, keeping the interface clean.
- **Faster dashboard loading.** Switching to the Dashboard and Map tabs is now instant — no more brief lag or delay when navigating between sections.
- **Expand icon for data panels.** Pages, Referrers, Locations, Technology, and Campaigns panels now show a small expand icon next to the title when there's more data to see, replacing the old "View all" button at the bottom.
- **Better expanded views.** When you expand a data panel, the popup is now wider and taller so you can see more at once. Each row shows a percentage on hover, clicking a row filters your dashboard, and there's a search bar at the top to quickly find what you're looking for.
- **Smoother theme switching.** Toggling between light and dark mode now plays a satisfying circular reveal animation that expands from the toggle button, instead of everything just flipping instantly.
- **Cleaner site navigation.** Dashboard, Uptime, Funnels, and Settings now use an underline tab bar instead of floating buttons. The active section is highlighted with an orange underline, making it easy to see where you are and switch between views.
- **Consistent icon style.** All dashboard icons now use a single, unified icon set for a cleaner look across Technology, Locations, Campaigns, and Referrers panels.
### Fixed
- **Correct Instagram attribution.** Visits from Instagram's in-app browser were showing as "Facebook" because Instagram routes shared links through Facebook's URL redirector. Pulse now checks the User-Agent to detect the real source app.
- **Android and iOS now show up in OS stats.** A bug in the User-Agent parsing order meant Android was always classified as "Linux" (because Android UAs contain "Linux") and iOS as "macOS" (because iPhone UAs contain "like Mac OS X"). Both are now detected correctly.
- **Charts no longer show tomorrow's date.** The visitor chart on 7-day and 30-day views could display the next day with zero traffic, making it look like a sudden drop. The chart now ends on today.
- **Capitalized technology labels.** Device types, browsers, and OS names in the Technology panel now display with a capital first letter (e.g. "Desktop" instead of "desktop").
- **Login no longer gets stuck after updates.** If you happened to have Pulse open when a new version was deployed, logging back in could get stuck on a loading screen. The app now automatically refreshes itself to pick up the latest version.
- **City and region data is now accurate.** Location data was incorrectly showing the CDN server's location (e.g. Paris, Villeurbanne) instead of the visitor's actual city. Fixed by reading the correct visitor IP header from Bunny CDN.
- **"Reset Data" now clears everything.** Previously, resetting a site's data in Settings only removed pageviews and daily stats. Uptime check history, uptime daily stats, and cached dashboard data were left behind. All collected data is now properly cleared when you reset, while your site configuration, goals, funnels, and uptime monitors are kept.

View File

@@ -58,7 +58,7 @@ function FAQItem({ faq, index }: { faq: typeof faqs[0]; index: number }) {
>
<button
onClick={() => setIsOpen(!isOpen)}
className="w-full py-6 flex items-center justify-between text-left hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="w-full py-6 flex items-center justify-between text-left hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white pr-4">
{faq.question}

View File

@@ -83,12 +83,12 @@ const capabilities = [
description: 'Automatically parse UTM parameters. Built-in link builder for campaigns, sources, and mediums.',
},
{
icon: Share2Icon,
icon: <Share2Icon className="w-5 h-5" />,
title: 'Shared Dashboards',
description: 'Generate a public link to share analytics with clients or teammates — no login required.',
},
{
icon: GlobeIcon,
icon: <GlobeIcon className="w-5 h-5" />,
title: 'Geographic Insights',
description: 'Country, region, and city-level breakdowns. IPs are never stored — derived at request time only.',
},
@@ -190,7 +190,7 @@ export default function FeaturesPage() {
className="flex gap-4"
>
<div className="w-10 h-10 rounded-lg bg-brand-orange/10 flex items-center justify-center shrink-0 text-brand-orange mt-0.5">
{typeof cap.icon === 'object' ? cap.icon : <cap.icon className="w-5 h-5" />}
{cap.icon}
</div>
<div>
<h3 className="font-bold text-neutral-900 dark:text-white mb-1">

View File

@@ -285,7 +285,7 @@ export default function IntegrationsPage() {
>
<Link
href={`/integrations/${integration.id}`}
className="group relative p-6 bg-white/50 dark:bg-neutral-900/50 backdrop-blur-sm border border-neutral-200 dark:border-neutral-800 rounded-2xl hover:border-brand-orange/50 dark:hover:border-brand-orange/50 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl block h-full focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="group relative p-6 bg-white/50 dark:bg-neutral-900/50 backdrop-blur-sm border border-neutral-200 dark:border-neutral-800 rounded-2xl hover:border-brand-orange/50 dark:hover:border-brand-orange/50 transition-all duration-300 hover:-translate-y-1 hover:shadow-xl block h-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
<div className="flex items-start justify-between mb-6">
<div className="p-3 bg-neutral-100 dark:bg-neutral-800 rounded-xl group-hover:scale-110 transition-transform duration-300">
@@ -336,7 +336,7 @@ export default function IntegrationsPage() {
</p>
<a
href="mailto:support@ciphera.net"
className="inline-flex items-center gap-2 px-5 py-2.5 bg-brand-orange text-white font-medium rounded-lg hover:bg-brand-orange/90 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="inline-flex items-center gap-2 px-5 py-2.5 bg-brand-orange text-white font-medium rounded-lg hover:bg-brand-orange/90 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
Request Integration
</a>
@@ -361,7 +361,7 @@ export default function IntegrationsPage() {
</p>
<a
href="mailto:support@ciphera.net"
className="text-sm font-medium text-brand-orange hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm font-medium text-brand-orange hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:rounded"
>
Request Integration
</a>

View File

@@ -1,5 +1,6 @@
import { ThemeProviders, Toaster } from '@ciphera-net/ui'
import { AuthProvider } from '@/lib/auth/context'
import SWRProvider from '@/components/SWRProvider'
import type { Metadata, Viewport } from 'next'
import { Plus_Jakarta_Sans } from 'next/font/google'
import LayoutContent from './layout-content'
@@ -46,12 +47,14 @@ export default function RootLayout({
return (
<html lang="en" className={plusJakartaSans.variable} suppressHydrationWarning>
<body className="antialiased min-h-screen flex flex-col bg-white dark:bg-neutral-950 text-neutral-900 dark:text-neutral-50">
<ThemeProviders>
<AuthProvider>
<LayoutContent>{children}</LayoutContent>
<Toaster />
</AuthProvider>
</ThemeProviders>
<SWRProvider>
<ThemeProviders>
<AuthProvider>
<LayoutContent>{children}</LayoutContent>
<Toaster />
</AuthProvider>
</ThemeProviders>
</SWRProvider>
</body>
</html>
)

View File

@@ -475,11 +475,11 @@ export default function HomePage() {
)}
<div className="mt-2 flex gap-2">
{subscription.has_payment_method ? (
<Link href="/org-settings?tab=billing" className="text-sm font-medium text-brand-orange hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Link href="/org-settings?tab=billing" className="text-sm font-medium text-brand-orange hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:rounded">
Manage billing
</Link>
) : (
<Link href="/pricing" className="text-sm font-medium text-brand-orange hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Link href="/pricing" className="text-sm font-medium text-brand-orange hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:rounded">
Upgrade
</Link>
)}

View File

@@ -238,6 +238,7 @@ export default function PublicDashboardPage() {
setCaptchaToken(token || '')
}}
apiUrl={process.env.NEXT_PUBLIC_CAPTCHA_API_URL}
action="share-access"
/>
</div>
<Button

View File

@@ -0,0 +1,20 @@
'use client'
import SiteNav from '@/components/dashboard/SiteNav'
export default function SiteLayoutShell({
siteId,
children,
}: {
siteId: string
children: React.ReactNode
}) {
return (
<>
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pt-8">
<SiteNav siteId={siteId} />
</div>
{children}
</>
)
}

View File

@@ -1,40 +1,15 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { ApiError } from '@/lib/api/client'
import { getFunnel, getFunnelStats, deleteFunnel, type Funnel, type FunnelStats } from '@/lib/api/funnels'
import { toast, Select, DatePicker, ChevronLeftIcon, ArrowRightIcon, TrashIcon, useTheme, Button } from '@ciphera-net/ui'
import { toast, Select, DatePicker, ChevronLeftIcon, ArrowRightIcon, TrashIcon, Button } from '@ciphera-net/ui'
import { FunnelDetailSkeleton, useMinimumLoading } from '@/components/skeletons'
import Link from 'next/link'
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Cell
} from 'recharts'
import { FunnelChart } from '@/components/ui/funnel-chart'
import { getDateRange } from '@ciphera-net/ui'
const CHART_COLORS_LIGHT = {
border: 'var(--color-neutral-200)',
axis: 'var(--color-neutral-400)',
tooltipBg: '#ffffff',
tooltipBorder: 'var(--color-neutral-200)',
}
const CHART_COLORS_DARK = {
border: 'var(--color-neutral-700)',
axis: 'var(--color-neutral-500)',
tooltipBg: 'var(--color-neutral-800)',
tooltipBorder: 'var(--color-neutral-700)',
}
const BRAND_ORANGE = 'var(--color-brand-orange)'
export default function FunnelReportPage() {
const params = useParams()
const router = useRouter()
@@ -74,12 +49,6 @@ export default function FunnelReportPage() {
loadData()
}, [loadData])
const { resolvedTheme } = useTheme()
const chartColors = useMemo(
() => (resolvedTheme === 'dark' ? CHART_COLORS_DARK : CHART_COLORS_LIGHT),
[resolvedTheme]
)
const handleDelete = async () => {
if (!confirm('Are you sure you want to delete this funnel?')) return
@@ -100,7 +69,7 @@ export default function FunnelReportPage() {
if (loadError === 'not_found' || (!funnel && !stats && !loadError)) {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400">Funnel not found</p>
</div>
)
@@ -108,7 +77,7 @@ export default function FunnelReportPage() {
if (loadError === 'forbidden') {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400">Access denied</p>
<Link href={`/sites/${siteId}/funnels`}>
<Button variant="primary" className="mt-4">
@@ -121,7 +90,7 @@ export default function FunnelReportPage() {
if (loadError === 'error') {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400 mb-4">Unable to load funnel</p>
<Button type="button" onClick={() => loadData()} variant="primary">
Try again
@@ -132,21 +101,19 @@ export default function FunnelReportPage() {
if (!funnel || !stats) {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400">Funnel not found</p>
</div>
)
}
const chartData = stats.steps.map(s => ({
name: s.step.name,
visitors: s.visitors,
dropoff: s.dropoff,
conversion: s.conversion
label: s.step.name,
value: s.visitors,
}))
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-4">
@@ -204,64 +171,13 @@ export default function FunnelReportPage() {
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white mb-6">
Funnel Visualization
</h3>
<div className="h-[400px] w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke={chartColors.border} />
<XAxis
dataKey="name"
stroke={chartColors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
/>
<YAxis
stroke={chartColors.axis}
fontSize={12}
tickLine={false}
axisLine={false}
/>
<Tooltip
cursor={{ fill: 'transparent' }}
content={({ active, payload, label }) => {
if (active && payload && payload.length) {
const data = payload[0].payload;
return (
<div
className="p-3 rounded-xl shadow-lg border transition-shadow duration-300"
style={{
backgroundColor: chartColors.tooltipBg,
borderColor: chartColors.tooltipBorder,
}}
>
<p className="font-medium text-neutral-900 dark:text-white mb-1">{label}</p>
<p className="text-brand-orange font-bold text-lg">
{data.visitors.toLocaleString()} visitors
</p>
{data.dropoff > 0 && (
<p className="text-red-500 text-sm">
{Math.round(data.dropoff)}% drop-off
</p>
)}
{data.conversion > 0 && (
<p className="text-green-500 text-sm">
{Math.round(data.conversion)}% conversion (overall)
</p>
)}
</div>
);
}
return null;
}}
/>
<Bar dataKey="visitors" radius={[4, 4, 0, 0]} barSize={60}>
{chartData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={BRAND_ORANGE} fillOpacity={Math.max(0.1, 1 - index * 0.15)} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<FunnelChart
data={chartData}
orientation="vertical"
color="var(--chart-1)"
layers={3}
className="mx-auto max-w-md"
/>
</div>
{/* Detailed Stats Table */}

View File

@@ -91,7 +91,7 @@ export default function CreateFunnelPage() {
}
return (
<div className="w-full max-w-3xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-3xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<Link
href={`/sites/${siteId}/funnels`}

View File

@@ -6,7 +6,6 @@ import { listFunnels, deleteFunnel, type Funnel } from '@/lib/api/funnels'
import { toast, PlusIcon, ArrowRightIcon, ChevronLeftIcon, TrashIcon, Button } from '@ciphera-net/ui'
import { FunnelsListSkeleton, useMinimumLoading } from '@/components/skeletons'
import Link from 'next/link'
import SiteNav from '@/components/dashboard/SiteNav'
export default function FunnelsPage() {
const params = useParams()
@@ -52,9 +51,7 @@ export default function FunnelsPage() {
}
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<SiteNav siteId={siteId} />
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<div className="flex items-center justify-between mb-6">
<div>

View File

@@ -1,4 +1,5 @@
import type { Metadata } from 'next'
import SiteLayoutShell from './SiteLayoutShell'
export const metadata: Metadata = {
title: 'Dashboard | Pulse',
@@ -6,10 +7,13 @@ export const metadata: Metadata = {
robots: { index: false, follow: false },
}
export default function SiteLayout({
export default async function SiteLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ id: string }>
}) {
return children
const { id } = await params
return <SiteLayoutShell siteId={id}>{children}</SiteLayoutShell>
}

View File

@@ -2,9 +2,8 @@
import { logger } from '@/lib/utils/logger'
import { useCallback, useEffect, useState, useMemo } from 'react'
import { useCallback, useEffect, useRef, useState, useMemo } from 'react'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import { motion } from 'framer-motion'
import {
getPerformanceByPage,
getTopPages,
@@ -19,39 +18,37 @@ import {
type Stats,
type DailyStat,
} from '@/lib/api/stats'
import { getDateRange } from '@ciphera-net/ui'
import { getDateRange, formatDate } from '@ciphera-net/ui'
import { toast } from '@ciphera-net/ui'
import { Button } from '@ciphera-net/ui'
import { Select, DatePicker, DownloadIcon } from '@ciphera-net/ui'
import dynamic from 'next/dynamic'
import { DashboardSkeleton, useMinimumLoading } from '@/components/skeletons'
import ExportModal from '@/components/dashboard/ExportModal'
import FilterBar from '@/components/dashboard/FilterBar'
import AddFilterDropdown, { type FilterSuggestion, type FilterSuggestions } from '@/components/dashboard/AddFilterDropdown'
import Chart from '@/components/dashboard/Chart'
import ContentStats from '@/components/dashboard/ContentStats'
import TopReferrers from '@/components/dashboard/TopReferrers'
import Locations from '@/components/dashboard/Locations'
import TechSpecs from '@/components/dashboard/TechSpecs'
import Chart from '@/components/dashboard/Chart'
import PerformanceStats from '@/components/dashboard/PerformanceStats'
import GoalStats from '@/components/dashboard/GoalStats'
import ScrollDepth from '@/components/dashboard/ScrollDepth'
import Campaigns from '@/components/dashboard/Campaigns'
import SiteNav from '@/components/dashboard/SiteNav'
import FilterBar from '@/components/dashboard/FilterBar'
import AddFilterDropdown, { type FilterSuggestion, type FilterSuggestions } from '@/components/dashboard/AddFilterDropdown'
import EventProperties from '@/components/dashboard/EventProperties'
const PerformanceStats = dynamic(() => import('@/components/dashboard/PerformanceStats'))
const GoalStats = dynamic(() => import('@/components/dashboard/GoalStats'))
const ScrollDepth = dynamic(() => import('@/components/dashboard/ScrollDepth'))
const Campaigns = dynamic(() => import('@/components/dashboard/Campaigns'))
const PeakHours = dynamic(() => import('@/components/dashboard/PeakHours'))
const EventProperties = dynamic(() => import('@/components/dashboard/EventProperties'))
const ExportModal = dynamic(() => import('@/components/dashboard/ExportModal'))
import { type DimensionFilter, serializeFilters, parseFiltersFromURL } from '@/lib/filters'
import {
useDashboardOverview,
useDashboardPages,
useDashboardLocations,
useDashboardDevices,
useDashboardReferrers,
useDashboardPerformance,
useDashboardGoals,
useDashboard,
useRealtime,
useStats,
useDailyStats,
useCampaigns,
useAnnotations,
} from '@/lib/swr/dashboard'
import { createAnnotation, updateAnnotation, deleteAnnotation, type AnnotationCategory } from '@/lib/api/annotations'
function loadSavedSettings(): {
type?: string
@@ -68,17 +65,37 @@ function loadSavedSettings(): {
}
}
function getThisWeekRange(): { start: string; end: string } {
const today = new Date()
const dayOfWeek = today.getDay()
const monday = new Date(today)
monday.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1))
return { start: formatDate(monday), end: formatDate(today) }
}
function getThisMonthRange(): { start: string; end: string } {
const today = new Date()
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
return { start: formatDate(firstOfMonth), end: formatDate(today) }
}
function getInitialDateRange(): { start: string; end: string } {
const settings = loadSavedSettings()
if (settings?.type === 'today') {
const today = new Date().toISOString().split('T')[0]
const today = formatDate(new Date())
return { start: today, end: today }
}
if (settings?.type === '7') return getDateRange(7)
if (settings?.type === 'week') return getThisWeekRange()
if (settings?.type === 'month') return getThisMonthRange()
if (settings?.type === 'custom' && settings.dateRange) return settings.dateRange
return getDateRange(30)
}
function getInitialPeriod(): string {
return loadSavedSettings()?.type || '30'
}
export default function SiteDashboardPage() {
@@ -88,6 +105,7 @@ export default function SiteDashboardPage() {
const siteId = params.id as string
// UI state - initialized from localStorage synchronously to avoid double-fetch
const [period, setPeriod] = useState(getInitialPeriod)
const [dateRange, setDateRange] = useState(getInitialDateRange)
const [todayInterval, setTodayInterval] = useState<'minute' | 'hour'>(
() => loadSavedSettings()?.todayInterval || 'hour'
@@ -97,8 +115,7 @@ export default function SiteDashboardPage() {
)
const [isDatePickerOpen, setIsDatePickerOpen] = useState(false)
const [isExportModalOpen, setIsExportModalOpen] = useState(false)
const [lastUpdatedAt, setLastUpdatedAt] = useState<number | null>(null)
const [, setTick] = useState(0)
const lastUpdatedAtRef = useRef<number | null>(null)
// Dimension filters state
const searchParams = useSearchParams()
@@ -219,39 +236,53 @@ export default function SiteDashboardPage() {
return { start: prevStart.toISOString().split('T')[0], end: prevEnd.toISOString().split('T')[0] }
}, [dateRange])
// SWR hooks - replace manual useState + useEffect + setInterval polling
// Each hook handles its own refresh interval, deduplication, and error retry
// Filters are included in cache keys so changing filters auto-refetches
const { data: overview, isLoading: overviewLoading, error: overviewError } = useDashboardOverview(siteId, dateRange.start, dateRange.end, interval, filtersParam || undefined)
const { data: pages } = useDashboardPages(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
const { data: locations } = useDashboardLocations(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
const { data: devicesData } = useDashboardDevices(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
const { data: referrers } = useDashboardReferrers(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
const { data: performanceData } = useDashboardPerformance(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
const { data: goalsData } = useDashboardGoals(siteId, dateRange.start, dateRange.end, filtersParam || undefined)
// Single dashboard request replaces 7 focused hooks (overview, pages, locations,
// devices, referrers, performance, goals). The backend runs all queries in parallel
// and caches the result in Redis, reducing requests from 12 to 6 per refresh cycle.
const { data: dashboard, isLoading: dashboardLoading, error: dashboardError } = useDashboard(siteId, dateRange.start, dateRange.end, interval, filtersParam || undefined)
const { data: realtimeData } = useRealtime(siteId)
const { data: prevStats } = useStats(siteId, prevRange.start, prevRange.end)
const { data: prevDailyStats } = useDailyStats(siteId, prevRange.start, prevRange.end, interval)
const { data: campaigns } = useCampaigns(siteId, dateRange.start, dateRange.end)
const { data: annotations, mutate: mutateAnnotations } = useAnnotations(siteId, dateRange.start, dateRange.end)
// Derive typed values from SWR data
const site = overview?.site ?? null
const stats: Stats = overview?.stats ?? { pageviews: 0, visitors: 0, bounce_rate: 0, avg_duration: 0 }
const realtime = realtimeData?.visitors ?? overview?.realtime_visitors ?? 0
const dailyStats: DailyStat[] = overview?.daily_stats ?? []
// Annotation mutation handlers
const handleCreateAnnotation = async (data: { date: string; time?: string; text: string; category: string }) => {
await createAnnotation(siteId, { ...data, category: data.category as AnnotationCategory })
mutateAnnotations()
toast.success('Annotation added')
}
const handleUpdateAnnotation = async (id: string, data: { date: string; time?: string; text: string; category: string }) => {
await updateAnnotation(siteId, id, { ...data, category: data.category as AnnotationCategory })
mutateAnnotations()
toast.success('Annotation updated')
}
const handleDeleteAnnotation = async (id: string) => {
await deleteAnnotation(siteId, id)
mutateAnnotations()
toast.success('Annotation deleted')
}
// Derive typed values from single dashboard response
const site = dashboard?.site ?? null
const stats: Stats = dashboard?.stats ?? { pageviews: 0, visitors: 0, bounce_rate: 0, avg_duration: 0 }
const realtime = realtimeData?.visitors ?? dashboard?.realtime_visitors ?? 0
const dailyStats: DailyStat[] = dashboard?.daily_stats ?? []
// Build filter suggestions from current dashboard data
const filterSuggestions = useMemo<FilterSuggestions>(() => {
const s: FilterSuggestions = {}
// Pages
const topPages = pages?.top_pages ?? []
const topPages = dashboard?.top_pages ?? []
if (topPages.length > 0) {
s.page = topPages.map(p => ({ value: p.path, label: p.path, count: p.pageviews }))
}
// Referrers
const refs = referrers?.top_referrers ?? []
const refs = dashboard?.top_referrers ?? []
if (refs.length > 0) {
s.referrer = refs.filter(r => r.referrer && r.referrer !== '').map(r => ({
value: r.referrer,
@@ -261,7 +292,7 @@ export default function SiteDashboardPage() {
}
// Countries
const ctrs = locations?.countries ?? []
const ctrs = dashboard?.countries ?? []
if (ctrs.length > 0) {
const regionNames = (() => { try { return new Intl.DisplayNames(['en'], { type: 'region' }) } catch { return null } })()
s.country = ctrs.filter(c => c.country && c.country !== 'Unknown').map(c => ({
@@ -272,7 +303,7 @@ export default function SiteDashboardPage() {
}
// Regions
const regs = locations?.regions ?? []
const regs = dashboard?.regions ?? []
if (regs.length > 0) {
s.region = regs.filter(r => r.region && r.region !== 'Unknown').map(r => ({
value: r.region,
@@ -282,7 +313,7 @@ export default function SiteDashboardPage() {
}
// Cities
const cts = locations?.cities ?? []
const cts = dashboard?.cities ?? []
if (cts.length > 0) {
s.city = cts.filter(c => c.city && c.city !== 'Unknown').map(c => ({
value: c.city,
@@ -292,7 +323,7 @@ export default function SiteDashboardPage() {
}
// Browsers
const brs = devicesData?.browsers ?? []
const brs = dashboard?.browsers ?? []
if (brs.length > 0) {
s.browser = brs.filter(b => b.browser && b.browser !== 'Unknown').map(b => ({
value: b.browser,
@@ -302,7 +333,7 @@ export default function SiteDashboardPage() {
}
// OS
const oses = devicesData?.os ?? []
const oses = dashboard?.os ?? []
if (oses.length > 0) {
s.os = oses.filter(o => o.os && o.os !== 'Unknown').map(o => ({
value: o.os,
@@ -312,7 +343,7 @@ export default function SiteDashboardPage() {
}
// Devices
const devs = devicesData?.devices ?? []
const devs = dashboard?.devices ?? []
if (devs.length > 0) {
s.device = devs.filter(d => d.device && d.device !== 'Unknown').map(d => ({
value: d.device,
@@ -338,25 +369,19 @@ export default function SiteDashboardPage() {
}
return s
}, [pages, referrers, locations, devicesData, campaigns])
}, [dashboard, campaigns])
// Show error toast on fetch failure
useEffect(() => {
if (overviewError) {
if (dashboardError) {
toast.error('Failed to load dashboard analytics')
}
}, [overviewError])
}, [dashboardError])
// Track when data was last updated (for "Live · Xs ago" display)
useEffect(() => {
if (overview) setLastUpdatedAt(Date.now())
}, [overview])
// Tick every 1s so "Live · Xs ago" counts in real time
useEffect(() => {
const timer = setInterval(() => setTick((t) => t + 1), 1000)
return () => clearInterval(timer)
}, [])
if (dashboard) lastUpdatedAtRef.current = Date.now()
}, [dashboard])
// Save settings to localStorage
const saveSettings = (type: string, newDateRange?: { start: string; end: string }) => {
@@ -377,7 +402,7 @@ export default function SiteDashboardPage() {
// Save intervals when they change
useEffect(() => {
let type = 'custom'
const today = new Date().toISOString().split('T')[0]
const today = formatDate(new Date())
if (dateRange.start === today && dateRange.end === today) type = 'today'
else if (dateRange.start === getDateRange(7).start) type = '7'
else if (dateRange.start === getDateRange(30).start) type = '30'
@@ -396,7 +421,9 @@ export default function SiteDashboardPage() {
if (site?.domain) document.title = `${site.domain} | Pulse`
}, [site?.domain])
const showSkeleton = useMinimumLoading(overviewLoading)
// Skip the minimum-loading skeleton when SWR already has cached data
// (prevents the 300ms flash when navigating back to the dashboard)
const showSkeleton = useMinimumLoading(dashboardLoading && !dashboard)
if (showSkeleton) {
return <DashboardSkeleton />
@@ -404,19 +431,14 @@ export default function SiteDashboardPage() {
if (!site) {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400">Site not found</p>
</div>
)
}
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.2 }}
className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8"
>
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-4">
@@ -457,33 +479,35 @@ export default function SiteDashboardPage() {
<Select
variant="input"
className="min-w-[140px]"
value={
dateRange.start === new Date().toISOString().split('T')[0] && dateRange.end === new Date().toISOString().split('T')[0]
? 'today'
: dateRange.start === getDateRange(7).start
? '7'
: dateRange.start === getDateRange(30).start
? '30'
: 'custom'
}
value={period}
onChange={(value) => {
if (value === '7') {
const range = getDateRange(7)
setDateRange(range)
saveSettings('7', range)
}
else if (value === '30') {
const range = getDateRange(30)
setDateRange(range)
saveSettings('30', range)
}
else if (value === 'today') {
const today = new Date().toISOString().split('T')[0]
if (value === 'today') {
const today = formatDate(new Date())
const range = { start: today, end: today }
setDateRange(range)
setPeriod('today')
saveSettings('today', range)
}
else if (value === 'custom') {
} else if (value === '7') {
const range = getDateRange(7)
setDateRange(range)
setPeriod('7')
saveSettings('7', range)
} else if (value === 'week') {
const range = getThisWeekRange()
setDateRange(range)
setPeriod('week')
saveSettings('week', range)
} else if (value === '30') {
const range = getDateRange(30)
setDateRange(range)
setPeriod('30')
saveSettings('30', range)
} else if (value === 'month') {
const range = getThisMonthRange()
setDateRange(range)
setPeriod('month')
saveSettings('month', range)
} else if (value === 'custom') {
setIsDatePickerOpen(true)
}
}}
@@ -491,6 +515,10 @@ export default function SiteDashboardPage() {
{ value: 'today', label: 'Today' },
{ value: '7', label: 'Last 7 days' },
{ value: '30', label: 'Last 30 days' },
{ value: 'divider-1', label: '', divider: true },
{ value: 'week', label: 'This week' },
{ value: 'month', label: 'This month' },
{ value: 'divider-2', label: '', divider: true },
{ value: 'custom', label: 'Custom' },
]}
/>
@@ -499,8 +527,6 @@ export default function SiteDashboardPage() {
</div>
</div>
<SiteNav siteId={siteId} />
{/* Dimension Filters */}
<div className="flex items-center gap-2 flex-wrap mb-2">
<AddFilterDropdown onAdd={handleAddFilter} suggestions={filterSuggestions} onFetchSuggestions={handleFetchSuggestions} />
@@ -516,11 +542,17 @@ export default function SiteDashboardPage() {
prevStats={prevStats}
interval={dateRange.start === dateRange.end ? todayInterval : multiDayInterval}
dateRange={dateRange}
period={period}
todayInterval={todayInterval}
setTodayInterval={setTodayInterval}
multiDayInterval={multiDayInterval}
setMultiDayInterval={setMultiDayInterval}
lastUpdatedAt={lastUpdatedAt}
lastUpdatedAt={lastUpdatedAtRef.current}
annotations={annotations}
canManageAnnotations={true}
onCreateAnnotation={handleCreateAnnotation}
onUpdateAnnotation={handleUpdateAnnotation}
onDeleteAnnotation={handleDeleteAnnotation}
/>
</div>
@@ -528,8 +560,8 @@ export default function SiteDashboardPage() {
{site.enable_performance_insights && (
<div className="mb-8">
<PerformanceStats
stats={performanceData?.performance ?? { lcp: 0, cls: 0, inp: 0 }}
performanceByPage={performanceData?.performance_by_page ?? null}
stats={dashboard?.performance ?? { lcp: 0, cls: 0, inp: 0 }}
performanceByPage={dashboard?.performance_by_page ?? null}
siteId={siteId}
startDate={dateRange.start}
endDate={dateRange.end}
@@ -540,9 +572,9 @@ export default function SiteDashboardPage() {
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<ContentStats
topPages={pages?.top_pages ?? []}
entryPages={pages?.entry_pages ?? []}
exitPages={pages?.exit_pages ?? []}
topPages={dashboard?.top_pages ?? []}
entryPages={dashboard?.entry_pages ?? []}
exitPages={dashboard?.exit_pages ?? []}
domain={site.domain}
collectPagePaths={site.collect_page_paths ?? true}
siteId={siteId}
@@ -550,7 +582,7 @@ export default function SiteDashboardPage() {
onFilter={handleAddFilter}
/>
<TopReferrers
referrers={referrers?.top_referrers ?? []}
referrers={dashboard?.top_referrers ?? []}
collectReferrers={site.collect_referrers ?? true}
siteId={siteId}
dateRange={dateRange}
@@ -560,19 +592,19 @@ export default function SiteDashboardPage() {
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<Locations
countries={locations?.countries ?? []}
cities={locations?.cities ?? []}
regions={locations?.regions ?? []}
countries={dashboard?.countries ?? []}
cities={dashboard?.cities ?? []}
regions={dashboard?.regions ?? []}
geoDataLevel={site.collect_geo_data || 'full'}
siteId={siteId}
dateRange={dateRange}
onFilter={handleAddFilter}
/>
<TechSpecs
browsers={devicesData?.browsers ?? []}
os={devicesData?.os ?? []}
devices={devicesData?.devices ?? []}
screenResolutions={devicesData?.screen_resolutions ?? []}
browsers={dashboard?.browsers ?? []}
os={dashboard?.os ?? []}
devices={dashboard?.devices ?? []}
screenResolutions={dashboard?.screen_resolutions ?? []}
collectDeviceInfo={site.collect_device_info ?? true}
collectScreenResolution={site.collect_screen_resolution ?? true}
siteId={siteId}
@@ -583,14 +615,15 @@ export default function SiteDashboardPage() {
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<Campaigns siteId={siteId} dateRange={dateRange} filters={filtersParam || undefined} onFilter={handleAddFilter} />
<GoalStats
goalCounts={(goalsData?.goal_counts ?? []).filter(g => !/^scroll_\d+$/.test(g.event_name))}
onSelectEvent={setSelectedEvent}
/>
<PeakHours siteId={siteId} dateRange={dateRange} />
</div>
<div className="mb-8">
<ScrollDepth goalCounts={goalsData?.goal_counts ?? []} totalPageviews={stats.pageviews} />
<div className="grid gap-6 lg:grid-cols-2 mb-8">
<GoalStats
goalCounts={(dashboard?.goal_counts ?? []).filter(g => !/^scroll_\d+$/.test(g.event_name))}
onSelectEvent={setSelectedEvent}
/>
<ScrollDepth goalCounts={dashboard?.goal_counts ?? []} totalPageviews={stats.pageviews} />
</div>
{/* Event Properties Breakdown */}
@@ -610,6 +643,7 @@ export default function SiteDashboardPage() {
onClose={() => setIsDatePickerOpen(false)}
onApply={(range) => {
setDateRange(range)
setPeriod('custom')
saveSettings('custom', range)
setIsDatePickerOpen(false)
}}
@@ -621,10 +655,10 @@ export default function SiteDashboardPage() {
onClose={() => setIsExportModalOpen(false)}
data={dailyStats}
stats={stats}
topPages={pages?.top_pages}
topReferrers={referrers?.top_referrers}
topPages={dashboard?.top_pages}
topReferrers={dashboard?.top_referrers}
campaigns={campaigns}
/>
</motion.div>
</div>
)
}

View File

@@ -3,7 +3,8 @@
import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { getSite, type Site } from '@/lib/api/sites'
import { getRealtimeVisitors, getSessionDetails, type Visitor, type SessionEvent } from '@/lib/api/realtime'
import { getSessionDetails, type Visitor, type SessionEvent } from '@/lib/api/realtime'
import { useRealtimeSSE } from '@/lib/hooks/useRealtimeSSE'
import { toast } from '@ciphera-net/ui'
import { getAuthErrorMessage } from '@ciphera-net/ui'
import { UserIcon } from '@ciphera-net/ui'
@@ -27,28 +28,20 @@ export default function RealtimePage() {
const siteId = params.id as string
const [site, setSite] = useState<Site | null>(null)
const [visitors, setVisitors] = useState<Visitor[]>([])
const { visitors } = useRealtimeSSE(siteId)
const [selectedVisitor, setSelectedVisitor] = useState<Visitor | null>(null)
const [sessionEvents, setSessionEvents] = useState<SessionEvent[]>([])
const [loading, setLoading] = useState(true)
const [loadingEvents, setLoadingEvents] = useState(false)
// Load site info and initial visitors
// Load site info
useEffect(() => {
const init = async () => {
try {
const [siteData, visitorsData] = await Promise.all([
getSite(siteId),
getRealtimeVisitors(siteId)
])
const siteData = await getSite(siteId)
setSite(siteData)
setVisitors(visitorsData || [])
// Select first visitor if available
if (visitorsData && visitorsData.length > 0) {
handleSelectVisitor(visitorsData[0])
}
} catch (error: unknown) {
toast.error(getAuthErrorMessage(error) || 'Failed to load realtime visitors')
toast.error(getAuthErrorMessage(error) || 'Failed to load site')
} finally {
setLoading(false)
}
@@ -56,27 +49,12 @@ export default function RealtimePage() {
init()
}, [siteId])
// Poll for updates
// Auto-select the first visitor when the list populates and nothing is selected
useEffect(() => {
const interval = setInterval(async () => {
try {
const data = await getRealtimeVisitors(siteId)
setVisitors(data || [])
// Update selected visitor reference if they are still in the list
if (selectedVisitor) {
const updatedVisitor = data?.find(v => v.session_id === selectedVisitor.session_id)
if (updatedVisitor) {
// Don't overwrite the selectedVisitor state directly to avoid flickering details
// But we could update "last seen" indicators if we wanted
}
}
} catch (e) {
// Silent fail
}
}, 5000)
return () => clearInterval(interval)
}, [siteId, selectedVisitor])
if (visitors.length > 0 && !selectedVisitor) {
handleSelectVisitor(visitors[0])
}
}, [visitors]) // eslint-disable-line react-hooks/exhaustive-deps
const handleSelectVisitor = async (visitor: Visitor) => {
setSelectedVisitor(visitor)
@@ -101,11 +79,11 @@ export default function RealtimePage() {
if (!site) return <div className="p-8">Site not found</div>
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8 h-[calc(100vh-64px)] flex flex-col">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8 h-[calc(100vh-64px)] flex flex-col">
<div className="mb-6 flex items-center justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<button onClick={() => router.push(`/sites/${siteId}`)} className="text-sm text-neutral-500 hover:text-neutral-900 dark:hover:text-white transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<button onClick={() => router.push(`/sites/${siteId}`)} className="text-sm text-neutral-500 hover:text-neutral-900 dark:hover:text-white transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:rounded">
&larr; Back to Dashboard
</button>
</div>
@@ -152,7 +130,7 @@ export default function RealtimePage() {
exit={{ opacity: 0, x: -10 }}
transition={{ duration: 0.2 }}
onClick={() => handleSelectVisitor(visitor)}
className={`w-full text-left p-4 hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-inset ${
className={`w-full text-left p-4 hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-inset ${
selectedVisitor?.session_id === visitor.session_id ? 'bg-neutral-50 dark:bg-neutral-800/50 ring-1 ring-inset ring-neutral-200 dark:ring-neutral-700' : ''
}`}
>

View File

@@ -15,7 +15,6 @@ import { APP_URL } from '@/lib/api/client'
import { generatePrivacySnippet } from '@/lib/utils/privacySnippet'
import { useUnsavedChanges } from '@/lib/hooks/useUnsavedChanges'
import { getSubscription, type SubscriptionDetails } from '@/lib/api/billing'
import SiteNav from '@/components/dashboard/SiteNav'
import { getRetentionOptionsForPlan, formatRetentionMonths } from '@/lib/plans'
import { motion, AnimatePresence } from 'framer-motion'
import { useAuth } from '@/lib/auth/context'
@@ -73,6 +72,8 @@ export default function SiteSettingsPage() {
enable_performance_insights: false,
// Bot and noise filtering
filter_bots: true,
// Hide unknown locations
hide_unknown_locations: false,
// Data retention (6 = free-tier max; safe default)
data_retention_months: 6
})
@@ -146,6 +147,8 @@ export default function SiteSettingsPage() {
enable_performance_insights: data.enable_performance_insights ?? false,
// Bot and noise filtering (default to true)
filter_bots: data.filter_bots ?? true,
// Hide unknown locations (default to false)
hide_unknown_locations: data.hide_unknown_locations ?? false,
// Data retention (default 6 = free-tier max; avoids flash-then-clamp for existing sites)
data_retention_months: data.data_retention_months ?? 6
})
@@ -161,6 +164,7 @@ export default function SiteSettingsPage() {
collect_screen_resolution: data.collect_screen_resolution ?? true,
enable_performance_insights: data.enable_performance_insights ?? false,
filter_bots: data.filter_bots ?? true,
hide_unknown_locations: data.hide_unknown_locations ?? false,
data_retention_months: data.data_retention_months ?? 6
})
if (data.has_password) {
@@ -277,6 +281,8 @@ export default function SiteSettingsPage() {
enable_performance_insights: formData.enable_performance_insights,
// Bot and noise filtering
filter_bots: formData.filter_bots,
// Hide unknown locations
hide_unknown_locations: formData.hide_unknown_locations,
// Data retention
data_retention_months: formData.data_retention_months
})
@@ -293,6 +299,7 @@ export default function SiteSettingsPage() {
collect_screen_resolution: formData.collect_screen_resolution,
enable_performance_insights: formData.enable_performance_insights,
filter_bots: formData.filter_bots,
hide_unknown_locations: formData.hide_unknown_locations,
data_retention_months: formData.data_retention_months
})
loadSite()
@@ -360,6 +367,7 @@ export default function SiteSettingsPage() {
collect_screen_resolution: formData.collect_screen_resolution,
enable_performance_insights: formData.enable_performance_insights,
filter_bots: formData.filter_bots,
hide_unknown_locations: formData.hide_unknown_locations,
data_retention_months: formData.data_retention_months
}) !== initialFormRef.current
@@ -373,7 +381,7 @@ export default function SiteSettingsPage() {
if (showSkeleton) {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="space-y-8">
<div>
<div className="h-8 w-40 animate-pulse rounded bg-neutral-100 dark:bg-neutral-800 mb-2" />
@@ -396,15 +404,14 @@ export default function SiteSettingsPage() {
if (!site) {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<p className="text-neutral-600 dark:text-neutral-400">Site not found</p>
</div>
)
}
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<SiteNav siteId={siteId} />
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="space-y-8">
<div>
@@ -421,7 +428,7 @@ export default function SiteSettingsPage() {
onClick={() => setActiveTab('general')}
role="tab"
aria-selected={activeTab === 'general'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'general'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -434,7 +441,7 @@ export default function SiteSettingsPage() {
onClick={() => setActiveTab('visibility')}
role="tab"
aria-selected={activeTab === 'visibility'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'visibility'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -447,7 +454,7 @@ export default function SiteSettingsPage() {
onClick={() => setActiveTab('data')}
role="tab"
aria-selected={activeTab === 'data'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'data'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -460,7 +467,7 @@ export default function SiteSettingsPage() {
onClick={() => setActiveTab('goals')}
role="tab"
aria-selected={activeTab === 'goals'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'goals'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -561,7 +568,7 @@ export default function SiteSettingsPage() {
<button
type="button"
onClick={() => setShowVerificationModal(true)}
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
<ZapIcon className="w-4 h-4" />
Verify Installation
@@ -596,7 +603,7 @@ export default function SiteSettingsPage() {
</div>
<button
onClick={handleResetData}
className="px-4 py-2 bg-white dark:bg-neutral-900 border border-red-200 dark:border-red-900 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-sm font-medium focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
className="px-4 py-2 bg-white dark:bg-neutral-900 border border-red-200 dark:border-red-900 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
>
Reset Data
</button>
@@ -609,7 +616,7 @@ export default function SiteSettingsPage() {
</div>
<button
onClick={handleDeleteSite}
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
>
Delete Site
</button>
@@ -675,7 +682,7 @@ export default function SiteSettingsPage() {
<button
type="button"
onClick={copyLink}
className="px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-900 dark:text-white rounded-xl font-medium hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-900 dark:text-white rounded-xl font-medium hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
{linkCopied ? 'Copied!' : 'Copy Link'}
</button>
@@ -885,6 +892,25 @@ export default function SiteSettingsPage() {
</label>
</div>
</div>
<div className="p-6 bg-neutral-50 dark:bg-neutral-900/50 rounded-2xl border border-neutral-100 dark:border-neutral-800">
<div className="flex items-center justify-between">
<div>
<h4 className="font-medium text-neutral-900 dark:text-white">Hide unknown locations</h4>
<p className="text-sm text-neutral-500 dark:text-neutral-400 mt-0.5">
Exclude entries where geographic data could not be resolved from location stats
</p>
</div>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={formData.hide_unknown_locations}
onChange={(e) => setFormData({ ...formData, hide_unknown_locations: e.target.checked })}
className="sr-only peer"
/>
<div className="w-11 h-6 bg-neutral-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-orange/20 dark:peer-focus:ring-brand-orange/20 rounded-full peer dark:bg-neutral-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-neutral-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-neutral-600 peer-checked:bg-brand-orange"></div>
</label>
</div>
</div>
</div>
{/* Performance Insights Toggle */}

View File

@@ -21,7 +21,6 @@ import { toast } from '@ciphera-net/ui'
import { useTheme } from '@ciphera-net/ui'
import { getAuthErrorMessage } from '@ciphera-net/ui'
import { Button, Modal } from '@ciphera-net/ui'
import SiteNav from '@/components/dashboard/SiteNav'
import { UptimeSkeleton, ChecksSkeleton, useMinimumLoading } from '@/components/skeletons'
import {
AreaChart,
@@ -29,28 +28,15 @@ import {
XAxis,
YAxis,
CartesianGrid,
Tooltip as RechartsTooltip,
ResponsiveContainer,
} from 'recharts'
import type { TooltipProps } from 'recharts'
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from '@/components/charts'
// * Chart theme colors (consistent with main Pulse chart)
const CHART_COLORS_LIGHT = {
border: 'var(--color-neutral-200)',
text: 'var(--color-neutral-900)',
textMuted: 'var(--color-neutral-500)',
axis: 'var(--color-neutral-400)',
tooltipBg: '#ffffff',
tooltipBorder: 'var(--color-neutral-200)',
}
const CHART_COLORS_DARK = {
border: 'var(--color-neutral-700)',
text: 'var(--color-neutral-50)',
textMuted: 'var(--color-neutral-400)',
axis: 'var(--color-neutral-500)',
tooltipBg: 'var(--color-neutral-800)',
tooltipBorder: 'var(--color-neutral-700)',
}
const responseTimeChartConfig = {
ms: {
label: 'Response Time',
color: 'var(--chart-1)',
},
} satisfies ChartConfig
// * Status color mapping
function getStatusColor(status: string): string {
@@ -285,9 +271,6 @@ function UptimeStatusBar({
// * Component: Response time chart (Recharts area chart)
function ResponseTimeChart({ checks }: { checks: UptimeCheck[] }) {
const { resolvedTheme } = useTheme()
const colors = resolvedTheme === 'dark' ? CHART_COLORS_DARK : CHART_COLORS_LIGHT
// * Prepare data in chronological order (oldest first)
const data = [...checks]
.reverse()
@@ -303,71 +286,58 @@ function ResponseTimeChart({ checks }: { checks: UptimeCheck[] }) {
if (data.length < 2) return null
const CustomTooltip = ({ active, payload, label }: TooltipProps<number, string>) => {
if (!active || !payload?.length) return null
return (
<div
className="rounded-xl px-3 py-2 text-xs shadow-lg border transition-shadow duration-300"
style={{
background: colors.tooltipBg,
borderColor: colors.tooltipBorder,
color: colors.text,
}}
>
<div className="font-medium mb-0.5">{label}</div>
<div style={{ color: 'var(--color-brand-orange)' }} className="font-semibold">
{payload[0].value}ms
</div>
</div>
)
}
return (
<div className="mt-4">
<h4 className="text-xs font-semibold text-neutral-500 dark:text-neutral-400 uppercase tracking-wider mb-3">
Response Time
</h4>
<div className="h-40">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="responseTimeGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="var(--color-brand-orange)" stopOpacity={0.3} />
<stop offset="100%" stopColor="var(--color-brand-orange)" stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke={colors.border}
strokeOpacity={0.5}
vertical={false}
/>
<XAxis
dataKey="time"
tick={{ fontSize: 10, fill: colors.axis }}
tickLine={false}
axisLine={false}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 10, fill: colors.axis }}
tickLine={false}
axisLine={false}
tickFormatter={(v: number) => `${v}ms`}
/>
<RechartsTooltip content={<CustomTooltip />} />
<Area
type="monotone"
dataKey="ms"
stroke="var(--color-brand-orange)"
strokeWidth={2}
fill="url(#responseTimeGradient)"
dot={false}
activeDot={{ r: 4, fill: 'var(--color-brand-orange)', strokeWidth: 0 }}
/>
</AreaChart>
</ResponsiveContainer>
</div>
<ChartContainer config={responseTimeChartConfig} className="h-40">
<AreaChart accessibilityLayer data={data} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="responseTimeGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="var(--color-ms)" stopOpacity={0.3} />
<stop offset="100%" stopColor="var(--color-ms)" stopOpacity={0.02} />
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--chart-grid)"
strokeOpacity={0.5}
vertical={false}
/>
<XAxis
dataKey="time"
tick={{ fontSize: 10, fill: 'var(--chart-axis)' }}
tickLine={false}
axisLine={false}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 10, fill: 'var(--chart-axis)' }}
tickLine={false}
axisLine={false}
tickFormatter={(v: number) => `${v}ms`}
/>
<ChartTooltip
content={
<ChartTooltipContent
className="text-xs"
labelKey="time"
formatter={(value) => <span className="font-semibold">{value}ms</span>}
/>
}
/>
<Area
type="monotone"
dataKey="ms"
stroke="var(--color-ms)"
strokeWidth={2}
fill="url(#responseTimeGradient)"
dot={false}
activeDot={{ r: 4, fill: 'var(--color-ms)', strokeWidth: 0 }}
/>
</AreaChart>
</ChartContainer>
</div>
)
}
@@ -718,14 +688,7 @@ export default function UptimePage() {
const overallStatus = uptimeData?.status ?? 'operational'
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.2 }}
className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8"
>
<SiteNav siteId={siteId} />
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
{/* Header */}
<div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
@@ -845,7 +808,7 @@ export default function UptimePage() {
siteDomain={site.domain}
/>
</Modal>
</motion.div>
</div>
)
}

View File

@@ -133,7 +133,7 @@ export default function NewSitePage() {
<button
type="button"
onClick={() => setShowVerificationModal(true)}
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
<span className="text-brand-orange">Verify installation</span>
</button>

View File

@@ -475,7 +475,7 @@ function WelcomeContent() {
<button
type="button"
onClick={() => setStep(1)}
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus:outline-none focus:ring-2 focus:ring-brand-orange rounded"
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded"
aria-label="Back to welcome"
>
<ArrowLeftIcon className="h-4 w-4" />
@@ -546,7 +546,7 @@ function WelcomeContent() {
<button
type="button"
onClick={() => setStep(2)}
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus:outline-none focus:ring-2 focus:ring-brand-orange rounded"
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded"
aria-label="Back to organization"
>
<ArrowLeftIcon className="h-4 w-4" />
@@ -604,14 +604,14 @@ function WelcomeContent() {
<button
type="button"
onClick={() => router.push('/pricing')}
className="text-sm text-brand-orange hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange rounded"
className="text-sm text-brand-orange hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded"
>
Choose a different plan
</button>
</p>
) : (
<p className="mt-4 text-center">
<Link href="/pricing" className="text-sm text-brand-orange hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange rounded">
<Link href="/pricing" className="text-sm text-brand-orange hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded">
View pricing
</Link>
</p>
@@ -631,7 +631,7 @@ function WelcomeContent() {
<button
type="button"
onClick={() => setStep(3)}
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus:outline-none focus:ring-2 focus:ring-brand-orange rounded"
className="flex items-center gap-2 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300 mb-6 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded"
aria-label="Back to plan"
>
<ArrowLeftIcon className="h-4 w-4" />
@@ -750,7 +750,7 @@ function WelcomeContent() {
<button
type="button"
onClick={() => setShowVerificationModal(true)}
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2"
className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-700 transition-all text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2"
>
<span className="text-brand-orange">Verify installation</span>
</button>

View File

@@ -52,16 +52,16 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
© 2024-{year} Ciphera. All rights reserved.
</div>
<div className="flex gap-6 text-sm font-medium text-neutral-600 dark:text-neutral-300">
<Component href="/about" className="hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Component href="/about" className="hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded">
Why {appName}
</Component>
<Component href="/changelog" className="hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Component href="/changelog" className="hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded">
Changelog
</Component>
<Component href="/pricing" className="hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Component href="/pricing" className="hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded">
Pricing
</Component>
<Component href="/faq" className="hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded">
<Component href="/faq" className="hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded">
FAQ
</Component>
</div>
@@ -106,7 +106,7 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
href="https://github.com/ciphera-net"
target="_blank"
rel="noopener noreferrer"
className="w-9 h-9 rounded-lg bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-200 dark:hover:bg-neutral-700 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange"
className="w-9 h-9 rounded-lg bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-200 dark:hover:bg-neutral-700 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange"
aria-label="GitHub"
>
<GithubIcon className="w-5 h-5" />
@@ -115,7 +115,7 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
href="https://x.com/cipheranet"
target="_blank"
rel="noopener noreferrer"
className="w-9 h-9 rounded-lg bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-200 dark:hover:bg-neutral-700 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange"
className="w-9 h-9 rounded-lg bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-200 dark:hover:bg-neutral-700 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange"
aria-label="X (Twitter)"
>
<TwitterIcon className="w-5 h-5" />
@@ -134,14 +134,14 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
href={link.href}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</a>
) : (
<Component
href={link.href}
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</Component>
@@ -162,14 +162,14 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
href={link.href}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</a>
) : (
<Component
href={link.href}
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</Component>
@@ -190,14 +190,14 @@ export function Footer({ LinkComponent = Link, appName = 'Pulse', isAuthenticate
href={link.href}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</a>
) : (
<Component
href={link.href}
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="text-sm text-neutral-600 dark:text-neutral-400 hover:text-brand-orange dark:hover:text-brand-orange transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus:rounded"
>
{link.name}
</Component>

View File

@@ -1,13 +1,13 @@
'use client';
import { FiWifiOff } from 'react-icons/fi';
import { WifiSlash } from '@phosphor-icons/react';
export function OfflineBanner({ isOnline }: { isOnline: boolean }) {
if (isOnline) return null;
return (
<div className="fixed top-0 left-0 right-0 z-[100] rounded-b-xl bg-yellow-500/15 dark:bg-yellow-500/25 border-b border-yellow-500/30 dark:border-yellow-500/40 text-yellow-700 dark:text-yellow-300 px-4 sm:px-8 py-2.5 text-sm flex items-center justify-center gap-2 font-medium shadow-md transition-shadow duration-300">
<FiWifiOff className="w-4 h-4 shrink-0" />
<WifiSlash className="w-4 h-4 shrink-0" />
<span>You are currently offline. Changes may not be saved.</span>
</div>
);

View File

@@ -267,7 +267,7 @@ export default function PricingSection() {
onClick={() => setIsYearly(false)}
role="radio"
aria-checked={!isYearly}
className={`min-w-[88px] px-4 py-2 rounded-lg text-sm font-medium transition-all focus:outline-none focus:ring-2 focus:ring-brand-orange ${
className={`min-w-[88px] px-4 py-2 rounded-lg text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${
!isYearly
? 'bg-white dark:bg-neutral-700 text-neutral-900 dark:text-white shadow-sm'
: 'text-neutral-500 hover:text-neutral-900 dark:hover:text-white'
@@ -279,7 +279,7 @@ export default function PricingSection() {
onClick={() => setIsYearly(true)}
role="radio"
aria-checked={isYearly}
className={`min-w-[88px] px-4 py-2 rounded-lg text-sm font-medium transition-all focus:outline-none focus:ring-2 focus:ring-brand-orange ${
className={`min-w-[88px] px-4 py-2 rounded-lg text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${
isYearly
? 'bg-white dark:bg-neutral-700 text-neutral-900 dark:text-white shadow-sm'
: 'text-neutral-500 hover:text-neutral-900 dark:hover:text-white'

View File

@@ -0,0 +1,12 @@
'use client'
import { SWRConfig } from 'swr'
import { boundedCacheProvider } from '@/lib/swr/cache-provider'
export default function SWRProvider({ children }: { children: React.ReactNode }) {
return (
<SWRConfig value={{ provider: boundedCacheProvider }}>
{children}
</SWRConfig>
)
}

323
components/charts/chart.tsx Normal file
View File

@@ -0,0 +1,323 @@
'use client'
import * as React from 'react'
import { Tooltip, Legend, ResponsiveContainer } from 'recharts'
import { cn } from '@ciphera-net/ui'
// ─── ChartConfig ────────────────────────────────────────────────────
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
color?: string
theme?: { light: string; dark: string }
}
>
// ─── ChartContext ───────────────────────────────────────────────────
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error('useChart must be used within a <ChartContainer />')
}
return context
}
// ─── ChartContainer ────────────────────────────────────────────────
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<'div'> & {
config: ChartConfig
children: React.ComponentProps<typeof ResponsiveContainer>['children']
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`
// Build CSS variables from config
const colorVars = React.useMemo(() => {
const vars: Record<string, string> = {}
for (const [key, value] of Object.entries(config)) {
if (value.color) {
vars[`--color-${key}`] = value.color
}
}
return vars
}, [config])
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"[&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-[var(--chart-grid)]",
"[&_.recharts-curve.recharts-tooltip-cursor]:stroke-[var(--chart-grid)]",
"[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-[var(--chart-grid)]",
"[&_.recharts-reference-line_[stroke='#ccc']]:stroke-[var(--chart-grid)]",
'[&_.recharts-sector]:outline-none',
'[&_.recharts-surface]:outline-none',
className,
)}
style={colorVars as React.CSSProperties}
{...props}
>
<ResponsiveContainer width="100%" height="100%">
{children}
</ResponsiveContainer>
</div>
</ChartContext.Provider>
)
})
ChartContainer.displayName = 'ChartContainer'
// ─── ChartTooltip ──────────────────────────────────────────────────
const ChartTooltip = Tooltip
// ─── ChartTooltipContent ───────────────────────────────────────────
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof Tooltip> &
React.ComponentProps<'div'> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: 'line' | 'dot' | 'dashed'
nameKey?: string
labelKey?: string
labelFormatter?: (value: string, payload: Record<string, unknown>[]) => React.ReactNode
}
>(
(
{
active,
payload,
className,
indicator = 'dot',
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelKey,
nameKey,
},
ref,
) => {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) return null
const item = payload[0]
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === 'string'
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return labelFormatter(
value as string,
payload as Record<string, unknown>[],
)
}
return value
}, [label, labelFormatter, payload, hideLabel, config, labelKey])
if (!active || !payload?.length) return null
const nestLabel = payload.length === 1 && indicator !== 'dot'
return (
<div
ref={ref}
className={cn(
'grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 px-2.5 py-1.5 text-xs shadow-xl',
className,
)}
>
{!nestLabel ? tooltipLabel ? (
<div className="font-medium text-neutral-900 dark:text-neutral-50">
{tooltipLabel}
</div>
) : null : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = item.fill || item.color
return (
<div
key={item.dataKey || index}
className={cn(
'flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground',
indicator === 'dot' && 'items-center',
)}
>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
'shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]',
indicator === 'dot' && 'h-2.5 w-2.5 rounded-full',
indicator === 'line' && 'w-1',
indicator === 'dashed' &&
'w-0 border-[1.5px] border-dashed bg-transparent',
nestLabel && indicator === 'dashed'
? 'my-0.5'
: 'my-0.5',
)}
style={
{
'--color-bg': indicatorColor,
'--color-border': indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
'flex flex-1 justify-between leading-none',
nestLabel ? 'items-end' : 'items-center',
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium tabular-nums text-neutral-900 dark:text-neutral-50">
{typeof item.value === 'number'
? item.value.toLocaleString()
: item.value}
</span>
)}
</div>
</div>
)
})}
</div>
</div>
)
},
)
ChartTooltipContent.displayName = 'ChartTooltipContent'
// ─── ChartLegend ───────────────────────────────────────────────────
const ChartLegend = Legend
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<'div'> &
Pick<React.ComponentProps<typeof Legend>, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean
nameKey?: string
}
>(
(
{ className, hideIcon = false, payload, verticalAlign = 'bottom', nameKey },
ref,
) => {
const { config } = useChart()
if (!payload?.length) return null
return (
<div
ref={ref}
className={cn(
'flex items-center justify-center gap-4',
verticalAlign === 'top' ? 'pb-3' : 'pt-3',
className,
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className="flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{ backgroundColor: item.color }}
/>
)}
<span className="text-xs text-muted-foreground">
{itemConfig?.label}
</span>
</div>
)
})}
</div>
)
},
)
ChartLegendContent.displayName = 'ChartLegendContent'
// ─── Helpers ───────────────────────────────────────────────────────
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string,
) {
if (typeof payload !== 'object' || payload === null) return undefined
const payloadPayload =
'payload' in payload &&
typeof (payload as Record<string, unknown>).payload === 'object' &&
(payload as Record<string, unknown>).payload !== null
? ((payload as Record<string, unknown>).payload as Record<string, unknown>)
: undefined
let configLabelKey = key
if (
key in config
) {
configLabelKey = key
} else if (payloadPayload) {
const payloadKey = Object.keys(payloadPayload).find(
(k) => payloadPayload[k] === key && k in config,
)
if (payloadKey) configLabelKey = payloadKey
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartContext,
useChart,
}

View File

@@ -0,0 +1,8 @@
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
type ChartConfig,
} from './chart'

View File

@@ -7,9 +7,10 @@ import Image from 'next/image'
import { formatNumber } from '@ciphera-net/ui'
import { Modal, ArrowRightIcon } from '@ciphera-net/ui'
import { ListSkeleton } from '@/components/skeletons'
import VirtualList from './VirtualList'
import { getCampaigns, CampaignStat } from '@/lib/api/stats'
import { getReferrerFavicon, getReferrerIcon, getReferrerDisplayName } from '@/lib/utils/icons'
import { FaBullhorn } from 'react-icons/fa'
import { Megaphone, FrameCornersIcon } from '@phosphor-icons/react'
import UtmBuilder from '@/components/tools/UtmBuilder'
import { type DimensionFilter } from '@/lib/filters'
@@ -26,6 +27,7 @@ export default function Campaigns({ siteId, dateRange, filters, onFilter }: Camp
const [data, setData] = useState<CampaignStat[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isModalOpen, setIsModalOpen] = useState(false)
const [modalSearch, setModalSearch] = useState('')
const [isBuilderOpen, setIsBuilderOpen] = useState(false)
const [fullData, setFullData] = useState<CampaignStat[]>([])
const [isLoadingFull, setIsLoadingFull] = useState(false)
@@ -124,9 +126,20 @@ export default function Campaigns({ siteId, dateRange, filters, onFilter }: Camp
<>
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Campaigns
</h3>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Campaigns
</h3>
{showViewAll && (
<button
onClick={() => setIsModalOpen(true)}
className="p-1.5 text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-all cursor-pointer rounded-lg"
aria-label="View all campaigns"
>
<FrameCornersIcon className="w-4 h-4" weight="bold" />
</button>
)}
</div>
<button
onClick={() => setIsBuilderOpen(true)}
className="text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer"
@@ -171,26 +184,14 @@ export default function Campaigns({ siteId, dateRange, filters, onFilter }: Camp
</div>
)
})}
{showViewAll ? (
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center justify-center gap-1.5 h-9 w-full text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer rounded-lg px-2 -mx-2"
>
View all
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
) : (
Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))
)}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
<div className="rounded-full bg-neutral-100 dark:bg-neutral-800 p-4">
<FaBullhorn className="w-8 h-8 text-neutral-500 dark:text-neutral-400" />
<Megaphone className="w-8 h-8 text-neutral-500 dark:text-neutral-400" />
</div>
<h4 className="font-semibold text-neutral-900 dark:text-white">
Track your marketing campaigns
@@ -200,7 +201,7 @@ export default function Campaigns({ siteId, dateRange, filters, onFilter }: Camp
</p>
<Link
href="/installation"
className="inline-flex items-center gap-2 text-sm font-medium text-brand-orange hover:text-brand-orange/90 hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange/20 rounded"
className="inline-flex items-center gap-2 text-sm font-medium text-brand-orange hover:text-brand-orange/90 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange/20 rounded"
>
Learn more
<ArrowRightIcon className="w-4 h-4" />
@@ -212,56 +213,80 @@ export default function Campaigns({ siteId, dateRange, filters, onFilter }: Camp
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
title="All Campaigns"
onClose={() => { setIsModalOpen(false); setModalSearch('') }}
title="Campaigns"
className="max-w-2xl"
>
<div className="space-y-1 max-h-[60vh] overflow-y-auto pr-2">
<div>
<input
type="text"
value={modalSearch}
onChange={(e) => setModalSearch(e.target.value)}
placeholder="Search campaigns..."
className="w-full px-3 py-2 mb-3 text-sm bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-lg text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-brand-orange/50"
/>
</div>
<div className="max-h-[80vh]">
{isLoadingFull ? (
<div className="py-4">
<ListSkeleton rows={10} />
</div>
) : (
<>
<div className="flex items-center justify-end mb-2">
<button
onClick={handleExportCampaigns}
className="text-xs font-medium text-neutral-400 hover:text-brand-orange transition-colors cursor-pointer"
>
Export CSV
</button>
</div>
{sortedFullData.map((item) => {
return (
<div
key={`${item.source}|${item.medium}|${item.campaign}`}
className="flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors"
) : (() => {
const filteredCampaigns = !modalSearch ? sortedFullData : sortedFullData.filter(item => {
const search = modalSearch.toLowerCase()
return item.source.toLowerCase().includes(search) || (item.medium || '').toLowerCase().includes(search) || (item.campaign || '').toLowerCase().includes(search)
})
const modalTotal = filteredCampaigns.reduce((sum, item) => sum + item.visitors, 0)
return (
<>
<div className="flex items-center justify-end mb-2">
<button
onClick={handleExportCampaigns}
className="text-xs font-medium text-neutral-400 hover:text-brand-orange transition-colors cursor-pointer"
>
<div className="flex-1 flex items-center gap-3 min-w-0">
{renderSourceIcon(item.source)}
<div className="min-w-0">
<div className="text-neutral-900 dark:text-white font-medium truncate text-sm" title={item.source}>
{getReferrerDisplayName(item.source)}
</div>
<div className="flex items-center gap-1.5 text-[11px] text-neutral-400 dark:text-neutral-500">
<span>{item.medium || '—'}</span>
<span>·</span>
<span className="truncate">{item.campaign || '—'}</span>
Export CSV
</button>
</div>
<VirtualList
items={filteredCampaigns}
estimateSize={36}
className="max-h-[80vh] overflow-y-auto pr-2"
renderItem={(item) => (
<div
key={`${item.source}|${item.medium}|${item.campaign}`}
onClick={() => { if (onFilter) { onFilter({ dimension: 'utm_source', operator: 'is', values: [item.source] }); setIsModalOpen(false) } }}
className={`flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 transition-colors${onFilter ? ' cursor-pointer' : ''}`}
>
<div className="flex-1 flex items-center gap-3 min-w-0">
{renderSourceIcon(item.source)}
<div className="min-w-0">
<div className="text-neutral-900 dark:text-white font-medium truncate text-sm" title={item.source}>
{getReferrerDisplayName(item.source)}
</div>
<div className="flex items-center gap-1.5 text-[11px] text-neutral-400 dark:text-neutral-500">
<span>{item.medium || '—'}</span>
<span>·</span>
<span className="truncate">{item.campaign || '—'}</span>
</div>
</div>
</div>
<div className="flex items-center gap-4 ml-4 text-sm">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{modalTotal > 0 ? `${Math.round((item.visitors / modalTotal) * 100)}%` : ''}
</span>
<span className="font-semibold text-neutral-900 dark:text-white">
{formatNumber(item.visitors)}
</span>
<span className="text-neutral-400 dark:text-neutral-500 w-16 text-right">
{formatNumber(item.pageviews)} pv
</span>
</div>
</div>
<div className="flex items-center gap-4 ml-4 text-sm">
<span className="font-semibold text-neutral-900 dark:text-white">
{formatNumber(item.visitors)}
</span>
<span className="text-neutral-400 dark:text-neutral-500 w-16 text-right">
{formatNumber(item.pageviews)} pv
</span>
</div>
</div>
)
})}
</>
)}
)}
/>
</>
)
})()}
</div>
</Modal>

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,15 @@
'use client'
import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { logger } from '@/lib/utils/logger'
import { formatNumber } from '@ciphera-net/ui'
import { useTabListKeyboard } from '@/lib/hooks/useTabListKeyboard'
import { TopPage, getTopPages, getEntryPages, getExitPages } from '@/lib/api/stats'
import { FrameCornersIcon } from '@phosphor-icons/react'
import { Modal, ArrowUpRightIcon, LayoutDashboardIcon } from '@ciphera-net/ui'
import { ListSkeleton } from '@/components/skeletons'
import VirtualList from './VirtualList'
import { type DimensionFilter } from '@/lib/filters'
interface ContentStatsProps {
@@ -28,6 +31,7 @@ export default function ContentStats({ topPages, entryPages, exitPages, domain,
const [activeTab, setActiveTab] = useState<Tab>('top_pages')
const handleTabKeyDown = useTabListKeyboard()
const [isModalOpen, setIsModalOpen] = useState(false)
const [modalSearch, setModalSearch] = useState('')
const [fullData, setFullData] = useState<TopPage[]>([])
const [isLoadingFull, setIsLoadingFull] = useState(false)
@@ -96,9 +100,20 @@ export default function ContentStats({ topPages, entryPages, exitPages, domain,
<>
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Pages
</h3>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Pages
</h3>
{showViewAll && (
<button
onClick={() => setIsModalOpen(true)}
className="p-1.5 text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-all cursor-pointer rounded-lg"
aria-label="View all pages"
>
<FrameCornersIcon className="w-4 h-4" weight="bold" />
</button>
)}
</div>
<div className="flex gap-1" role="tablist" aria-label="Pages view tabs" onKeyDown={handleTabKeyDown}>
{(['top_pages', 'entry_pages', 'exit_pages'] as Tab[]).map((tab) => (
<button
@@ -106,13 +121,20 @@ export default function ContentStats({ topPages, entryPages, exitPages, domain,
onClick={() => setActiveTab(tab)}
role="tab"
aria-selected={activeTab === tab}
className={`px-2.5 py-1 text-xs font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange rounded cursor-pointer border-b-2 ${
className={`relative px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded cursor-pointer ${
activeTab === tab
? 'border-brand-orange text-neutral-900 dark:text-white'
: 'border-transparent text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
? 'text-neutral-900 dark:text-white'
: 'text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
}`}
>
{getTabLabel(tab)}
{activeTab === tab && (
<motion.div
layoutId="contentStatsTab"
className="absolute inset-x-0 -bottom-px h-0.5 bg-brand-orange"
transition={{ type: 'spring', stiffness: 500, damping: 35 }}
/>
)}
</button>
))}
</div>
@@ -153,21 +175,9 @@ export default function ContentStats({ topPages, entryPages, exitPages, domain,
</div>
</div>
))}
{showViewAll ? (
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center justify-center gap-1.5 h-9 w-full text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer rounded-lg px-2 -mx-2"
>
View all
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
) : (
Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))
)}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
@@ -187,34 +197,57 @@ export default function ContentStats({ topPages, entryPages, exitPages, domain,
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
title={`Pages - ${getTabLabel(activeTab)}`}
onClose={() => { setIsModalOpen(false); setModalSearch('') }}
title={getTabLabel(activeTab)}
className="max-w-2xl"
>
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-2">
<div>
<input
type="text"
value={modalSearch}
onChange={(e) => setModalSearch(e.target.value)}
placeholder="Search pages..."
className="w-full px-3 py-2 mb-3 text-sm bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-lg text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-brand-orange/50"
/>
</div>
<div className="max-h-[80vh]">
{isLoadingFull ? (
<div className="py-4">
<ListSkeleton rows={10} />
</div>
) : (
(fullData.length > 0 ? fullData : data).map((page) => (
<div key={page.path} className="flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors">
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center">
<a
href={`https://${domain.replace(/^https?:\/\//, '')}${page.path}`}
target="_blank"
rel="noopener noreferrer"
className="hover:underline flex items-center"
>
{page.path}
<ArrowUpRightIcon className="w-3 h-3 ml-2 text-neutral-400 opacity-0 group-hover:opacity-100 transition-opacity" />
</a>
</div>
<div className="text-sm font-semibold text-neutral-600 dark:text-neutral-400 ml-4">
{formatNumber(page.pageviews)}
</div>
</div>
))
)}
) : (() => {
const modalData = (fullData.length > 0 ? fullData : data).filter(p => !modalSearch || p.path.toLowerCase().includes(modalSearch.toLowerCase()))
const modalTotal = modalData.reduce((sum, p) => sum + p.pageviews, 0)
return (
<VirtualList
items={modalData}
estimateSize={36}
className="max-h-[80vh] overflow-y-auto pr-2"
renderItem={(page) => {
const canFilter = onFilter && page.path
return (
<div
key={page.path}
onClick={() => { if (canFilter) { onFilter({ dimension: 'page', operator: 'is', values: [page.path] }); setIsModalOpen(false) } }}
className={`flex items-center justify-between h-9 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 transition-colors${canFilter ? ' cursor-pointer' : ''}`}
>
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center">
<span className="truncate">{page.path}</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{modalTotal > 0 ? `${Math.round((page.pageviews / modalTotal) * 100)}%` : ''}
</span>
<span className="text-sm font-semibold text-neutral-600 dark:text-neutral-400">
{formatNumber(page.pageviews)}
</span>
</div>
</div>
)
}}
/>
)
})()}
</div>
</Modal>
</>

View File

@@ -0,0 +1,160 @@
'use client'
import { useMemo, useState } from 'react'
import { createMap } from 'svg-dotted-map'
import { cn, formatNumber } from '@ciphera-net/ui'
import { countryCentroids } from '@/lib/country-centroids'
// ─── Module-level constants ────────────────────────────────────────
// Computed once when the module loads, survives component unmount/remount.
const MAP_WIDTH = 150
const MAP_HEIGHT = 68
const DOT_RADIUS = 0.25
const { points: MAP_POINTS, addMarkers } = createMap({ width: MAP_WIDTH, height: MAP_HEIGHT, mapSamples: 8000 })
// Pre-compute stagger helpers (row offsets for hex-grid pattern)
const _stagger = (() => {
const sorted = [...MAP_POINTS].sort((a, b) => a.y - b.y || a.x - b.x)
const rowMap = new Map<number, number>()
let step = 0
let prevY = Number.NaN
let prevXInRow = Number.NaN
for (const p of sorted) {
if (p.y !== prevY) {
prevY = p.y
prevXInRow = Number.NaN
if (!rowMap.has(p.y)) rowMap.set(p.y, rowMap.size)
}
if (!Number.isNaN(prevXInRow)) {
const delta = p.x - prevXInRow
if (delta > 0) step = step === 0 ? delta : Math.min(step, delta)
}
prevXInRow = p.x
}
return { xStep: step || 1, yToRowIndex: rowMap }
})()
// Pre-compute the base map dots as a single SVG path string (~8000 circles → 1 path)
const BASE_DOTS_PATH = (() => {
const r = DOT_RADIUS
const d = r * 2
const parts: string[] = []
for (const point of MAP_POINTS) {
const rowIndex = _stagger.yToRowIndex.get(point.y) ?? 0
const offsetX = rowIndex % 2 === 1 ? _stagger.xStep / 2 : 0
const cx = point.x + offsetX
const cy = point.y
parts.push(`M${cx - r},${cy}a${r},${r} 0 1,0 ${d},0a${r},${r} 0 1,0 ${-d},0`)
}
return parts.join('')
})()
// ─── Component ─────────────────────────────────────────────────────
interface DottedMapProps {
data: Array<{ country: string; pageviews: number }>
className?: string
}
function getCountryName(code: string): string {
try {
const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
return regionNames.of(code) || code
} catch {
return code
}
}
export default function DottedMap({ data, className }: DottedMapProps) {
const [tooltip, setTooltip] = useState<{ x: number; y: number; country: string; pageviews: number } | null>(null)
const markerData = useMemo(() => {
if (!data.length) return []
const max = Math.max(...data.map((d) => d.pageviews))
if (max === 0) return []
return data
.filter((d) => d.country && d.country !== 'Unknown' && countryCentroids[d.country])
.map((d) => ({
lat: countryCentroids[d.country].lat,
lng: countryCentroids[d.country].lng,
size: 0.4 + (d.pageviews / max) * 0.8,
country: d.country,
pageviews: d.pageviews,
}))
}, [data])
const processedMarkers = useMemo(
() => addMarkers(markerData.map((d) => ({ lat: d.lat, lng: d.lng, size: d.size }))),
[markerData],
)
return (
<div className="relative w-full h-full flex items-center justify-center">
<svg
viewBox={`0 0 ${MAP_WIDTH} ${MAP_HEIGHT}`}
className={cn('text-neutral-400 dark:text-neutral-500', className)}
style={{ width: '100%', height: '100%' }}
>
<defs>
<filter id="marker-glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="0.8" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 0.4 0 0 0 0 0 0 0 0 0 0 0 0.6 0" />
<feMerge>
<feMergeNode />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<path
d={BASE_DOTS_PATH}
fill="currentColor"
/>
{processedMarkers.map((marker, index) => {
const rowIndex = _stagger.yToRowIndex.get(marker.y) ?? 0
const offsetX = rowIndex % 2 === 1 ? _stagger.xStep / 2 : 0
const info = markerData[index]
return (
<circle
cx={marker.x + offsetX}
cy={marker.y}
r={marker.size ?? DOT_RADIUS}
fill="#FD5E0F"
filter="url(#marker-glow)"
className="cursor-pointer"
key={`marker-${marker.x}-${marker.y}-${index}`}
onMouseEnter={(e) => {
if (info) {
const rect = (e.target as SVGCircleElement).closest('svg')!.getBoundingClientRect()
const svgX = marker.x + offsetX
const svgY = marker.y
setTooltip({
x: rect.left + (svgX / MAP_WIDTH) * rect.width,
y: rect.top + (svgY / MAP_HEIGHT) * rect.height,
country: info.country,
pageviews: info.pageviews,
})
}
}}
onMouseLeave={() => setTooltip(null)}
/>
)
})}
</svg>
{tooltip && (
<div
className="fixed z-50 px-2.5 py-1.5 text-xs font-medium text-white bg-neutral-900 dark:bg-neutral-800 border border-neutral-700 rounded-lg shadow-lg pointer-events-none -translate-x-1/2 -translate-y-full -mt-2"
style={{ left: tooltip.x, top: tooltip.y }}
>
<span>{getCountryName(tooltip.country)}</span>
<span className="ml-1.5 text-brand-orange font-bold">{formatNumber(tooltip.pageviews)}</span>
</div>
)}
</div>
)
}

View File

@@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useState, useCallback } from 'react'
import { Modal, Button, Checkbox, Input, Select } from '@ciphera-net/ui'
import * as XLSX from 'xlsx'
import jsPDF from 'jspdf'
@@ -49,6 +49,7 @@ export default function ExportModal({ isOpen, onClose, data, stats, topPages, to
const [format, setFormat] = useState<ExportFormat>('csv')
const [filename, setFilename] = useState(`pulse_export_${new Date().toISOString().split('T')[0]}`)
const [includeHeader, setIncludeHeader] = useState(true)
const [isExporting, setIsExporting] = useState(false)
const [selectedFields, setSelectedFields] = useState<Record<keyof DailyStat, boolean>>({
date: true,
pageviews: true,
@@ -61,300 +62,312 @@ export default function ExportModal({ isOpen, onClose, data, stats, topPages, to
setSelectedFields((prev) => ({ ...prev, [field]: checked }))
}
const handleExport = async () => {
// Filter fields
const fields = (Object.keys(selectedFields) as Array<keyof DailyStat>).filter((k) => selectedFields[k])
// Prepare data
const exportData = data.map((item) => {
const filteredItem: Record<string, string | number> = {}
fields.forEach((field) => {
filteredItem[field] = item[field]
})
return filteredItem
})
const handleExport = () => {
setIsExporting(true)
// Let the browser paint the loading state before starting heavy work
requestAnimationFrame(() => {
setTimeout(async () => {
try {
// Filter fields
const fields = (Object.keys(selectedFields) as Array<keyof DailyStat>).filter((k) => selectedFields[k])
let content = ''
let mimeType = ''
let extension = ''
// Prepare data
const exportData = data.map((item) => {
const filteredItem: Record<string, string | number> = {}
fields.forEach((field) => {
filteredItem[field] = item[field]
})
return filteredItem
})
if (format === 'csv') {
const header = fields.join(',')
const rows = exportData.map((row) =>
fields.map((field) => {
const val = row[field]
if (field === 'date' && typeof val === 'string') {
return new Date(val).toISOString()
let content = ''
let mimeType = ''
let extension = ''
if (format === 'csv') {
const header = fields.join(',')
const rows = exportData.map((row) =>
fields.map((field) => {
const val = row[field]
if (field === 'date' && typeof val === 'string') {
return new Date(val).toISOString()
}
return val
}).join(',')
)
content = (includeHeader ? header + '\n' : '') + rows.join('\n')
mimeType = 'text/csv;charset=utf-8;'
extension = 'csv'
} else if (format === 'xlsx') {
const ws = XLSX.utils.json_to_sheet(exportData)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, 'Data')
if (campaigns && campaigns.length > 0) {
const campaignsSheet = XLSX.utils.json_to_sheet(
campaigns.map(c => ({
Source: getReferrerDisplayName(c.source),
Medium: c.medium || '—',
Campaign: c.campaign || '—',
Visitors: c.visitors,
Pageviews: c.pageviews,
}))
)
XLSX.utils.book_append_sheet(wb, campaignsSheet, 'Campaigns')
}
return val
}).join(',')
)
content = (includeHeader ? header + '\n' : '') + rows.join('\n')
mimeType = 'text/csv;charset=utf-8;'
extension = 'csv'
} else if (format === 'xlsx') {
const ws = XLSX.utils.json_to_sheet(exportData)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, 'Data')
if (campaigns && campaigns.length > 0) {
const campaignsSheet = XLSX.utils.json_to_sheet(
campaigns.map(c => ({
Source: getReferrerDisplayName(c.source),
Medium: c.medium || '—',
Campaign: c.campaign || '—',
Visitors: c.visitors,
Pageviews: c.pageviews,
}))
)
XLSX.utils.book_append_sheet(wb, campaignsSheet, 'Campaigns')
}
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
const blob = new Blob([wbout], { type: 'application/octet-stream' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', url)
link.setAttribute('download', `${filename || 'export'}.${extension || 'xlsx'}`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
onClose()
return
} else if (format === 'pdf') {
const doc = new jsPDF()
// Header Section
try {
// Logo
const logoData = await loadImage('/pulse_icon_no_margins.png')
doc.addImage(logoData, 'PNG', 14, 12, 12, 12) // x, y, w, h
// Title
doc.setFontSize(22)
doc.setTextColor(249, 115, 22) // Brand Orange #F97316
doc.text('Pulse', 32, 20)
doc.setFontSize(12)
doc.setTextColor(100, 100, 100)
doc.text('Analytics Export', 32, 25)
} catch (e) {
// Fallback if logo fails
doc.setFontSize(22)
doc.setTextColor(249, 115, 22)
doc.text('Pulse Analytics', 14, 20)
}
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
const blob = new Blob([wbout], { type: 'application/octet-stream' })
// Metadata (Top Right)
doc.setFontSize(9)
doc.setTextColor(150, 150, 150)
const generatedDate = new Date().toLocaleDateString()
const dateRange = data.length > 0
? `${new Date(data[0].date).toLocaleDateString()} - ${new Date(data[data.length - 1].date).toLocaleDateString()}`
: generatedDate
const pageWidth = doc.internal.pageSize.width
doc.text(`Generated: ${generatedDate}`, pageWidth - 14, 18, { align: 'right' })
doc.text(`Range: ${dateRange}`, pageWidth - 14, 23, { align: 'right' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', url)
link.setAttribute('download', `${filename || 'export'}.${extension || 'xlsx'}`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
onClose()
return
} else if (format === 'pdf') {
const doc = new jsPDF()
let startY = 35
// Header Section
try {
// Logo
const logoData = await loadImage('/pulse_icon_no_margins.png')
doc.addImage(logoData, 'PNG', 14, 12, 12, 12) // x, y, w, h
// Summary Section
if (stats) {
const summaryY = 35
const cardWidth = (pageWidth - 28 - 15) / 4 // 4 cards with 5mm gap
const cardHeight = 20
const drawCard = (x: number, label: string, value: string) => {
doc.setFillColor(255, 247, 237) // Very light orange
doc.setDrawColor(254, 215, 170) // Light orange border
doc.roundedRect(x, summaryY, cardWidth, cardHeight, 2, 2, 'FD')
doc.setFontSize(8)
// Title
doc.setFontSize(22)
doc.setTextColor(249, 115, 22) // Brand Orange #F97316
doc.text('Pulse', 32, 20)
doc.setFontSize(12)
doc.setTextColor(100, 100, 100)
doc.text('Analytics Export', 32, 25)
} catch (e) {
// Fallback if logo fails
doc.setFontSize(22)
doc.setTextColor(249, 115, 22)
doc.text('Pulse Analytics', 14, 20)
}
// Metadata (Top Right)
doc.setFontSize(9)
doc.setTextColor(150, 150, 150)
doc.text(label, x + 3, summaryY + 6)
doc.setFontSize(12)
doc.setTextColor(23, 23, 23) // Neutral 900
doc.setFont('helvetica', 'bold')
doc.text(value, x + 3, summaryY + 14)
doc.setFont('helvetica', 'normal')
}
const generatedDate = new Date().toLocaleDateString()
const dateRange = data.length > 0
? `${new Date(data[0].date).toLocaleDateString()} - ${new Date(data[data.length - 1].date).toLocaleDateString()}`
: generatedDate
drawCard(14, 'Unique Visitors', formatNumber(stats.visitors))
drawCard(14 + cardWidth + 5, 'Total Pageviews', formatNumber(stats.pageviews))
drawCard(14 + (cardWidth + 5) * 2, 'Bounce Rate', `${Math.round(stats.bounce_rate)}%`)
drawCard(14 + (cardWidth + 5) * 3, 'Avg Duration', formatDuration(stats.avg_duration))
startY = 65 // Move table down
}
const pageWidth = doc.internal.pageSize.width
doc.text(`Generated: ${generatedDate}`, pageWidth - 14, 18, { align: 'right' })
doc.text(`Range: ${dateRange}`, pageWidth - 14, 23, { align: 'right' })
// Check if data is hourly (same date for multiple rows)
const isHourly = data.length > 1 && data[0].date.split('T')[0] === data[1].date.split('T')[0]
let startY = 35
const tableData = exportData.map(row =>
fields.map(field => {
const val = row[field]
if (field === 'date' && typeof val === 'string') {
const date = new Date(val)
return isHourly
? date.toLocaleString('en-US', { month: 'numeric', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' })
: date.toLocaleDateString()
// Summary Section
if (stats) {
const summaryY = 35
const cardWidth = (pageWidth - 28 - 15) / 4 // 4 cards with 5mm gap
const cardHeight = 20
const drawCard = (x: number, label: string, value: string) => {
doc.setFillColor(255, 247, 237) // Very light orange
doc.setDrawColor(254, 215, 170) // Light orange border
doc.roundedRect(x, summaryY, cardWidth, cardHeight, 2, 2, 'FD')
doc.setFontSize(8)
doc.setTextColor(150, 150, 150)
doc.text(label, x + 3, summaryY + 6)
doc.setFontSize(12)
doc.setTextColor(23, 23, 23) // Neutral 900
doc.setFont('helvetica', 'bold')
doc.text(value, x + 3, summaryY + 14)
doc.setFont('helvetica', 'normal')
}
drawCard(14, 'Unique Visitors', formatNumber(stats.visitors))
drawCard(14 + cardWidth + 5, 'Total Pageviews', formatNumber(stats.pageviews))
drawCard(14 + (cardWidth + 5) * 2, 'Bounce Rate', `${Math.round(stats.bounce_rate)}%`)
drawCard(14 + (cardWidth + 5) * 3, 'Avg Duration', formatDuration(stats.avg_duration))
startY = 65 // Move table down
}
// Check if data is hourly (same date for multiple rows)
const isHourly = data.length > 1 && data[0].date.split('T')[0] === data[1].date.split('T')[0]
const tableData = exportData.map(row =>
fields.map(field => {
const val = row[field]
if (field === 'date' && typeof val === 'string') {
const date = new Date(val)
return isHourly
? date.toLocaleString('en-US', { month: 'numeric', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' })
: date.toLocaleDateString()
}
if (typeof val === 'number') {
if (field === 'bounce_rate') return `${Math.round(val)}%`
if (field === 'avg_duration') return formatDuration(val)
if (field === 'pageviews' || field === 'visitors') return formatNumber(val)
}
return val ?? ''
})
)
autoTable(doc, {
startY: startY,
head: [fields.map(f => f.charAt(0).toUpperCase() + f.slice(1).replace('_', ' '))],
body: tableData as (string | number)[][],
styles: {
font: 'helvetica',
fontSize: 9,
cellPadding: 4,
lineColor: [229, 231, 235], // Neutral 200
lineWidth: 0.1,
},
headStyles: {
fillColor: [249, 115, 22], // Brand Orange
textColor: [255, 255, 255],
fontStyle: 'bold',
halign: 'left'
},
columnStyles: {
0: { halign: 'left' }, // Date
1: { halign: 'right' }, // Pageviews
2: { halign: 'right' }, // Visitors
3: { halign: 'right' }, // Bounce Rate
4: { halign: 'right' }, // Avg Duration
},
alternateRowStyles: {
fillColor: [255, 250, 245], // Very very light orange
},
didDrawPage: (data) => {
// Footer
const pageSize = doc.internal.pageSize
const pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight()
doc.setFontSize(8)
doc.setTextColor(150, 150, 150)
doc.text('Powered by Ciphera', 14, pageHeight - 10)
const str = 'Page ' + doc.getNumberOfPages()
doc.text(str, pageSize.width - 14, pageHeight - 10, { align: 'right' })
}
})
let finalY = doc.lastAutoTable.finalY + 10
// Top Pages Table
if (topPages && topPages.length > 0) {
// Check if we need a new page
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Top Pages', 14, finalY)
finalY += 5
const pagesData = topPages.slice(0, 10).map(p => [p.path, formatNumber(p.pageviews)])
autoTable(doc, {
startY: finalY,
head: [['Path', 'Pageviews']],
body: pagesData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 1: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
finalY = doc.lastAutoTable.finalY + 10
}
// Top Referrers Table
if (topReferrers && topReferrers.length > 0) {
// Check if we need a new page
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Top Referrers', 14, finalY)
finalY += 5
const mergedReferrers = mergeReferrersByDisplayName(topReferrers)
const referrersData = mergedReferrers.slice(0, 10).map(r => [getReferrerDisplayName(r.referrer), formatNumber(r.pageviews)])
autoTable(doc, {
startY: finalY,
head: [['Referrer', 'Pageviews']],
body: referrersData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 1: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
finalY = doc.lastAutoTable.finalY + 10
}
// Campaigns Table
if (campaigns && campaigns.length > 0) {
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Campaigns', 14, finalY)
finalY += 5
const campaignsData = campaigns.slice(0, 10).map(c => [
getReferrerDisplayName(c.source),
c.medium || '—',
c.campaign || '—',
formatNumber(c.visitors),
formatNumber(c.pageviews),
])
autoTable(doc, {
startY: finalY,
head: [['Source', 'Medium', 'Campaign', 'Visitors', 'Pageviews']],
body: campaignsData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 3: { halign: 'right' }, 4: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
}
doc.save(`${filename || 'export'}.pdf`)
onClose()
return
} else {
content = JSON.stringify(exportData, null, 2)
mimeType = 'application/json;charset=utf-8;'
extension = 'json'
}
if (typeof val === 'number') {
if (field === 'bounce_rate') return `${Math.round(val)}%`
if (field === 'avg_duration') return formatDuration(val)
if (field === 'pageviews' || field === 'visitors') return formatNumber(val)
}
return val ?? ''
})
)
autoTable(doc, {
startY: startY,
head: [fields.map(f => f.charAt(0).toUpperCase() + f.slice(1).replace('_', ' '))],
body: tableData as (string | number)[][],
styles: {
font: 'helvetica',
fontSize: 9,
cellPadding: 4,
lineColor: [229, 231, 235], // Neutral 200
lineWidth: 0.1,
},
headStyles: {
fillColor: [249, 115, 22], // Brand Orange
textColor: [255, 255, 255],
fontStyle: 'bold',
halign: 'left'
},
columnStyles: {
0: { halign: 'left' }, // Date
1: { halign: 'right' }, // Pageviews
2: { halign: 'right' }, // Visitors
3: { halign: 'right' }, // Bounce Rate
4: { halign: 'right' }, // Avg Duration
},
alternateRowStyles: {
fillColor: [255, 250, 245], // Very very light orange
},
didDrawPage: (data) => {
// Footer
const pageSize = doc.internal.pageSize
const pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight()
doc.setFontSize(8)
doc.setTextColor(150, 150, 150)
doc.text('Powered by Ciphera', 14, pageHeight - 10)
const str = 'Page ' + doc.getNumberOfPages()
doc.text(str, pageSize.width - 14, pageHeight - 10, { align: 'right' })
const blob = new Blob([content], { type: mimeType })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', url)
link.setAttribute('download', `${filename || 'export'}.${extension}`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
onClose()
} catch (e) {
console.error('Export failed:', e)
} finally {
setIsExporting(false)
}
})
let finalY = doc.lastAutoTable.finalY + 10
// Top Pages Table
if (topPages && topPages.length > 0) {
// Check if we need a new page
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Top Pages', 14, finalY)
finalY += 5
const pagesData = topPages.slice(0, 10).map(p => [p.path, formatNumber(p.pageviews)])
autoTable(doc, {
startY: finalY,
head: [['Path', 'Pageviews']],
body: pagesData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 1: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
finalY = doc.lastAutoTable.finalY + 10
}
// Top Referrers Table
if (topReferrers && topReferrers.length > 0) {
// Check if we need a new page
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Top Referrers', 14, finalY)
finalY += 5
const mergedReferrers = mergeReferrersByDisplayName(topReferrers)
const referrersData = mergedReferrers.slice(0, 10).map(r => [getReferrerDisplayName(r.referrer), formatNumber(r.pageviews)])
autoTable(doc, {
startY: finalY,
head: [['Referrer', 'Pageviews']],
body: referrersData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 1: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
finalY = doc.lastAutoTable.finalY + 10
}
// Campaigns Table
if (campaigns && campaigns.length > 0) {
if (finalY + 40 > doc.internal.pageSize.height) {
doc.addPage()
finalY = 20
}
doc.setFontSize(14)
doc.setTextColor(23, 23, 23)
doc.text('Campaigns', 14, finalY)
finalY += 5
const campaignsData = campaigns.slice(0, 10).map(c => [
getReferrerDisplayName(c.source),
c.medium || '—',
c.campaign || '—',
formatNumber(c.visitors),
formatNumber(c.pageviews),
])
autoTable(doc, {
startY: finalY,
head: [['Source', 'Medium', 'Campaign', 'Visitors', 'Pageviews']],
body: campaignsData,
styles: { font: 'helvetica', fontSize: 9, cellPadding: 3 },
headStyles: { fillColor: [249, 115, 22], textColor: [255, 255, 255], fontStyle: 'bold' },
columnStyles: { 3: { halign: 'right' }, 4: { halign: 'right' } },
alternateRowStyles: { fillColor: [255, 250, 245] },
})
}
doc.save(`${filename || 'export'}.pdf`)
onClose()
return
} else {
content = JSON.stringify(exportData, null, 2)
mimeType = 'application/json;charset=utf-8;'
extension = 'json'
}
const blob = new Blob([content], { type: mimeType })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', url)
link.setAttribute('download', `${filename || 'export'}.${extension}`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
onClose()
}, 0)
})
}
return (
@@ -440,11 +453,11 @@ export default function ExportModal({ isOpen, onClose, data, stats, topPages, to
{/* Actions */}
<div className="flex justify-end gap-3 pt-4">
<Button variant="secondary" onClick={onClose}>
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
Cancel
</Button>
<Button variant="primary" onClick={handleExport}>
Export Data
<Button variant="primary" onClick={handleExport} disabled={isExporting}>
{isExporting ? 'Exporting...' : 'Export Data'}
</Button>
</div>
</div>

View File

@@ -0,0 +1,113 @@
'use client'
import { useEffect, useMemo, useRef } from 'react'
import createGlobe from 'cobe'
import { useTheme } from '@ciphera-net/ui'
import { countryCentroids } from '@/lib/country-centroids'
interface GlobeProps {
data: Array<{ country: string; pageviews: number }>
className?: string
}
export default function Globe({ data, className }: GlobeProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const phiRef = useRef(0)
const dragRef = useRef(0)
const pointerRef = useRef<number | null>(null)
const { resolvedTheme } = useTheme()
const isDarkRef = useRef(resolvedTheme === 'dark')
const markersRef = useRef<Array<{ location: [number, number]; size: number }>>([])
// Update refs without causing effect re-runs
isDarkRef.current = resolvedTheme === 'dark'
// Compute markers into ref (memoized to avoid recalculating on every render)
const markers = useMemo(() => {
const max = data.length ? Math.max(...data.map((d) => d.pageviews)) : 0
return max > 0
? data
.filter((d) => d.country && d.country !== 'Unknown' && countryCentroids[d.country])
.map((d) => ({
location: [countryCentroids[d.country].lat, countryCentroids[d.country].lng] as [number, number],
size: 0.03 + (d.pageviews / max) * 0.12,
}))
: []
}, [data])
markersRef.current = markers
useEffect(() => {
if (!canvasRef.current) return
const size = canvasRef.current.offsetWidth
const pixelRatio = Math.min(window.devicePixelRatio, 2)
const isDark = isDarkRef.current
const globe = createGlobe(canvasRef.current, {
width: size * pixelRatio,
height: size * pixelRatio,
devicePixelRatio: pixelRatio,
phi: phiRef.current,
theta: 0.3,
dark: isDark ? 1 : 0,
diffuse: isDark ? 2 : 0.4,
mapSamples: 16000,
mapBrightness: isDark ? 2 : 1.2,
baseColor: isDark ? [0.5, 0.5, 0.5] : [1, 1, 1],
markerColor: [253 / 255, 94 / 255, 15 / 255],
glowColor: isDark ? [0.15, 0.15, 0.15] : [1, 1, 1],
markers: markersRef.current,
onRender: (state) => {
if (!pointerRef.current) phiRef.current += 0.002
state.phi = phiRef.current + dragRef.current
},
})
setTimeout(() => {
if (canvasRef.current) canvasRef.current.style.opacity = '1'
}, 0)
return () => { globe.destroy() }
// Only recreate on theme change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [resolvedTheme])
return (
<div className={`relative w-full h-full overflow-hidden ${className ?? ''}`}>
<div className="absolute left-1/2 -translate-x-1/2 top-0 aspect-square w-[130%]">
<canvas
className="size-full opacity-0 transition-opacity duration-500"
style={{ contain: 'layout paint size' }}
ref={canvasRef}
onPointerDown={(e) => {
pointerRef.current = e.clientX
canvasRef.current!.style.cursor = 'grabbing'
}}
onPointerUp={() => {
pointerRef.current = null
canvasRef.current!.style.cursor = 'grab'
}}
onPointerOut={() => {
pointerRef.current = null
if (canvasRef.current) canvasRef.current.style.cursor = 'grab'
}}
onMouseMove={(e) => {
if (pointerRef.current !== null) {
const delta = e.clientX - pointerRef.current
dragRef.current += delta / 800
pointerRef.current = e.clientX
}
}}
onTouchMove={(e) => {
if (pointerRef.current !== null && e.touches[0]) {
const delta = e.touches[0].clientX - pointerRef.current
dragRef.current += delta / 800
pointerRef.current = e.touches[0].clientX
}
}}
/>
</div>
<div className="pointer-events-none absolute inset-0 h-full bg-[radial-gradient(circle_at_50%_200%,rgba(0,0,0,0.2),rgba(255,255,255,0))]" />
</div>
)
}

View File

@@ -15,6 +15,8 @@ const LIMIT = 10
export default function GoalStats({ goalCounts, onSelectEvent }: GoalStatsProps) {
const list = (goalCounts || []).slice(0, LIMIT)
const hasData = list.length > 0
const total = list.reduce((sum, r) => sum + r.count, 0)
const emptySlots = Math.max(0, 6 - list.length)
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
@@ -25,24 +27,34 @@ export default function GoalStats({ goalCounts, onSelectEvent }: GoalStatsProps)
</div>
{hasData ? (
<div className="space-y-2 flex-1 min-h-[200px]">
<div className="flex-1 min-h-[270px]">
{list.map((row) => (
<div
key={row.event_name}
onClick={() => onSelectEvent?.(row.event_name)}
className={`flex items-center justify-between py-2 px-3 rounded-lg bg-neutral-50 dark:bg-neutral-800/50 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors${onSelectEvent ? ' cursor-pointer' : ''}`}
className={`flex items-center justify-between h-9 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors${onSelectEvent ? ' cursor-pointer' : ''}`}
>
<span className="text-sm font-medium text-neutral-900 dark:text-white truncate">
{row.display_name ?? row.event_name.replace(/_/g, ' ')}
</span>
<span className="text-sm font-semibold text-brand-orange tabular-nums">
{formatNumber(row.count)}
</span>
<div className="flex items-center flex-1 min-w-0">
<span className="text-sm font-medium text-neutral-900 dark:text-white truncate">
{row.display_name ?? row.event_name.replace(/_/g, ' ')}
</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{total > 0 ? `${Math.round((row.count / total) * 100)}%` : ''}
</span>
<span className="text-sm font-semibold text-neutral-600 dark:text-neutral-400 tabular-nums">
{formatNumber(row.count)}
</span>
</div>
</div>
))}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</div>
) : (
<div className="flex-1 min-h-[200px] flex flex-col items-center justify-center text-center px-6 py-8 gap-4">
<div className="flex-1 min-h-[270px] flex flex-col items-center justify-center text-center px-6 py-8 gap-4">
<div className="rounded-full bg-neutral-100 dark:bg-neutral-800 p-4">
<BookOpenIcon className="w-8 h-8 text-neutral-500 dark:text-neutral-400" />
</div>
@@ -54,7 +66,7 @@ export default function GoalStats({ goalCounts, onSelectEvent }: GoalStatsProps)
</p>
<Link
href="/installation"
className="inline-flex items-center gap-2 text-sm font-medium text-brand-orange hover:text-brand-orange/90 hover:underline focus:outline-none focus:ring-2 focus:ring-brand-orange/20 rounded"
className="inline-flex items-center gap-2 text-sm font-medium text-brand-orange hover:text-brand-orange/90 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange/20 rounded"
>
Read documentation
<ArrowRightIcon className="w-4 h-4" />

View File

@@ -1,16 +1,20 @@
'use client'
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef } from 'react'
import dynamic from 'next/dynamic'
import { motion } from 'framer-motion'
import { logger } from '@/lib/utils/logger'
import { formatNumber } from '@ciphera-net/ui'
import { useTabListKeyboard } from '@/lib/hooks/useTabListKeyboard'
import * as Flags from 'country-flag-icons/react/3x2'
import iso3166 from 'iso-3166-2'
import WorldMap from './WorldMap'
const DottedMap = dynamic(() => import('./DottedMap'), { ssr: false })
const Globe = dynamic(() => import('./Globe'), { ssr: false })
import { Modal, GlobeIcon } from '@ciphera-net/ui'
import { ListSkeleton } from '@/components/skeletons'
import { SiTorproject } from 'react-icons/si'
import { FaUserSecret, FaSatellite } from 'react-icons/fa'
import VirtualList from './VirtualList'
import { ShieldCheck, Detective, Broadcast, FrameCornersIcon } from '@phosphor-icons/react'
import { getCountries, getCities, getRegions } from '@/lib/api/stats'
import { type DimensionFilter } from '@/lib/filters'
@@ -24,7 +28,7 @@ interface LocationProps {
onFilter?: (filter: DimensionFilter) => void
}
type Tab = 'map' | 'countries' | 'regions' | 'cities'
type Tab = 'map' | 'globe' | 'countries' | 'regions' | 'cities'
const LIMIT = 7
@@ -34,10 +38,25 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
const [activeTab, setActiveTab] = useState<Tab>('map')
const handleTabKeyDown = useTabListKeyboard()
const [isModalOpen, setIsModalOpen] = useState(false)
const [modalSearch, setModalSearch] = useState('')
type LocationItem = { country?: string; city?: string; region?: string; pageviews: number }
const [fullData, setFullData] = useState<LocationItem[]>([])
const [isLoadingFull, setIsLoadingFull] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const [inView, setInView] = useState(false)
useEffect(() => {
const el = containerRef.current
if (!el) return
const observer = new IntersectionObserver(
([entry]) => { if (entry.isIntersecting) setInView(true) },
{ rootMargin: '200px' }
)
observer.observe(el)
return () => observer.disconnect()
}, [])
useEffect(() => {
if (isModalOpen) {
const fetchData = async () => {
@@ -69,11 +88,11 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
switch (countryCode) {
case 'T1':
return <SiTorproject className="w-5 h-5 text-purple-600 dark:text-purple-400" />
return <ShieldCheck className="w-5 h-5 text-purple-600 dark:text-purple-400" />
case 'A1':
return <FaUserSecret className="w-5 h-5 text-neutral-600 dark:text-neutral-400" />
return <Detective className="w-5 h-5 text-neutral-600 dark:text-neutral-400" />
case 'A2':
return <FaSatellite className="w-5 h-5 text-blue-500 dark:text-blue-400" />
return <Broadcast className="w-5 h-5 text-blue-500 dark:text-blue-400" />
case 'O1':
case 'EU':
case 'AP':
@@ -174,15 +193,16 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
})
}
const rawData = activeTab === 'map' ? [] : getData()
const isVisualTab = activeTab === 'map' || activeTab === 'globe'
const rawData = isVisualTab ? [] : getData()
const data = filterUnknown(rawData)
const totalPageviews = data.reduce((sum, item) => sum + item.pageviews, 0)
const hasData = activeTab === 'map'
const hasData = isVisualTab
? (countries && filterUnknown(countries).length > 0)
: (data && data.length > 0)
const displayedData = (activeTab !== 'map' && hasData) ? data.slice(0, LIMIT) : []
const displayedData = (!isVisualTab && hasData) ? data.slice(0, LIMIT) : []
const emptySlots = Math.max(0, LIMIT - displayedData.length)
const showViewAll = activeTab !== 'map' && hasData && data.length > LIMIT
const showViewAll = !isVisualTab && hasData && data.length > LIMIT
const getDisabledMessage = () => {
if (geoDataLevel === 'none') {
@@ -196,25 +216,43 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
return (
<>
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div ref={containerRef} className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Locations
</h3>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Locations
</h3>
{showViewAll && (
<button
onClick={() => setIsModalOpen(true)}
className="p-1.5 text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-all cursor-pointer rounded-lg"
aria-label="View all locations"
>
<FrameCornersIcon className="w-4 h-4" weight="bold" />
</button>
)}
</div>
<div className="flex gap-1" role="tablist" aria-label="Location view tabs" onKeyDown={handleTabKeyDown}>
{(['map', 'countries', 'regions', 'cities'] as Tab[]).map((tab) => (
{(['map', 'globe', 'countries', 'regions', 'cities'] as Tab[]).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
role="tab"
aria-selected={activeTab === tab}
className={`px-2.5 py-1 text-xs font-medium transition-colors capitalize focus:outline-none focus:ring-2 focus:ring-brand-orange rounded cursor-pointer border-b-2 ${
className={`relative px-2.5 py-1 text-xs font-medium transition-colors capitalize focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded cursor-pointer ${
activeTab === tab
? 'border-brand-orange text-neutral-900 dark:text-white'
: 'border-transparent text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
? 'text-neutral-900 dark:text-white'
: 'text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
}`}
>
{tab}
{activeTab === tab && (
<motion.div
layoutId="locationsTab"
className="absolute inset-x-0 -bottom-px h-0.5 bg-brand-orange"
transition={{ type: 'spring', stiffness: 500, damping: 35 }}
/>
)}
</button>
))}
</div>
@@ -225,8 +263,12 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
<div className="h-full flex flex-col items-center justify-center text-center px-4">
<p className="text-neutral-500 dark:text-neutral-400 text-sm">{getDisabledMessage()}</p>
</div>
) : activeTab === 'map' ? (
hasData ? <WorldMap data={filterUnknown(countries) as { country: string; pageviews: number }[]} /> : (
) : isVisualTab ? (
hasData ? (
activeTab === 'globe'
? (inView ? <Globe data={filterUnknown(countries) as { country: string; pageviews: number }[]} /> : null)
: (inView ? <DottedMap data={filterUnknown(countries) as { country: string; pageviews: number }[]} /> : null)
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
<div className="rounded-full bg-neutral-100 dark:bg-neutral-800 p-4">
<GlobeIcon className="w-8 h-8 text-neutral-500 dark:text-neutral-400" />
@@ -271,21 +313,9 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
</div>
)
})}
{showViewAll ? (
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center justify-center gap-1.5 h-9 w-full text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer rounded-lg px-2 -mx-2"
>
View all
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
) : (
Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))
)}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
@@ -306,31 +336,69 @@ export default function Locations({ countries, cities, regions, geoDataLevel = '
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
title={`Locations - ${activeTab.charAt(0).toUpperCase() + activeTab.slice(1)}`}
onClose={() => { setIsModalOpen(false); setModalSearch('') }}
title={activeTab.charAt(0).toUpperCase() + activeTab.slice(1)}
className="max-w-2xl"
>
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-2">
<div>
<input
type="text"
value={modalSearch}
onChange={(e) => setModalSearch(e.target.value)}
placeholder="Search locations..."
className="w-full px-3 py-2 mb-3 text-sm bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-lg text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-brand-orange/50"
/>
</div>
<div className="max-h-[80vh]">
{isLoadingFull ? (
<div className="py-4">
<ListSkeleton rows={10} />
</div>
) : (
(fullData.length > 0 ? fullData : data).map((item) => (
<div key={`${item.country ?? ''}-${item.region ?? ''}-${item.city ?? ''}`} className="flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors">
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
<span className="shrink-0">{getFlagComponent(item.country ?? '')}</span>
<span className="truncate">
{activeTab === 'countries' ? getCountryName(item.country ?? '') :
activeTab === 'regions' ? getRegionName(item.region ?? '', item.country ?? '') :
getCityName(item.city ?? '')}
</span>
</div>
<div className="text-sm font-semibold text-neutral-600 dark:text-neutral-400 ml-4">
{formatNumber(item.pageviews)}
</div>
</div>
))
)}
) : (() => {
const rawModalData = fullData.length > 0 ? fullData : data
const search = modalSearch.toLowerCase()
const modalData = !modalSearch ? rawModalData : rawModalData.filter(item => {
const label = activeTab === 'countries' ? getCountryName(item.country ?? '') : activeTab === 'regions' ? getRegionName(item.region ?? '', item.country ?? '') : getCityName(item.city ?? '')
return label.toLowerCase().includes(search)
})
const modalTotal = modalData.reduce((sum, item) => sum + item.pageviews, 0)
return (
<VirtualList
items={modalData}
estimateSize={36}
className="max-h-[80vh] overflow-y-auto pr-2"
renderItem={(item) => {
const dim = TAB_TO_DIMENSION[activeTab]
const filterValue = activeTab === 'countries' ? item.country : activeTab === 'regions' ? item.region : item.city
const canFilter = onFilter && dim && filterValue
return (
<div
key={`${item.country ?? ''}-${item.region ?? ''}-${item.city ?? ''}`}
onClick={() => { if (canFilter) { onFilter({ dimension: dim, operator: 'is', values: [filterValue!] }); setIsModalOpen(false) } }}
className={`flex items-center justify-between h-9 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 transition-colors${canFilter ? ' cursor-pointer' : ''}`}
>
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
<span className="shrink-0">{getFlagComponent(item.country ?? '')}</span>
<span className="truncate">
{activeTab === 'countries' ? getCountryName(item.country ?? '') :
activeTab === 'regions' ? getRegionName(item.region ?? '', item.country ?? '') :
getCityName(item.city ?? '')}
</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{modalTotal > 0 ? `${Math.round((item.pageviews / modalTotal) * 100)}%` : ''}
</span>
<span className="text-sm font-semibold text-neutral-600 dark:text-neutral-400">
{formatNumber(item.pageviews)}
</span>
</div>
</div>
)
}}
/>
)
})()}
</div>
</Modal>
</>

View File

@@ -0,0 +1,271 @@
'use client'
import { useState, useEffect, useMemo, useRef, type CSSProperties } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { logger } from '@/lib/utils/logger'
import { getDailyStats } from '@/lib/api/stats'
import type { DailyStat } from '@/lib/api/stats'
interface PeakHoursProps {
siteId: string
dateRange: { start: string, end: string }
}
const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const BUCKETS = 12 // 2-hour buckets
// Label at bucket index 0=12am, 3=6am, 6=12pm, 9=6pm
const BUCKET_LABELS: Record<number, string> = { 0: '12am', 3: '6am', 6: '12pm', 9: '6pm' }
const HIGHLIGHT_COLORS = [
'rgba(253,94,15,0.18)',
'rgba(253,94,15,0.38)',
'rgba(253,94,15,0.62)',
'#FD5E0F',
]
function formatBucket(bucket: number): string {
const hour = bucket * 2
if (hour === 0) return '12am2am'
if (hour === 12) return '12pm2pm'
return hour < 12 ? `${hour}am${hour + 2}am` : `${hour - 12}pm${hour - 10}pm`
}
function formatHour(hour: number): string {
if (hour === 0) return '12am'
if (hour === 12) return '12pm'
return hour < 12 ? `${hour}am` : `${hour - 12}pm`
}
function getHighlightColor(value: number, max: number): string {
if (value === 0) return HIGHLIGHT_COLORS[0]
const ratio = value / max
if (ratio < 0.25) return HIGHLIGHT_COLORS[1]
if (ratio < 0.6) return HIGHLIGHT_COLORS[2]
return HIGHLIGHT_COLORS[3]
}
export default function PeakHours({ siteId, dateRange }: PeakHoursProps) {
const [data, setData] = useState<DailyStat[]>([])
const [isLoading, setIsLoading] = useState(true)
const [animKey, setAnimKey] = useState(0)
const [hovered, setHovered] = useState<{ day: number; bucket: number } | null>(null)
const [tooltipPos, setTooltipPos] = useState<{ x: number; y: number } | null>(null)
const gridRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
try {
const result = await getDailyStats(siteId, dateRange.start, dateRange.end, 'hour')
setData(result)
setAnimKey(k => k + 1)
} catch (e) {
logger.error(e)
} finally {
setIsLoading(false)
}
}
fetchData()
}, [siteId, dateRange])
const { grid, max, dayTotals, bucketTotals, weekTotal } = useMemo(() => {
// grid[day][bucket] — aggregate 2-hour buckets
const grid: number[][] = Array.from({ length: 7 }, () => Array(BUCKETS).fill(0))
for (const d of data) {
const date = new Date(d.date)
const day = date.getDay()
const hour = date.getHours()
const adjustedDay = day === 0 ? 6 : day - 1
const bucket = Math.floor(hour / 2)
grid[adjustedDay][bucket] += d.pageviews
}
const max = Math.max(...grid.flat(), 1)
const dayTotals = grid.map(buckets => buckets.reduce((a, b) => a + b, 0))
const bucketTotals = Array.from({ length: BUCKETS }, (_, b) => grid.reduce((a, row) => a + row[b], 0))
const weekTotal = dayTotals.reduce((a, b) => a + b, 0)
return { grid, max, dayTotals, bucketTotals, weekTotal }
}, [data])
const hasData = data.some(d => d.pageviews > 0)
const bestTime = useMemo(() => {
if (!hasData) return null
let bestDay = 0, bestBucket = 0, bestVal = 0
for (let d = 0; d < 7; d++) {
for (let b = 0; b < BUCKETS; b++) {
if (grid[d][b] > bestVal) {
bestVal = grid[d][b]
bestDay = d
bestBucket = b
}
}
}
return { day: bestDay, bucket: bestBucket }
}, [grid, hasData])
const tooltipData = useMemo(() => {
if (!hovered) return null
const { day, bucket } = hovered
const value = grid[day][bucket]
const pct = weekTotal > 0 ? Math.round((value / weekTotal) * 100) : 0
return { value, dayTotal: dayTotals[day], bucketTotal: bucketTotals[bucket], pct }
}, [hovered, grid, dayTotals, bucketTotals, weekTotal])
const handleCellMouseEnter = (
e: React.MouseEvent<HTMLDivElement>,
dayIdx: number,
bucket: number
) => {
setHovered({ day: dayIdx, bucket })
if (gridRef.current) {
const gridRect = gridRef.current.getBoundingClientRect()
const cellRect = (e.currentTarget as HTMLDivElement).getBoundingClientRect()
setTooltipPos({
x: cellRect.left - gridRect.left + cellRect.width / 2,
y: cellRect.top - gridRect.top,
})
}
}
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-1">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">Peak Hours</h3>
</div>
<p className="text-sm text-neutral-500 dark:text-neutral-400 mb-5">
When your visitors are most active
</p>
{isLoading ? (
<div className="flex-1 min-h-[270px] flex flex-col justify-center gap-1.5">
{Array.from({ length: 7 }).map((_, i) => (
<div key={i} className="flex items-center gap-1">
<div className="w-7 h-3 rounded bg-neutral-200 dark:bg-neutral-800 animate-pulse" />
<div className="flex-1 h-5 rounded bg-neutral-200 dark:bg-neutral-800 animate-pulse" />
</div>
))}
</div>
) : hasData ? (
<>
<div className="flex-1 min-h-[270px] flex flex-col justify-center gap-[5px] relative" ref={gridRef}>
{grid.map((buckets, dayIdx) => (
<div key={dayIdx} className="flex items-center gap-1.5">
<span className="text-[11px] text-neutral-400 dark:text-neutral-500 w-7 flex-shrink-0 text-right leading-none">
{DAYS[dayIdx]}
</span>
<div
className="flex-1"
style={{ display: 'grid', gridTemplateColumns: `repeat(${BUCKETS}, 1fr)`, gap: '5px' }}
>
{buckets.map((value, bucket) => {
const isHoveredCell = hovered?.day === dayIdx && hovered?.bucket === bucket
const isBestCell = bestTime?.day === dayIdx && bestTime?.bucket === bucket
const isActive = value > 0
const highlightColor = getHighlightColor(value, max)
return (
<div
key={`${animKey}-${dayIdx}-${bucket}`}
className={[
'aspect-square w-full rounded-[4px] border cursor-default transition-transform duration-100',
'border-neutral-200 dark:border-neutral-800',
isActive ? 'animate-cell-highlight' : '',
isHoveredCell ? 'scale-110 z-10 relative' : '',
isBestCell && !isHoveredCell ? 'ring-1 ring-brand-orange/40' : '',
].join(' ')}
style={{
animationDelay: isActive
? `${((dayIdx * BUCKETS + bucket) * 0.008).toFixed(3)}s`
: undefined,
'--highlight': highlightColor,
} as CSSProperties}
onMouseEnter={(e) => handleCellMouseEnter(e, dayIdx, bucket)}
onMouseLeave={() => { setHovered(null); setTooltipPos(null) }}
/>
)
})}
</div>
</div>
))}
{/* Hour axis labels */}
<div className="flex items-center gap-1.5 mt-1">
<span className="w-7 flex-shrink-0" />
<div className="flex-1 relative h-3">
{Object.entries(BUCKET_LABELS).map(([b, label]) => (
<span
key={b}
className="absolute text-[10px] text-neutral-400 dark:text-neutral-600 -translate-x-1/2"
style={{ left: `${(Number(b) / BUCKETS) * 100}%` }}
>
{label}
</span>
))}
<span
className="absolute text-[10px] text-neutral-400 dark:text-neutral-600 -translate-x-full"
style={{ left: '100%' }}
>
12am
</span>
</div>
</div>
{/* Cell-anchored tooltip */}
<AnimatePresence>
{hovered && tooltipData && tooltipPos && (
<motion.div
key="tooltip"
initial={{ opacity: 0, y: 4, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 4, scale: 0.95 }}
transition={{ duration: 0.12 }}
className="absolute pointer-events-none z-20"
style={{
left: tooltipPos.x,
top: tooltipPos.y - 8,
transform: 'translate(-50%, -100%)',
}}
>
<div className="bg-neutral-900 dark:bg-neutral-800 border border-neutral-700 text-white text-xs px-3 py-2 rounded-lg shadow-xl whitespace-nowrap">
<div className="font-semibold mb-1">
{DAYS[hovered.day]} {formatBucket(hovered.bucket)}
</div>
<div className="flex flex-col gap-0.5 text-neutral-300">
<span>{tooltipData.value.toLocaleString()} pageviews</span>
<span>{tooltipData.pct}% of week&apos;s traffic</span>
</div>
</div>
<div
className="absolute left-1/2 -translate-x-1/2 bottom-0 translate-y-full w-0 h-0"
style={{ borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTop: '5px solid #404040' }}
/>
</motion.div>
)}
</AnimatePresence>
</div>
{/* Best time callout */}
{bestTime && (
<motion.p
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.6 }}
className="mt-4 text-xs text-neutral-500 dark:text-neutral-400 text-center"
>
Your busiest time is{' '}
<span className="text-brand-orange font-medium">
{DAYS[bestTime.day]}s at {formatHour(bestTime.bucket * 2)}
</span>
</motion.p>
)}
</>
) : (
<div className="flex-1 min-h-[270px] flex flex-col items-center justify-center text-center gap-3">
<p className="text-sm text-neutral-500 dark:text-neutral-400">
No data available for this period
</p>
</div>
)}
</div>
)
}

View File

@@ -114,7 +114,7 @@ export default function PerformanceStats({ stats, performanceByPage, siteId, sta
<button
type="button"
onClick={() => setMainExpanded((o) => !o)}
className="flex w-full items-center justify-between gap-4 text-left rounded cursor-pointer hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-neutral-400 dark:focus:ring-neutral-500 focus:ring-offset-2 dark:focus:ring-offset-neutral-900"
className="flex w-full items-center justify-between gap-4 text-left rounded cursor-pointer hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 dark:focus-visible:ring-neutral-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-neutral-900"
aria-expanded={mainExpanded}
>
<div className="flex items-center gap-2 min-w-0">
@@ -170,7 +170,7 @@ export default function PerformanceStats({ stats, performanceByPage, siteId, sta
<button
type="button"
onClick={() => setWorstPagesOpen((o) => !o)}
className="flex items-center gap-2 text-left rounded cursor-pointer hover:opacity-80 focus:outline-none focus:ring-2 focus:ring-neutral-400 dark:focus:ring-neutral-500 focus:ring-offset-2 dark:focus:ring-offset-neutral-900"
className="flex items-center gap-2 text-left rounded cursor-pointer hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 dark:focus-visible:ring-neutral-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-neutral-900"
aria-expanded={worstPagesOpen}
>
<ChevronDownIcon

View File

@@ -1,6 +1,6 @@
'use client'
import { formatNumber } from '@ciphera-net/ui'
import { PolarAngleAxis, PolarGrid, Radar, RadarChart, Tooltip } from 'recharts'
import { BarChartIcon } from '@ciphera-net/ui'
import type { GoalCountStat } from '@/lib/api/stats'
@@ -22,48 +22,57 @@ export default function ScrollDepth({ goalCounts, totalPageviews }: ScrollDepthP
const hasData = scrollCounts.size > 0 && totalPageviews > 0
const chartData = THRESHOLDS.map((threshold) => ({
label: `${threshold}%`,
value: totalPageviews > 0 ? Math.round(((scrollCounts.get(threshold) ?? 0) / totalPageviews) * 100) : 0,
}))
return (
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center justify-between mb-1">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Scroll Depth
</h3>
</div>
<p className="text-sm text-neutral-500 dark:text-neutral-400 mb-4">
% of visitors who scrolled this far
</p>
{hasData ? (
<div className="space-y-3 flex-1 min-h-[200px]">
{THRESHOLDS.map((threshold) => {
const count = scrollCounts.get(threshold) ?? 0
const pct = totalPageviews > 0 ? Math.round((count / totalPageviews) * 100) : 0
const barWidth = Math.max(pct, 2)
return (
<div key={threshold} className="space-y-1">
<div className="flex items-center justify-between text-sm">
<span className="font-medium text-neutral-900 dark:text-white">
{threshold}%
</span>
<div className="flex items-center gap-2">
<span className="text-neutral-500 dark:text-neutral-400 tabular-nums">
{formatNumber(count)}
</span>
<span className="font-semibold text-brand-orange tabular-nums w-12 text-right">
{pct}%
</span>
</div>
</div>
<div className="h-2 rounded-full bg-neutral-100 dark:bg-neutral-800 overflow-hidden">
<div
className="h-full rounded-full bg-brand-orange transition-all duration-500"
style={{ width: `${barWidth}%` }}
/>
</div>
</div>
)
})}
<div className="flex-1 min-h-[270px] flex items-center justify-center">
<RadarChart
width={320}
height={260}
data={chartData}
margin={{ top: 16, right: 32, bottom: 16, left: 32 }}
>
<PolarGrid stroke="#404040" />
<PolarAngleAxis
dataKey="label"
tick={{ fill: '#a3a3a3', fontSize: 12, fontWeight: 500 }}
/>
<Tooltip
cursor={false}
contentStyle={{
backgroundColor: '#171717',
border: '1px solid #404040',
borderRadius: 8,
fontSize: 12,
color: '#fff',
}}
formatter={(value: number) => [`${value}%`, 'Reached']}
/>
<Radar
dataKey="value"
stroke="#FD5E0F"
fill="#FD5E0F"
fillOpacity={0.6}
dot={{ r: 4, fill: '#FD5E0F', fillOpacity: 1, strokeWidth: 0 }}
/>
</RadarChart>
</div>
) : (
<div className="flex-1 min-h-[200px] flex flex-col items-center justify-center text-center px-6 py-8 gap-4">
<div className="flex-1 min-h-[270px] flex flex-col items-center justify-center text-center px-6 py-8 gap-4">
<div className="rounded-full bg-neutral-100 dark:bg-neutral-800 p-4">
<BarChartIcon className="w-8 h-8 text-neutral-500 dark:text-neutral-400" />
</div>

View File

@@ -2,6 +2,7 @@
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { motion } from 'framer-motion'
import { useTabListKeyboard } from '@/lib/hooks/useTabListKeyboard'
import { useAuth } from '@/lib/auth/context'
@@ -39,13 +40,20 @@ export default function SiteNav({ siteId }: SiteNavProps) {
role="tab"
aria-selected={isActive(tab.href)}
tabIndex={isActive(tab.href) ? 0 : -1}
className={`px-3 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange rounded-t cursor-pointer border-b-2 -mb-px ${
className={`relative px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded-t cursor-pointer -mb-px ${
isActive(tab.href)
? 'border-brand-orange text-neutral-900 dark:text-white'
: 'border-transparent text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
? 'text-neutral-900 dark:text-white'
: 'text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
}`}
>
{tab.label}
{isActive(tab.href) && (
<motion.div
layoutId="activeTab"
className="absolute inset-x-0 -bottom-px h-0.5 bg-brand-orange"
transition={{ type: 'spring', stiffness: 500, damping: 35 }}
/>
)}
</Link>
))}
</nav>

View File

@@ -1,13 +1,15 @@
'use client'
import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { logger } from '@/lib/utils/logger'
import { formatNumber } from '@ciphera-net/ui'
import { useTabListKeyboard } from '@/lib/hooks/useTabListKeyboard'
import { getBrowserIcon, getOSIcon, getDeviceIcon } from '@/lib/utils/icons'
import { MdMonitor } from 'react-icons/md'
import { Monitor, FrameCornersIcon } from '@phosphor-icons/react'
import { Modal, GridIcon } from '@ciphera-net/ui'
import { ListSkeleton } from '@/components/skeletons'
import VirtualList from './VirtualList'
import { getBrowsers, getOS, getDevices, getScreenResolutions } from '@/lib/api/stats'
import { type DimensionFilter } from '@/lib/filters'
@@ -25,6 +27,11 @@ interface TechSpecsProps {
type Tab = 'browsers' | 'os' | 'devices' | 'screens'
function capitalize(s: string): string {
if (!s) return s
return s.charAt(0).toUpperCase() + s.slice(1)
}
const LIMIT = 7
const TAB_TO_DIMENSION: Record<string, string> = { browsers: 'browser', os: 'os', devices: 'device' }
@@ -33,6 +40,7 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
const [activeTab, setActiveTab] = useState<Tab>('browsers')
const handleTabKeyDown = useTabListKeyboard()
const [isModalOpen, setIsModalOpen] = useState(false)
const [modalSearch, setModalSearch] = useState('')
type TechItem = { name: string; pageviews: number; icon: React.ReactNode }
const [fullData, setFullData] = useState<TechItem[]>([])
const [isLoadingFull, setIsLoadingFull] = useState(false)
@@ -59,7 +67,7 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
data = res.map(d => ({ name: d.device, pageviews: d.pageviews, icon: getDeviceIcon(d.device) }))
} else if (activeTab === 'screens') {
const res = await getScreenResolutions(siteId, dateRange.start, dateRange.end, 100)
data = res.map(s => ({ name: s.screen_resolution, pageviews: s.pageviews, icon: <MdMonitor className="text-neutral-500" /> }))
data = res.map(s => ({ name: s.screen_resolution, pageviews: s.pageviews, icon: <Monitor className="text-neutral-500" /> }))
}
setFullData(filterUnknown(data))
} catch (e) {
@@ -83,7 +91,7 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
case 'devices':
return devices.map(d => ({ name: d.device, pageviews: d.pageviews, icon: getDeviceIcon(d.device) }))
case 'screens':
return screenResolutions.map(s => ({ name: s.screen_resolution, pageviews: s.pageviews, icon: <MdMonitor className="text-neutral-500" /> }))
return screenResolutions.map(s => ({ name: s.screen_resolution, pageviews: s.pageviews, icon: <Monitor className="text-neutral-500" /> }))
default:
return []
}
@@ -122,9 +130,20 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
<>
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Technology
</h3>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Technology
</h3>
{showViewAll && (
<button
onClick={() => setIsModalOpen(true)}
className="p-1.5 text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-all cursor-pointer rounded-lg"
aria-label="View all technology"
>
<FrameCornersIcon className="w-4 h-4" weight="bold" />
</button>
)}
</div>
<div className="flex gap-1" role="tablist" aria-label="Technology view tabs" onKeyDown={handleTabKeyDown}>
{(['browsers', 'os', 'devices', 'screens'] as Tab[]).map((tab) => (
<button
@@ -132,13 +151,20 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
onClick={() => setActiveTab(tab)}
role="tab"
aria-selected={activeTab === tab}
className={`px-2.5 py-1 text-xs font-medium transition-colors capitalize focus:outline-none focus:ring-2 focus:ring-brand-orange rounded cursor-pointer border-b-2 ${
className={`relative px-2.5 py-1 text-xs font-medium transition-colors capitalize focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded cursor-pointer ${
activeTab === tab
? 'border-brand-orange text-neutral-900 dark:text-white'
: 'border-transparent text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
? 'text-neutral-900 dark:text-white'
: 'text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300'
}`}
>
{tab}
{activeTab === tab && (
<motion.div
layoutId="techSpecsTab"
className="absolute inset-x-0 -bottom-px h-0.5 bg-brand-orange"
transition={{ type: 'spring', stiffness: 500, damping: 35 }}
/>
)}
</button>
))}
</div>
@@ -162,7 +188,7 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
>
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
{item.icon && <span className="text-lg">{item.icon}</span>}
<span className="truncate">{item.name}</span>
<span className="truncate">{capitalize(item.name)}</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
@@ -175,21 +201,9 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
</div>
)
})}
{showViewAll ? (
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center justify-center gap-1.5 h-9 w-full text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer rounded-lg px-2 -mx-2"
>
View all
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
) : (
Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))
)}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
@@ -209,27 +223,59 @@ export default function TechSpecs({ browsers, os, devices, screenResolutions, co
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
title={`Technology - ${activeTab.charAt(0).toUpperCase() + activeTab.slice(1)}`}
onClose={() => { setIsModalOpen(false); setModalSearch('') }}
title={activeTab.charAt(0).toUpperCase() + activeTab.slice(1)}
className="max-w-2xl"
>
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-2">
<div>
<input
type="text"
value={modalSearch}
onChange={(e) => setModalSearch(e.target.value)}
placeholder="Search technology..."
className="w-full px-3 py-2 mb-3 text-sm bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-lg text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-brand-orange/50"
/>
</div>
<div className="max-h-[80vh]">
{isLoadingFull ? (
<div className="py-4">
<ListSkeleton rows={10} />
</div>
) : (
(fullData.length > 0 ? fullData : data).map((item) => (
<div key={item.name} className="flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors">
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
{item.icon && <span className="text-lg">{item.icon}</span>}
<span className="truncate">{item.name === 'Unknown' ? 'Unknown' : item.name}</span>
</div>
<div className="text-sm font-semibold text-neutral-600 dark:text-neutral-400 ml-4">
{formatNumber(item.pageviews)}
</div>
</div>
))
)}
) : (() => {
const modalData = (fullData.length > 0 ? fullData : data).filter(item => !modalSearch || item.name.toLowerCase().includes(modalSearch.toLowerCase()))
const modalTotal = modalData.reduce((sum, item) => sum + item.pageviews, 0)
const dim = TAB_TO_DIMENSION[activeTab]
return (
<VirtualList
items={modalData}
estimateSize={36}
className="max-h-[80vh] overflow-y-auto pr-2"
renderItem={(item) => {
const canFilter = onFilter && dim
return (
<div
key={item.name}
onClick={() => { if (canFilter) { onFilter({ dimension: dim, operator: 'is', values: [item.name] }); setIsModalOpen(false) } }}
className={`flex items-center justify-between h-9 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 transition-colors${canFilter ? ' cursor-pointer' : ''}`}
>
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
{item.icon && <span className="text-lg">{item.icon}</span>}
<span className="truncate">{capitalize(item.name)}</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{modalTotal > 0 ? `${Math.round((item.pageviews / modalTotal) * 100)}%` : ''}
</span>
<span className="text-sm font-semibold text-neutral-600 dark:text-neutral-400">
{formatNumber(item.pageviews)}
</span>
</div>
</div>
)
}}
/>
)
})()}
</div>
</Modal>
</>

View File

@@ -5,8 +5,10 @@ import { logger } from '@/lib/utils/logger'
import Image from 'next/image'
import { formatNumber } from '@ciphera-net/ui'
import { getReferrerDisplayName, getReferrerFavicon, getReferrerIcon, mergeReferrersByDisplayName } from '@/lib/utils/icons'
import { FrameCornersIcon } from '@phosphor-icons/react'
import { Modal, GlobeIcon } from '@ciphera-net/ui'
import { ListSkeleton } from '@/components/skeletons'
import VirtualList from './VirtualList'
import { getTopReferrers, TopReferrer } from '@/lib/api/stats'
import { type DimensionFilter } from '@/lib/filters'
@@ -22,6 +24,7 @@ const LIMIT = 7
export default function TopReferrers({ referrers, collectReferrers = true, siteId, dateRange, onFilter }: TopReferrersProps) {
const [isModalOpen, setIsModalOpen] = useState(false)
const [modalSearch, setModalSearch] = useState('')
const [fullData, setFullData] = useState<TopReferrer[]>([])
const [isLoadingFull, setIsLoadingFull] = useState(false)
const [faviconFailed, setFaviconFailed] = useState<Set<string>>(new Set())
@@ -85,9 +88,20 @@ export default function TopReferrers({ referrers, collectReferrers = true, siteI
<>
<div className="bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-6 h-full flex flex-col">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Referrers
</h3>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-neutral-900 dark:text-white">
Referrers
</h3>
{showViewAll && (
<button
onClick={() => setIsModalOpen(true)}
className="p-1.5 text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-all cursor-pointer rounded-lg"
aria-label="View all referrers"
>
<FrameCornersIcon className="w-4 h-4" weight="bold" />
</button>
)}
</div>
</div>
<div className="space-y-2 flex-1 min-h-[270px]">
@@ -117,21 +131,9 @@ export default function TopReferrers({ referrers, collectReferrers = true, siteI
</div>
</div>
))}
{showViewAll ? (
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center justify-center gap-1.5 h-9 w-full text-xs font-medium text-neutral-400 dark:text-neutral-500 hover:text-brand-orange dark:hover:text-brand-orange transition-colors cursor-pointer rounded-lg px-2 -mx-2"
>
View all
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
) : (
Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))
)}
{Array.from({ length: emptySlots }).map((_, i) => (
<div key={`empty-${i}`} className="h-9 px-2 -mx-2" aria-hidden="true" />
))}
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center px-6 py-8 gap-3">
@@ -151,27 +153,55 @@ export default function TopReferrers({ referrers, collectReferrers = true, siteI
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onClose={() => { setIsModalOpen(false); setModalSearch('') }}
title="Referrers"
className="max-w-2xl"
>
<div className="space-y-3 max-h-[60vh] overflow-y-auto pr-2">
<div>
<input
type="text"
value={modalSearch}
onChange={(e) => setModalSearch(e.target.value)}
placeholder="Search referrers..."
className="w-full px-3 py-2 mb-3 text-sm bg-neutral-50 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-lg text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-brand-orange/50"
/>
</div>
<div className="max-h-[80vh]">
{isLoadingFull ? (
<div className="py-4">
<ListSkeleton rows={10} />
</div>
) : (
mergeReferrersByDisplayName(fullData.length > 0 ? fullData : filteredReferrers).map((ref) => (
<div key={ref.referrer} className="flex items-center justify-between py-2 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 -mx-2 transition-colors">
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
{renderReferrerIcon(ref.referrer)}
<span className="truncate" title={ref.referrer}>{getReferrerDisplayName(ref.referrer)}</span>
</div>
<div className="text-sm font-semibold text-neutral-600 dark:text-neutral-400 ml-4">
{formatNumber(ref.pageviews)}
</div>
</div>
))
)}
) : (() => {
const modalData = mergeReferrersByDisplayName(fullData.length > 0 ? fullData : filteredReferrers).filter(r => !modalSearch || getReferrerDisplayName(r.referrer).toLowerCase().includes(modalSearch.toLowerCase()))
const modalTotal = modalData.reduce((sum, r) => sum + r.pageviews, 0)
return (
<VirtualList
items={modalData}
estimateSize={36}
className="max-h-[80vh] overflow-y-auto pr-2"
renderItem={(ref) => (
<div
key={ref.referrer}
onClick={() => { if (onFilter) { onFilter({ dimension: 'referrer', operator: 'is', values: [ref.referrer] }); setIsModalOpen(false) } }}
className={`flex items-center justify-between h-9 group hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded-lg px-2 transition-colors${onFilter ? ' cursor-pointer' : ''}`}
>
<div className="flex-1 truncate text-neutral-900 dark:text-white flex items-center gap-3">
{renderReferrerIcon(ref.referrer)}
<span className="truncate" title={ref.referrer}>{getReferrerDisplayName(ref.referrer)}</span>
</div>
<div className="flex items-center gap-2 ml-4">
<span className="text-xs font-medium text-brand-orange opacity-0 translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-200">
{modalTotal > 0 ? `${Math.round((ref.pageviews / modalTotal) * 100)}%` : ''}
</span>
<span className="text-sm font-semibold text-neutral-600 dark:text-neutral-400">
{formatNumber(ref.pageviews)}
</span>
</div>
</div>
)}
/>
)
})()}
</div>
</Modal>
</>

View File

@@ -0,0 +1,53 @@
'use client'
import { useRef } from 'react'
import { useVirtualizer } from '@tanstack/react-virtual'
interface VirtualListProps<T> {
items: T[]
estimateSize: number
className?: string
renderItem: (item: T, index: number) => React.ReactNode
}
export default function VirtualList<T>({ items, estimateSize, className, renderItem }: VirtualListProps<T>) {
const parentRef = useRef<HTMLDivElement>(null)
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => estimateSize,
overscan: 10,
})
// For small lists (< 50 items), render directly without virtualization
if (items.length < 50) {
return (
<div className={className}>
{items.map((item, index) => renderItem(item, index))}
</div>
)
}
return (
<div ref={parentRef} className={className} style={{ overflow: 'auto' }}>
<div style={{ height: `${virtualizer.getTotalSize()}px`, width: '100%', position: 'relative' }}>
{virtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualRow.size}px`,
transform: `translateY(${virtualRow.start}px)`,
}}
>
{renderItem(items[virtualRow.index], virtualRow.index)}
</div>
))}
</div>
</div>
)
}

View File

@@ -1,110 +0,0 @@
'use client'
import React, { memo, useMemo, useState } from 'react'
import { ComposableMap, Geographies, Geography } from 'react-simple-maps'
import countries from 'i18n-iso-countries'
import enLocale from 'i18n-iso-countries/langs/en.json'
import { useTheme } from '@ciphera-net/ui'
countries.registerLocale(enLocale)
const geoUrl = "https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json"
interface WorldMapProps {
data: Array<{ country: string; pageviews: number }>
}
const WorldMap = ({ data }: WorldMapProps) => {
const { resolvedTheme } = useTheme()
const [tooltipContent, setTooltipContent] = useState<{ content: string; x: number; y: number } | null>(null)
const processedData = useMemo(() => {
const map = new Map<string, number>()
let max = 0
data.forEach(item => {
if (item.country === 'Unknown') return
// API returns 2 letter code. Convert to numeric (3 digits string)
const numericCode = countries.alpha2ToNumeric(item.country)
if (numericCode) {
map.set(numericCode, item.pageviews)
if (item.pageviews > max) max = item.pageviews
}
})
return { map, max }
}, [data])
// Plausible-like colors based on provided SVG snippet
const isDark = resolvedTheme === 'dark'
const defaultFill = isDark ? "var(--color-neutral-800)" : "var(--color-neutral-100)"
const defaultStroke = isDark ? "var(--color-neutral-900)" : "#ffffff"
const brandOrange = "var(--color-brand-orange)"
return (
<div className="relative w-full">
<ComposableMap
width={800}
height={400}
projectionConfig={{ rotate: [-10, 0, 0], scale: 170, center: [0, 10] }}
className="w-full h-auto"
>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies
.filter(geo => geo.id !== "010") // Remove Antarctica
.map((geo) => {
const id = String(geo.id).padStart(3, '0')
const count = processedData.map.get(id) || 0
const fillColor = count > 0 ? brandOrange : defaultFill
return (
<Geography
key={geo.rsmKey}
geography={geo}
fill={fillColor}
stroke={defaultStroke}
strokeWidth={0.5}
style={{
default: { outline: "none", transition: "all 250ms" },
hover: {
fill: fillColor,
stroke: brandOrange,
strokeWidth: 2,
outline: "none",
cursor: 'pointer',
zIndex: 100 // Bring border to front
},
pressed: { outline: "none" },
}}
onMouseEnter={(evt) => {
const { name } = geo.properties
setTooltipContent({
content: `${name}: ${count} visitors`,
x: evt.clientX,
y: evt.clientY
})
}}
onMouseLeave={() => {
setTooltipContent(null)
}}
onMouseMove={(evt) => {
setTooltipContent(prev => prev ? { ...prev, x: evt.clientX, y: evt.clientY } : null)
}}
/>
)
})
}
</Geographies>
</ComposableMap>
{tooltipContent && (
<div
className="fixed z-50 px-2 py-1 text-xs font-medium text-white bg-black/80 backdrop-blur-sm rounded shadow pointer-events-none transform -translate-x-1/2 -translate-y-full -mt-2.5"
style={{ left: tooltipContent.x, top: tooltipContent.y }}
>
{tooltipContent.content}
</div>
)}
</div>
)
}
export default memo(WorldMap)

View File

@@ -515,7 +515,7 @@ export default function OrganizationSettings() {
onClick={() => handleTabChange('general')}
role="tab"
aria-selected={activeTab === 'general'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'general'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -528,7 +528,7 @@ export default function OrganizationSettings() {
onClick={() => handleTabChange('members')}
role="tab"
aria-selected={activeTab === 'members'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'members'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -541,7 +541,7 @@ export default function OrganizationSettings() {
onClick={() => handleTabChange('billing')}
role="tab"
aria-selected={activeTab === 'billing'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'billing'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -555,7 +555,7 @@ export default function OrganizationSettings() {
onClick={() => handleTabChange('notifications')}
role="tab"
aria-selected={activeTab === 'notifications'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'notifications'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -569,7 +569,7 @@ export default function OrganizationSettings() {
onClick={() => handleTabChange('audit')}
role="tab"
aria-selected={activeTab === 'audit'}
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 ${
className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 ${
activeTab === 'audit'
? 'bg-brand-orange/10 text-brand-orange'
: 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -733,6 +733,7 @@ export default function OrganizationSettings() {
setCaptchaToken(token || '')
}}
apiUrl={process.env.NEXT_PUBLIC_CAPTCHA_API_URL}
action="org-settings"
/>
</div>
</div>
@@ -1026,7 +1027,7 @@ export default function OrganizationSettings() {
type="button"
onClick={handleManageSubscription}
disabled={isRedirectingToPortal}
className="inline-flex items-center gap-2 text-sm text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white transition-colors disabled:opacity-50 focus:outline-none focus:ring-2 focus:ring-brand-orange focus:rounded"
className="inline-flex items-center gap-2 text-sm text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white transition-colors disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:rounded"
>
<ExternalLinkIcon className="w-4 h-4" />
Payment method & invoices
@@ -1036,7 +1037,7 @@ export default function OrganizationSettings() {
<button
type="button"
onClick={() => setShowCancelPrompt(true)}
className="inline-flex items-center gap-2 rounded-xl border border-neutral-200 dark:border-neutral-700 px-3.5 py-1.5 text-sm text-neutral-600 dark:text-neutral-400 hover:border-red-300 hover:text-red-600 dark:hover:border-red-800 dark:hover:text-red-400 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
className="inline-flex items-center gap-2 rounded-xl border border-neutral-200 dark:border-neutral-700 px-3.5 py-1.5 text-sm text-neutral-600 dark:text-neutral-400 hover:border-red-300 hover:text-red-600 dark:hover:border-red-800 dark:hover:text-red-400 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
>
Cancel subscription
</button>
@@ -1077,14 +1078,14 @@ export default function OrganizationSettings() {
</span>
{invoice.invoice_pdf && (
<a href={invoice.invoice_pdf} target="_blank" rel="noopener noreferrer"
className="inline-flex items-center gap-2 px-2.5 py-1.5 text-xs font-medium text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange" title="Download PDF">
className="inline-flex items-center gap-2 px-2.5 py-1.5 text-xs font-medium text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange" title="Download PDF">
<DownloadIcon className="w-3.5 h-3.5" />
Download PDF
</a>
)}
{invoice.hosted_invoice_url && (
<a href={invoice.hosted_invoice_url} target="_blank" rel="noopener noreferrer"
className={`inline-flex items-center gap-2 px-2.5 py-1.5 text-xs font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange ${
className={`inline-flex items-center gap-2 px-2.5 py-1.5 text-xs font-medium rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${
invoice.status === 'open'
? 'bg-brand-orange text-white hover:bg-brand-orange-hover'
: 'text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800'
@@ -1153,7 +1154,7 @@ export default function OrganizationSettings() {
.finally(() => setIsSavingNotificationSettings(false))
}}
disabled={isSavingNotificationSettings}
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-orange focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange focus-visible:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
notificationSettings[cat.id] !== false ? 'bg-brand-orange' : 'bg-neutral-200 dark:bg-neutral-700'
}`}
>
@@ -1461,7 +1462,7 @@ export default function OrganizationSettings() {
<button
type="button"
onClick={() => setShowChangePlanModal(false)}
className="text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-400 focus:outline-none focus:ring-2 focus:ring-brand-orange rounded-lg p-1"
className="text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange rounded-lg p-1"
disabled={isChangingPlan}
aria-label="Close dialog"
>
@@ -1487,7 +1488,7 @@ export default function OrganizationSettings() {
key={plan.id}
type="button"
onClick={() => setChangePlanId(plan.id)}
className={`relative p-3 rounded-xl border text-left transition-all focus:outline-none focus:ring-2 focus:ring-brand-orange ${
className={`relative p-3 rounded-xl border text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${
isSelected
? 'border-brand-orange bg-brand-orange/5 dark:bg-brand-orange/10'
: 'border-neutral-200 dark:border-neutral-700 hover:border-neutral-300 dark:hover:border-neutral-600'
@@ -1527,14 +1528,14 @@ export default function OrganizationSettings() {
<button
type="button"
onClick={() => setChangePlanYearly(false)}
className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange ${!changePlanYearly ? 'bg-brand-orange text-white' : 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'}`}
className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${!changePlanYearly ? 'bg-brand-orange text-white' : 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'}`}
>
Monthly
</button>
<button
type="button"
onClick={() => setChangePlanYearly(true)}
className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-brand-orange ${changePlanYearly ? 'bg-brand-orange text-white' : 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'}`}
className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-orange ${changePlanYearly ? 'bg-brand-orange text-white' : 'text-neutral-600 dark:text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800'}`}
>
Yearly
</button>

View File

@@ -99,7 +99,7 @@ function SiteCard({ site, stats, statsLoading, onDelete, canDelete }: SiteCardPr
<button
type="button"
onClick={() => onDelete(site.id)}
className="flex items-center justify-center rounded-lg border border-neutral-200 px-3 hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800 text-neutral-500 hover:text-red-600 dark:hover:text-red-400 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
className="flex items-center justify-center rounded-lg border border-neutral-200 px-3 hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800 text-neutral-500 hover:text-red-600 dark:hover:text-red-400 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
title="Delete Site"
>
<SettingsIcon className="h-4 w-4" />

View File

@@ -122,7 +122,7 @@ export function ChartSkeleton() {
export function DashboardSkeleton() {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
{/* Header */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
@@ -170,7 +170,7 @@ export function DashboardSkeleton() {
export function RealtimeSkeleton() {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8 h-[calc(100vh-64px)] flex flex-col">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8 h-[calc(100vh-64px)] flex flex-col">
<div className="mb-6">
<SkeletonLine className="h-4 w-32 mb-2" />
<SkeletonLine className="h-8 w-64" />
@@ -242,7 +242,7 @@ export function SessionEventsSkeleton() {
export function UptimeSkeleton() {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<SkeletonLine className="h-4 w-32 mb-2" />
<SkeletonLine className="h-8 w-24 mb-1" />
@@ -295,7 +295,7 @@ export function ChecksSkeleton() {
export function FunnelsListSkeleton() {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<div className="flex items-center gap-4 mb-6">
<SkeletonLine className="h-10 w-10 rounded-xl" />
@@ -329,7 +329,7 @@ export function FunnelsListSkeleton() {
export function FunnelDetailSkeleton() {
return (
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 py-8">
<div className="w-full max-w-6xl mx-auto px-4 sm:px-6 pb-8">
<div className="mb-8">
<SkeletonLine className="h-4 w-32 mb-2" />
<SkeletonLine className="h-8 w-48 mb-1" />

View File

@@ -2,7 +2,7 @@
import { useState, useEffect } from 'react'
import { logger } from '@/lib/utils/logger'
import { CopyIcon, CheckIcon } from '@radix-ui/react-icons'
import { Copy, Check } from '@phosphor-icons/react'
import { listSites, Site } from '@/lib/api/sites'
import { Select, Input, Button } from '@ciphera-net/ui'
@@ -205,7 +205,7 @@ export default function UtmBuilder({ initialSiteId }: UtmBuilderProps) {
className="ml-4 shrink-0 h-9 w-9 p-0 rounded-lg"
title="Copy to clipboard"
>
{copied ? <CheckIcon className="w-4 h-4 text-green-500" /> : <CopyIcon className="w-4 h-4" />}
{copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
</Button>
</div>
)}

67
components/ui/avatar.tsx Normal file
View File

@@ -0,0 +1,67 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
import { cva, VariantProps } from 'class-variance-authority';
import { Avatar as AvatarPrimitive } from 'radix-ui';
const avatarStatusVariants = cva('flex items-center rounded-full size-2 border-2 border-background', {
variants: {
variant: {
online: 'bg-green-600',
offline: 'bg-zinc-600 dark:bg-zinc-300',
busy: 'bg-yellow-600',
away: 'bg-blue-600',
},
},
defaultVariants: {
variant: 'online',
},
});
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root data-slot="avatar" className={cn('relative flex shrink-0 size-10', className)} {...props} />
);
}
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<div className={cn('relative overflow-hidden rounded-full', className)}>
<AvatarPrimitive.Image data-slot="avatar-image" className={cn('aspect-square h-full w-full')} {...props} />
</div>
);
}
function AvatarFallback({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
'flex h-full w-full items-center justify-center rounded-full border border-border bg-accent text-accent-foreground text-xs',
className,
)}
{...props}
/>
);
}
function AvatarIndicator({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
data-slot="avatar-indicator"
className={cn('absolute flex size-6 items-center justify-center', className)}
{...props}
/>
);
}
function AvatarStatus({
className,
variant,
...props
}: React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof avatarStatusVariants>) {
return <div data-slot="avatar-status" className={cn(avatarStatusVariants({ variant }), className)} {...props} />;
}
export { Avatar, AvatarFallback, AvatarImage, AvatarIndicator, AvatarStatus, avatarStatusVariants };

230
components/ui/badge-2.tsx Normal file
View File

@@ -0,0 +1,230 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot as SlotPrimitive } from 'radix-ui';
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {
asChild?: boolean;
dotClassName?: string;
disabled?: boolean;
}
export interface BadgeButtonProps
extends React.ButtonHTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeButtonVariants> {
asChild?: boolean;
}
export type BadgeDotProps = React.HTMLAttributes<HTMLSpanElement>;
const badgeVariants = cva(
'inline-flex items-center justify-center border border-transparent font-medium focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 [&_svg]:-ms-px [&_svg]:shrink-0',
{
variants: {
variant: {
primary: 'bg-primary text-primary-foreground',
secondary: 'bg-secondary text-secondary-foreground',
success:
'bg-[var(--color-success-accent,#22c55e)] text-[var(--color-success-foreground,#ffffff)]',
warning:
'bg-[var(--color-warning-accent,#eab308)] text-[var(--color-warning-foreground,#ffffff)]',
info: 'bg-[var(--color-info-accent,#8b5cf6)] text-[var(--color-info-foreground,#ffffff)]',
outline: 'bg-transparent border border-border text-secondary-foreground',
destructive: 'bg-destructive text-destructive-foreground',
},
appearance: {
default: '',
light: '',
outline: '',
ghost: 'border-transparent bg-transparent',
},
disabled: {
true: 'opacity-50 pointer-events-none',
},
size: {
lg: 'rounded-md px-[0.5rem] h-7 min-w-7 gap-1.5 text-xs [&_svg]:size-3.5',
md: 'rounded-md px-[0.45rem] h-6 min-w-6 gap-1.5 text-xs [&_svg]:size-3.5 ',
sm: 'rounded-sm px-[0.325rem] h-5 min-w-5 gap-1 text-[0.6875rem] leading-[0.75rem] [&_svg]:size-3',
xs: 'rounded-sm px-[0.25rem] h-4 min-w-4 gap-1 text-[0.625rem] leading-[0.5rem] [&_svg]:size-3',
},
shape: {
default: '',
circle: 'rounded-full',
},
},
compoundVariants: [
/* Light */
{
variant: 'primary',
appearance: 'light',
className:
'text-blue-700 bg-blue-50 dark:bg-blue-950 dark:text-blue-600',
},
{
variant: 'secondary',
appearance: 'light',
className: 'bg-secondary dark:bg-secondary/50 text-secondary-foreground',
},
{
variant: 'success',
appearance: 'light',
className:
'text-green-800 bg-green-100 dark:bg-green-950 dark:text-green-600',
},
{
variant: 'warning',
appearance: 'light',
className:
'text-yellow-700 bg-yellow-100 dark:bg-yellow-950 dark:text-yellow-600',
},
{
variant: 'info',
appearance: 'light',
className:
'text-violet-700 bg-violet-100 dark:bg-violet-950 dark:text-violet-400',
},
{
variant: 'destructive',
appearance: 'light',
className:
'text-red-700 bg-red-50 dark:bg-red-950 dark:text-red-600',
},
/* Outline */
{
variant: 'primary',
appearance: 'outline',
className:
'text-blue-700 border-blue-100 bg-blue-50 dark:bg-blue-950 dark:border-blue-900 dark:text-blue-600',
},
{
variant: 'success',
appearance: 'outline',
className:
'text-[#10B981] border-[#10B981]/20 bg-[#10B981]/10',
},
{
variant: 'warning',
appearance: 'outline',
className:
'text-yellow-700 border-yellow-200 bg-yellow-50 dark:bg-yellow-950 dark:border-yellow-900 dark:text-yellow-600',
},
{
variant: 'info',
appearance: 'outline',
className:
'text-violet-700 border-violet-100 bg-violet-50 dark:bg-violet-950 dark:border-violet-900 dark:text-violet-400',
},
{
variant: 'destructive',
appearance: 'outline',
className:
'text-[#EF4444] border-[#EF4444]/20 bg-[#EF4444]/10',
},
/* Ghost */
{
variant: 'primary',
appearance: 'ghost',
className: 'text-primary',
},
{
variant: 'secondary',
appearance: 'ghost',
className: 'text-secondary-foreground',
},
{
variant: 'success',
appearance: 'ghost',
className: 'text-green-500',
},
{
variant: 'warning',
appearance: 'ghost',
className: 'text-yellow-500',
},
{
variant: 'info',
appearance: 'ghost',
className: 'text-violet-500',
},
{
variant: 'destructive',
appearance: 'ghost',
className: 'text-destructive',
},
{ size: 'lg', appearance: 'ghost', className: 'px-0' },
{ size: 'md', appearance: 'ghost', className: 'px-0' },
{ size: 'sm', appearance: 'ghost', className: 'px-0' },
{ size: 'xs', appearance: 'ghost', className: 'px-0' },
],
defaultVariants: {
variant: 'primary',
appearance: 'default',
size: 'md',
},
},
);
const badgeButtonVariants = cva(
'cursor-pointer transition-all inline-flex items-center justify-center leading-none size-3.5 [&>svg]:opacity-100! [&>svg]:size-3.5 p-0 rounded-md -me-0.5 opacity-60 hover:opacity-100',
{
variants: {
variant: {
default: '',
},
},
defaultVariants: {
variant: 'default',
},
},
);
function Badge({
className,
variant,
size,
appearance,
shape,
asChild = false,
disabled,
...props
}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? SlotPrimitive.Slot : 'span';
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant, size, appearance, shape, disabled }), className)}
{...props}
/>
);
}
function BadgeButton({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<'button'> & VariantProps<typeof badgeButtonVariants> & { asChild?: boolean }) {
const Comp = asChild ? SlotPrimitive.Slot : 'span';
return (
<Comp
data-slot="badge-button"
className={cn(badgeButtonVariants({ variant, className }))}
role="button"
{...props}
/>
);
}
function BadgeDot({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="badge-dot"
className={cn('size-1.5 rounded-full bg-[currentColor] opacity-75', className)}
{...props}
/>
);
}
export { Badge, BadgeButton, BadgeDot, badgeVariants };

412
components/ui/button-1.tsx Normal file
View File

@@ -0,0 +1,412 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { CaretDown } from '@phosphor-icons/react';
import { Slot as SlotPrimitive } from 'radix-ui';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'cursor-pointer group whitespace-nowrap focus-visible:outline-hidden inline-flex items-center justify-center has-data-[arrow=true]:justify-between whitespace-nowrap text-sm font-medium ring-offset-background transition-[color,box-shadow] disabled:pointer-events-none disabled:opacity-60 [&_svg]:shrink-0',
{
variants: {
variant: {
primary: 'bg-primary text-primary-foreground hover:bg-primary/90 data-[state=open]:bg-primary/90',
mono: 'bg-zinc-950 text-white dark:bg-zinc-300 dark:text-black hover:bg-zinc-950/90 dark:hover:bg-zinc-300/90 data-[state=open]:bg-zinc-950/90 dark:data-[state=open]:bg-zinc-300/90',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90 data-[state=open]:bg-destructive/90',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/90 data-[state=open]:bg-secondary/90',
outline: 'bg-background text-accent-foreground border border-input hover:bg-accent data-[state=open]:bg-accent',
dashed:
'text-accent-foreground border border-input border-dashed bg-background hover:bg-accent hover:text-accent-foreground data-[state=open]:text-accent-foreground',
ghost:
'text-accent-foreground hover:bg-accent hover:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
dim: 'text-muted-foreground hover:text-foreground data-[state=open]:text-foreground',
foreground: '',
inverse: '',
},
appearance: {
default: '',
ghost: '',
},
underline: {
solid: '',
dashed: '',
},
underlined: {
solid: '',
dashed: '',
},
size: {
lg: 'h-10 rounded-md px-4 text-sm gap-1.5 [&_svg:not([class*=size-])]:size-4',
md: 'h-8.5 rounded-md px-3 gap-1.5 text-[0.8125rem] leading-[--text-sm--line-height] [&_svg:not([class*=size-])]:size-4',
sm: 'h-7 rounded-md px-2.5 gap-1.25 text-xs [&_svg:not([class*=size-])]:size-3.5',
icon: 'size-8.5 rounded-md [&_svg:not([class*=size-])]:size-4 shrink-0',
},
autoHeight: {
true: '',
false: '',
},
shape: {
default: '',
circle: 'rounded-full',
},
mode: {
default: 'focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
icon: 'focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
link: 'text-primary h-auto p-0 bg-transparent rounded-none hover:bg-transparent data-[state=open]:bg-transparent',
input: `
justify-start font-normal hover:bg-background [&_svg]:transition-colors [&_svg]:hover:text-foreground data-[state=open]:bg-background
focus-visible:border-ring focus-visible:outline-hidden focus-visible:ring-[3px] focus-visible:ring-ring/30
[[data-state=open]>&]:border-ring [[data-state=open]>&]:outline-hidden [[data-state=open]>&]:ring-[3px]
[[data-state=open]>&]:ring-ring/30
aria-invalid:border-destructive/60 aria-invalid:ring-destructive/10 dark:aria-invalid:border-destructive dark:aria-invalid:ring-destructive/20
in-data-[invalid=true]:border-destructive/60 in-data-[invalid=true]:ring-destructive/10 dark:in-data-[invalid=true]:border-destructive dark:in-data-[invalid=true]:ring-destructive/20
`,
},
placeholder: {
true: 'text-muted-foreground',
false: '',
},
},
compoundVariants: [
// Icons opacity for default mode
{
variant: 'ghost',
mode: 'default',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
{
variant: 'outline',
mode: 'default',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
{
variant: 'dashed',
mode: 'default',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
{
variant: 'secondary',
mode: 'default',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
// Icons opacity for default mode
{
variant: 'outline',
mode: 'input',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
{
variant: 'outline',
mode: 'icon',
className: '[&_svg:not([role=img]):not([class*=text-]):not([class*=opacity-])]:opacity-60',
},
// Auto height
{
size: 'md',
autoHeight: true,
className: 'h-auto min-h-8.5',
},
{
size: 'sm',
autoHeight: true,
className: 'h-auto min-h-7',
},
{
size: 'lg',
autoHeight: true,
className: 'h-auto min-h-10',
},
// Shadow support
{
variant: 'primary',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'mono',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'secondary',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'outline',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'dashed',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'destructive',
mode: 'default',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
// Shadow support
{
variant: 'primary',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'mono',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'secondary',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'outline',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'dashed',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
{
variant: 'destructive',
mode: 'icon',
appearance: 'default',
className: 'shadow-xs shadow-black/5',
},
// Link
{
variant: 'primary',
mode: 'link',
underline: 'solid',
className:
'font-medium text-primary hover:text-primary/90 [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-solid',
},
{
variant: 'primary',
mode: 'link',
underline: 'dashed',
className:
'font-medium text-primary hover:text-primary/90 [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-dashed decoration-1',
},
{
variant: 'primary',
mode: 'link',
underlined: 'solid',
className:
'font-medium text-primary hover:text-primary/90 [&_svg:not([role=img]):not([class*=text-])]:opacity-60 underline underline-offset-4 decoration-solid',
},
{
variant: 'primary',
mode: 'link',
underlined: 'dashed',
className:
'font-medium text-primary hover:text-primary/90 [&_svg]:opacity-60 underline underline-offset-4 decoration-dashed decoration-1',
},
{
variant: 'inverse',
mode: 'link',
underline: 'solid',
className:
'font-medium text-inherit [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-solid',
},
{
variant: 'inverse',
mode: 'link',
underline: 'dashed',
className:
'font-medium text-inherit [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-dashed decoration-1',
},
{
variant: 'inverse',
mode: 'link',
underlined: 'solid',
className:
'font-medium text-inherit [&_svg:not([role=img]):not([class*=text-])]:opacity-60 underline underline-offset-4 decoration-solid',
},
{
variant: 'inverse',
mode: 'link',
underlined: 'dashed',
className:
'font-medium text-inherit [&_svg:not([role=img]):not([class*=text-])]:opacity-60 underline underline-offset-4 decoration-dashed decoration-1',
},
{
variant: 'foreground',
mode: 'link',
underline: 'solid',
className:
'font-medium text-foreground [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-solid',
},
{
variant: 'foreground',
mode: 'link',
underline: 'dashed',
className:
'font-medium text-foreground [&_svg:not([role=img]):not([class*=text-])]:opacity-60 hover:underline hover:underline-offset-4 hover:decoration-dashed decoration-1',
},
{
variant: 'foreground',
mode: 'link',
underlined: 'solid',
className:
'font-medium text-foreground [&_svg:not([role=img]):not([class*=text-])]:opacity-60 underline underline-offset-4 decoration-solid',
},
{
variant: 'foreground',
mode: 'link',
underlined: 'dashed',
className:
'font-medium text-foreground [&_svg:not([role=img]):not([class*=text-])]:opacity-60 underline underline-offset-4 decoration-dashed decoration-1',
},
// Ghost
{
variant: 'primary',
appearance: 'ghost',
className: 'bg-transparent text-primary/90 hover:bg-primary/5 data-[state=open]:bg-primary/5',
},
{
variant: 'destructive',
appearance: 'ghost',
className: 'bg-transparent text-destructive/90 hover:bg-destructive/5 data-[state=open]:bg-destructive/5',
},
{
variant: 'ghost',
mode: 'icon',
className: 'text-muted-foreground',
},
// Size
{
size: 'sm',
mode: 'icon',
className: 'w-7 h-7 p-0 [&_svg:not([class*=size-])]:size-3.5',
},
{
size: 'md',
mode: 'icon',
className: 'w-8.5 h-8.5 p-0 [&_svg:not([class*=size-])]:size-4',
},
{
size: 'icon',
className: 'w-8.5 h-8.5 p-0 [&_svg:not([class*=size-])]:size-4',
},
{
size: 'lg',
mode: 'icon',
className: 'w-10 h-10 p-0 [&_svg:not([class*=size-])]:size-4',
},
// Input mode
{
mode: 'input',
placeholder: true,
variant: 'outline',
className: 'font-normal text-muted-foreground',
},
{
mode: 'input',
variant: 'outline',
size: 'sm',
className: 'gap-1.25',
},
{
mode: 'input',
variant: 'outline',
size: 'md',
className: 'gap-1.5',
},
{
mode: 'input',
variant: 'outline',
size: 'lg',
className: 'gap-1.5',
},
],
defaultVariants: {
variant: 'primary',
mode: 'default',
size: 'md',
shape: 'default',
appearance: 'default',
},
},
);
function Button({
className,
selected,
variant,
shape,
appearance,
mode,
size,
autoHeight,
underlined,
underline,
asChild = false,
placeholder = false,
...props
}: React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & {
selected?: boolean;
asChild?: boolean;
}) {
const Comp = asChild ? SlotPrimitive.Slot : 'button';
return (
<Comp
data-slot="button"
className={cn(
buttonVariants({
variant,
size,
shape,
appearance,
mode,
autoHeight,
placeholder,
underlined,
underline,
className,
}),
asChild && props.disabled && 'pointer-events-none opacity-50',
)}
{...(selected && { 'data-state': 'open' })}
{...props}
/>
);
}
interface ButtonArrowProps extends React.SVGProps<SVGSVGElement> {
icon?: React.ComponentType<{ className?: string }>;
}
function ButtonArrow({ icon: Icon = CaretDown, className, ...props }: ButtonArrowProps) {
return <Icon data-slot="button-arrow" className={cn('ms-auto -me-1', className)} {...(props as Record<string, unknown>)} />;
}
export { Button, ButtonArrow, buttonVariants };

147
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,147 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
import { cva, type VariantProps } from 'class-variance-authority';
// Define CardContext
type CardContextType = {
variant: 'default' | 'accent';
};
const CardContext = React.createContext<CardContextType>({
variant: 'default', // Default value
});
// Hook to use CardContext
const useCardContext = () => {
const context = React.useContext(CardContext);
if (!context) {
throw new Error('useCardContext must be used within a Card component');
}
return context;
};
// Variants
const cardVariants = cva('flex flex-col items-stretch text-card-foreground rounded-xl', {
variants: {
variant: {
default: 'bg-card border border-border shadow-xs black/5',
accent: 'bg-muted shadow-xs p-1',
},
},
defaultVariants: {
variant: 'default',
},
});
const cardHeaderVariants = cva('flex items-center justify-between flex-wrap px-5 min-h-14 gap-2.5', {
variants: {
variant: {
default: 'border-b border-border',
accent: '',
},
},
defaultVariants: {
variant: 'default',
},
});
const cardContentVariants = cva('grow p-5', {
variants: {
variant: {
default: '',
accent: 'bg-card rounded-t-xl [&:last-child]:rounded-b-xl',
},
},
defaultVariants: {
variant: 'default',
},
});
const cardTableVariants = cva('grid grow', {
variants: {
variant: {
default: '',
accent: 'bg-card rounded-xl',
},
},
defaultVariants: {
variant: 'default',
},
});
const cardFooterVariants = cva('flex items-center px-5 min-h-14', {
variants: {
variant: {
default: 'border-t border-border',
accent: 'bg-card rounded-b-xl mt-[2px]',
},
},
defaultVariants: {
variant: 'default',
},
});
// Card Component
function Card({
className,
variant = 'default',
...props
}: React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof cardVariants>) {
return (
<CardContext.Provider value={{ variant: variant || 'default' }}>
<div data-slot="card" className={cn(cardVariants({ variant }), className)} {...props} />
</CardContext.Provider>
);
}
// CardHeader Component
function CardHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
const { variant } = useCardContext();
return <div data-slot="card-header" className={cn(cardHeaderVariants({ variant }), className)} {...props} />;
}
// CardContent Component
function CardContent({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
const { variant } = useCardContext();
return <div data-slot="card-content" className={cn(cardContentVariants({ variant }), className)} {...props} />;
}
// CardTable Component
function CardTable({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
const { variant } = useCardContext();
return <div data-slot="card-table" className={cn(cardTableVariants({ variant }), className)} {...props} />;
}
// CardFooter Component
function CardFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
const { variant } = useCardContext();
return <div data-slot="card-footer" className={cn(cardFooterVariants({ variant }), className)} {...props} />;
}
// Other Components
function CardHeading({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div data-slot="card-heading" className={cn('space-y-1', className)} {...props} />;
}
function CardToolbar({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div data-slot="card-toolbar" className={cn('flex items-center gap-2.5', className)} {...props} />;
}
function CardTitle({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) {
return (
<h3
data-slot="card-title"
className={cn('text-base font-semibold leading-none tracking-tight', className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div data-slot="card-description" className={cn('text-sm text-muted-foreground', className)} {...props} />;
}
// Exports
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardHeading, CardTable, CardTitle, CardToolbar };

View File

@@ -0,0 +1,935 @@
"use client";
import { motion, useSpring, useTransform } from "motion/react";
import {
type CSSProperties,
type ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
// ─── Utils ───────────────────────────────────────────────────────────────────
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// ─── PatternLines ────────────────────────────────────────────────────────────
export interface PatternLinesProps {
id: string;
width?: number;
height?: number;
stroke?: string;
strokeWidth?: number;
orientation?: ("diagonal" | "horizontal" | "vertical")[];
background?: string;
}
export function PatternLines({
id,
width = 6,
height = 6,
stroke = "var(--chart-line-primary)",
strokeWidth = 1,
orientation = ["diagonal"],
background,
}: PatternLinesProps) {
const paths: string[] = [];
for (const o of orientation) {
if (o === "diagonal") {
paths.push(`M0,${height}l${width},${-height}`);
paths.push(`M${-width / 4},${height / 4}l${width / 2},${-height / 2}`);
paths.push(
`M${(3 * width) / 4},${height + height / 4}l${width / 2},${-height / 2}`
);
} else if (o === "horizontal") {
paths.push(`M0,${height / 2}l${width},0`);
} else if (o === "vertical") {
paths.push(`M${width / 2},0l0,${height}`);
}
}
return (
<pattern
id={id}
width={width}
height={height}
patternUnits="userSpaceOnUse"
>
{background && (
<rect width={width} height={height} fill={background} />
)}
<path
d={paths.join(" ")}
fill="none"
stroke={stroke}
strokeWidth={strokeWidth}
strokeLinecap="square"
/>
</pattern>
);
}
PatternLines.displayName = "PatternLines";
// ─── Types ───────────────────────────────────────────────────────────────────
export interface FunnelGradientStop {
offset: string | number;
color: string;
}
export interface FunnelStage {
label: string;
value: number;
displayValue?: string;
color?: string;
gradient?: FunnelGradientStop[];
}
export interface FunnelChartProps {
data: FunnelStage[];
orientation?: "horizontal" | "vertical";
color?: string;
layers?: number;
className?: string;
style?: CSSProperties;
showPercentage?: boolean;
showValues?: boolean;
showLabels?: boolean;
hoveredIndex?: number | null;
onHoverChange?: (index: number | null) => void;
formatPercentage?: (pct: number) => string;
formatValue?: (value: number) => string;
staggerDelay?: number;
gap?: number;
renderPattern?: (id: string, color: string) => ReactNode;
edges?: "curved" | "straight";
labelLayout?: "spread" | "grouped";
labelOrientation?: "vertical" | "horizontal";
labelAlign?: "center" | "start" | "end";
grid?:
| boolean
| {
bands?: boolean;
bandColor?: string;
lines?: boolean;
lineColor?: string;
lineOpacity?: number;
lineWidth?: number;
};
}
// ─── Defaults ────────────────────────────────────────────────────────────────
const fmtPct = (p: number) => `${Math.round(p)}%`;
const fmtVal = (v: number) => v.toLocaleString("en-US");
const springConfig = { stiffness: 120, damping: 20, mass: 1 };
const hoverSpring = { stiffness: 300, damping: 24 };
// ─── SVG Helpers ─────────────────────────────────────────────────────────────
function hSegmentPath(
normStart: number,
normEnd: number,
segW: number,
H: number,
layerScale: number,
straight = false
) {
const my = H / 2;
const h0 = normStart * H * 0.44 * layerScale;
const h1 = normEnd * H * 0.44 * layerScale;
if (straight) {
return `M 0 ${my - h0} L ${segW} ${my - h1} L ${segW} ${my + h1} L 0 ${my + h0} Z`;
}
const cx = segW * 0.55;
const top = `M 0 ${my - h0} C ${cx} ${my - h0}, ${segW - cx} ${my - h1}, ${segW} ${my - h1}`;
const bot = `L ${segW} ${my + h1} C ${segW - cx} ${my + h1}, ${cx} ${my + h0}, 0 ${my + h0}`;
return `${top} ${bot} Z`;
}
function vSegmentPath(
normStart: number,
normEnd: number,
segH: number,
W: number,
layerScale: number,
straight = false
) {
const mx = W / 2;
const w0 = normStart * W * 0.44 * layerScale;
const w1 = normEnd * W * 0.44 * layerScale;
if (straight) {
return `M ${mx - w0} 0 L ${mx - w1} ${segH} L ${mx + w1} ${segH} L ${mx + w0} 0 Z`;
}
const cy = segH * 0.55;
const left = `M ${mx - w0} 0 C ${mx - w0} ${cy}, ${mx - w1} ${segH - cy}, ${mx - w1} ${segH}`;
const right = `L ${mx + w1} ${segH} C ${mx + w1} ${segH - cy}, ${mx + w0} ${cy}, ${mx + w0} 0`;
return `${left} ${right} Z`;
}
// ─── Animated Ring ───────────────────────────────────────────────────────────
function HRing({
d,
color,
fill,
opacity,
hovered,
ringIndex,
totalRings,
}: {
d: string;
color: string;
fill?: string;
opacity: number;
hovered: boolean;
ringIndex: number;
totalRings: number;
}) {
const extraScale = 1 + (ringIndex / Math.max(totalRings - 1, 1)) * 0.12;
const ringSpring = {
stiffness: 300 - ringIndex * 60,
damping: 24 - ringIndex * 3,
};
const scaleY = useSpring(1, ringSpring);
useEffect(() => {
scaleY.set(hovered ? extraScale : 1);
}, [hovered, scaleY, extraScale]);
return (
<motion.path
d={d}
fill={fill ?? color}
opacity={opacity}
style={{ scaleY, transformOrigin: "center center" }}
/>
);
}
function VRing({
d,
color,
fill,
opacity,
hovered,
ringIndex,
totalRings,
}: {
d: string;
color: string;
fill?: string;
opacity: number;
hovered: boolean;
ringIndex: number;
totalRings: number;
}) {
const extraScale = 1 + (ringIndex / Math.max(totalRings - 1, 1)) * 0.12;
const ringSpring = {
stiffness: 300 - ringIndex * 60,
damping: 24 - ringIndex * 3,
};
const scaleX = useSpring(1, ringSpring);
useEffect(() => {
scaleX.set(hovered ? extraScale : 1);
}, [hovered, scaleX, extraScale]);
return (
<motion.path
d={d}
fill={fill ?? color}
opacity={opacity}
style={{ scaleX, transformOrigin: "center center" }}
/>
);
}
// ─── Animated Segments ───────────────────────────────────────────────────────
function HSegment({
index,
normStart,
normEnd,
segW,
fullH,
color,
layers,
staggerDelay,
hovered,
dimmed,
renderPattern,
straight,
gradientStops,
}: {
index: number;
normStart: number;
normEnd: number;
segW: number;
fullH: number;
color: string;
layers: number;
staggerDelay: number;
hovered: boolean;
dimmed: boolean;
renderPattern?: (id: string, color: string) => ReactNode;
straight: boolean;
gradientStops?: FunnelGradientStop[];
}) {
const patternId = `funnel-h-pattern-${index}`;
const gradientId = `funnel-h-grad-${index}`;
const growProgress = useSpring(0, springConfig);
const entranceScaleX = useTransform(growProgress, [0, 1], [0, 1]);
const entranceScaleY = useTransform(growProgress, [0, 1], [0, 1]);
const dimOpacity = useSpring(1, hoverSpring);
useEffect(() => {
dimOpacity.set(dimmed ? 0.4 : 1);
}, [dimmed, dimOpacity]);
useEffect(() => {
const timeout = setTimeout(
() => growProgress.set(1),
index * staggerDelay * 1000
);
return () => clearTimeout(timeout);
}, [growProgress, index, staggerDelay]);
const rings = Array.from({ length: layers }, (_, l) => {
const scale = 1 - (l / layers) * 0.35;
const opacity = 0.18 + (l / (layers - 1 || 1)) * 0.65;
return {
d: hSegmentPath(normStart, normEnd, segW, fullH, scale, straight),
opacity,
};
});
return (
<motion.div
className="pointer-events-none relative shrink-0 overflow-visible"
style={{
width: segW,
height: fullH,
zIndex: hovered ? 10 : 1,
opacity: dimOpacity,
}}
>
<motion.div
className="absolute inset-0 overflow-visible"
style={{
scaleX: entranceScaleX,
scaleY: entranceScaleY,
transformOrigin: "left center",
}}
>
<svg
aria-hidden="true"
className="absolute inset-0 h-full w-full overflow-visible"
preserveAspectRatio="none"
role="presentation"
viewBox={`0 0 ${segW} ${fullH}`}
>
<defs>
{gradientStops && (
<linearGradient id={gradientId} x1="0" x2="1" y1="0" y2="0">
{gradientStops.map((stop) => (
<stop
key={`${stop.offset}-${stop.color}`}
offset={
typeof stop.offset === "number"
? `${stop.offset * 100}%`
: stop.offset
}
stopColor={stop.color}
/>
))}
</linearGradient>
)}
{renderPattern?.(patternId, color)}
</defs>
{rings.map((r, i) => {
const isInnermost = i === rings.length - 1;
let ringFill: string | undefined;
if (isInnermost && renderPattern) {
ringFill = `url(#${patternId})`;
} else if (isInnermost && gradientStops) {
ringFill = `url(#${gradientId})`;
}
return (
<HRing
color={color}
d={r.d}
fill={ringFill}
hovered={hovered}
key={`h-ring-${r.opacity.toFixed(2)}`}
opacity={r.opacity}
ringIndex={i}
totalRings={layers}
/>
);
})}
</svg>
</motion.div>
</motion.div>
);
}
function VSegment({
index,
normStart,
normEnd,
segH,
fullW,
color,
layers,
staggerDelay,
hovered,
dimmed,
renderPattern,
straight,
gradientStops,
}: {
index: number;
normStart: number;
normEnd: number;
segH: number;
fullW: number;
color: string;
layers: number;
staggerDelay: number;
hovered: boolean;
dimmed: boolean;
renderPattern?: (id: string, color: string) => ReactNode;
straight: boolean;
gradientStops?: FunnelGradientStop[];
}) {
const patternId = `funnel-v-pattern-${index}`;
const gradientId = `funnel-v-grad-${index}`;
const growProgress = useSpring(0, springConfig);
const entranceScaleY = useTransform(growProgress, [0, 1], [0, 1]);
const entranceScaleX = useTransform(growProgress, [0, 1], [0, 1]);
const dimOpacity = useSpring(1, hoverSpring);
useEffect(() => {
dimOpacity.set(dimmed ? 0.4 : 1);
}, [dimmed, dimOpacity]);
useEffect(() => {
const timeout = setTimeout(
() => growProgress.set(1),
index * staggerDelay * 1000
);
return () => clearTimeout(timeout);
}, [growProgress, index, staggerDelay]);
const rings = Array.from({ length: layers }, (_, l) => {
const scale = 1 - (l / layers) * 0.35;
const opacity = 0.18 + (l / (layers - 1 || 1)) * 0.65;
return {
d: vSegmentPath(normStart, normEnd, segH, fullW, scale, straight),
opacity,
};
});
return (
<motion.div
className="pointer-events-none relative shrink-0 overflow-visible"
style={{
width: fullW,
height: segH,
zIndex: hovered ? 10 : 1,
opacity: dimOpacity,
}}
>
<motion.div
className="absolute inset-0 overflow-visible"
style={{
scaleY: entranceScaleY,
scaleX: entranceScaleX,
transformOrigin: "center top",
}}
>
<svg
aria-hidden="true"
className="absolute inset-0 h-full w-full overflow-visible"
preserveAspectRatio="none"
role="presentation"
viewBox={`0 0 ${fullW} ${segH}`}
>
<defs>
{gradientStops && (
<linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">
{gradientStops.map((stop) => (
<stop
key={`${stop.offset}-${stop.color}`}
offset={
typeof stop.offset === "number"
? `${stop.offset * 100}%`
: stop.offset
}
stopColor={stop.color}
/>
))}
</linearGradient>
)}
{renderPattern?.(patternId, color)}
</defs>
{rings.map((r, i) => {
const isInnermost = i === rings.length - 1;
let ringFill: string | undefined;
if (isInnermost && renderPattern) {
ringFill = `url(#${patternId})`;
} else if (isInnermost && gradientStops) {
ringFill = `url(#${gradientId})`;
}
return (
<VRing
color={color}
d={r.d}
fill={ringFill}
hovered={hovered}
key={`v-ring-${r.opacity.toFixed(2)}`}
opacity={r.opacity}
ringIndex={i}
totalRings={layers}
/>
);
})}
</svg>
</motion.div>
</motion.div>
);
}
// ─── Label Overlay ───────────────────────────────────────────────────────────
function SegmentLabel({
stage,
pct,
isHorizontal,
showValues,
showPercentage,
showLabels,
formatPercentage,
formatValue,
index,
staggerDelay,
layout = "spread",
orientation,
align = "center",
}: {
stage: FunnelStage;
pct: number;
isHorizontal: boolean;
showValues: boolean;
showPercentage: boolean;
showLabels: boolean;
formatPercentage: (p: number) => string;
formatValue: (v: number) => string;
index: number;
staggerDelay: number;
layout?: "spread" | "grouped";
orientation?: "vertical" | "horizontal";
align?: "center" | "start" | "end";
}) {
const display = stage.displayValue ?? formatValue(stage.value);
const valueEl = showValues && (
<span className="whitespace-nowrap font-semibold text-foreground text-sm">
{display}
</span>
);
const pctEl = showPercentage && (
<span className="rounded-full bg-foreground px-3 py-1 font-bold text-background text-xs shadow-sm">
{formatPercentage(pct)}
</span>
);
const labelEl = showLabels && (
<span className="whitespace-nowrap font-medium text-muted-foreground text-xs">
{stage.label}
</span>
);
if (layout === "spread") {
return (
<motion.div
animate={{ opacity: 1 }}
className={cn(
"absolute inset-0 flex",
isHorizontal ? "flex-col items-center" : "flex-row items-center"
)}
initial={{ opacity: 0 }}
transition={{
delay: index * staggerDelay + 0.25,
duration: 0.35,
ease: "easeOut",
}}
>
{isHorizontal ? (
<>
<div className="flex h-[16%] items-end justify-center pb-1">
{valueEl}
</div>
<div className="flex flex-1 items-center justify-center">
{pctEl}
</div>
<div className="flex h-[16%] items-start justify-center pt-1">
{labelEl}
</div>
</>
) : (
<>
<div className="flex w-[16%] items-center justify-end pr-2">
{valueEl}
</div>
<div className="flex flex-1 items-center justify-center">
{pctEl}
</div>
<div className="flex w-[16%] items-center justify-start pl-2">
{labelEl}
</div>
</>
)}
</motion.div>
);
}
// Grouped layout
const resolvedOrientation =
orientation ?? (isHorizontal ? "vertical" : "horizontal");
const isVerticalStack = resolvedOrientation === "vertical";
const justifyMap = {
start: "justify-start",
center: "justify-center",
end: "justify-end",
} as const;
const itemsMap = {
start: "items-start",
center: "items-center",
end: "items-end",
} as const;
return (
<motion.div
animate={{ opacity: 1 }}
className={cn(
"absolute inset-0 flex",
isHorizontal
? cn("flex-col items-center", justifyMap[align])
: cn("flex-row items-center", justifyMap[align])
)}
initial={{ opacity: 0 }}
style={{
padding: isHorizontal ? "8% 0" : "0 8%",
}}
transition={{
delay: index * staggerDelay + 0.25,
duration: 0.35,
ease: "easeOut",
}}
>
<div
className={cn(
"flex gap-1.5",
isVerticalStack
? cn("flex-col", itemsMap[isHorizontal ? "center" : align])
: cn("flex-row", itemsMap.center)
)}
>
{valueEl}
{pctEl}
{labelEl}
</div>
</motion.div>
);
}
// ─── FunnelChart ─────────────────────────────────────────────────────────────
export function FunnelChart({
data,
orientation = "horizontal",
color = "var(--chart-1)",
layers = 3,
className,
style,
showPercentage = true,
showValues = true,
showLabels = true,
hoveredIndex: hoveredIndexProp,
onHoverChange,
formatPercentage = fmtPct,
formatValue = fmtVal,
staggerDelay = 0.12,
gap = 4,
renderPattern,
edges = "curved",
labelLayout = "spread",
labelOrientation,
labelAlign = "center",
grid: gridProp = false,
}: FunnelChartProps) {
const ref = useRef<HTMLDivElement>(null);
const [sz, setSz] = useState({ w: 0, h: 0 });
const [internalHoveredIndex, setInternalHoveredIndex] = useState<
number | null
>(null);
const isControlled = hoveredIndexProp !== undefined;
const hoveredIndex = isControlled ? hoveredIndexProp : internalHoveredIndex;
const setHoveredIndex = useCallback(
(index: number | null) => {
if (isControlled) {
onHoverChange?.(index);
} else {
setInternalHoveredIndex(index);
}
},
[isControlled, onHoverChange]
);
const measure = useCallback(() => {
if (!ref.current) return;
const { width: w, height: h } = ref.current.getBoundingClientRect();
if (w > 0 && h > 0) setSz({ w, h });
}, []);
useEffect(() => {
measure();
const ro = new ResizeObserver(measure);
if (ref.current) ro.observe(ref.current);
return () => ro.disconnect();
}, [measure]);
if (!data.length) return null;
const first = data[0];
if (!first) return null;
const max = first.value;
const n = data.length;
const norms = data.map((d) => d.value / max);
const horiz = orientation === "horizontal";
const { w: W, h: H } = sz;
const totalGap = gap * (n - 1);
const segW = (W - (horiz ? totalGap : 0)) / n;
const segH = (H - (horiz ? 0 : totalGap)) / n;
// Grid config
const gridEnabled = gridProp !== false;
const gridCfg = typeof gridProp === "object" ? gridProp : {};
const showBands = gridEnabled && (gridCfg.bands ?? true);
const bandColor = gridCfg.bandColor ?? "var(--color-muted)";
const showGridLines = gridEnabled && (gridCfg.lines ?? true);
const gridLineColor = gridCfg.lineColor ?? "var(--chart-grid)";
const gridLineOpacity = gridCfg.lineOpacity ?? 1;
const gridLineWidth = gridCfg.lineWidth ?? 1;
return (
<div
className={cn("relative w-full select-none overflow-visible", className)}
ref={ref}
style={{
aspectRatio: horiz ? "2.2 / 1" : "1 / 1.8",
...style,
}}
>
{W > 0 && H > 0 && (
<>
{/* Grid background bands */}
{gridEnabled && (
<svg
aria-hidden="true"
className="pointer-events-none absolute inset-0 h-full w-full"
preserveAspectRatio="none"
role="presentation"
viewBox={`0 0 ${W} ${H}`}
>
{showBands &&
data.map((stage, i) => {
if (i % 2 !== 0) return null;
if (horiz) {
const x = (segW + gap) * i;
return (
<rect
fill={bandColor}
height={H}
key={`band-${stage.label}`}
width={segW}
x={x}
y={0}
/>
);
}
const y = (segH + gap) * i;
return (
<rect
fill={bandColor}
height={segH}
key={`band-${stage.label}`}
width={W}
x={0}
y={y}
/>
);
})}
</svg>
)}
{/* Segments */}
<div
className={cn(
"absolute inset-0 flex overflow-visible",
horiz ? "flex-row" : "flex-col"
)}
style={{ gap }}
>
{data.map((stage, i) => {
const normStart = norms[i] ?? 0;
const normEnd = norms[Math.min(i + 1, n - 1)] ?? 0;
const firstStop = stage.gradient?.[0];
const segColor = firstStop
? firstStop.color
: (stage.color ?? color);
return horiz ? (
<HSegment
color={segColor}
dimmed={hoveredIndex !== null && hoveredIndex !== i}
fullH={H}
gradientStops={stage.gradient}
hovered={hoveredIndex === i}
index={i}
key={stage.label}
layers={layers}
normEnd={normEnd}
normStart={normStart}
renderPattern={renderPattern}
segW={segW}
staggerDelay={staggerDelay}
straight={edges === "straight"}
/>
) : (
<VSegment
color={segColor}
dimmed={hoveredIndex !== null && hoveredIndex !== i}
fullW={W}
gradientStops={stage.gradient}
hovered={hoveredIndex === i}
index={i}
key={stage.label}
layers={layers}
normEnd={normEnd}
normStart={normStart}
renderPattern={renderPattern}
segH={segH}
staggerDelay={staggerDelay}
straight={edges === "straight"}
/>
);
})}
</div>
{/* Grid lines */}
{gridEnabled && showGridLines && (
<svg
aria-hidden="true"
className="pointer-events-none absolute inset-0 h-full w-full"
preserveAspectRatio="none"
role="presentation"
viewBox={`0 0 ${W} ${H}`}
>
{Array.from({ length: n - 1 }, (_, i) => {
const idx = i + 1;
if (horiz) {
const x = segW * idx + gap * i + gap / 2;
return (
<line
key={`grid-${idx}`}
stroke={gridLineColor}
strokeOpacity={gridLineOpacity}
strokeWidth={gridLineWidth}
x1={x}
x2={x}
y1={0}
y2={H}
/>
);
}
const y = segH * idx + gap * i + gap / 2;
return (
<line
key={`grid-${idx}`}
stroke={gridLineColor}
strokeOpacity={gridLineOpacity}
strokeWidth={gridLineWidth}
x1={0}
x2={W}
y1={y}
y2={y}
/>
);
})}
</svg>
)}
{/* Label overlays — hover triggers */}
{data.map((stage, i) => {
const pct = (stage.value / max) * 100;
const posStyle: CSSProperties = horiz
? { left: (segW + gap) * i, width: segW, top: 0, height: H }
: { top: (segH + gap) * i, height: segH, left: 0, width: W };
const isDimmed = hoveredIndex !== null && hoveredIndex !== i;
return (
<motion.div
animate={{ opacity: isDimmed ? 0.4 : 1 }}
className="absolute cursor-pointer"
key={`lbl-${stage.label}`}
onMouseEnter={() => setHoveredIndex(i)}
onMouseLeave={() => setHoveredIndex(null)}
style={{ ...posStyle, zIndex: 20 }}
transition={{ type: "spring", stiffness: 300, damping: 24 }}
>
<SegmentLabel
align={labelAlign}
formatPercentage={formatPercentage}
formatValue={formatValue}
index={i}
isHorizontal={horiz}
layout={labelLayout}
orientation={labelOrientation}
pct={pct}
showLabels={showLabels}
showPercentage={showPercentage}
showValues={showValues}
stage={stage}
staggerDelay={staggerDelay}
/>
</motion.div>
);
})}
</>
)}
</div>
);
}
FunnelChart.displayName = "FunnelChart";
export default FunnelChart;

View File

@@ -0,0 +1,290 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
import * as RechartsPrimitive from 'recharts';
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const;
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode;
icon?: React.ComponentType;
} & ({ color?: string; theme?: never } | { color?: never; theme: Record<keyof typeof THEMES, string> });
};
type ChartContextProps = {
config: ChartConfig;
};
const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error('useChart must be used within a <ChartContainer />');
}
return context;
}
function ChartContainer({
id,
className,
children,
config,
...props
}: React.ComponentProps<'div'> & {
config: ChartConfig;
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children'];
}) {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`;
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color);
if (!colorConfig.length) {
return null;
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join('\n')}
}
`,
)
.join('\n'),
}}
/>
);
};
const ChartTooltip = RechartsPrimitive.Tooltip;
function ChartTooltipContent({
active,
payload,
className,
indicator = 'dot',
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<'div'> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: 'line' | 'dot' | 'dashed';
nameKey?: string;
labelKey?: string;
}) {
const { config } = useChart();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}
const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value =
!labelKey && typeof label === 'string' ? config[label as keyof typeof config]?.label || label : itemConfig?.label;
if (labelFormatter) {
return <div className={cn('font-medium', labelClassName)}>{labelFormatter(value, payload)}</div>;
}
if (!value) {
return null;
}
return <div className={cn('font-medium', labelClassName)}>{value}</div>;
}, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]);
if (!active || !payload?.length) {
return null;
}
const nestLabel = payload.length === 1 && indicator !== 'dot';
return (
<div
className={cn(
'border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl',
className,
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (
<div
key={item.dataKey}
className={cn(
'[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
indicator === 'dot' && 'items-center',
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn('shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]', {
'h-2.5 w-2.5': indicator === 'dot',
'w-1': indicator === 'line',
'w-0 border-[1.5px] border-dashed bg-transparent': indicator === 'dashed',
'my-0.5': nestLabel && indicator === 'dashed',
})}
style={
{
'--color-bg': indicatorColor,
'--color-border': indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn('flex flex-1 justify-between leading-none', nestLabel ? 'items-end' : 'items-center')}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">{itemConfig?.label || item.name}</span>
</div>
{item.value && (
<span className="text-foreground font-mono font-medium tabular-nums">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
}
const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = 'bottom',
nameKey,
}: React.ComponentProps<'div'> &
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean;
nameKey?: string;
}) {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (
<div className={cn('flex items-center justify-center gap-4', verticalAlign === 'top' ? 'pb-3' : 'pt-3', className)}>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (
<div
key={item.value}
className={cn('[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3')}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
);
})}
</div>
);
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
if (typeof payload !== 'object' || payload === null) {
return undefined;
}
const payloadPayload =
'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
? payload.payload
: undefined;
let configLabelKey: string = key;
if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
configLabelKey = payload[key as keyof typeof payload] as string;
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) {
configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string;
}
return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config];
}
export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle };

58
lib/api/annotations.ts Normal file
View File

@@ -0,0 +1,58 @@
import apiRequest from './client'
export type AnnotationCategory = 'deploy' | 'campaign' | 'incident' | 'other'
export interface Annotation {
id: string
site_id: string
date: string
time?: string | null
text: string
category: AnnotationCategory
created_by: string
created_at: string
updated_at: string
}
export interface CreateAnnotationRequest {
date: string
time?: string
text: string
category?: AnnotationCategory
}
export interface UpdateAnnotationRequest {
date: string
time?: string
text: string
category: AnnotationCategory
}
export async function listAnnotations(siteId: string, startDate?: string, endDate?: string): Promise<Annotation[]> {
const params = new URLSearchParams()
if (startDate) params.set('start_date', startDate)
if (endDate) params.set('end_date', endDate)
const qs = params.toString()
const res = await apiRequest<{ annotations: Annotation[] }>(`/sites/${siteId}/annotations${qs ? `?${qs}` : ''}`)
return res?.annotations ?? []
}
export async function createAnnotation(siteId: string, data: CreateAnnotationRequest): Promise<Annotation> {
return apiRequest<Annotation>(`/sites/${siteId}/annotations`, {
method: 'POST',
body: JSON.stringify(data),
})
}
export async function updateAnnotation(siteId: string, annotationId: string, data: UpdateAnnotationRequest): Promise<Annotation> {
return apiRequest<Annotation>(`/sites/${siteId}/annotations/${annotationId}`, {
method: 'PUT',
body: JSON.stringify(data),
})
}
export async function deleteAnnotation(siteId: string, annotationId: string): Promise<void> {
await apiRequest(`/sites/${siteId}/annotations/${annotationId}`, {
method: 'DELETE',
})
}

View File

@@ -202,9 +202,9 @@ async function apiRequest<T>(
// * We rely on HttpOnly cookies, so no manual Authorization header injection.
// * We MUST set credentials: 'include' for the browser to send cookies cross-origin (or same-site).
// * Add CSRF token for state-changing requests to Auth API
// * Auth API uses Double Submit Cookie pattern for CSRF protection
if (isAuthRequest && isStateChangingMethod(method)) {
// * Add CSRF token for all state-changing requests (Pulse API and Auth API).
// * Both backends enforce the double-submit cookie pattern server-side.
if (isStateChangingMethod(method)) {
const csrfToken = getCSRFToken()
if (csrfToken) {
headers['X-CSRF-Token'] = csrfToken

View File

@@ -21,6 +21,8 @@ export interface Site {
enable_performance_insights?: boolean
// Bot and noise filtering
filter_bots?: boolean
// Hide unknown locations from stats
hide_unknown_locations?: boolean
// Data retention (months); 0 = keep forever
data_retention_months?: number
created_at: string
@@ -49,6 +51,8 @@ export interface UpdateSiteRequest {
enable_performance_insights?: boolean
// Bot and noise filtering
filter_bots?: boolean
// Hide unknown locations from stats
hide_unknown_locations?: boolean
// Data retention (months); 0 = keep forever
data_retention_months?: number
}

View File

@@ -245,8 +245,8 @@ export interface DashboardData {
goal_counts?: GoalCountStat[]
}
export function getDashboard(siteId: string, startDate?: string, endDate?: string, limit = 10, interval?: string): Promise<DashboardData> {
return apiRequest<DashboardData>(`/sites/${siteId}/dashboard${buildQuery({ startDate, endDate, limit, interval })}`)
export function getDashboard(siteId: string, startDate?: string, endDate?: string, limit = 10, interval?: string, filters?: string): Promise<DashboardData> {
return apiRequest<DashboardData>(`/sites/${siteId}/dashboard${buildQuery({ startDate, endDate, limit, interval, filters })}`)
}
export function getPublicDashboard(

View File

@@ -7,6 +7,7 @@ import { LoadingOverlay, useSessionSync, SessionExpiryWarning } from '@ciphera-n
import { logoutAction, getSessionAction, setSessionAction } from '@/app/actions/auth'
import { getUserOrganizations, switchContext } from '@/lib/api/organization'
import { logger } from '@/lib/utils/logger'
import { cleanupStaleStorage } from '@/lib/utils/storage-cleanup'
interface User {
id: string
@@ -131,6 +132,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
// Initial load
useEffect(() => {
const init = async () => {
cleanupStaleStorage()
// * 1. Check server-side session (cookies)
let session: Awaited<ReturnType<typeof getSessionAction>> = null
try {

205
lib/country-centroids.ts Normal file
View File

@@ -0,0 +1,205 @@
/**
* Country centroids: ISO 3166-1 alpha-2 → { lat, lng }
* Used to place markers on the DottedMap for visitor locations.
*/
export const countryCentroids: Record<string, { lat: number; lng: number }> = {
AD: { lat: 42.5, lng: 1.5 },
AE: { lat: 24.0, lng: 54.0 },
AF: { lat: 33.0, lng: 65.0 },
AG: { lat: 17.1, lng: -61.8 },
AL: { lat: 41.0, lng: 20.0 },
AM: { lat: 40.0, lng: 45.0 },
AO: { lat: -12.5, lng: 18.5 },
AR: { lat: -34.0, lng: -64.0 },
AT: { lat: 47.3, lng: 13.3 },
AU: { lat: -25.0, lng: 134.0 },
AZ: { lat: 40.5, lng: 47.5 },
BA: { lat: 44.0, lng: 17.8 },
BB: { lat: 13.2, lng: -59.5 },
BD: { lat: 24.0, lng: 90.0 },
BE: { lat: 50.8, lng: 4.0 },
BF: { lat: 13.0, lng: -1.5 },
BG: { lat: 43.0, lng: 25.0 },
BH: { lat: 26.0, lng: 50.6 },
BI: { lat: -3.5, lng: 29.9 },
BJ: { lat: 9.3, lng: 2.3 },
BN: { lat: 4.5, lng: 114.7 },
BO: { lat: -17.0, lng: -65.0 },
BR: { lat: -10.0, lng: -55.0 },
BS: { lat: 24.3, lng: -76.0 },
BT: { lat: 27.5, lng: 90.5 },
BW: { lat: -22.0, lng: 24.0 },
BY: { lat: 53.0, lng: 28.0 },
BZ: { lat: 17.3, lng: -88.8 },
CA: { lat: 56.0, lng: -96.0 },
CD: { lat: -3.0, lng: 23.0 },
CF: { lat: 7.0, lng: 21.0 },
CG: { lat: -1.0, lng: 15.0 },
CH: { lat: 47.0, lng: 8.0 },
CI: { lat: 8.0, lng: -5.5 },
CL: { lat: -30.0, lng: -71.0 },
CM: { lat: 6.0, lng: 12.5 },
CN: { lat: 35.0, lng: 105.0 },
CO: { lat: 4.0, lng: -72.0 },
CR: { lat: 10.0, lng: -84.0 },
CU: { lat: 22.0, lng: -79.5 },
CV: { lat: 16.0, lng: -24.0 },
CY: { lat: 35.0, lng: 33.0 },
CZ: { lat: 49.8, lng: 15.5 },
DE: { lat: 51.2, lng: 10.4 },
DJ: { lat: 11.5, lng: 43.1 },
DK: { lat: 56.0, lng: 10.0 },
DM: { lat: 15.4, lng: -61.4 },
DO: { lat: 19.0, lng: -70.7 },
DZ: { lat: 28.0, lng: 3.0 },
EC: { lat: -2.0, lng: -77.5 },
EE: { lat: 59.0, lng: 26.0 },
EG: { lat: 27.0, lng: 30.0 },
ER: { lat: 15.0, lng: 39.0 },
ES: { lat: 40.0, lng: -4.0 },
ET: { lat: 8.0, lng: 38.0 },
FI: { lat: 64.0, lng: 26.0 },
FJ: { lat: -18.0, lng: 175.0 },
FM: { lat: 6.9, lng: 158.2 },
FR: { lat: 46.0, lng: 2.0 },
GA: { lat: -1.0, lng: 11.8 },
GB: { lat: 54.0, lng: -2.0 },
GD: { lat: 12.1, lng: -61.7 },
GE: { lat: 42.0, lng: 43.5 },
GH: { lat: 8.0, lng: -2.0 },
GM: { lat: 13.5, lng: -15.3 },
GN: { lat: 11.0, lng: -10.0 },
GQ: { lat: 2.0, lng: 10.0 },
GR: { lat: 39.0, lng: 22.0 },
GT: { lat: 15.5, lng: -90.3 },
GW: { lat: 12.0, lng: -15.0 },
GY: { lat: 5.0, lng: -59.0 },
HK: { lat: 22.3, lng: 114.2 },
HN: { lat: 15.0, lng: -86.5 },
HR: { lat: 45.2, lng: 15.5 },
HT: { lat: 19.0, lng: -72.4 },
HU: { lat: 47.0, lng: 20.0 },
ID: { lat: -5.0, lng: 120.0 },
IE: { lat: 53.0, lng: -8.0 },
IL: { lat: 31.5, lng: 34.8 },
IN: { lat: 20.0, lng: 77.0 },
IQ: { lat: 33.0, lng: 44.0 },
IR: { lat: 32.0, lng: 53.0 },
IS: { lat: 65.0, lng: -18.0 },
IT: { lat: 42.8, lng: 12.8 },
JM: { lat: 18.3, lng: -77.4 },
JO: { lat: 31.0, lng: 36.0 },
JP: { lat: 36.0, lng: 138.0 },
KE: { lat: 1.0, lng: 38.0 },
KG: { lat: 41.0, lng: 75.0 },
KH: { lat: 13.0, lng: 105.0 },
KI: { lat: 1.4, lng: 173.0 },
KM: { lat: -12.2, lng: 44.2 },
KN: { lat: 17.3, lng: -62.7 },
KP: { lat: 40.0, lng: 127.0 },
KR: { lat: 37.0, lng: 127.5 },
KW: { lat: 29.5, lng: 47.8 },
KZ: { lat: 48.0, lng: 68.0 },
LA: { lat: 18.0, lng: 105.0 },
LB: { lat: 33.9, lng: 35.8 },
LC: { lat: 13.9, lng: -61.0 },
LI: { lat: 47.2, lng: 9.5 },
LK: { lat: 7.0, lng: 81.0 },
LR: { lat: 6.5, lng: -9.5 },
LS: { lat: -29.5, lng: 28.5 },
LT: { lat: 56.0, lng: 24.0 },
LU: { lat: 49.8, lng: 6.2 },
LV: { lat: 57.0, lng: 25.0 },
LY: { lat: 25.0, lng: 17.0 },
MA: { lat: 32.0, lng: -5.0 },
MC: { lat: 43.7, lng: 7.4 },
MD: { lat: 47.0, lng: 29.0 },
ME: { lat: 42.5, lng: 19.3 },
MG: { lat: -20.0, lng: 47.0 },
MK: { lat: 41.8, lng: 22.0 },
ML: { lat: 17.0, lng: -4.0 },
MM: { lat: 22.0, lng: 98.0 },
MN: { lat: 46.0, lng: 105.0 },
MO: { lat: 22.2, lng: 113.5 },
MR: { lat: 20.0, lng: -12.0 },
MT: { lat: 35.9, lng: 14.4 },
MU: { lat: -20.3, lng: 57.6 },
MV: { lat: 3.2, lng: 73.2 },
MW: { lat: -13.5, lng: 34.0 },
MX: { lat: 23.0, lng: -102.0 },
MY: { lat: 2.5, lng: 112.5 },
MZ: { lat: -18.3, lng: 35.0 },
NA: { lat: -22.0, lng: 17.0 },
NE: { lat: 16.0, lng: 8.0 },
NG: { lat: 10.0, lng: 8.0 },
NI: { lat: 13.0, lng: -85.0 },
NL: { lat: 52.5, lng: 5.8 },
NO: { lat: 62.0, lng: 10.0 },
NP: { lat: 28.0, lng: 84.0 },
NR: { lat: -0.5, lng: 166.9 },
NZ: { lat: -41.0, lng: 174.0 },
OM: { lat: 21.0, lng: 57.0 },
PA: { lat: 9.0, lng: -80.0 },
PE: { lat: -10.0, lng: -76.0 },
PG: { lat: -6.0, lng: 147.0 },
PH: { lat: 13.0, lng: 122.0 },
PK: { lat: 30.0, lng: 70.0 },
PL: { lat: 52.0, lng: 20.0 },
PR: { lat: 18.3, lng: -66.6 },
PS: { lat: 31.9, lng: 35.2 },
PT: { lat: 39.5, lng: -8.0 },
PW: { lat: 7.5, lng: 134.6 },
PY: { lat: -23.0, lng: -58.0 },
QA: { lat: 25.5, lng: 51.3 },
RO: { lat: 46.0, lng: 25.0 },
RS: { lat: 44.0, lng: 21.0 },
RU: { lat: 60.0, lng: 100.0 },
RW: { lat: -2.0, lng: 29.9 },
SA: { lat: 24.0, lng: 45.0 },
SB: { lat: -8.0, lng: 159.0 },
SC: { lat: -4.7, lng: 55.5 },
SD: { lat: 15.0, lng: 30.0 },
SE: { lat: 62.0, lng: 15.0 },
SG: { lat: 1.4, lng: 103.8 },
SI: { lat: 46.1, lng: 15.0 },
SK: { lat: 48.7, lng: 19.5 },
SL: { lat: 8.5, lng: -11.8 },
SM: { lat: 43.9, lng: 12.4 },
SN: { lat: 14.5, lng: -14.5 },
SO: { lat: 5.0, lng: 46.0 },
SR: { lat: 4.0, lng: -56.0 },
SS: { lat: 7.0, lng: 30.0 },
ST: { lat: 1.0, lng: 7.0 },
SV: { lat: 13.8, lng: -88.9 },
SY: { lat: 35.0, lng: 38.0 },
SZ: { lat: -26.5, lng: 31.5 },
TD: { lat: 15.0, lng: 19.0 },
TG: { lat: 8.0, lng: 1.2 },
TH: { lat: 15.0, lng: 100.0 },
TJ: { lat: 39.0, lng: 71.0 },
TL: { lat: -8.8, lng: 126.0 },
TM: { lat: 40.0, lng: 60.0 },
TN: { lat: 34.0, lng: 9.0 },
TO: { lat: -20.0, lng: -175.0 },
TR: { lat: 39.0, lng: 35.0 },
TT: { lat: 10.5, lng: -61.3 },
TV: { lat: -8.0, lng: 178.0 },
TW: { lat: 23.5, lng: 121.0 },
TZ: { lat: -6.0, lng: 35.0 },
UA: { lat: 49.0, lng: 32.0 },
UG: { lat: 1.0, lng: 32.0 },
US: { lat: 39.8, lng: -98.5 },
UY: { lat: -33.0, lng: -56.0 },
UZ: { lat: 41.0, lng: 64.0 },
VA: { lat: 41.9, lng: 12.5 },
VC: { lat: 13.3, lng: -61.2 },
VE: { lat: 8.0, lng: -66.0 },
VN: { lat: 16.0, lng: 108.0 },
VU: { lat: -16.0, lng: 167.0 },
WS: { lat: -13.8, lng: -172.1 },
XK: { lat: 42.6, lng: 21.0 },
YE: { lat: 15.0, lng: 48.0 },
ZA: { lat: -29.0, lng: 24.0 },
ZM: { lat: -15.0, lng: 28.0 },
ZW: { lat: -20.0, lng: 30.0 },
}

View File

@@ -0,0 +1,53 @@
// * SSE hook for real-time visitor streaming.
// * Replaces 5-second polling with a persistent EventSource connection.
// * The backend broadcasts one DB query per site to all connected clients,
// * so 1,000 users on the same site share a single query instead of each
// * triggering their own.
import { useEffect, useRef, useState, useCallback } from 'react'
import { API_URL } from '@/lib/api/client'
import type { Visitor } from '@/lib/api/realtime'
interface UseRealtimeSSEReturn {
visitors: Visitor[]
connected: boolean
}
export function useRealtimeSSE(siteId: string): UseRealtimeSSEReturn {
const [visitors, setVisitors] = useState<Visitor[]>([])
const [connected, setConnected] = useState(false)
const esRef = useRef<EventSource | null>(null)
// Stable callback so we don't recreate EventSource on every render
const handleMessage = useCallback((event: MessageEvent) => {
try {
const data = JSON.parse(event.data)
setVisitors(data.visitors || [])
} catch {
// Ignore malformed messages
}
}, [])
useEffect(() => {
if (!siteId) return
const url = `${API_URL}/api/v1/sites/${siteId}/realtime/stream`
const es = new EventSource(url, { withCredentials: true })
esRef.current = es
es.onopen = () => setConnected(true)
es.onmessage = handleMessage
es.onerror = () => {
setConnected(false)
// EventSource auto-reconnects with exponential backoff
}
return () => {
es.close()
esRef.current = null
setConnected(false)
}
}, [siteId, handleMessage])
return { visitors, connected }
}

42
lib/swr/cache-provider.ts Normal file
View File

@@ -0,0 +1,42 @@
// * Bounded LRU cache provider for SWR
// * Prevents unbounded memory growth during long sessions across many sites
const MAX_CACHE_ENTRIES = 200
export function boundedCacheProvider() {
const map = new Map()
const accessOrder: string[] = []
const touch = (key: string) => {
const idx = accessOrder.indexOf(key)
if (idx > -1) accessOrder.splice(idx, 1)
accessOrder.push(key)
}
const evict = () => {
while (map.size > MAX_CACHE_ENTRIES && accessOrder.length > 0) {
const oldest = accessOrder.shift()!
map.delete(oldest)
}
}
return {
get(key: string) {
if (map.has(key)) touch(key)
return map.get(key)
},
set(key: string, value: any) {
map.set(key, value)
touch(key)
evict()
},
delete(key: string) {
map.delete(key)
const idx = accessOrder.indexOf(key)
if (idx > -1) accessOrder.splice(idx, 1)
},
keys() {
return map.keys()
},
}
}

View File

@@ -16,12 +16,15 @@ import {
getStats,
getDailyStats,
} from '@/lib/api/stats'
import { listAnnotations } from '@/lib/api/annotations'
import type { Annotation } from '@/lib/api/annotations'
import { getSite } from '@/lib/api/sites'
import type { Site } from '@/lib/api/sites'
import type {
Stats,
DailyStat,
CampaignStat,
DashboardData,
DashboardOverviewData,
DashboardPagesData,
DashboardLocationsData,
@@ -34,7 +37,7 @@ import type {
// * SWR fetcher functions
const fetchers = {
site: (siteId: string) => getSite(siteId),
dashboard: (siteId: string, start: string, end: string) => getDashboard(siteId, start, end),
dashboard: (siteId: string, start: string, end: string, interval?: string, filters?: string) => getDashboard(siteId, start, end, 10, interval, filters),
dashboardOverview: (siteId: string, start: string, end: string, interval?: string, filters?: string) => getDashboardOverview(siteId, start, end, interval, filters),
dashboardPages: (siteId: string, start: string, end: string, filters?: string) => getDashboardPages(siteId, start, end, undefined, filters),
dashboardLocations: (siteId: string, start: string, end: string, filters?: string) => getDashboardLocations(siteId, start, end, undefined, undefined, filters),
@@ -48,6 +51,7 @@ const fetchers = {
realtime: (siteId: string) => getRealtime(siteId),
campaigns: (siteId: string, start: string, end: string, limit: number) =>
getCampaigns(siteId, start, end, limit),
annotations: (siteId: string, start: string, end: string) => listAnnotations(siteId, start, end),
}
// * Standard SWR config for dashboard data
@@ -78,14 +82,15 @@ export function useSite(siteId: string) {
)
}
// * Hook for dashboard summary data (refreshed less frequently)
export function useDashboard(siteId: string, start: string, end: string) {
return useSWR(
siteId && start && end ? ['dashboard', siteId, start, end] : null,
() => fetchers.dashboard(siteId, start, end),
// * Hook for full dashboard data (single request replaces 7 focused hooks)
// * The backend runs all queries in parallel and caches the result in Redis (30s TTL)
export function useDashboard(siteId: string, start: string, end: string, interval?: string, filters?: string) {
return useSWR<DashboardData>(
siteId && start && end ? ['dashboard', siteId, start, end, interval, filters] : null,
() => fetchers.dashboard(siteId, start, end, interval, filters),
{
...dashboardSWRConfig,
// * Refresh every 60 seconds for dashboard summary
// * Refresh every 60 seconds for dashboard data
refreshInterval: 60 * 1000,
// * Deduping interval to prevent duplicate requests
dedupingInterval: 10 * 1000,
@@ -247,5 +252,18 @@ export function useCampaigns(siteId: string, start: string, end: string, limit =
)
}
// * Hook for annotations data
export function useAnnotations(siteId: string, startDate: string, endDate: string) {
return useSWR<Annotation[]>(
siteId && startDate && endDate ? ['annotations', siteId, startDate, endDate] : null,
() => fetchers.annotations(siteId, startDate, endDate),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Re-export for convenience
export { fetchers }

1
lib/utils.ts Normal file
View File

@@ -0,0 +1 @@
export { cn } from '@ciphera-net/ui'

View File

@@ -1,101 +1,96 @@
import React from 'react'
import {
Globe,
WindowsLogo,
AppleLogo,
LinuxLogo,
AndroidLogo,
Question,
DeviceMobile,
DeviceTablet,
Desktop,
GoogleLogo,
FacebookLogo,
XLogo,
LinkedinLogo,
InstagramLogo,
GithubLogo,
YoutubeLogo,
RedditLogo,
Robot,
Link,
WhatsappLogo,
TelegramLogo,
SnapchatLogo,
PinterestLogo,
ThreadsLogo,
} from '@phosphor-icons/react'
/**
* Google's public favicon service base URL.
* Append `?domain=<host>&sz=<px>` to get a favicon.
*/
export const FAVICON_SERVICE_URL = 'https://www.google.com/s2/favicons'
import {
FaChrome,
FaFirefox,
FaSafari,
FaEdge,
FaOpera,
FaInternetExplorer,
FaWindows,
FaApple,
FaLinux,
FaAndroid,
FaDesktop,
FaMobileAlt,
FaTabletAlt,
FaGoogle,
FaFacebook,
FaLinkedin,
FaInstagram,
FaGithub,
FaYoutube,
FaReddit,
FaQuestion,
FaGlobe
} from 'react-icons/fa'
import { FaXTwitter } from 'react-icons/fa6'
import { SiBrave, SiOpenai, SiPerplexity, SiAnthropic, SiGooglegemini } from 'react-icons/si'
import { RiRobot2Fill } from 'react-icons/ri'
import { MdDeviceUnknown, MdSmartphone, MdTabletMac, MdDesktopWindows } from 'react-icons/md'
export function getBrowserIcon(browserName: string) {
if (!browserName) return <FaGlobe className="text-neutral-400" />
const lower = browserName.toLowerCase()
if (lower.includes('chrome')) return <FaChrome className="text-blue-500" />
if (lower.includes('firefox')) return <FaFirefox className="text-orange-500" />
if (lower.includes('safari')) return <FaSafari className="text-blue-400" />
if (lower.includes('edge')) return <FaEdge className="text-blue-600" />
if (lower.includes('opera')) return <FaOpera className="text-red-500" />
if (lower.includes('ie') || lower.includes('explorer')) return <FaInternetExplorer className="text-blue-500" />
if (lower.includes('brave')) return <SiBrave className="text-orange-600" />
return <FaGlobe className="text-neutral-400" />
if (!browserName) return <Globe className="text-neutral-400" />
return <Globe className="text-neutral-500" />
}
export function getOSIcon(osName: string) {
if (!osName) return <MdDeviceUnknown className="text-neutral-400" />
if (!osName) return <Question className="text-neutral-400" />
const lower = osName.toLowerCase()
if (lower.includes('win')) return <FaWindows className="text-blue-500" />
if (lower.includes('mac') || lower.includes('ios')) return <FaApple className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('linux') || lower.includes('ubuntu') || lower.includes('debian')) return <FaLinux className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('android')) return <FaAndroid className="text-green-500" />
return <MdDeviceUnknown className="text-neutral-400" />
if (lower.includes('win')) return <WindowsLogo className="text-blue-500" />
if (lower.includes('mac') || lower.includes('ios')) return <AppleLogo className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('linux') || lower.includes('ubuntu') || lower.includes('debian')) return <LinuxLogo className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('android')) return <AndroidLogo className="text-green-500" />
return <Question className="text-neutral-400" />
}
export function getDeviceIcon(deviceName: string) {
if (!deviceName) return <MdDeviceUnknown className="text-neutral-400" />
if (!deviceName) return <Question className="text-neutral-400" />
const lower = deviceName.toLowerCase()
if (lower.includes('mobile') || lower.includes('phone')) return <MdSmartphone className="text-neutral-500" />
if (lower.includes('tablet') || lower.includes('ipad')) return <MdTabletMac className="text-neutral-500" />
if (lower.includes('desktop') || lower.includes('laptop')) return <MdDesktopWindows className="text-neutral-500" />
return <MdDeviceUnknown className="text-neutral-400" />
if (lower.includes('mobile') || lower.includes('phone')) return <DeviceMobile className="text-neutral-500" />
if (lower.includes('tablet') || lower.includes('ipad')) return <DeviceTablet className="text-neutral-500" />
if (lower.includes('desktop') || lower.includes('laptop')) return <Desktop className="text-neutral-500" />
return <Question className="text-neutral-400" />
}
export function getReferrerIcon(referrerName: string) {
if (!referrerName) return <FaGlobe className="text-neutral-400" />
if (!referrerName) return <Globe className="text-neutral-400" />
const lower = referrerName.toLowerCase()
if (lower.includes('google')) return <FaGoogle className="text-blue-500" />
if (lower.includes('facebook')) return <FaFacebook className="text-blue-600" />
if (lower.includes('twitter') || lower.includes('t.co') || lower.includes('x.com')) return <FaXTwitter className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('linkedin')) return <FaLinkedin className="text-blue-700" />
if (lower.includes('instagram')) return <FaInstagram className="text-pink-600" />
if (lower.includes('github')) return <FaGithub className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('youtube')) return <FaYoutube className="text-red-600" />
if (lower.includes('reddit')) return <FaReddit className="text-orange-600" />
if (lower.includes('google')) return <GoogleLogo className="text-blue-500" />
if (lower.includes('facebook')) return <FacebookLogo className="text-blue-600" />
if (lower.includes('twitter') || lower.includes('t.co') || lower.includes('x.com')) return <XLogo className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('linkedin')) return <LinkedinLogo className="text-blue-700" />
if (lower.includes('instagram')) return <InstagramLogo className="text-pink-600" />
if (lower.includes('github')) return <GithubLogo className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('youtube')) return <YoutubeLogo className="text-red-600" />
if (lower.includes('reddit')) return <RedditLogo className="text-orange-600" />
if (lower.includes('whatsapp')) return <WhatsappLogo className="text-green-500" />
if (lower.includes('telegram')) return <TelegramLogo className="text-blue-500" />
if (lower.includes('snapchat')) return <SnapchatLogo className="text-yellow-400" />
if (lower.includes('pinterest')) return <PinterestLogo className="text-red-600" />
if (lower.includes('threads')) return <ThreadsLogo className="text-neutral-800 dark:text-neutral-200" />
// AI assistants and search tools
if (lower.includes('chatgpt') || lower.includes('openai')) return <SiOpenai className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('perplexity')) return <SiPerplexity className="text-teal-600" />
if (lower.includes('claude') || lower.includes('anthropic')) return <SiAnthropic className="text-orange-500" />
if (lower.includes('gemini')) return <SiGooglegemini className="text-blue-500" />
if (lower.includes('copilot')) return <FaGlobe className="text-blue-500" />
if (lower.includes('deepseek')) return <RiRobot2Fill className="text-blue-600" />
if (lower.includes('grok') || lower.includes('x.ai')) return <FaXTwitter className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('phind')) return <RiRobot2Fill className="text-purple-600" />
if (lower.includes('you.com')) return <RiRobot2Fill className="text-indigo-600" />
if (lower.includes('chatgpt') || lower.includes('openai')) return <Robot className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('perplexity')) return <Robot className="text-teal-600" />
if (lower.includes('claude') || lower.includes('anthropic')) return <Robot className="text-orange-500" />
if (lower.includes('gemini')) return <Robot className="text-blue-500" />
if (lower.includes('copilot')) return <Robot className="text-blue-500" />
if (lower.includes('deepseek')) return <Robot className="text-blue-600" />
if (lower.includes('grok') || lower.includes('x.ai')) return <XLogo className="text-neutral-800 dark:text-neutral-200" />
if (lower.includes('phind')) return <Robot className="text-purple-600" />
if (lower.includes('you.com')) return <Robot className="text-indigo-600" />
// Shared Link (unattributed deep-page traffic)
if (lower === 'shared link') return <Link className="text-neutral-500" />
// Try to use a generic globe or maybe check if it is a URL
return <FaGlobe className="text-neutral-400" />
return <Globe className="text-neutral-400" />
}
const REFERRER_NO_FAVICON = ['direct', 'unknown', '']
const REFERRER_NO_FAVICON = ['direct', 'shared link', 'unknown', '']
/** Common subdomains to skip when deriving the main label (e.g. l.instagram.com → instagram). */
const REFERRER_SUBDOMAIN_SKIP = new Set([
@@ -118,6 +113,7 @@ const REFERRER_DISPLAY_OVERRIDES: Record<string, string> = {
telegram: 'Telegram',
pinterest: 'Pinterest',
snapchat: 'Snapchat',
threads: 'Threads',
tumblr: 'Tumblr',
quora: 'Quora',
't.co': 'X',
@@ -222,6 +218,8 @@ export function getReferrerFavicon(referrer: string): string | null {
if (!referrer || typeof referrer !== 'string') return null
const normalized = referrer.trim().toLowerCase()
if (REFERRER_NO_FAVICON.includes(normalized)) return null
// Plain names without a dot (e.g. "Instagram", "WhatsApp") are not real domains
if (!normalized.includes('.')) return null
try {
const url = new URL(referrer.startsWith('http') ? referrer : `https://${referrer}`)
if (REFERRER_USE_X_ICON.has(url.hostname.toLowerCase())) return null

View File

@@ -0,0 +1,17 @@
// * Cleans up stale localStorage entries on app initialization
// * Prevents accumulation from abandoned OAuth flows
export function cleanupStaleStorage() {
if (typeof window === 'undefined') return
try {
// * PKCE keys are only needed during the OAuth callback
// * If we're not on the callback page, they're stale leftovers
if (!window.location.pathname.includes('/auth/callback')) {
localStorage.removeItem('oauth_state')
localStorage.removeItem('oauth_code_verifier')
}
} catch {
// * Ignore errors (private browsing, storage disabled, etc.)
}
}

View File

@@ -16,7 +16,7 @@ const cspDirectives = [
"img-src 'self' data: blob: https://www.google.com https://*.gstatic.com https://ciphera.net",
"font-src 'self'",
`connect-src 'self' https://*.ciphera.net https://ciphera.net https://www.google.com https://*.gstatic.com https://cdn.jsdelivr.net${process.env.NODE_ENV === 'development' ? ' http://localhost:*' : ''}`,
"worker-src 'self'",
"worker-src 'self' blob:",
"frame-src 'none'",
"object-src 'none'",
"base-uri 'self'",
@@ -30,7 +30,7 @@ const nextConfig: NextConfig = {
// * Privacy-first: Disable analytics and telemetry
productionBrowserSourceMaps: false,
experimental: {
optimizePackageImports: ['react-icons'],
optimizePackageImports: ['@phosphor-icons/react'],
},
images: {
remotePatterns: [

2119
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "pulse-frontend",
"version": "0.13.0-alpha",
"version": "0.14.0-alpha",
"private": true,
"scripts": {
"dev": "next dev",
@@ -12,29 +12,32 @@
"test:watch": "vitest"
},
"dependencies": {
"@ciphera-net/ui": "^0.0.92",
"@ciphera-net/ui": "^0.2.4",
"@ducanh2912/next-pwa": "^10.2.9",
"@radix-ui/react-icons": "^1.3.0",
"@phosphor-icons/react": "^2.1.10",
"@simplewebauthn/browser": "^13.2.2",
"@stripe/react-stripe-js": "^5.6.0",
"@stripe/stripe-js": "^8.7.0",
"@tanstack/react-virtual": "^3.13.21",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1",
"cobe": "^0.6.5",
"country-flag-icons": "^1.6.4",
"d3-scale": "^4.0.2",
"framer-motion": "^12.23.26",
"html-to-image": "^1.11.13",
"i18n-iso-countries": "^7.14.0",
"iso-3166-2": "^1.0.0",
"jspdf": "^4.0.0",
"jspdf-autotable": "^5.0.7",
"motion": "^12.35.2",
"next": "^16.1.1",
"radix-ui": "^1.4.3",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-icons": "^5.5.0",
"react-markdown": "^10.1.0",
"react-simple-maps": "^3.0.0",
"recharts": "^2.15.0",
"sonner": "^2.0.7",
"svg-dotted-map": "^2.0.1",
"swr": "^2.3.3",
"xlsx": "^0.18.5"
},
@@ -52,7 +55,6 @@
"@types/node": "^20.14.12",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/react-simple-maps": "^3.0.6",
"@vitejs/plugin-react": "^5.1.4",
"autoprefixer": "^10.4.19",
"eslint": "^9.39.2",

View File

@@ -8,6 +8,51 @@
--color-success: #10B981;
--color-warning: #F59E0B;
--color-error: #EF4444;
/* * Chart colors */
--chart-1: #FD5E0F;
--chart-2: #3b82f6;
--chart-3: #22c55e;
--chart-4: #a855f7;
--chart-5: #f59e0b;
--chart-grid: #f5f5f5;
--chart-axis: #a3a3a3;
/* * shadcn-compatible semantic tokens (for 21st.dev components) */
--background: 255 255 255;
--foreground: 23 23 23;
--card: 255 255 255;
--card-foreground: 23 23 23;
--popover: 255 255 255;
--popover-foreground: 23 23 23;
--primary: 253 94 15;
--primary-foreground: 255 255 255;
--secondary: 245 245 245;
--secondary-foreground: 23 23 23;
--destructive-foreground: 255 255 255;
}
.dark {
--chart-1: #FD5E0F;
--chart-2: #60a5fa;
--chart-3: #4ade80;
--chart-4: #c084fc;
--chart-5: #fbbf24;
--chart-grid: #262626;
--chart-axis: #737373;
/* * shadcn-compatible dark mode overrides */
--background: 10 10 10;
--foreground: 250 250 250;
--card: 23 23 23;
--card-foreground: 250 250 250;
--popover: 23 23 23;
--popover-foreground: 250 250 250;
--primary: 253 94 15;
--primary-foreground: 255 255 255;
--secondary: 38 38 38;
--secondary-foreground: 250 250 250;
--destructive-foreground: 255 255 255;
}
body {

View File

@@ -13,9 +13,45 @@ const config: Config = {
],
theme: {
extend: {
keyframes: {
'cell-highlight': {
'0%': { backgroundColor: 'transparent' },
'100%': { backgroundColor: 'var(--highlight)' },
},
'cell-flash': {
'0%': { backgroundColor: 'transparent' },
'50%': { backgroundColor: 'var(--highlight)' },
'100%': { backgroundColor: 'transparent' },
},
},
animation: {
'cell-highlight': 'cell-highlight 0.5s ease forwards',
'cell-flash': 'cell-flash 0.6s ease forwards',
},
fontFamily: {
sans: ['var(--font-plus-jakarta-sans)', 'system-ui', 'sans-serif'],
},
colors: {
background: 'rgb(var(--background) / <alpha-value>)',
foreground: 'rgb(var(--foreground) / <alpha-value>)',
card: {
DEFAULT: 'rgb(var(--card) / <alpha-value>)',
foreground: 'rgb(var(--card-foreground) / <alpha-value>)',
},
popover: {
DEFAULT: 'rgb(var(--popover) / <alpha-value>)',
foreground: 'rgb(var(--popover-foreground) / <alpha-value>)',
},
primary: {
DEFAULT: 'rgb(var(--primary) / <alpha-value>)',
foreground: 'rgb(var(--primary-foreground) / <alpha-value>)',
},
secondary: {
DEFAULT: 'rgb(var(--secondary) / <alpha-value>)',
foreground: 'rgb(var(--secondary-foreground) / <alpha-value>)',
},
border: 'rgb(var(--border) / <alpha-value>)',
},
},
},
plugins: [