-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
386 lines (342 loc) · 12.6 KB
/
Copy pathcontent.js
File metadata and controls
386 lines (342 loc) · 12.6 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
(() => {
'use strict';
let popup = null;
let selectedHTML = '';
let selectedText = '';
// --- SVG Icons ---
const ICONS = {
plainText: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>`,
markdown: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 3h20v18H2z"/><path d="M7 8v8l3-3 3 3V8"/><path d="M17 12h-2l2-4 2 4h-2v4"/></svg>`,
html: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`,
withSource: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,
logo: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#7C3AED" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,
check: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`
};
// --- HTML to Markdown converter ---
function htmlToMarkdown(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return convertNode(doc.body).trim();
}
function convertNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent;
}
if (node.nodeType !== Node.ELEMENT_NODE) return '';
const tag = node.tagName.toLowerCase();
const children = Array.from(node.childNodes).map(convertNode).join('');
switch (tag) {
case 'h1': return `\n# ${children.trim()}\n\n`;
case 'h2': return `\n## ${children.trim()}\n\n`;
case 'h3': return `\n### ${children.trim()}\n\n`;
case 'h4': return `\n#### ${children.trim()}\n\n`;
case 'h5': return `\n##### ${children.trim()}\n\n`;
case 'h6': return `\n###### ${children.trim()}\n\n`;
case 'strong':
case 'b':
return `**${children.trim()}**`;
case 'em':
case 'i':
return `*${children.trim()}*`;
case 'a': {
const href = node.getAttribute('href') || '';
return `[${children.trim()}](${href})`;
}
case 'img': {
const src = node.getAttribute('src') || '';
const alt = node.getAttribute('alt') || '';
return ``;
}
case 'code':
if (node.parentElement && node.parentElement.tagName.toLowerCase() === 'pre') {
return children;
}
return `\`${children}\``;
case 'pre': {
const codeEl = node.querySelector('code');
const content = codeEl ? codeEl.textContent : children;
return `\n\`\`\`\n${content.trim()}\n\`\`\`\n\n`;
}
case 'ul': {
const items = Array.from(node.children)
.filter(c => c.tagName.toLowerCase() === 'li')
.map(li => `- ${convertNode(li).trim()}`)
.join('\n');
return `\n${items}\n\n`;
}
case 'ol': {
const items = Array.from(node.children)
.filter(c => c.tagName.toLowerCase() === 'li')
.map((li, i) => `${i + 1}. ${convertNode(li).trim()}`)
.join('\n');
return `\n${items}\n\n`;
}
case 'li':
return children;
case 'br':
return '\n';
case 'p':
return `\n${children.trim()}\n\n`;
case 'blockquote':
return `\n> ${children.trim().replace(/\n/g, '\n> ')}\n\n`;
case 'table': return convertTable(node);
case 'hr': return '\n---\n\n';
case 'div':
case 'span':
case 'section':
case 'article':
case 'main':
case 'header':
case 'footer':
case 'nav':
case 'body':
return children;
default:
return children;
}
}
function convertTable(table) {
const rows = Array.from(table.querySelectorAll('tr'));
if (rows.length === 0) return '';
const matrix = rows.map(row =>
Array.from(row.querySelectorAll('th, td')).map(cell => convertNode(cell).trim())
);
const colCount = Math.max(...matrix.map(r => r.length));
const normalized = matrix.map(r => {
while (r.length < colCount) r.push('');
return r;
});
let md = '\n';
md += '| ' + normalized[0].join(' | ') + ' |\n';
md += '| ' + normalized[0].map(() => '---').join(' | ') + ' |\n';
for (let i = 1; i < normalized.length; i++) {
md += '| ' + normalized[i].join(' | ') + ' |\n';
}
return md + '\n';
}
// --- Clean HTML ---
function cleanHTML(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
// Remove scripts, styles, and event attributes
doc.querySelectorAll('script, style, link').forEach(el => el.remove());
doc.querySelectorAll('*').forEach(el => {
const attrs = Array.from(el.attributes);
attrs.forEach(attr => {
if (attr.name.startsWith('on') || attr.name === 'class' || attr.name === 'id' || attr.name === 'style') {
el.removeAttribute(attr.name);
}
});
});
return doc.body.innerHTML.trim();
}
// --- Format "With Source" ---
function formatWithSource(text) {
const now = new Date();
const day = String(now.getDate()).padStart(2, '0');
const month = String(now.getMonth() + 1).padStart(2, '0');
const year = now.getFullYear();
const title = document.title || 'Sans titre';
const url = window.location.href;
return `${text}\n\n— Copié depuis [${title}](${url}) le ${day}/${month}/${year}`;
}
// --- Copy to clipboard ---
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// Fallback
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
return true;
}
}
// --- Get selection position ---
function getSelectionPosition() {
const selection = window.getSelection();
if (!selection.rangeCount) return null;
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top,
bottom: rect.bottom,
width: rect.width
};
}
// --- Get selected HTML ---
function getSelectedHTML() {
const selection = window.getSelection();
if (!selection.rangeCount) return '';
const range = selection.getRangeAt(0);
const container = document.createElement('div');
container.appendChild(range.cloneContents());
return container.innerHTML;
}
// --- Create popup ---
function createPopup(pos) {
removePopup();
popup = document.createElement('div');
popup.id = 'copybetter-popup';
const header = document.createElement('div');
header.className = 'copybetter-header';
header.innerHTML = `${ICONS.logo}<span>Copy as</span>`;
popup.appendChild(header);
const formats = [
{ id: 'plain', icon: ICONS.plainText, title: 'Plain Text', desc: 'Clean plain text' },
{ id: 'markdown', icon: ICONS.markdown, title: 'Markdown', desc: 'Links, lists, formatting' },
{ id: 'html', icon: ICONS.html, title: 'HTML', desc: 'Source code' },
{ id: 'source', icon: ICONS.withSource, title: 'With Source', desc: 'Text + page URL & date' }
];
formats.forEach(fmt => {
const btn = document.createElement('button');
btn.className = 'copybetter-btn';
btn.dataset.format = fmt.id;
btn.innerHTML = `
<span class="copybetter-icon">${fmt.icon}</span>
<span class="copybetter-label">
<span class="copybetter-label-title">${fmt.title}</span>
<span class="copybetter-label-desc">${fmt.desc}</span>
</span>
`;
btn.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
});
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
handleFormatClick(fmt.id, btn);
});
popup.appendChild(btn);
});
// Position popup
const popupWidth = 280;
let left = pos.x - popupWidth / 2;
let top = pos.y - 10; // above selection
// Adjust horizontal bounds
if (left < 8) left = 8;
if (left + popupWidth > window.innerWidth - 8) {
left = window.innerWidth - popupWidth - 8;
}
// Will measure after adding to DOM
popup.style.left = `${left + window.scrollX}px`;
popup.style.top = '0px';
popup.style.visibility = 'hidden';
document.body.appendChild(popup);
const popupHeight = popup.offsetHeight;
// Try above selection, if not enough space, go below
if (pos.y - popupHeight - 10 > 0) {
top = pos.y - popupHeight - 10;
} else {
top = pos.bottom + 10;
}
popup.style.top = `${top + window.scrollY}px`;
popup.style.visibility = 'visible';
// Close when clicking outside
setTimeout(() => {
document.addEventListener('mousedown', onOutsideClick);
}, 10);
}
function onOutsideClick(e) {
if (popup && !popup.contains(e.target)) {
removePopup();
}
}
function removePopup() {
if (popup) {
popup.remove();
popup = null;
}
document.removeEventListener('mousedown', onOutsideClick);
}
// --- Handle format button click ---
async function handleFormatClick(formatId, btn) {
let textToCopy = '';
switch (formatId) {
case 'plain':
textToCopy = selectedText;
break;
case 'markdown':
textToCopy = htmlToMarkdown(selectedHTML);
break;
case 'html':
textToCopy = cleanHTML(selectedHTML);
break;
case 'source':
textToCopy = formatWithSource(selectedText);
break;
}
await copyToClipboard(textToCopy);
// Increment counter
chrome.storage.local.get({ copyCount: 0 }, (data) => {
chrome.storage.local.set({ copyCount: data.copyCount + 1 });
});
// Visual feedback
btn.classList.add('copybetter-active');
const titleEl = btn.querySelector('.copybetter-label-title');
const origTitle = titleEl.textContent;
titleEl.textContent = 'Copied ✓';
setTimeout(() => {
removePopup();
}, 600);
}
// --- Apply default format directly ---
async function applyDefaultFormat(format) {
let textToCopy = '';
switch (format) {
case 'plain':
textToCopy = selectedText;
break;
case 'markdown':
textToCopy = htmlToMarkdown(selectedHTML);
break;
case 'html':
textToCopy = cleanHTML(selectedHTML);
break;
case 'source':
textToCopy = formatWithSource(selectedText);
break;
}
// Small delay to let the native copy happen first, then overwrite
setTimeout(async () => {
await copyToClipboard(textToCopy);
chrome.storage.local.get({ copyCount: 0 }, (data) => {
chrome.storage.local.set({ copyCount: data.copyCount + 1 });
});
}, 10);
}
// --- Listen for copy event ---
document.addEventListener('copy', (e) => {
const selection = window.getSelection();
if (!selection || selection.isCollapsed) return;
selectedText = selection.toString().trim();
selectedHTML = getSelectedHTML();
if (!selectedText) return;
// Check settings
chrome.storage.local.get({ enabled: true, defaultFormat: 'ask' }, (data) => {
if (!data.enabled) return;
if (data.defaultFormat !== 'ask') {
// Apply default format silently
applyDefaultFormat(data.defaultFormat);
} else {
// Show popup
const pos = getSelectionPosition();
if (pos) {
createPopup(pos);
}
}
});
});
// Close popup on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && popup) {
removePopup();
}
});
})();