-
-
Notifications
You must be signed in to change notification settings - Fork 622
Expand file tree
/
Copy pathclipboard.js
More file actions
72 lines (58 loc) · 1.67 KB
/
clipboard.js
File metadata and controls
72 lines (58 loc) · 1.67 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
import { reactive } from 'vue';
const STORAGE_KEY = 'statamic.clipboard';
const DEFAULT_TTL = 10 * 60 * 1000;
const state = reactive({
data: null,
expiresAt: null,
});
function loadFromStorage() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) {
state.data = null;
state.expiresAt = null;
return;
}
const parsed = JSON.parse(raw);
state.expiresAt = parsed.expiresAt;
state.data = parsed.payload;
} catch {
state.data = null;
state.expiresAt = null;
}
}
function isExpired() {
return !state.expiresAt || Date.now() > state.expiresAt;
}
loadFromStorage();
window.addEventListener('storage', (event) => {
if (event.key === STORAGE_KEY) {
loadFromStorage();
}
});
export default function useClipboard() {
const get = () => {
if (isExpired()) {
return null;
}
return state.data;
};
const set = (type, items, ttl = DEFAULT_TTL) => {
const expiresAt = Date.now() + ttl;
localStorage.setItem(STORAGE_KEY, JSON.stringify({ expiresAt, payload: { type, items } }));
state.expiresAt = expiresAt;
state.data = { type, items };
};
const clear = () => {
localStorage.removeItem(STORAGE_KEY);
state.data = null;
state.expiresAt = null;
};
const canPaste = (type, allowedHashes) => {
if (isExpired() || !state.data || state.data.type !== type) {
return false;
}
return state.data.items.every((item) => allowedHashes.includes(item.configHash));
};
return { state, get, set, clear, canPaste };
}