Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions app/benchmark/utils/useSearchParamsState.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {
decodeSearchParamState,
encodeSearchParamState,
} from "./useSearchParamsState";

describe("search param state codec", () => {
it("round trips unicode values through base64 JSON", () => {
const value = {
label: "Ethereum - Base — Sepolia",
params: {
quote: "smart “wallet”",
},
};

expect(decodeSearchParamState(encodeSearchParamState(value))).toEqual(value);
});
});
24 changes: 21 additions & 3 deletions app/benchmark/utils/useSearchParamsState.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
import { useCallback, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

export function encodeSearchParamState(value: unknown): string {
const jsonString = JSON.stringify(value);
const bytes = new TextEncoder().encode(jsonString);
let binaryString = "";

for (const byte of bytes) {
binaryString += String.fromCharCode(byte);
}

return btoa(binaryString);
}

export function decodeSearchParamState<T>(value: string): T {
const binaryString = atob(value);
const bytes = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
const jsonString = new TextDecoder().decode(bytes);
return JSON.parse(jsonString) as T;
}

/**
* Hook for storing state in URL search parameters as base64 encoded JSON
* Supports multiple instances without conflicts
Expand All @@ -27,8 +46,7 @@ export function useSearchParamsState<T>(
if (paramValue) {
try {
// Decode base64 back to JSON string and then parse
const jsonString = atob(paramValue);
return JSON.parse(jsonString) as T;
return decodeSearchParamState<T>(paramValue);
} catch (e) {
console.error(
`Error parsing state from URL parameter ${paramName}:`,
Expand All @@ -52,7 +70,7 @@ export function useSearchParamsState<T>(
// keeps filter churn out of the back-button history, matching the
// react-router original's `{ replace: true }`.
const newParams = new URLSearchParams(searchParams.toString());
newParams.set(paramName, btoa(JSON.stringify(newValue)));
newParams.set(paramName, encodeSearchParamState(newValue));
router.replace(`${pathname}?${newParams.toString()}`, {
scroll: false,
});
Expand Down