hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits
| 1 | import { createSignal, onMount } from "solid-js"; |
| 2 | |
| 3 | /** TanStack `columnVisibility` shape: column id → visible. Absent = visible. */ |
| 4 | export type ColumnVisibility = Record<string, boolean>; |
| 5 | |
| 6 | export type TablePreferences = { |
| 7 | visibility: ColumnVisibility; |
| 8 | }; |
| 9 | |
| 10 | const STORAGE_PREFIX = "hezarfen.table."; |
| 11 | |
| 12 | export const defaultTablePreferences: TablePreferences = { |
| 13 | visibility: {}, |
| 14 | }; |
| 15 | |
| 16 | export 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 | |
| 30 | function 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 | |
| 39 | export 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 | */ |
| 46 | export 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 | } |