🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Revert "Refactor URL parameter handling to improve state management (#707)"
Bill Yang408a6abe79ff
diff --git a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx b/client/src/app/[site]/components/Sidebar/SiteSelector.tsxindex e05d8d621..60cefabb5 100644--- a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx+++ b/client/src/app/[site]/components/Sidebar/SiteSelector.tsx@@ -1,5 +1,5 @@import { ChevronDown, Plus } from "lucide-react";-import { usePathname, useRouter } from "next/navigation";+import { usePathname, useRouter, useSearchParams } from "next/navigation";import { useState, Suspense } from "react";import { useGetSite, useGetSitesFromOrg } from "../../../../api/admin/sites";import { Favicon } from "../../../../components/Favicon";@@ -22,6 +22,7 @@ function SiteSelectorContent({ onSiteSelect }: { onSiteSelect: () => void }) {const pathname = usePathname();const router = useRouter();+ const searchParams = useSearchParams();const currentSiteId = Number(pathname.split("/")[1]);const { user } = userStore();@@ -56,8 +57,8 @@ function SiteSelectorContent({ onSiteSelect }: { onSiteSelect: () => void }) {const pathSegments = pathname.split("/");pathSegments[1] = site.siteId.toString();const newPath = pathSegments.join("/");- const queryString = window.location.search;- router.push(queryString ? `${newPath}${queryString}` : newPath);+ const queryString = searchParams.toString();+ router.push(queryString ? `${newPath}?${queryString}` : newPath);onSiteSelect(); // Close popover immediately}}className={cn(@@ -100,8 +101,8 @@ function SiteSelectorContent({ onSiteSelect }: { onSiteSelect: () => void }) {const pathSegments = pathname.split("/");pathSegments[1] = site.siteId.toString();const newPath = pathSegments.join("/");- const queryString = window.location.search;- router.push(queryString ? `${newPath}${queryString}` : newPath);+ const queryString = searchParams.toString();+ router.push(queryString ? `${newPath}?${queryString}` : newPath);onSiteSelect(); // Close popover immediately}}className={cn(diff --git a/client/src/app/[site]/gsc/select-property/page.tsx b/client/src/app/[site]/gsc/select-property/page.tsxindex a01579c12..578e739f3 100644--- a/client/src/app/[site]/gsc/select-property/page.tsx+++ b/client/src/app/[site]/gsc/select-property/page.tsx@@ -1,6 +1,6 @@"use client";-import { useParams, useRouter } from "next/navigation";+import { useSearchParams, useParams, useRouter } from "next/navigation";import { useState } from "react";import { Button } from "@/components/ui/button";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";@@ -8,9 +8,9 @@ import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";import { Label } from "@/components/ui/label";import { toast } from "sonner";import { authedFetch } from "@/api/utils";-import { useQueryState, parseAsJson } from "nuqs";export default function SelectGSCPropertyPage() {+ const searchParams = useSearchParams();const params = useParams();const router = useRouter();const site = params.site as string;@@ -19,10 +19,8 @@ export default function SelectGSCPropertyPage() {const [isSubmitting, setIsSubmitting] = useState(false);// Parse properties from query params- const [properties] = useQueryState(- "properties",- parseAsJson<string[]>((value) => value as string[]).withDefault([])- );+ const propertiesParam = searchParams.get("properties");+ const properties: string[] = propertiesParam ? JSON.parse(decodeURIComponent(propertiesParam)) : [];const handleSubmit = async () => {if (!selectedProperty) {diff --git a/client/src/app/[site]/utils.ts b/client/src/app/[site]/utils.tsindex 28b02ebc0..62df40354 100644--- a/client/src/app/[site]/utils.ts+++ b/client/src/app/[site]/utils.ts@@ -1,14 +1,15 @@"use client";-import { useQueryState, parseAsBoolean } from "nuqs";+import { useSearchParams } from "next/navigation";import { useCurrentSite } from "../../api/admin/sites";export const useEmbedablePage = () => {- const [embed] = useQueryState("embed", parseAsBoolean);+ const searchParams = useSearchParams();+ const embed = searchParams.get("embed");const { subscription } = useCurrentSite();- if (embed && subscription?.planName !== "free") {+ if (embed === "true" && subscription?.planName !== "free") {return true;}diff --git a/client/src/app/as/callback/page.tsx b/client/src/app/as/callback/page.tsxindex 5dd488786..22c0f02a1 100644--- a/client/src/app/as/callback/page.tsx+++ b/client/src/app/as/callback/page.tsx@@ -12,10 +12,9 @@ import { motion } from "framer-motion";import { ArrowRight, Check } from "lucide-react";import Image from "next/image";import Link from "next/link";-import { useRouter } from "next/navigation";-import React, { useEffect, useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import React, { Suspense, useEffect, useState } from "react";import { addSite } from "../../../api/admin/sites";-import { useQueryStates, parseAsInteger, parseAsString } from "nuqs";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { authClient } from "../../../lib/auth";import { IS_CLOUD } from "../../../lib/const";@@ -29,6 +28,32 @@ const contentVariants = {visible: { opacity: 1, x: 0, transition: { duration: 0.3 } },};+// Client component to handle AppSumo code from URL params+function AppSumoCodeHandler({+ onSetCode,+ onSetStep,+}: {+ onSetCode: (code: string) => void;+ onSetStep: (step: number) => void;+}) {+ const searchParams = useSearchParams();++ useEffect(() => {+ const code = searchParams.get("code");+ if (code) {+ onSetCode(code);+ }++ // Handle step override for testing+ const step = searchParams.get("step");+ if (step && !isNaN(Number(step))) {+ onSetStep(Number(step));+ }+ }, [searchParams, onSetCode, onSetStep]);++ return null;+}+export default function AppSumoSignupPage() {useSetPageTitle("Rybbit · AppSumo Signup");@@ -38,22 +63,6 @@ export default function AppSumoSignupPage() {const [appsumoCode, setAppsumoCode] = useState<string>("");const router = useRouter();- // Get code and step from URL params- const [{ code, step: stepParam }] = useQueryStates({- code: parseAsString,- step: parseAsInteger,- });-- // Sync URL params with local state- useEffect(() => {- if (code) {- setAppsumoCode(code);- }- if (stepParam && stepParam >= 1 && stepParam <= 3) {- setCurrentStep(stepParam);- }- }, [code, stepParam]);-// Step 1: Account creationconst [email, setEmail] = useState("");const [password, setPassword] = useState("");@@ -367,6 +376,11 @@ export default function AppSumoSignupPage() {return (<div className="flex justify-center items-center h-dvh w-full p-4 "><div className="flex flex-col items-center bg-background relative">+ {/* Suspense boundary for the URL parameter handler */}+ <Suspense fallback={null}>+ <AppSumoCodeHandler onSetCode={setAppsumoCode} onSetStep={setCurrentStep} />+ </Suspense>+{/* Background gradients similar to docs page */}<div className="absolute top-0 left-0 w-[550px] h-[550px] bg-emerald-500/40 rounded-full blur-[80px] opacity-40"></div><div className="absolute top-20 left-20 w-[400px] h-[400px] bg-emerald-600/30 rounded-full blur-[70px] opacity-30"></div>diff --git a/client/src/app/auth/subscription/success/page.tsx b/client/src/app/auth/subscription/success/page.tsxindex a4dedcf05..80cd8c080 100644--- a/client/src/app/auth/subscription/success/page.tsx+++ b/client/src/app/auth/subscription/success/page.tsx@@ -2,6 +2,7 @@import { useEffect } from "react";import { useRouter } from "next/navigation";+import { useSearchParams } from "next/navigation";export default function StripeSuccessPage() {const router = useRouter();diff --git a/client/src/app/invitation/page.tsx b/client/src/app/invitation/page.tsxindex fdd1a3256..9c307b272 100644--- a/client/src/app/invitation/page.tsx+++ b/client/src/app/invitation/page.tsx@@ -1,7 +1,7 @@"use client";import { AlertCircle } from "lucide-react";-import { useRouter } from "next/navigation";+import { useRouter, useSearchParams } from "next/navigation";import { Suspense, useState } from "react";import { ThreeDotLoader } from "../../components/Loaders";import { RybbitLogo } from "../../components/RybbitLogo";@@ -12,13 +12,10 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../components/ui/taimport { authClient } from "../../lib/auth";import { Login } from "./components/login";import { Signup } from "./components/signup";-import { useQueryStates, parseAsString } from "nuqs";function AuthComponent() {- const [{ organization, inviterEmail }] = useQueryStates({- organization: parseAsString,- inviterEmail: parseAsString,- });+ const organization = useSearchParams().get("organization");+ const inviterEmail = useSearchParams().get("inviterEmail");const [activeTab, setActiveTab] = useState<"login" | "signup">("signup");return (@@ -49,11 +46,9 @@ function AuthComponent() {}function AcceptInvitationInner() {- const [{ invitationId, organization, inviterEmail }] = useQueryStates({- invitationId: parseAsString,- organization: parseAsString,- inviterEmail: parseAsString,- });+ const invitationId = useSearchParams().get("invitationId");+ const organization = useSearchParams().get("organization");+ const inviterEmail = useSearchParams().get("inviterEmail");const router = useRouter();const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string>("");diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsxindex 3eeb5c48a..1aa1bafd1 100644--- a/client/src/app/signup/page.tsx+++ b/client/src/app/signup/page.tsx@@ -12,8 +12,8 @@ import { Label } from "@/components/ui/label";import { motion } from "framer-motion";import { ArrowRight, Check } from "lucide-react";import Link from "next/link";-import { useRouter } from "next/navigation";-import React, { useEffect, useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import React, { Suspense, useEffect, useState } from "react";import { addSite } from "../../api/admin/sites";import { RybbitLogo, RybbitTextLogo } from "../../components/RybbitLogo";import { useSetPageTitle } from "../../hooks/useSetPageTitle";@@ -22,7 +22,6 @@ import { useConfigs } from "../../lib/configs";import { IS_CLOUD } from "../../lib/const";import { userStore } from "../../lib/userStore";import { cn, isValidDomain, normalizeDomain } from "../../lib/utils";-import { useQueryState, parseAsInteger } from "nuqs";// Animation variants for step transitionsconst contentVariants = {@@ -30,19 +29,25 @@ const contentVariants = {visible: { opacity: 1, x: 0, transition: { duration: 0.3 } },};+// Client component to handle step from URL params+function StepHandler({ onSetStep }: { onSetStep: (step: number) => void }) {+ const searchParams = useSearchParams();++ useEffect(() => {+ const step = searchParams.get("step");+ if (step && !isNaN(Number(step))) {+ onSetStep(Number(step));+ }+ }, [searchParams, onSetStep]);++ return null;+}+export default function SignupPage() {const { configs, isLoading: isLoadingConfigs } = useConfigs();useSetPageTitle("Rybbit · Signup");const [currentStep, setCurrentStep] = useState(1);- const [stepParam] = useQueryState("step", parseAsInteger);-- // Sync URL step param with local state on mount- useEffect(() => {- if (stepParam && stepParam >= 1 && stepParam <= 3) {- setCurrentStep(stepParam);- }- }, [stepParam]);const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string>("");const router = useRouter();@@ -375,6 +380,11 @@ export default function SignupPage() {return (<div className="flex justify-center items-center h-dvh w-full p-4 "><div className="flex flex-col items-center bg-background relative">+ {/* Suspense boundary for the URL parameter handler */}+ <Suspense fallback={null}>+ <StepHandler onSetStep={setCurrentStep} />+ </Suspense>+{/* Background gradients similar to docs page */}{/* <div className="absolute top-0 left-0 w-[550px] h-[550px] bg-emerald-500/40 rounded-full blur-[80px] opacity-40"></div><div className="absolute top-20 left-20 w-[400px] h-[400px] bg-emerald-600/30 rounded-full blur-[70px] opacity-30"></div>diff --git a/client/src/components/SiteSettings/GSCManager.tsx b/client/src/components/SiteSettings/GSCManager.tsxindex 783bf07b4..414d54665 100644--- a/client/src/components/SiteSettings/GSCManager.tsx+++ b/client/src/components/SiteSettings/GSCManager.tsx@@ -5,16 +5,16 @@ import { ConfirmationModal } from "@/components/ConfirmationModal";import { Button } from "@/components/ui/button";import { SiGoogle } from "@icons-pack/react-simple-icons";import { ExternalLink } from "lucide-react";+import { useSearchParams } from "next/navigation";import { useEffect, useState } from "react";import { toast } from "sonner";-import { useQueryState, parseAsString } from "nuqs";interface GSCManagerProps {disabled?: boolean;}export function GSCManager({ disabled = false }: GSCManagerProps) {- const [gscStatus] = useQueryState("gsc", parseAsString);+ const searchParams = useSearchParams();const { data: connection, isLoading, refetch } = useGSCConnection();const { mutate: connect, isPending: isConnecting } = useConnectGSC();const { mutate: disconnect, isPending: isDisconnecting } = useDisconnectGSC();@@ -22,11 +22,12 @@ export function GSCManager({ disabled = false }: GSCManagerProps) {// Check for OAuth success/error in URL paramsuseEffect(() => {+ const gscStatus = searchParams.get("gsc");if (gscStatus === "success") {toast.success("Google Search Console connected successfully");refetch();}- }, [gscStatus, refetch]);+ }, [searchParams, refetch]);const handleDisconnect = async () => {return new Promise((resolve, reject) => {diff --git a/client/src/lib/parsers.ts b/client/src/lib/parsers.tsdeleted file mode 100644index cad2fd193..000000000--- a/client/src/lib/parsers.ts+++ /dev/null@@ -1,118 +0,0 @@-import { Filter, TimeBucket } from "@rybbit/shared";-import { createParser, parseAsBoolean, parseAsInteger, parseAsJson, parseAsString, parseAsStringEnum } from "nuqs";-import { StatType } from "./store";-import { Time } from "@/components/DateSelector/types";--// Basic parsers-export const parseAsOptionalString = parseAsString;-export const parseAsOptionalInteger = parseAsInteger;-export const parseAsOptionalBoolean = parseAsBoolean;--// TimeBucket parser with validation-const timeBucketValues: TimeBucket[] = [- "minute",- "five_minutes",- "ten_minutes",- "fifteen_minutes",- "hour",- "day",- "week",- "month",- "year",-];--export const parseAsTimeBucket = parseAsStringEnum<TimeBucket>(timeBucketValues);--// StatType parser-const statTypeValues: StatType[] = [- "pageviews",- "sessions",- "users",- "pages_per_session",- "bounce_rate",- "session_duration",-];--export const parseAsStatType = parseAsStringEnum<StatType>(statTypeValues);--// Time mode parser-const timeModeValues: string[] = [- "day",- "range",- "week",- "month",- "year",- "all-time",- "past-minutes",-];--export const parseAsTimeMode = parseAsStringEnum(timeModeValues);--// Well-known preset parser-const wellKnownValues: string[] = [- "today",- "yesterday",- "last-3-days",- "last-7-days",- "last-14-days",- "last-30-days",- "last-60-days",- "this-week",- "last-week",- "this-month",- "last-month",- "this-year",- "last-30-minutes",- "last-1-hour",- "last-6-hours",- "last-24-hours",- "all-time",-];--export const parseAsWellKnown = parseAsStringEnum(wellKnownValues);--// ISO date string parser (for dates like "2024-01-01")-export const parseAsIsoDate = parseAsString;--// JSON parsers for complex types-export const parseAsFilters = parseAsJson<Filter[]>((value) => value as Filter[]);-export const parseAsStringArray = parseAsJson<string[]>((value) => value as string[]);--// GSC status parser (for OAuth callback)-export const parseAsGscStatus = parseAsString;--// Invitation parameters-export const invitationParsers = {- organization: parseAsString,- inviterEmail: parseAsString,- invitationId: parseAsString,-};--// AppSumo callback parameters-export const appSumoCallbackParsers = {- code: parseAsString,- step: parseAsInteger,-};--// URL parameters for analytics/dashboard pages-export const analyticsParsers = {- // Time parameters- timeMode: parseAsTimeMode,- wellKnown: parseAsWellKnown,- day: parseAsIsoDate,- startDate: parseAsIsoDate,- endDate: parseAsIsoDate,- week: parseAsIsoDate,- month: parseAsIsoDate,- year: parseAsIsoDate,- past_minutes_start: parseAsInteger,- past_minutes_end: parseAsInteger,-- // Display parameters- bucket: parseAsTimeBucket,- stat: parseAsStatType,- filters: parseAsFilters,-- // Feature flags- embed: parseAsBoolean,-};diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.tsindex 02b10c175..e442b5db8 100644--- a/client/src/lib/urlParams.ts+++ b/client/src/lib/urlParams.ts@@ -1,12 +1,9 @@-"use client";-+import { Filter, TimeBucket } from "@rybbit/shared";import { DateTime } from "luxon";-import { usePathname } from "next/navigation";-import { useQueryStates } from "nuqs";+import { usePathname, useRouter, useSearchParams } from "next/navigation";import React, { useEffect } from "react";import { Time } from "../components/DateSelector/types";-import { analyticsParsers } from "./parsers";-import { useStore } from "./store";+import { StatType, useStore } from "./store";// Map of wellKnown presets to their dynamic time calculationsconst wellKnownPresets: Record<string, () => Time> = {@@ -86,12 +83,159 @@ const wellKnownPresets: Record<string, () => Time> = {"all-time": () => ({ mode: "all-time", wellKnown: "all-time" }),};+// Serialize store state to URL parameters+const serializeStateToUrl = (+ time: Time,+ bucket: TimeBucket,+ selectedStat: StatType,+ filters: Filter[]+): URLSearchParams => {+ const params = new URLSearchParams();++ // Serialize time+ params.set("timeMode", time.mode);++ // If wellKnown preset, only store that+ if (time.wellKnown) {+ params.set("wellKnown", time.wellKnown);+ } else {+ // Otherwise store explicit date fields+ if (time.mode === "day") {+ params.set("day", time.day);+ } else if (time.mode === "range") {+ params.set("startDate", time.startDate);+ params.set("endDate", time.endDate);+ } else if (time.mode === "week") {+ params.set("week", time.week);+ } else if (time.mode === "month") {+ params.set("month", time.month);+ } else if (time.mode === "year") {+ params.set("year", time.year);+ } else if (time.mode === "past-minutes") {+ params.set("past_minutes_start", time.pastMinutesStart.toString());+ params.set("past_minutes_end", time.pastMinutesEnd.toString());+ }+ }++ // Serialize bucket+ params.set("bucket", bucket);++ // Serialize selectedStat+ params.set("stat", selectedStat);++ // Serialize filters+ if (filters.length > 0) {+ params.set("filters", JSON.stringify(filters));+ }++ return params;+};++// Deserialize URL parameters to store state+const deserializeUrlToState = (+ searchParams: URLSearchParams+): {+ time: Time | null;+ bucket: TimeBucket | null;+ selectedStat: StatType | null;+ filters: Filter[] | null;+} => {+ const result = {+ time: null as Time | null,+ bucket: null as TimeBucket | null,+ selectedStat: null as StatType | null,+ filters: null as Filter[] | null,+ };++ // Deserialize time+ const timeMode = searchParams.get("timeMode") as Time["mode"] | null;+ const wellKnown = searchParams.get("wellKnown");++ // Try to resolve wellKnown preset first+ if (wellKnown && wellKnownPresets[wellKnown]) {+ result.time = wellKnownPresets[wellKnown]();+ } else if (timeMode) {+ // Fallback to explicit date parameters+ if (timeMode === "day") {+ const day = searchParams.get("day");+ if (day) result.time = { mode: "day", day };+ } else if (timeMode === "range") {+ const startDate = searchParams.get("startDate");+ const endDate = searchParams.get("endDate");+ if (startDate && endDate) result.time = { mode: "range", startDate, endDate };+ } else if (timeMode === "week") {+ const week = searchParams.get("week");+ if (week) result.time = { mode: "week", week };+ } else if (timeMode === "month") {+ const month = searchParams.get("month");+ if (month) result.time = { mode: "month", month };+ } else if (timeMode === "year") {+ const year = searchParams.get("year");+ if (year) result.time = { mode: "year", year };+ } else if (timeMode === "past-minutes") {+ const past_minutes_start = searchParams.get("past_minutes_start");+ const past_minutes_end = searchParams.get("past_minutes_end");+ if (past_minutes_start && past_minutes_end) {+ result.time = {+ mode: "past-minutes",+ pastMinutesStart: Number(past_minutes_start),+ pastMinutesEnd: Number(past_minutes_end),+ };+ }+ } else if (timeMode === "all-time") {+ result.time = { mode: "all-time" };+ }+ }++ // Deserialize bucket with validation+ const bucketParam = searchParams.get("bucket");+ if (bucketParam) {+ // Validate that it's a valid TimeBucket value+ const validBuckets: TimeBucket[] = [+ "minute",+ "five_minutes",+ "ten_minutes",+ "fifteen_minutes",+ "hour",+ "day",+ "week",+ "month",+ "year",+ ];++ if (validBuckets.includes(bucketParam as TimeBucket)) {+ result.bucket = bucketParam as TimeBucket;+ }+ }++ // Deserialize selectedStat+ const stat = searchParams.get("stat") as StatType | null;+ if (stat) {+ result.selectedStat = stat;+ }++ // Deserialize filters+ const filtersStr = searchParams.get("filters");+ if (filtersStr) {+ try {+ result.filters = JSON.parse(filtersStr);+ } catch (e) {+ console.error("Failed to parse filters from URL", e);+ }+ }++ return result;+};+// Hook to sync store state with URLexport const useSyncStateWithUrl = () => {+ const searchParams = useSearchParams();const pathname = usePathname();+ const router = useRouter();const { time, bucket, selectedStat, filters, setTime, setBucket, setSelectedStat, setFilters, site } = useStore();// Use a ref to track if we've already loaded from URL+ // This prevents overriding user changes if the effect re-runsconst initializedFromUrlRef = React.useRef(false);// Check if we're on a path where we should sync URL params@@ -114,121 +258,73 @@ export const useSyncStateWithUrl = () => {].includes(pathParts[2]);};- // Get URL params using nuqs- const [urlParams, setUrlParams] = useQueryStates(analyticsParsers, {- history: "replace",- shallow: true,- });-// Initialize from URL params after site is set+ // This fixes the issue where setSite would override URL paramsuseEffect(() => {+ // Only proceed if site has been set and we haven't initialized yet+ // and we're on a path where we should sync URL paramsif (!site || initializedFromUrlRef.current || !shouldSyncUrl()) return;+ const state = deserializeUrlToState(searchParams);let needsUpdate = false;- // Deserialize time from URL- let timeFromUrl: Time | null = null;-- // Try to resolve wellKnown preset first- if (urlParams.wellKnown && wellKnownPresets[urlParams.wellKnown]) {- timeFromUrl = wellKnownPresets[urlParams.wellKnown]();- } else if (urlParams.timeMode) {- // Fallback to explicit date parameters- if (urlParams.timeMode === "day" && urlParams.day) {- timeFromUrl = { mode: "day", day: urlParams.day };- } else if (urlParams.timeMode === "range" && urlParams.startDate && urlParams.endDate) {- timeFromUrl = { mode: "range", startDate: urlParams.startDate, endDate: urlParams.endDate };- } else if (urlParams.timeMode === "week" && urlParams.week) {- timeFromUrl = { mode: "week", week: urlParams.week };- } else if (urlParams.timeMode === "month" && urlParams.month) {- timeFromUrl = { mode: "month", month: urlParams.month };- } else if (urlParams.timeMode === "year" && urlParams.year) {- timeFromUrl = { mode: "year", year: urlParams.year };- } else if (- urlParams.timeMode === "past-minutes" &&- urlParams.past_minutes_start !== null &&- urlParams.past_minutes_end !== null- ) {- timeFromUrl = {- mode: "past-minutes",- pastMinutesStart: urlParams.past_minutes_start,- pastMinutesEnd: urlParams.past_minutes_end,- };- } else if (urlParams.timeMode === "all-time") {- timeFromUrl = { mode: "all-time" };- }+ // Process time first without changing bucket+ if (state.time) {+ setTime(state.time, false); // Don't change bucket+ needsUpdate = true;}- if (timeFromUrl) {- setTime(timeFromUrl, false); // Don't change bucket+ // Process bucket separately to ensure it's not overridden by setTime+ if (state.bucket) {+ setBucket(state.bucket);needsUpdate = true;}- // Process bucket separately- if (urlParams.bucket) {- setBucket(urlParams.bucket);+ if (state.selectedStat) {+ setSelectedStat(state.selectedStat);needsUpdate = true;}- if (urlParams.stat) {- setSelectedStat(urlParams.stat);+ if (state.filters) {+ setFilters(state.filters);needsUpdate = true;}- if (urlParams.filters) {- setFilters(urlParams.filters);- needsUpdate = true;+ // If we updated the state from URL, also update the previousTime+ // but make sure not to change the bucket again+ if (needsUpdate && state.time) {+ // Force a recalculation of the previousTime by setting the time again+ // But explicitly tell it not to change the bucket+ setTime(state.time, false);}// Mark that we've initialized from URLinitializedFromUrlRef.current = true;- }, [urlParams, site, setTime, setBucket, setSelectedStat, setFilters, shouldSyncUrl, pathname]);+ }, [searchParams, site, setTime, setBucket, setSelectedStat, setFilters]); // Added all dependencies// Update URL when state changesuseEffect(() => {+ // Don't update URL if site hasn't been set yet+ // or if we're not on a path where we should sync URL paramsif (!site || !shouldSyncUrl()) return;- // Build params object to update - values, not parsers- const newParams: Record<string, any> = {- timeMode: time.mode,- bucket,- stat: selectedStat,- filters: filters.length > 0 ? filters : null,- };-- // If wellKnown preset, only store that- if (time.wellKnown) {- newParams.wellKnown = time.wellKnown;- // Clear explicit date fields- newParams.day = null;- newParams.startDate = null;- newParams.endDate = null;- newParams.week = null;- newParams.month = null;- newParams.year = null;- newParams.past_minutes_start = null;- newParams.past_minutes_end = null;- } else {- newParams.wellKnown = null;- // Store explicit date fields based on mode- if (time.mode === "day" && "day" in time) {- newParams.day = time.day;- } else if (time.mode === "range" && "startDate" in time && "endDate" in time) {- newParams.startDate = time.startDate;- newParams.endDate = time.endDate;- } else if (time.mode === "week" && "week" in time) {- newParams.week = time.week;- } else if (time.mode === "month" && "month" in time) {- newParams.month = time.month;- } else if (time.mode === "year" && "year" in time) {- newParams.year = time.year;- } else if (time.mode === "past-minutes" && "pastMinutesStart" in time && "pastMinutesEnd" in time) {- newParams.past_minutes_start = time.pastMinutesStart;- newParams.past_minutes_end = time.pastMinutesEnd;+ const params = serializeStateToUrl(time, bucket, selectedStat, filters);+ const newSearch = params.toString();++ // Only update if the search params have changed to avoid infinite loops+ // Create a copy of current search params without the embed param for comparison+ const currentParamsForComparison = new URLSearchParams(searchParams);+ currentParamsForComparison.delete("embed");+ const currentSearch = currentParamsForComparison.toString();++ if (newSearch !== currentSearch) {+ // Preserve the embed param if it exists+ const embedParam = searchParams.get("embed");+ if (embedParam) {+ params.set("embed", embedParam);}+ // Replace the current URL with the new one to avoid adding to history+ router.replace(`${pathname}?${params.toString()}`);}-- // Note: embed param is automatically preserved by nuqs- setUrlParams(newParams);- }, [time, bucket, selectedStat, filters, site, setUrlParams, shouldSyncUrl, pathname]);+ }, [time, bucket, selectedStat, filters, pathname, router, site, searchParams]); // Added searchParams};