-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
431 lines (366 loc) · 13.9 KB
/
storage.js
File metadata and controls
431 lines (366 loc) · 13.9 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
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
export function getFromStorage(key) {
return new Promise((resolve) => {
chrome.storage.local.get([key], (result) => resolve(result[key] ?? null));
});
}
export function setToStorage(key, value) {
return new Promise((resolve) => {
chrome.storage.local.set({ [key]: value }, resolve);
});
}
export const DEFAULT_SETTINGS = {
enabled: true, // master Lens toggle
theme: "auto", // auto | light | dark
fontSize: "medium", // small | medium | large
width: "normal", // normal | wide
compact: false, // tighter row spacing
markVisited: true, // gray out visited posts
highlightShow: true, // colored left bar for Show HN
highlightAsk: true, // colored left bar for Ask HN
highlightLaunch:true, // colored left bar for Launch HN
language: "", // "" = autodetect
autoTranslate: false, // translate comment previews in the side panel
autoTranslatePinned: false, // translate pinned card titles inside the side panel
translateTo: "", // "" = browser language; "en", "pt", "es", etc.
uiLanguage: "", // "" = autodetect; otherwise an i18n code like "pt-BR"
zebraEnabled: false, // alternating row backgrounds for plain posts
zebraColor: "#ff8800", // hex; applied with chosen intensity
zebraIntensity: 12 // % opacity (5-40)
};
export async function getSettings() {
const stored = await getFromStorage("settings");
return { ...DEFAULT_SETTINGS, ...(stored || {}) };
}
export function saveSettings(settings) {
return setToStorage("settings", settings);
}
// ── Visited posts (keyed by HN post id) ──
const VISITED_TTL_MS = 30 * 86400 * 1000; // 30 days
export async function getVisitedSet() {
const raw = await getFromStorage("visited");
if (!raw) return new Set();
const now = Date.now();
const fresh = {};
for (const [id, ts] of Object.entries(raw)) {
if (now - ts < VISITED_TTL_MS) fresh[id] = ts;
}
// Persist pruned version
if (Object.keys(fresh).length !== Object.keys(raw).length) {
await setToStorage("visited", fresh);
}
return new Set(Object.keys(fresh));
}
export async function markVisited(postId) {
const raw = (await getFromStorage("visited")) || {};
raw[String(postId)] = Date.now();
await setToStorage("visited", raw);
}
// ── Pinned posts ──
// Stored as a map: { [postId]: { id, title, url, domain, score, comments, author, ageText, itemUrl, type, pinnedAt } }
export async function getPinnedMap() {
return (await getFromStorage("pinned")) || {};
}
export async function isPinned(postId) {
const map = await getPinnedMap();
return !!map[String(postId)];
}
export async function addPin(postData) {
const map = await getPinnedMap();
const id = String(postData.id);
map[id] = { ...postData, id, pinnedAt: Date.now() };
await setToStorage("pinned", map);
return map;
}
export async function removePin(postId) {
const map = await getPinnedMap();
delete map[String(postId)];
await setToStorage("pinned", map);
return map;
}
// ── Comment preview cache (10 minutes) ──
const COMMENTS_TTL_MS = 10 * 60 * 1000;
export async function getCachedComments(postId) {
const cached = await getFromStorage(`comments_${postId}`);
if (!cached) return null;
if (Date.now() - cached.ts > COMMENTS_TTL_MS) return null;
return cached.comments;
}
export async function setCachedComments(postId, comments) {
return setToStorage(`comments_${postId}`, { ts: Date.now(), comments });
}
// ── Tags on pinned items ──
export function normalizeTag(s) {
return String(s || "")
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^a-z0-9\-_À-ɏЀ-ӿ]/g, "")
.slice(0, 30);
}
// Deterministic hue (0-360) from a tag name. Same tag → same color, always.
export function tagHue(tag) {
if (!tag) return 25;
let hash = 0;
for (let i = 0; i < tag.length; i++) {
hash = ((hash << 5) - hash) + tag.charCodeAt(i);
hash |= 0; // keep 32-bit
}
return Math.abs(hash) % 360;
}
export async function setPinnedTags(postId, tags) {
const map = await getPinnedMap();
const id = String(postId);
if (!map[id]) return map;
map[id].tags = Array.from(new Set(tags.map(normalizeTag).filter(Boolean)));
await setToStorage("pinned", map);
return map;
}
export async function getRecentTags() {
return (await getFromStorage("recentTags")) || [];
}
export async function pushRecentTag(tag) {
const n = normalizeTag(tag);
if (!n) return;
const list = await getRecentTags();
const next = [n, ...list.filter(t => t !== n)].slice(0, 40);
await setToStorage("recentTags", next);
}
// ── Per-card collapsed state in the side panel ──
export async function getCollapsedCards() {
return (await getFromStorage("collapsedCards")) || {};
}
export async function setCardCollapsed(postId, collapsed) {
const map = await getCollapsedCards();
if (collapsed) map[postId] = true;
else delete map[postId];
await setToStorage("collapsedCards", map);
return map;
}
// ── Radar snapshots + lists ──
// Store: { byPost: {id: {meta..., snapshots: [{ts,score,descendants}]}}, lists: {top:[ids], show:[ids], ask:[ids]}, lastFetch: {top:ts, ...} }
const RADAR_KEY = "radar";
const MAX_SNAPSHOTS_PER_POST = 12;
const MIN_SNAPSHOT_GAP_MS = 4 * 60 * 1000; // don't snapshot more often than 4min
export async function getRadarStore() {
return (await getFromStorage(RADAR_KEY)) || { byPost: {}, lists: {}, lastFetch: {} };
}
export async function updateRadarSnapshots(category, items) {
const store = await getRadarStore();
const now = Date.now();
const ids = [];
for (const item of items) {
if (!item || !item.id) continue;
ids.push(item.id);
if (!store.byPost[item.id]) {
store.byPost[item.id] = { id: item.id, snapshots: [] };
}
const post = store.byPost[item.id];
// Update meta on every fetch
post.id = item.id;
post.title = item.title;
post.by = item.by;
post.time = item.time;
post.url = item.url;
post.type = item.type;
post.score = item.score || 0;
post.descendants = item.descendants || 0;
// Add snapshot (throttled)
const last = post.snapshots[post.snapshots.length - 1];
if (!last || now - last.ts >= MIN_SNAPSHOT_GAP_MS) {
post.snapshots.push({ ts: now, score: post.score, descendants: post.descendants });
if (post.snapshots.length > MAX_SNAPSHOTS_PER_POST) {
post.snapshots = post.snapshots.slice(-MAX_SNAPSHOTS_PER_POST);
}
}
}
store.lists[category] = ids;
store.lastFetch[category] = now;
// Prune posts not in any list anymore
const referenced = new Set();
Object.values(store.lists).forEach((arr) => (arr || []).forEach((id) => referenced.add(Number(id))));
for (const id of Object.keys(store.byPost)) {
if (!referenced.has(Number(id))) delete store.byPost[id];
}
await setToStorage(RADAR_KEY, store);
return store;
}
// Velocity = (score_delta * 2 + comments_delta * 3) per hour.
// Returns { current, delta } where delta compares recent half vs older half of snapshots.
// Falls back to lifetime average when fewer than 2 snapshots exist.
export function computeVelocityDetail(post) {
if (!post) return { current: 0, delta: null };
const snaps = post.snapshots || [];
// ── Fallback when we have only one (or zero) snapshot ──
if (snaps.length < 2) {
const ageHours = Math.max(1, (Date.now() / 1000 - (post.time || 0)) / 3600);
const lifetime = (post.score / ageHours) * 2 + ((post.descendants || 0) / ageHours) * 3;
return { current: Math.max(0, lifetime), delta: null };
}
const first = snaps[0];
const last = snaps[snaps.length - 1];
const hoursFull = (last.ts - first.ts) / 3600000;
if (hoursFull <= 0.05) return { current: 0, delta: null };
const current = Math.max(0,
((last.score - first.score) * 2 + (last.descendants - first.descendants) * 3) / hoursFull
);
// Compute delta from first-half vs second-half velocities when we have ≥3 snapshots
let delta = null;
if (snaps.length >= 3) {
const midIdx = Math.floor(snaps.length / 2);
const midSnap = snaps[midIdx];
const h1 = (midSnap.ts - first.ts) / 3600000;
const h2 = (last.ts - midSnap.ts) / 3600000;
if (h1 > 0.05 && h2 > 0.05) {
const vel1 = ((midSnap.score - first.score) * 2 + (midSnap.descendants - first.descendants) * 3) / h1;
const vel2 = ((last.score - midSnap.score) * 2 + (last.descendants - midSnap.descendants) * 3) / h2;
delta = Math.round(vel2 - vel1);
}
}
return { current, delta };
}
// Back-compat
export function computeVelocity(post) {
return computeVelocityDetail(post).current;
}
// ── Muted domains ──
export async function getMutedDomains() {
const arr = (await getFromStorage("mutedDomains")) || [];
return Array.isArray(arr) ? arr : [];
}
export async function setMutedDomains(arr) {
const cleaned = Array.from(new Set(
(arr || []).map((d) => String(d || "").trim().toLowerCase().replace(/^www\./, "")).filter(Boolean)
));
await setToStorage("mutedDomains", cleaned);
return cleaned;
}
// ── OP active cache (per post id, 10min TTL) ──
const OP_ACTIVE_TTL_MS = 10 * 60 * 1000;
export async function getOPActiveCache() {
return (await getFromStorage("opActiveCache")) || {};
}
export async function getCachedOPActive(postId) {
const map = await getOPActiveCache();
const entry = map[String(postId)];
if (!entry) return undefined;
if (Date.now() - entry.ts > OP_ACTIVE_TTL_MS) return undefined;
return entry.active;
}
export async function setCachedOPActive(postId, active) {
const map = await getOPActiveCache();
map[String(postId)] = { active: !!active, ts: Date.now() };
await setToStorage("opActiveCache", map);
}
// ── Watchlist rules (Phase 3a) ──────────────────────────────
// Rules live as an array under "watchRules". Schema:
// { id, name, enabled, feeds: [...], predicates: { field: {gte|lte|eq: n} },
// createdAt, lastMatchAt, lastMatchCount }
const WATCH_RULES_KEY = "watchRules";
const WATCH_FIRED_KEY = "watchFired";
const WATCH_UNREAD_KEY = "watchUnread";
const WATCH_FIRED_TTL_MS = 24 * 60 * 60 * 1000; // 24h
const WATCH_UNREAD_CAP = 50; // keep last 50 in the bell
// Hard cap on the number of rules a user can have at any time.
// Forces focus: the watchlist is for the few alerts that actually matter.
// At 5/5 the "+ New rule" button is disabled until the user deletes one.
export const WATCH_RULES_MAX = 5;
export async function getWatchRules() {
const raw = await getFromStorage(WATCH_RULES_KEY);
return Array.isArray(raw) ? raw : [];
}
export async function saveWatchRules(rules) {
return setToStorage(WATCH_RULES_KEY, Array.isArray(rules) ? rules : []);
}
function uuid() {
if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
return "wr-" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
export async function addWatchRule(rule) {
const rules = await getWatchRules();
if (rules.length >= WATCH_RULES_MAX) {
throw Object.assign(
new Error(`Maximum number of rules reached (${WATCH_RULES_MAX}).`),
{ code: "MAX_REACHED" }
);
}
const full = {
id: rule.id || uuid(),
name: String(rule.name || "Untitled rule").slice(0, 60),
enabled: rule.enabled !== false,
feeds: Array.isArray(rule.feeds) ? rule.feeds : ["top"],
predicates: rule.predicates && typeof rule.predicates === "object" ? rule.predicates : {},
createdAt: Date.now(),
lastMatchAt: null,
lastMatchCount: 0,
};
rules.push(full);
await saveWatchRules(rules);
return full;
}
export async function updateWatchRule(id, patch) {
const rules = await getWatchRules();
const idx = rules.findIndex((r) => r.id === id);
if (idx === -1) return null;
rules[idx] = { ...rules[idx], ...patch };
await saveWatchRules(rules);
return rules[idx];
}
export async function deleteWatchRule(id) {
const rules = await getWatchRules();
const next = rules.filter((r) => r.id !== id);
await saveWatchRules(next);
// Also drop fired entries for this rule
const fired = await getWatchFired();
for (const key of Object.keys(fired)) {
if (key.startsWith(`${id}::`)) delete fired[key];
}
await recordWatchFired(fired);
return next;
}
// ── Watchlist idempotence cache ──
// Map "ruleId::postId" -> firedAt (ms). 24h TTL.
export async function getWatchFired() {
return (await getFromStorage(WATCH_FIRED_KEY)) || {};
}
export async function recordWatchFired(map) {
return setToStorage(WATCH_FIRED_KEY, map || {});
}
export async function pruneWatchFired() {
const map = await getWatchFired();
const now = Date.now();
let mutated = false;
for (const [key, ts] of Object.entries(map)) {
if (now - ts > WATCH_FIRED_TTL_MS) {
delete map[key];
mutated = true;
}
}
if (mutated) await recordWatchFired(map);
return map;
}
// ── Watchlist unread queue (bell badge) ──
// Array of recent match descriptors. Capped to WATCH_UNREAD_CAP entries.
export async function getWatchUnread() {
const arr = await getFromStorage(WATCH_UNREAD_KEY);
return Array.isArray(arr) ? arr : [];
}
export async function setWatchUnread(arr) {
return setToStorage(WATCH_UNREAD_KEY, Array.isArray(arr) ? arr : []);
}
export async function addWatchUnread(match) {
const arr = await getWatchUnread();
arr.unshift(match); // newest first
const trimmed = arr.slice(0, WATCH_UNREAD_CAP);
await setWatchUnread(trimmed);
return trimmed;
}
export async function clearWatchUnread() {
await setWatchUnread([]);
return [];
}
export async function removeWatchUnread(ruleId, postId) {
const arr = await getWatchUnread();
const next = arr.filter((m) => !(m.ruleId === ruleId && m.postId === postId));
await setWatchUnread(next);
return next;
}