πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor error and event components to utilize truncateString for improved text handling
Bill Yang06bced5da745
diff --git a/client/src/api/CLAUDE.md b/client/src/api/CLAUDE.mdnew file mode 100644index 000000000..c5e141148--- /dev/null+++ b/client/src/api/CLAUDE.md@@ -0,0 +1,79 @@+# API Layer++This directory contains all API-related code for the client application.++## Directory Structure++```+api/+βββ admin/ # Admin/settings API (sites, orgs, users)+β βββ endpoints/ # Pure fetch functions and types+β βββ hooks/ # React Query hooks+βββ analytics/ # Analytics data API+β βββ endpoints/ # Pure fetch functions and types+β βββ hooks/ # React Query hooks+βββ gsc/ # Google Search Console integration+βββ stripe/ # Stripe billing integration+βββ uptime/ # Uptime monitoring+βββ types.ts # Shared API types (APIResponse)+βββ utils.ts # Shared utilities (authedFetch, buildApiParams)+```++## Architecture Pattern++### Separation of Concerns++Each domain (admin, analytics) follows a two-layer pattern:++1. **endpoints/** - Pure async functions that call `authedFetch`+ - Contains TypeScript interfaces and types+ - No React dependencies+ - Reusable across different contexts+ - Exports via `index.ts` barrel file++2. **hooks/** - React Query hooks wrapping endpoints+ - Uses `useQuery` for data fetching+ - Uses `useMutation` for data mutations+ - Handles caching, invalidation, and React lifecycle++### Example++```typescript+// endpoints/sites.ts+export function fetchSite(siteId: string | number) {+ return authedFetch<SiteResponse>(`/sites/${siteId}`);+}++// hooks/useSites.ts+export function useGetSite(siteId?: string | number) {+ return useQuery({+ queryKey: ["get-site", siteId],+ queryFn: () => fetchSite(siteId!),+ enabled: !!siteId,+ });+}+```++## Key Utilities++### `authedFetch<T>(url, params?, config?)`++Wrapper around axios that:+- Prepends `BACKEND_URL` to relative URLs+- Sends credentials (cookies) with requests+- Converts array params to JSON strings+- Includes private key header when present+- Extracts and throws backend error messages++### `buildApiParams(time, options?)`++Converts a `Time` object to `CommonApiParams` for analytics endpoints.++## Conventions++- **Naming**: Endpoint functions use `fetch*`, `create*`, `update*`, `delete*` prefixes+- **Naming**: Hooks use `use*` prefix (e.g., `useGetSite`, `useCreateGoal`)+- **Types**: Export types alongside functions from endpoint files+- **Query Keys**: Use descriptive array keys like `["get-site", siteId]`+- **Error Handling**: Let errors propagate; hooks handle via React Query+- **Mutations**: Invalidate related queries in `onSuccess` callbacksdiff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsxindex ed547acbc..b03b22ebe 100644--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx@@ -1,24 +1,24 @@"use client";-import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetErrorEvents";import { ErrorEvent } from "@/api/analytics/endpoints";+import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetErrorEvents";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { userLocale } from "@/lib/dateTimeUtils";-import { getTimezone } from "@/lib/store";import { useGetRegionName } from "@/lib/geo";-import { getCountryName } from "@/lib/utils";+import { getTimezone } from "@/lib/store";+import { getCountryName, truncateString } from "@/lib/utils";import { AlertTriangle, Code, Hash, Laptop, Loader2, Smartphone, TriangleAlert, User } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";-import { memo, useMemo } from "react";+import { useParams } from "next/navigation";+import { useMemo } from "react";+import { ErrorState } from "../../../../components/ErrorState";import { Browser } from "../../components/shared/icons/Browser";import { CountryFlag } from "../../components/shared/icons/CountryFlag";import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";-import { useParams } from "next/navigation";-import { ErrorState } from "../../../../components/ErrorState";interface ErrorDetailsProps {errorMessage: string;@@ -35,13 +35,6 @@ function DeviceIcon({ deviceType }: { deviceType: string | null }) {return <Laptop className="w-4 h-4" />;}-// Function to truncate text for display-function truncateText(text: string | null, maxLength: number = 50) {- if (!text) return "-";- if (text.length <= maxLength) return text;- return `${text.substring(0, maxLength)}...`;-}-// Component to display individual error eventfunction ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {const { getRegionName } = useGetRegionName();@@ -189,7 +182,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {target="_blank"rel="noopener noreferrer">- {errorEvent.fileName && <span>{truncateText(errorEvent.fileName, 100)}</span>}+ {errorEvent.fileName && <span>{truncateString(errorEvent.fileName, 100)}</span>}{errorEvent.lineNumber && (<span className="text-neutral-900 dark:text-neutral-100">:{errorEvent.lineNumber}diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsxindex c21d8959b..f636e4ddf 100644--- a/client/src/app/[site]/events/components/EventLogItem.tsx+++ b/client/src/app/[site]/events/components/EventLogItem.tsx@@ -3,17 +3,17 @@import { Badge } from "@/components/ui/badge";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { getTimezone } from "@/lib/store";-import { ExternalLink, Eye, Laptop, MousePointerClick, Smartphone } from "lucide-react";+import { ExternalLink, Laptop, Smartphone } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";import { useParams } from "next/navigation";import { memo } from "react";import { Event } from "../../../../api/analytics/endpoints";-import { getCountryName } from "../../../../lib/utils";+import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";+import { getCountryName, truncateString } from "../../../../lib/utils";import { Browser } from "../../components/shared/icons/Browser";import { CountryFlag } from "../../components/shared/icons/CountryFlag";import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";-import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";// DeviceIcon component for displaying mobile/desktop iconsfunction DeviceIcon({ deviceType }: { deviceType: string }) {@@ -26,15 +26,6 @@ function DeviceIcon({ deviceType }: { deviceType: string }) {return <Laptop className="w-4 h-4" />;}-// Function to truncate path for display-function truncatePath(path: string, maxLength: number = 64) {- if (!path) return "-";- if (path.length <= maxLength) return path;-- // Keep the beginning of the path with ellipsis- return `${path.substring(0, maxLength)}...`;-}-interface EventLogItemProps {event: Event;}@@ -86,7 +77,7 @@ export function EventLogItem({ event }: EventLogItemProps) {{isPageview ? (<Link href={fullPath} target="_blank" rel="noopener noreferrer"><div className="text-sm truncate hover:underline" title={event.pathname}>- {truncatePath(`${event.pathname}${event.querystring ? `${event.querystring}` : ""}`)}+ {truncateString(`${event.pathname}${event.querystring ? `${event.querystring}` : ""}`, 64)}</div></Link>) : isOutbound ? (@@ -94,7 +85,7 @@ export function EventLogItem({ event }: EventLogItemProps) {eventProperties.url ? (<Link href={eventProperties.url} target="_blank" rel="noopener noreferrer"><div className="text-sm truncate hover:underline text-purple-400" title={eventProperties.url}>- {truncatePath(eventProperties.url)}+ {truncateString(eventProperties.url, 64)}</div></Link>) : (diff --git a/client/src/app/[site]/events/components/OutboundLinksList.tsx b/client/src/app/[site]/events/components/OutboundLinksList.tsxindex 4fe4db85c..2702d0029 100644--- a/client/src/app/[site]/events/components/OutboundLinksList.tsx+++ b/client/src/app/[site]/events/components/OutboundLinksList.tsx@@ -7,7 +7,7 @@ import { DateTime } from "luxon";import { memo } from "react";import { OutboundLink } from "../../../../api/analytics/endpoints";import { Favicon } from "../../../../components/Favicon";-import { cn } from "../../../../lib/utils";+import { cn, truncateUrl } from "../../../../lib/utils";import { ScrollArea } from "../../../../components/ui/scroll-area";// Skeleton component for OutboundLinksList@@ -70,33 +70,6 @@ interface OutboundLinksListProps {size?: "small" | "large";}-// Function to truncate URL for display-function truncateUrl(url: string, maxLength: number = 60) {- if (!url) return "-";- if (url.length <= maxLength) return url;-- try {- const urlObj = new URL(url);- const domain = urlObj.hostname;- const path = urlObj.pathname + urlObj.search;-- if (domain.length + path.length <= maxLength) {- return `${domain}${path}`;- }-- // If still too long, truncate the path- const availableSpace = maxLength - domain.length - 3; // 3 for "..."- if (availableSpace > 0) {- return `${domain}${path.substring(0, availableSpace)}...`;- } else {- return `${domain.substring(0, maxLength - 3)}...`;- }- } catch (e) {- // If URL parsing fails, just truncate the string- return `${url.substring(0, maxLength - 3)}...`;- }-}-export function OutboundLinksList({ outboundLinks, isLoading, size = "small" }: OutboundLinksListProps) {if (isLoading) {return <OutboundLinksListSkeleton size={size} />;diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsxindex 4553742ba..e33fe0908 100644--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx@@ -21,16 +21,7 @@ import { Button } from "../../../../components/ui/button";import { Dialog, DialogContent, DialogTitle } from "../../../../components/ui/dialog";import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";-import { cn, formatter } from "../../../../lib/utils";--// Function to truncate path for display-function truncatePath(path: string, maxLength: number = 32) {- if (!path) return "-";- if (path.length <= maxLength) return path;-- // Keep the beginning of the path with ellipsis- return `${path.substring(0, maxLength)}...`;-}+import { cn, formatter, truncateString } from "../../../../lib/utils";function SessionCardSkeleton() {return (@@ -137,7 +128,7 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number<Tooltip><TooltipTrigger asChild><span className="text-xs text-neutral-400 truncate max-w-[200px] inline-block">- {truncatePath(session.entry_page)}+ {truncateString(session.entry_page, 32)}</span></TooltipTrigger><TooltipContent>@@ -150,7 +141,7 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number<Tooltip><TooltipTrigger asChild><span className="text-xs text-neutral-400 truncate max-w-[200px] inline-block">- {truncatePath(session.exit_page)}+ {truncateString(session.exit_page, 32)}</span></TooltipTrigger><TooltipContent>diff --git a/client/src/app/[site]/main/components/sections/SearchConsole.tsx b/client/src/app/[site]/main/components/sections/SearchConsole.tsxindex 4f8651e3a..a8c2dccaf 100644--- a/client/src/app/[site]/main/components/sections/SearchConsole.tsx+++ b/client/src/app/[site]/main/components/sections/SearchConsole.tsx@@ -5,12 +5,13 @@ import { GSCDimension, useGSCData } from "../../../../../api/gsc/useGSCData";import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";import { Button } from "../../../../../components/ui/button";import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";-import { formatter, getCountryName } from "../../../../../lib/utils";+import { formatter, getCountryName, truncateString } from "../../../../../lib/utils";import { CountryFlag } from "../../../components/shared/icons/CountryFlag";import { StandardSkeleton } from "../../../components/shared/StandardSection/Skeleton";import { SearchConsoleDialog } from "./SearchConsoleDialog";import { SiGoogle } from "@icons-pack/react-simple-icons";import { round } from "lodash";+import { ScrollArea } from "../../../../../components/ui/scroll-area";type Tab = "queries" | "pages" | "countries" | "devices";@@ -61,48 +62,52 @@ function DataList({ dimension, label, renderName, expanded, close }: DataListPro<div className="w-24 text-right">Impressions</div></div></div>- {data && data.length > 0 ? (- data.slice(0, 10).map((item, index) => {- const percentage = item.clicks / totalClicks;- return (- <div- key={index}- className="relative flex flex-row gap-2 justify-between pr-1 text-xs py-1 hover:bg-neutral-150 dark:hover:bg-neutral-850 rounded px-2 group"- >- <div- className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"- style={{ width: `${percentage * ratio}%` }}- />- <div className="flex-1 truncate overflow-x-hidden z-10">- {renderName ? renderName(item.name) : item.name}- </div>- <div className="flex flex-row gap-2 z-10">- <div className="w-28 text-right pr-1 flex flex-row gap-2 items-center justify-end">- <div className="hidden group-hover:block text-neutral-600 dark:text-neutral-400">- {round(percentage * 100, 1)}%+ <ScrollArea className="h-[314px]">+ <div className="flex flex-col gap-2 overflow-x-hidden">+ {data && data.length > 0 ? (+ data.slice(0, 100).map((item, index) => {+ const percentage = item.clicks / totalClicks;+ return (+ <div+ key={index}+ className="relative flex flex-row gap-2 justify-between pr-1 text-xs py-1 hover:bg-neutral-150 dark:hover:bg-neutral-850 rounded px-2 group"+ >+ <div+ className="absolute inset-0 bg-dataviz py-2 opacity-25 rounded-md"+ style={{ width: `${percentage * ratio}%` }}+ />+ <div className="flex-1 truncate overflow-x-hidden z-10">+ {renderName ? renderName(item.name) : truncateString(item.name, 32)}+ </div>+ <div className="flex flex-row gap-2 z-10">+ <div className="w-28 text-right pr-1 flex flex-row gap-2 items-center justify-end">+ <div className="hidden group-hover:block text-neutral-600 dark:text-neutral-400">+ {round(percentage * 100, 1)}%+ </div>+ {formatter(item.clicks)}+ </div>+ <div className="w-24 text-right pr-1">{formatter(item.impressions)}</div></div>- {formatter(item.clicks)}</div>- <div className="w-24 text-right pr-1">{formatter(item.impressions)}</div>+ );+ })+ ) : isLoading ? (+ <StandardSkeleton />+ ) : (+ <div className="text-neutral-600 dark:text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <div className="text-neutral-500 dark:text-neutral-500">+ <div className="text-neutral-600 dark:text-neutral-300 w-full text-center flex flex-row gap-2 items-center justify-center">+ <Info className="w-5 h-5" />+ No Data+ </div>+ <div className="text-sm mt-2">+ Google Search Console data has a 2-3 day delay. Try selecting a wider date range.+ </div></div></div>- );- })- ) : isLoading ? (- <StandardSkeleton />- ) : (- <div className="text-neutral-600 dark:text-neutral-300 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">- <div className="text-neutral-500 dark:text-neutral-500">- <div className="text-neutral-600 dark:text-neutral-300 w-full text-center flex flex-row gap-2 items-center justify-center">- <Info className="w-5 h-5" />- No Data- </div>- <div className="text-sm mt-2">- Google Search Console data has a 2-3 day delay. Try selecting a wider date range.- </div>- </div>+ )}</div>- )}+ </ScrollArea></div></div><SearchConsoleDialog@@ -173,7 +178,7 @@ export function SearchConsole() {label="Page"renderName={name => (<div className="flex items-center gap-1">- <span className="truncate">{new URL(name).pathname || "/"}</span>+ <span className="truncate">{truncateString(new URL(name).pathname || "/", 32)}</span><a href={name} target="_blank" rel="noopener noreferrer" className="shrink-0"><SquareArrowOutUpRightclassName="ml-0.5 w-3.5 h-3.5 text-neutral-600 hover:text-neutral-900 dark:text-neutral-300 dark:hover:text-neutral-100"diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsxindex 7c2ced1f9..61fadf2bb 100644--- a/client/src/components/Sessions/SessionCard.tsx+++ b/client/src/components/Sessions/SessionCard.tsx@@ -6,7 +6,7 @@ import { DateTime } from "luxon";import { memo, useState } from "react";import { GetSessionsResponse } from "../../api/analytics/endpoints";import { formatShortDuration, hour12, userLocale } from "../../lib/dateTimeUtils";-import { cn, formatter, getUserDisplayName } from "../../lib/utils";+import { cn, formatter, getUserDisplayName, truncateString } from "../../lib/utils";import { Avatar } from "../Avatar";import { Channel } from "../Channel";import { EventIcon, PageviewIcon } from "../EventIcons";@@ -28,15 +28,6 @@ interface SessionCardProps {expandedByDefault?: boolean;}-// Function to truncate path for display-function truncatePath(path: string, maxLength: number = 32) {- if (!path) return "-";- if (path.length <= maxLength) return path;-- // Keep the beginning of the path with ellipsis- return `${path.substring(0, maxLength)}...`;-}-export function SessionCard({ session, onClick, userId, expandedByDefault }: SessionCardProps) {const [expanded, setExpanded] = useState(expandedByDefault || false);const [replayDrawerOpen, setReplayDrawerOpen] = useState(false);@@ -130,7 +121,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses<Tooltip><TooltipTrigger asChild><span className="text-xs text-neutral-500 dark:text-neutral-400 truncate max-w-[200px] inline-block">- {truncatePath(session.entry_page)}+ {truncateString(session.entry_page, 32)}</span></TooltipTrigger><TooltipContent>@@ -143,7 +134,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses<Tooltip><TooltipTrigger asChild><span className="text-xs text-neutral-500 dark:text-neutral-400 truncate max-w-[200px] inline-block">- {truncatePath(session.exit_page)}+ {truncateString(session.exit_page, 32)}</span></TooltipTrigger><TooltipContent>diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.tsindex 8ac811f42..d1450195d 100644--- a/client/src/lib/utils.ts+++ b/client/src/lib/utils.ts@@ -41,6 +41,33 @@ export function truncateString(str: string, n = 50) {return str.length > n ? str.substring(0, n) + "..." : str;}+// Function to truncate URL for display+export function truncateUrl(url: string, maxLength: number = 60) {+ if (!url) return "-";+ if (url.length <= maxLength) return url;++ try {+ const urlObj = new URL(url);+ const domain = urlObj.hostname;+ const path = urlObj.pathname + urlObj.search;++ if (domain.length + path.length <= maxLength) {+ return `${domain}${path}`;+ }++ // If still too long, truncate the path+ const availableSpace = maxLength - domain.length - 3; // 3 for "..."+ if (availableSpace > 0) {+ return `${domain}${path.substring(0, availableSpace)}...`;+ } else {+ return `${domain.substring(0, maxLength - 3)}...`;+ }+ } catch (e) {+ // If URL parsing fails, just truncate the string+ return `${url.substring(0, maxLength - 3)}...`;+ }+}+const regionNamesInEnglish = new Intl.DisplayNames(["en"], { type: "region" });const languageNamesInEnglish = new Intl.DisplayNames(["en"], {type: "language",