-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathviewAsUserStore.ts
More file actions
87 lines (72 loc) · 2.09 KB
/
viewAsUserStore.ts
File metadata and controls
87 lines (72 loc) · 2.09 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 { writable, get } from "svelte/store";
import type { V1User } from "../../client";
import { browser } from "$app/environment";
const STORAGE_KEY_PREFIX = "rill:viewAsUser:";
function getStorageKey(org: string, project: string): string {
return `${STORAGE_KEY_PREFIX}${org}/${project}`;
}
function createViewAsUserStore() {
const store = writable<V1User | null>(null);
let currentScope: { org: string; project: string } | null = null;
return {
subscribe: store.subscribe,
/**
* Initialize the store for a specific project scope.
* Loads persisted state from sessionStorage if available.
*/
initForProject(org: string, project: string): void {
if (!browser) return;
currentScope = { org, project };
const key = getStorageKey(org, project);
try {
const stored = sessionStorage.getItem(key);
if (stored) {
const user = JSON.parse(stored) as V1User;
store.set(user);
} else {
store.set(null);
}
} catch {
store.set(null);
}
},
/**
* Set the view-as user for the current project scope.
*/
set(user: V1User | null): void {
store.set(user);
if (!browser || !currentScope) return;
const key = getStorageKey(currentScope.org, currentScope.project);
try {
if (user) {
sessionStorage.setItem(key, JSON.stringify(user));
} else {
sessionStorage.removeItem(key);
}
} catch {
// Ignore storage errors
}
},
/**
* Clear the view-as state (e.g., when navigating away from project).
*/
clear(): void {
store.set(null);
if (!browser || !currentScope) return;
const key = getStorageKey(currentScope.org, currentScope.project);
try {
sessionStorage.removeItem(key);
} catch {
// Ignore storage errors
}
currentScope = null;
},
/**
* Get current value synchronously.
*/
get(): V1User | null {
return get(store);
},
};
}
export const viewAsUserStore = createViewAsUserStore();