-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_script.js
More file actions
379 lines (350 loc) · 14.9 KB
/
content_script.js
File metadata and controls
379 lines (350 loc) · 14.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
// content_script.js: 在 GitHub 用户页面注入展示来自 storage 的用户信息
// 使用 Shadow DOM 将样式隔离,避免污染宿主页面的全局样式
function getUsernameFromUrl() {
const parts = location.pathname.split('/').filter(Boolean);
// GitHub 用户主页通常是 /username
if (parts.length === 1) return parts[0];
// also try meta user-login if present
const meta = document.querySelector('meta[name="user-login"]');
if (meta && meta.content) return meta.content;
return null;
}
// shadow DOM 内的样式(从原来的 styles.css 中提取并调整为组件作用域)
const shadowStyles = `
:host { all: initial; display: block; font-family: Arial, Helvetica, sans-serif; }
.ghe-root { background: #fff; border: 1px solid #d8dee2; padding: 8px; border-radius: 6px; margin-top: 8px; color: #24292e; font-size: 13px; }
.ghe-row { margin: 6px 0; }
.ghe-strong { font-weight: 600; margin-right: 6px; }
.ghe-note { font-size: 12px; color: #666; }
`;
function createShadowBox(info) {
const host = document.createElement('div');
host.id = 'gh-enhancer-host';
// attach shadow root to isolate styles
const shadow = host.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = shadowStyles;
const wrapper = document.createElement('div');
wrapper.className = 'ghe-root';
wrapper.innerHTML = `
<div class="ghe-row"><span class="ghe-strong">姓名:</span> ${escapeHtml(info.name || '-')} </div>
<div class="ghe-row"><span class="ghe-strong">公司:</span> ${escapeHtml(info.company || '-')} </div>
<div class="ghe-row"><span class="ghe-strong">工号:</span> ${escapeHtml(info.employee_id || '-')} </div>
`;
shadow.appendChild(style);
shadow.appendChild(wrapper);
return host;
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function insertHost(host) {
// 优先插入到 profile 侧栏 vcard 或 header 下
const targetSelectors = [
'.js-profile-editable-area', // new layout
'.vcard-details',
'.h-card',
'.p-nickname' // fallback near nickname
];
for (const sel of targetSelectors) {
const el = document.querySelector(sel);
if (el) {
// avoid duplicate
if (!document.getElementById('gh-enhancer-host')) {
el.parentNode.insertBefore(host, el.nextSibling);
}
return true;
}
}
// fallback: append to main
const main = document.querySelector('main') || document.body;
if (!document.getElementById('gh-enhancer-host')) {
main.appendChild(host);
}
}
function updateOrCreate(info) {
const existing = document.getElementById('gh-enhancer-host');
if (existing && existing.shadowRoot) {
// update content inside shadow root
const wrapper = existing.shadowRoot.querySelector('.ghe-root');
if (wrapper) {
wrapper.innerHTML = `
<div class="ghe-row"><span class="ghe-strong">姓名:</span> ${escapeHtml(info.name || '-')} </div>
<div class="ghe-row"><span class="ghe-strong">公司:</span> ${escapeHtml(info.company || '-')} </div>
<div class="ghe-row"><span class="ghe-strong">工号:</span> ${escapeHtml(info.employee_id || '-')} </div>
`;
return;
}
}
const host = createShadowBox(info);
insertHost(host);
}
function tryShow() {
const username = getUsernameFromUrl();
if (!username) return;
chrome.storage.local.get('userMap', data => {
const map = data.userMap || {};
const info = map[username];
if (info) {
updateOrCreate(info);
}
});
}
// Run on load, and also observe DOM changes (single profile page apps may change content dynamically)
tryShow();
const observer = new MutationObserver((mutations) => {
// try again if profile area appears or URL changes within SPA
tryShow();
});
observer.observe(document.body, { childList: true, subtree: true });
// -----------------------------
// Hovercard(用户悬浮窗口)支持
// -----------------------------
const hoverSelectors = [
'.js-hovercard-content', // common class for hovercards
'.Popover-message',
'.hovercard',
'.Popover',
'[data-hovercard]'
];
const shadowStylesCompact = `
:host { all: initial; display: block; font-family: Arial, Helvetica, sans-serif; color: inherit; }
/* match common popover inner spacing: give horizontal padding so text aligns with popover content */
.ghe-root-compact { background: transparent; padding: 6px 12px 0 12px; color: inherit; font-size: 12px; width: 100%; max-width: 100%; box-sizing: border-box; border-top: 1px solid rgba(27,31,35,0.06); margin-top: 6px; }
.ghe-row-compact { margin: 2px 0; color: inherit; line-height: 1.3; }
.ghe-strong-compact { font-weight: 600; margin-right: 6px; color: inherit; }
/* stronger contrast for the label text */
.ghe-root-compact .ghe-strong-compact { color: rgba(0,0,0,0.85); }
/* value styling: make extra info (value) more visible */
.ghe-value-compact { color: #0366d6 !important; font-weight: 500; }
@media (prefers-color-scheme: dark) {
.ghe-root-compact { border-top-color: rgba(255,255,255,0.06); }
.ghe-root-compact .ghe-strong-compact { color: rgba(255,255,255,0.95); }
.ghe-value-compact { color: #58a6ff !important; }
}
`;
function createHoverBox(info) {
const host = document.createElement('div');
// do not set global id; hovercards are ephemeral and there may be multiple
// attach shadow root to isolate styles
const shadow = host.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = shadowStylesCompact;
const wrapper = document.createElement('div');
wrapper.className = 'ghe-root-compact';
wrapper.innerHTML = `
<div class="ghe-row-compact"><span class="ghe-strong-compact">姓名:</span><span class="ghe-value-compact">${escapeHtml(info.name || '-')}</span></div>
<div class="ghe-row-compact"><span class="ghe-strong-compact">公司:</span><span class="ghe-value-compact">${escapeHtml(info.company || '-')}</span></div>
`;
shadow.appendChild(style);
shadow.appendChild(wrapper);
return host;
}
function findUsernameInElement(el) {
// try to find a link that points to a top-level profile path like /username
// include absolute and relative links
const anchors = el.querySelectorAll('a[href]');
for (const a of anchors) {
let href = a.getAttribute('href');
if (!href) continue;
// try to handle absolute URLs by extracting pathname
try {
if (href.startsWith('http://') || href.startsWith('https://')) {
const u = new URL(href);
href = u.pathname;
}
} catch (e) {
// ignore URL parsing errors and fall back to raw href
}
// ignore anchors that are hashes or javascript
if (href.startsWith('#') || href.startsWith('javascript:')) continue;
const parts = href.split('/').filter(Boolean);
if (parts.length === 1) {
// simple username path
return parts[0];
}
// sometimes hovercard links include /users/username or /orgs/orgname
if (parts.length >= 2 && parts[0] === 'users') {
return parts[1];
}
}
// try data-hovercard-url on the element or its descendants
const hoverUrl = el.getAttribute && (el.getAttribute('data-hovercard-url') || el.dataset && el.dataset.hovercardUrl);
if (hoverUrl) {
const path = hoverUrl.startsWith('http') ? (new URL(hoverUrl)).pathname : hoverUrl;
const parts = path.split('/').filter(Boolean);
if (parts.length >= 2 && parts[0] === 'users') return parts[1];
if (parts.length === 1) return parts[0];
}
return null;
}
// tryInjectToHovercardElement: can be called with optional username and trigger
function tryInjectToHovercardElement(el, forcedUsername, triggerElement) {
try {
if (!el) return;
// allow retrying if earlier attempt marked but no right-side host exists
if (el.dataset.gheHoverInjected) {
const hasRight = el.querySelector && el.querySelector('[data-ghe-hover-right]');
if (hasRight) return;
}
let username = forcedUsername || findUsernameInElement(el);
if (!username) {
// sometimes the hovercard doesn't contain a link; try to find the trigger element
// that opened this hovercard (elements with data-hovercard-url) and match by proximity
const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null;
const candidates = Array.from(document.querySelectorAll('[data-hovercard-url]'));
for (const c of candidates) {
const url = c.getAttribute('data-hovercard-url') || c.dataset.hovercardUrl;
if (!url) continue;
let path = url;
try { if (path.startsWith('http')) path = (new URL(path)).pathname; } catch (e) {}
const parts = path.split('/').filter(Boolean);
const candUser = (parts.length >= 2 && parts[0] === 'users') ? parts[1] : (parts.length === 1 ? parts[0] : null);
if (!candUser) continue;
if (!rect) {
// no rect available, just pick the first candidate
username = candUser;
break;
}
const crect = c.getBoundingClientRect ? c.getBoundingClientRect() : null;
if (!crect) continue;
const dx = Math.abs((crect.left + crect.right)/2 - (rect.left + rect.right)/2);
const dy = Math.abs((crect.top + crect.bottom)/2 - (rect.top + rect.bottom)/2);
// heuristic: if centers are within 250px, assume it's the trigger
if (dx < 250 && dy < 250) {
username = candUser;
break;
}
}
}
if (!username) {
// mark as processed to avoid repeated work
el.dataset.gheHoverInjected = '1';
return;
}
chrome.storage.local.get('userMap', data => {
const map = data.userMap || {};
const info = map[username];
if (info) {
// create a right-side host designed to sit inside the Popover-message (absolute positioning)
// ensure we don't inject multiple times
if (el.querySelector && el.querySelector('[data-ghe-hover-right]')) {
el.dataset.gheHoverInjected = '1';
return;
}
const host = createHoverRightBox(info);
// append into the popover (Popover-message has position:relative) so absolute positioning works
el.appendChild(host);
}
el.dataset.gheHoverInjected = '1';
});
} catch (e) {
// fail silently
console.error('GHE hover inject error', e);
}
}
function scanExistingHovercards() {
const sel = hoverSelectors.join(',');
document.querySelectorAll(sel).forEach(el => tryInjectToHovercardElement(el));
}
// create a right-side box inside the Popover-message using Shadow DOM
function createHoverRightBox(info) {
const host = document.createElement('div');
host.setAttribute('data-ghe-hover-right', '1');
// this host will be absolutely positioned inside the Popover-message
host.style.position = 'absolute';
host.style.top = '12px';
host.style.right = '12px';
host.style.width = '140px';
host.style.boxSizing = 'border-box';
host.style.zIndex = '1';
const shadow = host.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = `
:host { all: initial; }
.ghe-right { background: transparent; color: inherit; font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
.ghe-right .ghe-row { margin-bottom: 6px; }
.ghe-right .ghe-label { font-weight: 600; margin-right: 6px; color: rgba(0,0,0,0.75); }
.ghe-right .ghe-value { color: #0366d6; font-weight: 500; }
@media (prefers-color-scheme: dark) {
.ghe-right .ghe-label { color: rgba(255,255,255,0.85); }
.ghe-right .ghe-value { color: #58a6ff; }
}
`;
const wrapper = document.createElement('div');
wrapper.className = 'ghe-right';
wrapper.innerHTML = `
<div class="ghe-row"><span class="ghe-label">姓名</span><span class="ghe-value">${escapeHtml(info.name || '-')}</span></div>
<div class="ghe-row"><span class="ghe-label">公司</span><span class="ghe-value">${escapeHtml(info.company || '-')}</span></div>
<div class="ghe-row"><span class="ghe-label">工号</span><span class="ghe-value">${escapeHtml(info.employee_id || info.id || '-')}</span></div>
`;
shadow.appendChild(style);
shadow.appendChild(wrapper);
return host;
}
// initial scan
scanExistingHovercards();
// extend existing observer to also watch for hovercards being added
const hoverObserver = new MutationObserver((mutations) => {
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType !== 1) continue;
const el = node;
// if the added node itself matches hover selectors
for (const sel of hoverSelectors) {
if (el.matches && el.matches(sel)) {
tryInjectToHovercardElement(el);
}
}
// also check descendants
const sel = hoverSelectors.join(',');
const found = el.querySelectorAll ? el.querySelectorAll(sel) : [];
found.forEach(n => tryInjectToHovercardElement(n));
}
}
});
hoverObserver.observe(document.body, { childList: true, subtree: true });
// Support direct trigger -> popover correlation: when user hovers a trigger anchor (with data-hovercard-url),
// try to inject into the popover that appears for that trigger. This helps cases (like issues list links)
// where popover content doesn't contain a username anchor we can parse.
document.addEventListener('mouseover', (e) => {
try {
const trg = e.target && e.target.closest && e.target.closest('[data-hovercard-url]');
if (!trg) return;
// parse username from trigger's data-hovercard-url
const url = trg.getAttribute('data-hovercard-url') || trg.dataset && trg.dataset.hovercardUrl;
if (!url) return;
let path = url;
try { if (path.startsWith('http')) path = (new URL(path)).pathname; } catch (e) {}
const parts = path.split('/').filter(Boolean);
const username = (parts.length >= 2 && parts[0] === 'users') ? parts[1] : (parts.length === 1 ? parts[0] : null);
if (!username) return;
// schedule a short task to allow popover to appear
setTimeout(() => {
// find visible popover elements
const pops = Array.from(document.querySelectorAll('.Popover.js-hovercard-content, .js-hovercard-content, .Popover'));
const trgRect = trg.getBoundingClientRect && trg.getBoundingClientRect();
for (const p of pops) {
if (!p || p.style && p.style.display === 'none') continue;
// prefer popovers that are near the trigger
const prect = p.getBoundingClientRect && p.getBoundingClientRect();
if (!prect) continue;
const dx = Math.abs((prect.left + prect.right)/2 - (trgRect.left + trgRect.right)/2);
const dy = Math.abs((prect.top + prect.bottom)/2 - (trgRect.top + trgRect.bottom)/2);
if (dx < 800 && dy < 800) {
// inject into this popover if not already
tryInjectToHovercardElement(p, username, trg);
// do not continue after first match
break;
}
}
}, 120);
} catch (err) {
// ignore
}
}, true);