forked from Cloud-Pipelines/pipeline-editor
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseRecentlyViewed.ts
More file actions
87 lines (73 loc) · 2.3 KB
/
useRecentlyViewed.ts
File metadata and controls
87 lines (73 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { useSyncExternalStore } from "react";
import { getStorage } from "@/utils/typedStorage";
const RECENTLY_VIEWED_KEY = "Home/recently_viewed";
const MAX_ITEMS = 5;
type RecentlyViewedType = "pipeline" | "run" | "component";
interface RecentlyViewedItem {
type: RecentlyViewedType;
id: string;
name: string;
viewedAt: number;
}
type RecentlyViewedStorageMapping = {
[RECENTLY_VIEWED_KEY]: RecentlyViewedItem[];
};
const storage = getStorage<
typeof RECENTLY_VIEWED_KEY,
RecentlyViewedStorageMapping
>();
// useSyncExternalStore requires getSnapshot to return a stable reference.
let cachedJson: string | null = null;
let cachedItems: RecentlyViewedItem[] = [];
function isRecentlyViewedItem(item: unknown): item is RecentlyViewedItem {
return (
typeof item === "object" &&
item !== null &&
"type" in item &&
"id" in item &&
"name" in item &&
"viewedAt" in item
);
}
function parseRecentlyViewed(json: string): RecentlyViewedItem[] {
try {
const parsed: unknown = JSON.parse(json);
return Array.isArray(parsed) ? parsed.filter(isRecentlyViewedItem) : [];
} catch {
return [];
}
}
function readRecentlyViewed(): RecentlyViewedItem[] {
const json = localStorage.getItem(RECENTLY_VIEWED_KEY);
if (json === cachedJson) return cachedItems;
cachedJson = json;
cachedItems = json ? parseRecentlyViewed(json) : [];
return cachedItems;
}
function subscribe(callback: () => void) {
const handler = (event: StorageEvent) => {
if (event.key === RECENTLY_VIEWED_KEY) callback();
};
window.addEventListener("storage", handler);
return () => window.removeEventListener("storage", handler);
}
export function useRecentlyViewed() {
const recentlyViewed = useSyncExternalStore(
subscribe,
readRecentlyViewed,
() => [],
);
const addRecentlyViewed = (item: Omit<RecentlyViewedItem, "viewedAt">) => {
const current = readRecentlyViewed();
// Remove any existing entry for the same item, then prepend the fresh one
const deduped = current.filter(
(existing) => !(existing.type === item.type && existing.id === item.id),
);
const updated = [{ ...item, viewedAt: Date.now() }, ...deduped].slice(
0,
MAX_ITEMS,
);
storage.setItem(RECENTLY_VIEWED_KEY, updated);
};
return { recentlyViewed, addRecentlyViewed };
}