Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
200 lines (183 loc) · 6.26 KB
/
Copy pathbackground.js
File metadata and controls
200 lines (183 loc) · 6.26 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
const STORAGE_KEY = 'gleaned';
const MAX_SUGGESTIONS = 5;
function makeId() {
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
function ensureContextMenus() {
try {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: 'glean',
title: 'Glean selection',
contexts: ['selection']
});
chrome.contextMenus.create({
id: 'glean-page',
title: 'Glean this page',
contexts: ['page']
});
});
} catch (e) {
console.error('Context menu setup failed:', e);
}
}
// MV3 service workers stop/start often (and onInstalled does NOT fire on a
// plain extension reload), so register menus on every worker start.
ensureContextMenus();
chrome.runtime.onInstalled.addListener((details) => {
ensureContextMenus();
if (details.reason === 'install' || details.reason === 'update') {
chrome.storage.sync.get(STORAGE_KEY, (syncRes) => {
const legacy = syncRes && syncRes[STORAGE_KEY];
if (!Array.isArray(legacy) || legacy.length === 0) return;
chrome.storage.local.get(STORAGE_KEY, (localRes) => {
const current = (localRes && localRes[STORAGE_KEY]) || [];
if (current.length > 0) return; // local already populated, don't overwrite
const migrated = legacy
.map((g) => ({
id: g.id || makeId(),
kind: g.kind === 'page' ? 'page' : 'clip',
text: String(g.text || '').trim(),
url: String(g.url || ''),
title: String(g.title || 'Untitled'),
timestamp: g.timestamp || new Date().toISOString(),
starred: !!g.starred,
tags: Array.isArray(g.tags) ? g.tags : [],
note: String(g.note || '')
}))
.filter((g) => g.text || g.title);
chrome.storage.local.set({ [STORAGE_KEY]: migrated }, () => {
if (!chrome.runtime.lastError) chrome.storage.sync.remove(STORAGE_KEY);
});
});
});
}
});
chrome.runtime.onStartup.addListener(ensureContextMenus);
function readGleanings(cb) {
chrome.storage.local.get(STORAGE_KEY, (res) => {
if (chrome.runtime.lastError) {
console.error('Load failed:', chrome.runtime.lastError);
cb([]);
return;
}
let list = res && res[STORAGE_KEY];
if (!Array.isArray(list)) {
chrome.storage.sync.get(STORAGE_KEY, (syncRes) => {
list = (syncRes && syncRes[STORAGE_KEY]) || [];
cb(Array.isArray(list) ? list : []);
});
return;
}
cb(list);
});
}
function saveGleaning(gleaning) {
readGleanings((gleaned) => {
const dup = gleaning.kind === 'page'
? gleaned.some((g) => g.kind === 'page' && g.url === gleaning.url)
: gleaned.some((g) => g.text === gleaning.text && g.url === gleaning.url);
if (dup) {
console.log('GleanBox: duplicate, skipped.');
return;
}
chrome.storage.local.set({ [STORAGE_KEY]: [...gleaned, gleaning] }, () => {
if (chrome.runtime.lastError) console.error('Save failed:', chrome.runtime.lastError);
else console.log('GleanBox: saved', gleaning.id);
});
});
}
function isHttpUrl(url) {
return /^https?:\/\//i.test(url || '');
}
chrome.contextMenus.onClicked.addListener((info, tab) => {
const url = (tab && tab.url) || '';
if (!isHttpUrl(url)) {
console.warn('GleanBox: can only glean from http(s) pages.');
return;
}
if (info.menuItemId === 'glean') {
const selected = (info.selectionText || '').trim();
if (!selected) return;
saveGleaning({
id: makeId(),
kind: 'clip',
text: selected,
url,
title: (tab && tab.title) || 'Untitled',
timestamp: new Date().toISOString(),
starred: false,
tags: [],
note: ''
});
} else if (info.menuItemId === 'glean-page') {
saveGleaning({
id: makeId(),
kind: 'page',
text: '',
url,
title: (tab && tab.title) || url,
timestamp: new Date().toISOString(),
starred: false,
tags: [],
note: ''
});
}
});
function matchesQuery(g, words) {
const haystack = `${g.text || ''} ${g.title || ''} ${g.url || ''} ${(g.tags || []).join(' ')} ${g.note || ''}`.toLowerCase();
return words.every((w) => haystack.includes(w));
}
function splitWords(text) {
return text.toLowerCase().split(/\s+/).map((w) => w.trim()).filter(Boolean);
}
function escapeOmnibox(s) {
return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function snippet(text, max = 72) {
const t = String(text || '').replace(/\s+/g, ' ').trim();
return t.length > max ? t.slice(0, max - 1) + '…' : t;
}
function labelOf(g) {
if (g.kind === 'page') return snippet(g.title, 80);
return snippet(g.text, 60);
}
// Omnibox: live suggestions while typing `g <keywords>`
chrome.omnibox.onInputChanged.addListener((text, suggest) => {
const words = splitWords(text);
if (words.length === 0) return;
readGleanings((gleaned) => {
const matches = gleaned.filter((g) => matchesQuery(g, words)).slice(0, MAX_SUGGESTIONS);
suggest(matches.map((g) => ({
content: g.url,
description: `${g.starred ? '★ ' : ''}<match>${escapeOmnibox(labelOf(g))}</match> <dim>— ${escapeOmnibox(snippet(g.title, 40))}</dim>`
})));
});
});
// Omnibox: Enter opens best match (or the picked suggestion URL), else Google search
chrome.omnibox.onInputEntered.addListener((text, disposition) => {
const openUrl = (url, fallbackToSearch) => {
if (isHttpUrl(url)) {
if (disposition === 'currentTab') chrome.tabs.update({ url });
else chrome.tabs.create({ url });
} else if (fallbackToSearch) {
const q = `https://www.google.com/search?q=${encodeURIComponent(text)}`;
if (disposition === 'currentTab') chrome.tabs.update({ url: q });
else chrome.tabs.create({ url: q });
}
};
// If the user picked a suggestion, `text` is already its URL
if (isHttpUrl(text)) {
openUrl(text, false);
return;
}
const words = splitWords(text);
readGleanings((gleaned) => {
const matches = words.length
? gleaned.filter((g) => matchesQuery(g, words))
: gleaned.slice(-1);
if (matches.length > 0) openUrl(matches[0].url, false);
else openUrl('', true);
});
});