Jake Vanderwerf
2026-05-12 c32ed859f4abd1591c882f4f2a6ee16b1ec275e2
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/***
 * A simpler cache, using localStorage
 * Mainly used to store settings locally
 * example:
 *  -> dark/light mode switch
 *  -> view mode selection
 *  -> tab navigation direction (for table views)
 **/
class SimpleCache {
    /**
     *
     * @param {string} base
     * @param {object} config
     * @param {string} config.namespace
     * @param {number} config.TTL
     * @param {number} config.maxSize
     */
    constructor(base, config = {}) {
        this.base = base;
        this.config = {
            namespace: `${jvbBase.base}cache`,
            TTL: 3600000,
            maxSize: 100,
            ...config
        };
 
 
        // Initialize memory cache
        this._cache = new Map();
        this.subscribers = new Set();
    }
 
    /**
     * Clear all memory cache
     * @returns {number} Number of items cleared
     */
    clearMemoryCache() {
        const count = this._cache.size;
        this._cache.clear();
 
        console.log(`Cleared ${count} items from memory cache`);
        return count;
    }
 
    /**
     * Get a setting value
     */
    get(key) {
        //Check memory cache first
        if (this._cache.has(key)) {
            return this._cache.get(key);
        }
 
        let cacheKey = `${this.base}_${key}`;
        let item;
        try {
            item =  localStorage.getItem(cacheKey);
            if (!item) {
                return null;
            }
            item = JSON.parse(item);
        } catch (error) {
            console.warn('Error getting from localStorage:', error);
            return null;
        }
 
        if (item) {
            this._cache.set(key, item);
        }
        return item;
    }
 
    /**
     * Set a setting value
     */
    set(key, value) {
        this._cache.set(key, value);
        let cacheKey = `${this.base}_${key}`;
 
        try {
            localStorage.setItem(cacheKey, JSON.stringify(value));
        } catch (error) {
            // Handle quota exceeded
            if (error instanceof DOMException && error.code === 22) {
                this.clearOldestLocalStorageItems();
                try {
                    localStorage.setItem(key, JSON.stringify(item));
                } catch (retryError) {
                    console.warn('Still failed to set localStorage item after cleanup:', retryError);
                }
            } else {
                console.warn('Error setting localStorage item:', error);
            }
        }
 
        // Notify subscribers
        this.notify('cache-saved', { key, value });
    }
 
    remove(key) {
        let cacheKey = `${this.base}_${key}`;
        try {
            localStorage.removeItem(cacheKey);
        } catch (error) {
            console.warn('Error removing localStorage item:', error);
        }
    }
 
    /**
     * Clear oldest items from localStorage when quota is exceeded
     */
    clearOldestLocalStorageItems() {
        try {
            const keysToRemove = [];
 
            // Find all our cache keys
            for (let i = 0; i < localStorage.length; i++) {
                const key = localStorage.key(i);
                if (key.startsWith(this.config.namespace)) {
                    try {
                        const item = JSON.parse(localStorage.getItem(key));
                        keysToRemove.push({ key, timestamp: item.timestamp || 0 });
                    } catch (e) {
                        // If it's not valid JSON or doesn't have a timestamp, prioritize for removal
                        keysToRemove.push({ key, timestamp: 0 });
                    }
                }
            }
 
            // Sort by timestamp (oldest first)
            keysToRemove.sort((a, b) => a.timestamp - b.timestamp);
 
            // Remove the oldest 20% of items
            const removeCount = Math.max(1, Math.ceil(keysToRemove.length * 0.2));
            for (let i = 0; i < removeCount; i++) {
                if (keysToRemove[i]) {
                    localStorage.removeItem(keysToRemove[i].key);
                }
            }
        } catch (error) {
            console.warn('Error cleaning up localStorage:', error);
        }
    }
 
    async loadFromCache() {
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            // Check if key starts with this cache's base prefix
            if (key.startsWith(`${this.base}_`)) {
                let cleanKey = key.replace(`${this.base}_`, '');
                try {
                    // Parse the JSON value before caching
                    const value = JSON.parse(localStorage.getItem(key));
                    this._cache.set(cleanKey, value);
                } catch (error) {
                    console.warn(`Failed to parse cached value for ${key}:`, error);
                }
            }
        }
    }
 
    /**
     * Clear all cache
     *
     * @returns {Promise<void>}
     */
    async clear() {
        this._cache.clear();
 
        try {
            for (let i = localStorage.length - 1; i >= 0; i--) {
                const key = localStorage.key(i);
                if (key && key.startsWith(this.config.namespace)) {
                    localStorage.removeItem(key);
                }
            }
        } catch (error) {
            console.warn('Error clearing localStorage cache:', error);
        }
    }
 
    /**
     * Subscribe to setting changes
     */
    subscribe(callback) {
        this.subscribers.add(callback);
        return () => this.subscribers.delete(callback);
    }
 
    /**
     * Notify subscribers
     */
    notify(event, data) {
        this.subscribers.forEach(cb => cb(event, data));
    }
}
 
window.jvbCache = SimpleCache;