forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

table-preferences.ts65 lines, 2.1 KiBHistoryRawDownload
1import { createSignal, onMount } from "solid-js";
2
3/** TanStack `columnVisibility` shape: column id → visible. Absent = visible. */
4export type ColumnVisibility = Record<string, boolean>;
5
6export type TablePreferences = {
7 visibility: ColumnVisibility;
8};
9
10const STORAGE_PREFIX = "hezarfen.table.";
11
12export const defaultTablePreferences: TablePreferences = {
13 visibility: {},
14};
15
16export function readTablePreferences(storageKey: string): TablePreferences {
17 if (typeof window === "undefined") return defaultTablePreferences;
18 try {
19 const raw = window.localStorage.getItem(STORAGE_PREFIX + storageKey);
20 if (!raw) return defaultTablePreferences;
21 const parsed = JSON.parse(raw) as Partial<TablePreferences>;
22 return {
23 visibility: typeof parsed.visibility === "object" && parsed.visibility ? parsed.visibility : {},
24 };
25 } catch {
26 return defaultTablePreferences;
27 }
28}
29
30function writePreferences(storageKey: string | undefined, preferences: TablePreferences) {
31 if (!storageKey || typeof window === "undefined") return;
32 try {
33 window.localStorage.setItem(STORAGE_PREFIX + storageKey, JSON.stringify(preferences));
34 } catch {
35 // Storage can be unavailable (private mode, quota); preferences stay in memory only.
36 }
37}
38
39export type TablePreferencesController = ReturnType<typeof createTablePreferences>;
40
41/**
42 * Column visibility persisted per table.
43 * When `storageKey` is omitted the preferences stay in memory only (ephemeral).
44 * Preferences load in `onMount` so the first render matches the SSR-free default.
45 */
46export function createTablePreferences(storageKey?: string) {
47 const [preferences, setPreferences] = createSignal<TablePreferences>(defaultTablePreferences);
48
49 onMount(() => {
50 if (storageKey) setPreferences(readTablePreferences(storageKey));
51 });
52
53 const patch = (next: Partial<TablePreferences>) => {
54 setPreferences((current) => {
55 const merged = { ...current, ...next };
56 writePreferences(storageKey, merged);
57 return merged;
58 });
59 };
60
61 return {
62 preferences,
63 setVisibility: (visibility: ColumnVisibility) => patch({ visibility }),
64 };
65}