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
70 lines (58 loc) · 1.91 KB
/
useRecentlyViewed.ts
File metadata and controls
70 lines (58 loc) · 1.91 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
import { useCallback, useSyncExternalStore } from "react";
import { getStorage } from "@/utils/typedStorage";
const RECENTLY_VIEWED_KEY = "Home/recently_viewed";
const MAX_ITEMS = 100;
type RecentlyViewedType = "pipeline" | "run" | "component";
export 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 readRecentlyViewed(): RecentlyViewedItem[] {
const json = localStorage.getItem(RECENTLY_VIEWED_KEY);
if (json === cachedJson) return cachedItems;
cachedJson = json;
cachedItems = json ? (JSON.parse(json) as RecentlyViewedItem[]) : [];
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 = useCallback(
(item: Omit<RecentlyViewedItem, "viewedAt">) => {
const current = readRecentlyViewed();
// Remove any existing entry for the same item, then prepend the fresh one
const deduped = current.filter(
(i) => !(i.type === item.type && i.id === item.id),
);
const updated = [{ ...item, viewedAt: Date.now() }, ...deduped].slice(
0,
MAX_ITEMS,
);
storage.setItem(RECENTLY_VIEWED_KEY, updated);
},
[],
);
return { recentlyViewed, addRecentlyViewed };
}