forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

url-state.ts157 lines, 6.2 KiBHistoryRawDownload
1import { createEffect, createSignal, on } from "solid-js";
2import { useLocation, useNavigate } from "@tanstack/solid-router";
3
4/**
5 * List and view state that lives in the URL search params, so Back and a
6 * reload land on the same page, search, sort, tab or calendar view the user
7 * left. Every write replaces the current history entry: typing into a search
8 * box must not push one entry per keystroke, and Back should leave the page
9 * rather than step through its filters.
10 */
11
12export type SearchRecord = Record<string, unknown>;
13
14/** A value the URL should not carry: the default state is a bare URL. */
15const isBlank = (value: unknown) => value === undefined || value === null || value === "";
16
17/** `prev` with `patch` merged in; blank values drop their key. */
18export function patchSearch(prev: SearchRecord, patch: SearchRecord): SearchRecord {
19 const next: SearchRecord = { ...prev };
20 for (const [key, value] of Object.entries(patch)) {
21 if (isBlank(value)) delete next[key];
22 else next[key] = value;
23 }
24 return next;
25}
26
27/**
28 * A search param as text. The router parses `?q=12` into the number 12 and
29 * `?q=true` into a boolean, so anything scalar is turned back into a string.
30 */
31export function readString(value: unknown): string {
32 if (typeof value === "string") return value;
33 if (typeof value === "number" || typeof value === "boolean") return String(value);
34 return "";
35}
36
37/** `?page=` is one-based for people; the table's index is zero-based. */
38export function readPageIndex(value: unknown): number {
39 const page = typeof value === "number" ? value : Number.parseInt(readString(value), 10);
40 return Number.isInteger(page) && page > 1 ? page - 1 : 0;
41}
42
43/** The first page is the default, so it leaves the URL bare. */
44export function encodePageIndex(index: number): number | undefined {
45 return index > 0 ? index + 1 : undefined;
46}
47
48export type SortEntry = { id: string; desc: boolean };
49
50/** `?sort=starts_at.desc` → one sort entry; anything unreadable → unsorted. */
51export function decodeSort(value: unknown): SortEntry[] {
52 const raw = readString(value).trim();
53 if (!raw) return [];
54 const dot = raw.lastIndexOf(".");
55 const direction = dot > 0 ? raw.slice(dot + 1) : "";
56 if (direction === "asc" || direction === "desc") return [{ id: raw.slice(0, dot), desc: direction === "desc" }];
57 return [{ id: raw, desc: false }];
58}
59
60/** The inverse of `decodeSort`; only the leading sort survives a round trip. */
61export function encodeSort(state: readonly SortEntry[]): string | undefined {
62 const first = state[0];
63 return first ? `${first.id}.${first.desc ? "desc" : "asc"}` : undefined;
64}
65
66/** A param that must be one of `allowed`, else `fallback`. */
67export function readEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
68 const raw = readString(value);
69 return (allowed as readonly string[]).includes(raw) ? (raw as T) : fallback;
70}
71
72export type UrlParamOptions<T> = {
73 /** Raw router value (string, number, boolean or undefined) → state. */
74 parse: (raw: unknown) => T;
75 /** State → URL value; `undefined` (or "") drops the key, e.g. for the default. */
76 serialize: (value: T) => unknown;
77};
78
79/** Stable key for comparing what was written with what the URL now says. */
80const fingerprint = (value: unknown) => (isBlank(value) ? "" : JSON.stringify(value));
81
82/**
83 * A signal mirrored into one search param. Reads are local and immediate —
84 * the input never waits for the router — and each write replaces the URL.
85 * A change that did not come from this signal (a nav link back to the bare
86 * route, the browser restoring an entry) flows back into it.
87 */
88export function createUrlParam<T>(key: string, options: UrlParamOptions<T>): [() => T, (value: T) => void] {
89 const location = useLocation();
90 const navigate = useNavigate();
91 const urlValue = () => ((location().search ?? {}) as SearchRecord)[key];
92 const [value, setValue] = createSignal<T>(options.parse(urlValue()));
93 // Writes still on their way through the router. Each one arrives in order;
94 // an arriving value we wrote is not an outside change and must not pull
95 // the input back to an older keystroke.
96 let pending: string[] = [];
97
98 createEffect(
99 on(
100 () => fingerprint(options.serialize(options.parse(urlValue()))),
101 (current) => {
102 const index = pending.indexOf(current);
103 if (index >= 0) {
104 pending = pending.slice(index + 1);
105 return;
106 }
107 pending = [];
108 setValue(() => options.parse(urlValue()));
109 },
110 { defer: true },
111 ),
112 );
113
114 const write = (next: T) => {
115 setValue(() => next);
116 const serialized = options.serialize(next);
117 const current = fingerprint(options.serialize(options.parse(urlValue())));
118 if (fingerprint(serialized) === current && pending.length === 0) return;
119 pending.push(fingerprint(serialized));
120 void navigate({
121 to: location().pathname,
122 search: (prev: SearchRecord) => patchSearch(prev ?? {}, { [key]: serialized }),
123 hash: location().hash || undefined,
124 replace: true,
125 resetScroll: false,
126 } as never);
127 };
128
129 return [value, write];
130}
131
132/** A text param (`?q=`, `?tab=`); `fallback` is the bare-URL value. */
133export function createUrlString(key: string, fallback = ""): [() => string, (value: string) => void] {
134 return createUrlParam(key, {
135 parse: (raw) => readString(raw) || fallback,
136 serialize: (value) => (value === fallback ? undefined : value),
137 });
138}
139
140/** One of a fixed set (`?tab=sessions`, `?view=week`); `fallback` stays out of the URL. */
141export function createUrlEnum<T extends string>(key: string, allowed: readonly T[], fallback: T): [() => T, (value: T) => void] {
142 return createUrlParam(key, {
143 parse: (raw) => readEnum(raw, allowed, fallback),
144 serialize: (value) => (value === fallback ? undefined : value),
145 });
146}
147
148/** A zero-based page index kept one-based in `?page=`. */
149export function createUrlPageIndex(key = "page"): [() => number, (value: number) => void] {
150 return createUrlParam(key, { parse: readPageIndex, serialize: encodePageIndex });
151}
152
153/** Search-param names for one list; a prefix keeps two lists on a page apart. */
154export function listParamKeys(prefix?: string) {
155 const name = (key: string) => (prefix ? `${prefix}.${key}` : key);
156 return { q: name("q"), page: name("page"), sort: name("sort") };
157}